xref: /aosp_15_r20/external/libtextclassifier/native/utils/java/jni-base.h (revision 993b0882672172b81d12fad7a7ac0c3e5c824a12)
1 /*
2  * Copyright (C) 2018 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 LIBTEXTCLASSIFIER_UTILS_JAVA_JNI_BASE_H_
18 #define LIBTEXTCLASSIFIER_UTILS_JAVA_JNI_BASE_H_
19 
20 #include <jni.h>
21 
22 #include <memory>
23 #include <string>
24 
25 #include "utils/base/statusor.h"
26 
27 // When we use a macro as an argument for a macro, an additional level of
28 // indirection is needed, if the macro argument is used with # or ##.
29 #define TC3_ADD_QUOTES_HELPER(TOKEN) #TOKEN
30 #define TC3_ADD_QUOTES(TOKEN) TC3_ADD_QUOTES_HELPER(TOKEN)
31 
32 #ifndef TC3_PACKAGE_NAME
33 #define TC3_PACKAGE_NAME com_google_android_textclassifier
34 #endif
35 
36 #ifndef TC3_PACKAGE_PATH
37 #define TC3_PACKAGE_PATH \
38   "com/google/android/textclassifier/"
39 #endif
40 
41 #define TC3_JNI_METHOD_NAME_INTERNAL(package_name, class_name, method_name) \
42   Java_##package_name##_##class_name##_##method_name
43 
44 #define TC3_JNI_METHOD_PRIMITIVE(return_type, package_name, class_name, \
45                                  method_name)                           \
46   JNIEXPORT return_type JNICALL TC3_JNI_METHOD_NAME_INTERNAL(           \
47       package_name, class_name, method_name)
48 
49 // The indirection is needed to correctly expand the TC3_PACKAGE_NAME macro.
50 // See the explanation near TC3_ADD_QUOTES macro.
51 #define TC3_JNI_METHOD2(return_type, package_name, class_name, method_name) \
52   TC3_JNI_METHOD_PRIMITIVE(return_type, package_name, class_name, method_name)
53 
54 #define TC3_JNI_METHOD(return_type, class_name, method_name) \
55   TC3_JNI_METHOD2(return_type, TC3_PACKAGE_NAME, class_name, method_name)
56 
57 #define TC3_JNI_METHOD_NAME2(package_name, class_name, method_name) \
58   TC3_JNI_METHOD_NAME_INTERNAL(package_name, class_name, method_name)
59 
60 #define TC3_JNI_METHOD_NAME(class_name, method_name) \
61   TC3_JNI_METHOD_NAME2(TC3_PACKAGE_NAME, class_name, method_name)
62 
63 namespace libtextclassifier3 {
64 
65 // Returns true if the requested capacity is available.
66 bool EnsureLocalCapacity(JNIEnv* env, int capacity);
67 
68 // Returns true if there was an exception. Also it clears the exception.
69 bool JniExceptionCheckAndClear(JNIEnv* env,
70                                bool print_exception_on_error = true);
71 
72 // A deleter to be used with std::unique_ptr to delete JNI global references.
73 class GlobalRefDeleter {
74  public:
GlobalRefDeleter(JavaVM * jvm)75   explicit GlobalRefDeleter(JavaVM* jvm) : jvm_(jvm) {}
76 
77   GlobalRefDeleter(const GlobalRefDeleter& orig) = default;
78 
79   // Copy assignment to allow move semantics in ScopedGlobalRef.
80   GlobalRefDeleter& operator=(const GlobalRefDeleter& rhs) {
81     TC3_CHECK_EQ(jvm_, rhs.jvm_);
82     return *this;
83   }
84 
85   // The delete operator.
operator()86   void operator()(jobject object) const {
87     JNIEnv* env;
88     if (object != nullptr && jvm_ != nullptr &&
89         JNI_OK ==
90             jvm_->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_4)) {
91       env->DeleteGlobalRef(object);
92     }
93   }
94 
95  private:
96   // The jvm_ stashed to use for deletion.
97   JavaVM* const jvm_;
98 };
99 
100 // A deleter to be used with std::unique_ptr to delete JNI local references.
101 class LocalRefDeleter {
102  public:
LocalRefDeleter(JNIEnv * env)103   explicit LocalRefDeleter(JNIEnv* env)
104       : env_(env) {}  // NOLINT(runtime/explicit)
105 
106   LocalRefDeleter(const LocalRefDeleter& orig) = default;
107 
108   // Copy assignment to allow move semantics in ScopedLocalRef.
109   LocalRefDeleter& operator=(const LocalRefDeleter& rhs) {
110     env_ = rhs.env_;
111     return *this;
112   }
113 
114   // The delete operator.
operator()115   void operator()(jobject object) const {
116     if (env_) {
117       env_->DeleteLocalRef(object);
118     }
119   }
120 
121  private:
122   // The env_ stashed to use for deletion. Thread-local, don't share!
123   JNIEnv* env_;
124 };
125 
126 // A smart pointer that deletes a reference when it goes out of scope.
127 //
128 // Note that this class is not thread-safe since it caches JNIEnv in
129 // the deleter. Do not use the same jobject across different threads.
130 template <typename T, typename Env, typename Deleter>
131 class ScopedRef {
132  public:
ScopedRef()133   ScopedRef() : ptr_(nullptr, Deleter(nullptr)) {}
ScopedRef(T value,Env * env)134   ScopedRef(T value, Env* env) : ptr_(value, Deleter(env)) {}
135 
get()136   T get() const { return ptr_.get(); }
137 
release()138   T release() { return ptr_.release(); }
139 
140   bool operator!() const { return !ptr_; }
141 
142   bool operator==(void* value) const { return ptr_.get() == value; }
143 
144   explicit operator bool() const { return ptr_ != nullptr; }
145 
reset(T value,Env * env)146   void reset(T value, Env* env) {
147     ptr_.reset(value);
148     ptr_.get_deleter() = Deleter(env);
149   }
150 
151  private:
152   std::unique_ptr<typename std::remove_pointer<T>::type, Deleter> ptr_;
153 };
154 
155 template <typename T, typename U, typename Env, typename Deleter>
156 inline bool operator==(const ScopedRef<T, Env, Deleter>& x,
157                        const ScopedRef<U, Env, Deleter>& y) {
158   return x.get() == y.get();
159 }
160 
161 template <typename T, typename Env, typename Deleter>
162 inline bool operator==(const ScopedRef<T, Env, Deleter>& x, std::nullptr_t) {
163   return x.get() == nullptr;
164 }
165 
166 template <typename T, typename Env, typename Deleter>
167 inline bool operator==(std::nullptr_t, const ScopedRef<T, Env, Deleter>& x) {
168   return nullptr == x.get();
169 }
170 
171 template <typename T, typename U, typename Env, typename Deleter>
172 inline bool operator!=(const ScopedRef<T, Env, Deleter>& x,
173                        const ScopedRef<U, Env, Deleter>& y) {
174   return x.get() != y.get();
175 }
176 
177 template <typename T, typename Env, typename Deleter>
178 inline bool operator!=(const ScopedRef<T, Env, Deleter>& x, std::nullptr_t) {
179   return x.get() != nullptr;
180 }
181 
182 template <typename T, typename Env, typename Deleter>
183 inline bool operator!=(std::nullptr_t, const ScopedRef<T, Env, Deleter>& x) {
184   return nullptr != x.get();
185 }
186 
187 template <typename T, typename U, typename Env, typename Deleter>
188 inline bool operator<(const ScopedRef<T, Env, Deleter>& x,
189                       const ScopedRef<U, Env, Deleter>& y) {
190   return x.get() < y.get();
191 }
192 
193 template <typename T, typename U, typename Env, typename Deleter>
194 inline bool operator>(const ScopedRef<T, Env, Deleter>& x,
195                       const ScopedRef<U, Env, Deleter>& y) {
196   return x.get() > y.get();
197 }
198 
199 // A smart pointer that deletes a JNI global reference when it goes out
200 // of scope. Usage is:
201 // ScopedGlobalRef<jobject> scoped_global(env->JniFunction(), jvm);
202 template <typename T>
203 using ScopedGlobalRef = ScopedRef<T, JavaVM, GlobalRefDeleter>;
204 
205 // Ditto, but usage is:
206 // ScopedLocalRef<jobject> scoped_local(env->JniFunction(), env);
207 template <typename T>
208 using ScopedLocalRef = ScopedRef<T, JNIEnv, LocalRefDeleter>;
209 
210 // A helper to create global references.
211 template <typename T>
MakeGlobalRef(T object,JNIEnv * env,JavaVM * jvm)212 ScopedGlobalRef<T> MakeGlobalRef(T object, JNIEnv* env, JavaVM* jvm) {
213   const jobject global_object = env->NewGlobalRef(object);
214   return ScopedGlobalRef<T>(reinterpret_cast<T>(global_object), jvm);
215 }
216 
217 }  // namespace libtextclassifier3
218 
219 #endif  // LIBTEXTCLASSIFIER_UTILS_JAVA_JNI_BASE_H_
220