• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2008 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define LOG_TAG "MemoryFile"
18 #include <utils/Log.h>
19 
20 #include <cutils/ashmem.h>
21 #include "core_jni_helpers.h"
22 #include <nativehelper/JNIHelp.h>
23 #include <unistd.h>
24 #include <sys/mman.h>
25 
26 
27 namespace android {
28 
android_os_MemoryFile_pin(JNIEnv * env,jobject clazz,jobject fileDescriptor,jboolean pin)29 static jboolean android_os_MemoryFile_pin(JNIEnv* env, jobject clazz, jobject fileDescriptor,
30         jboolean pin) {
31     int fd = jniGetFDFromFileDescriptor(env, fileDescriptor);
32     int result = (pin ? ashmem_pin_region(fd, 0, 0) : ashmem_unpin_region(fd, 0, 0));
33     if (result < 0) {
34         jniThrowException(env, "java/io/IOException", NULL);
35     }
36     return result == ASHMEM_WAS_PURGED;
37 }
38 
android_os_MemoryFile_get_size(JNIEnv * env,jobject clazz,jobject fileDescriptor)39 static jint android_os_MemoryFile_get_size(JNIEnv* env, jobject clazz,
40         jobject fileDescriptor) {
41     int fd = jniGetFDFromFileDescriptor(env, fileDescriptor);
42     // Use ASHMEM_GET_SIZE to find out if the fd refers to an ashmem region.
43     // ASHMEM_GET_SIZE should succeed for all ashmem regions, and the kernel
44     // should return ENOTTY for all other valid file descriptors
45     int result = ashmem_get_size_region(fd);
46     if (result < 0) {
47         if (errno == ENOTTY) {
48             // ENOTTY means that the ioctl does not apply to this object,
49             // i.e., it is not an ashmem region.
50             return (jint) -1;
51         }
52         // Some other error, throw exception
53         jniThrowIOException(env, errno);
54         return (jint) -1;
55     }
56     return (jint) result;
57 }
58 
59 static const JNINativeMethod methods[] = {
60     {"native_pin",   "(Ljava/io/FileDescriptor;Z)Z", (void*)android_os_MemoryFile_pin},
61     {"native_get_size", "(Ljava/io/FileDescriptor;)I",
62             (void*)android_os_MemoryFile_get_size}
63 };
64 
register_android_os_MemoryFile(JNIEnv * env)65 int register_android_os_MemoryFile(JNIEnv* env) {
66     return RegisterMethodsOrDie(env, "android/os/MemoryFile", methods, NELEM(methods));
67 }
68 
69 }
70