1 /* 2 * Copyright (C) 2019 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 #ifndef ANDROID_OS_HIDL_MEMORY_H 18 #define ANDROID_OS_HIDL_MEMORY_H 19 20 #include <jni.h> 21 #include <hidl/HidlSupport.h> 22 23 namespace android { 24 25 // A utility class for handling the android.os.HidlMemory class from JNI code. 26 class JHidlMemory final { 27 public: 28 // Convert an android.os.HidlMemory object to its C++ counterpart, 29 // hardware::hidl_memory. 30 // No duplication of file descriptors is performed. 31 // The returned reference is owned by the underlying Java object. 32 // Returns nullptr if conversion cannot be done. 33 static const hardware::hidl_memory* fromJava(JNIEnv* env, 34 jobject jobj); 35 36 // Convert a hardware::hidl_memory object to its Java counterpart, 37 // android.os.HidlMemory. 38 // No duplication of file descriptors is performed. 39 // Returns nullptr if conversion cannot be done. 40 static jobject toJava(JNIEnv* env, 41 const hardware::hidl_memory& cobj); 42 43 ~JHidlMemory(); 44 45 private: 46 // We store an instance of type JHidlMemory attached to every Java object 47 // of type HidlMemory, for holding any native context we need. This instance 48 // will get deleted when finalize() is called on the Java object. 49 // This method either extracts the native object from the Java object, or 50 // attached a new one if it doesn't yet exist. 51 static JHidlMemory* getNativeContext(JNIEnv* env, jobject obj); 52 53 // Convert an android.os.HidlMemory object to its C++ counterpart, 54 // hardware::hidl_memory. 55 // No duplication of file descriptors is performed. 56 // IMPORTANT: caller is responsible to native_handle_delete() the handle of the 57 // returned object. This is due to an underlying limitation of the hidl_handle 58 // type, where ownership of the handle implies ownership of the fd and we don't 59 // want the latter. 60 // Returns nullptr if conversion cannot be done. 61 static std::unique_ptr<hardware::hidl_memory> javaToNative(JNIEnv* env, 62 jobject jobj); 63 64 std::unique_ptr<hardware::hidl_memory> mObj; 65 }; 66 67 int register_android_os_HidlMemory(JNIEnv* env); 68 69 } // namespace android 70 71 #endif //ANDROID_OS_HIDL_MEMORY_H 72