1/* 2 * Copyright 2016, 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 17namespace android { 18 19/* JNI Helpers for wifi_hal to WifiNative bridge implementation */ 20 21class JNIHelper; 22 23template<typename T> 24class JNIObject { 25protected: 26 JNIHelper &mHelper; 27 T mObj; 28public: 29 JNIObject(JNIHelper &helper, T obj); 30 JNIObject(const JNIObject<T>& rhs); 31 virtual ~JNIObject(); 32 JNIHelper& getHelper() const { 33 return mHelper; 34 } 35 T get() const { 36 return mObj; 37 } 38 operator T() const { 39 return mObj; 40 } 41 bool isNull() const { 42 return mObj == NULL; 43 } 44 void release(); 45 T detach() { 46 T tObj = mObj; 47 mObj = NULL; 48 return tObj; 49 } 50 T clone(); 51 JNIObject<T>& operator = (const JNIObject<T>& rhs) { 52 release(); 53 mHelper = rhs.mHelper; 54 mObj = rhs.mObj; 55 return *this; 56 } 57 void print() { 58 ALOGD("holding %p", mObj); 59 } 60 61private: 62 template<typename T2> 63 JNIObject(const JNIObject<T2>& rhs); // NOLINT(implicit) 64}; 65 66class JNIHelper { 67 JavaVM *mVM; 68 JNIEnv *mEnv; 69 70public : 71 explicit JNIHelper(JavaVM *vm); 72 explicit JNIHelper(JNIEnv *env); 73 ~JNIHelper(); 74 75 /* helpers to deal with static members */ 76 JNIObject<jbyteArray> newByteArray(int num); 77 void setByteArrayRegion(jbyteArray array, int from, int to, const jbyte *bytes); 78 79private: 80 /* Jni wrappers */ 81 friend class JNIObject<jbyteArray>; 82 jobject newLocalRef(jobject obj); 83 void deleteLocalRef(jobject obj); 84}; 85 86template<typename T> 87JNIObject<T>::JNIObject(JNIHelper &helper, T obj) 88 : mHelper(helper), mObj(obj) 89{ } 90 91template<typename T> 92JNIObject<T>::JNIObject(const JNIObject<T>& rhs) 93 : mHelper(rhs.mHelper), mObj(NULL) 94{ 95 mObj = (T)mHelper.newLocalRef(rhs.mObj); 96} 97 98template<typename T> 99JNIObject<T>::~JNIObject() { 100 release(); 101} 102 103template<typename T> 104void JNIObject<T>::release() 105{ 106 if (mObj != NULL) { 107 mHelper.deleteLocalRef(mObj); 108 mObj = NULL; 109 } 110} 111 112template<typename T> 113T JNIObject<T>::clone() 114{ 115 return mHelper.newLocalRef(mObj); 116} 117} 118 119#define THROW(env, message) (env).throwException(message, __LINE__) 120