1 /*
2  *  Copyright 2017 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 // Originally these classes are from Chromium.
12 // https://cs.chromium.org/chromium/src/base/android/scoped_java_ref.h.
13 
14 #ifndef SDK_ANDROID_NATIVE_API_JNI_SCOPED_JAVA_REF_H_
15 #define SDK_ANDROID_NATIVE_API_JNI_SCOPED_JAVA_REF_H_
16 
17 #include <jni.h>
18 #include <utility>
19 
20 #include "rtc_base/constructor_magic.h"
21 #include "sdk/android/native_api/jni/jvm.h"
22 
23 namespace webrtc {
24 
25 // Generic base class for ScopedJavaLocalRef and ScopedJavaGlobalRef. Useful
26 // for allowing functions to accept a reference without having to mandate
27 // whether it is a local or global type.
28 template <typename T>
29 class JavaRef;
30 
31 // Template specialization of JavaRef, which acts as the base class for all
32 // other JavaRef<> template types. This allows you to e.g. pass JavaRef<jstring>
33 // into a function taking const JavaRef<jobject>&.
34 template <>
35 class JavaRef<jobject> {
36  public:
obj()37   jobject obj() const { return obj_; }
is_null()38   bool is_null() const {
39     // This is not valid for weak references. For weak references you need to
40     // use env->IsSameObject(objc_, nullptr), but that should be avoided anyway
41     // since it does not prevent the object from being freed immediately
42     // thereafter. Consequently, programmers should not use this check on weak
43     // references anyway and should first make a ScopedJavaLocalRef or
44     // ScopedJavaGlobalRef before checking if it is null.
45     return obj_ == nullptr;
46   }
47 
48  protected:
JavaRef()49   constexpr JavaRef() : obj_(nullptr) {}
JavaRef(jobject obj)50   explicit JavaRef(jobject obj) : obj_(obj) {}
51   jobject obj_;
52 
53  private:
54   RTC_DISALLOW_COPY_AND_ASSIGN(JavaRef);
55 };
56 
57 template <typename T>
58 class JavaRef : public JavaRef<jobject> {
59  public:
obj()60   T obj() const { return static_cast<T>(obj_); }
61 
62  protected:
JavaRef()63   JavaRef() : JavaRef<jobject>(nullptr) {}
JavaRef(T obj)64   explicit JavaRef(T obj) : JavaRef<jobject>(obj) {}
65 
66  private:
67   RTC_DISALLOW_COPY_AND_ASSIGN(JavaRef);
68 };
69 
70 // Holds a local reference to a JNI method parameter.
71 // Method parameters should not be deleted, and so this class exists purely to
72 // wrap them as a JavaRef<T> in the JNI binding generator. Do not create
73 // instances manually.
74 template <typename T>
75 class JavaParamRef : public JavaRef<T> {
76  public:
77   // Assumes that |obj| is a parameter passed to a JNI method from Java.
78   // Does not assume ownership as parameters should not be deleted.
JavaParamRef(T obj)79   explicit JavaParamRef(T obj) : JavaRef<T>(obj) {}
JavaParamRef(JNIEnv *,T obj)80   JavaParamRef(JNIEnv*, T obj) : JavaRef<T>(obj) {}
81 
82  private:
83   RTC_DISALLOW_COPY_AND_ASSIGN(JavaParamRef);
84 };
85 
86 // Holds a local reference to a Java object. The local reference is scoped
87 // to the lifetime of this object.
88 // Instances of this class may hold onto any JNIEnv passed into it until
89 // destroyed. Therefore, since a JNIEnv is only suitable for use on a single
90 // thread, objects of this class must be created, used, and destroyed, on a
91 // single thread.
92 // Therefore, this class should only be used as a stack-based object and from a
93 // single thread. If you wish to have the reference outlive the current
94 // callstack (e.g. as a class member) or you wish to pass it across threads,
95 // use a ScopedJavaGlobalRef instead.
96 template <typename T>
97 class ScopedJavaLocalRef : public JavaRef<T> {
98  public:
99   ScopedJavaLocalRef() = default;
ScopedJavaLocalRef(std::nullptr_t)100   ScopedJavaLocalRef(std::nullptr_t) {}  // NOLINT(runtime/explicit)
101 
ScopedJavaLocalRef(JNIEnv * env,const JavaRef<T> & other)102   ScopedJavaLocalRef(JNIEnv* env, const JavaRef<T>& other) : env_(env) {
103     Reset(other.obj(), OwnershipPolicy::RETAIN);
104   }
105   // Allow constructing e.g. ScopedJavaLocalRef<jobject> from
106   // ScopedJavaLocalRef<jstring>.
107   template <typename G>
ScopedJavaLocalRef(ScopedJavaLocalRef<G> && other)108   ScopedJavaLocalRef(ScopedJavaLocalRef<G>&& other) : env_(other.env()) {
109     Reset(other.Release(), OwnershipPolicy::ADOPT);
110   }
ScopedJavaLocalRef(const ScopedJavaLocalRef & other)111   ScopedJavaLocalRef(const ScopedJavaLocalRef& other) : env_(other.env_) {
112     Reset(other.obj(), OwnershipPolicy::RETAIN);
113   }
114 
115   // Assumes that |obj| is a reference to a Java object and takes
116   // ownership  of this  reference. This should preferably not be used
117   // outside of JNI helper functions.
ScopedJavaLocalRef(JNIEnv * env,T obj)118   ScopedJavaLocalRef(JNIEnv* env, T obj) : JavaRef<T>(obj), env_(env) {}
119 
~ScopedJavaLocalRef()120   ~ScopedJavaLocalRef() {
121     if (obj_ != nullptr)
122       env_->DeleteLocalRef(obj_);
123   }
124 
125   void operator=(const ScopedJavaLocalRef& other) {
126     Reset(other.obj(), OwnershipPolicy::RETAIN);
127   }
128   void operator=(ScopedJavaLocalRef&& other) {
129     Reset(other.Release(), OwnershipPolicy::ADOPT);
130   }
131 
132   // Releases the reference to the caller. The caller *must* delete the
133   // reference when it is done with it. Note that calling a Java method
134   // is *not* a transfer of ownership and Release() should not be used.
Release()135   T Release() {
136     T obj = static_cast<T>(obj_);
137     obj_ = nullptr;
138     return obj;
139   }
140 
env()141   JNIEnv* env() const { return env_; }
142 
143  private:
144   using JavaRef<T>::obj_;
145 
146   enum OwnershipPolicy {
147     // The scoped object takes ownership of an object by taking over an existing
148     // ownership claim.
149     ADOPT,
150     // The scoped object will retain the the object and any initial ownership is
151     // not changed.
152     RETAIN
153   };
154 
Reset(T obj,OwnershipPolicy policy)155   void Reset(T obj, OwnershipPolicy policy) {
156     if (obj_ != nullptr)
157       env_->DeleteLocalRef(obj_);
158     obj_ = (obj != nullptr && policy == OwnershipPolicy::RETAIN)
159                ? env_->NewLocalRef(obj)
160                : obj;
161   }
162 
163   JNIEnv* const env_ = AttachCurrentThreadIfNeeded();
164 };
165 
166 // Holds a global reference to a Java object. The global reference is scoped
167 // to the lifetime of this object. This class does not hold onto any JNIEnv*
168 // passed to it, hence it is safe to use across threads (within the constraints
169 // imposed by the underlying Java object that it references).
170 template <typename T>
171 class ScopedJavaGlobalRef : public JavaRef<T> {
172  public:
173   using JavaRef<T>::obj_;
174 
ScopedJavaGlobalRef(std::nullptr_t)175   explicit constexpr ScopedJavaGlobalRef(std::nullptr_t) {}
ScopedJavaGlobalRef(JNIEnv * env,const JavaRef<T> & other)176   ScopedJavaGlobalRef(JNIEnv* env, const JavaRef<T>& other)
177       : JavaRef<T>(static_cast<T>(env->NewGlobalRef(other.obj()))) {}
ScopedJavaGlobalRef(const ScopedJavaLocalRef<T> & other)178   explicit ScopedJavaGlobalRef(const ScopedJavaLocalRef<T>& other)
179       : ScopedJavaGlobalRef(other.env(), other) {}
ScopedJavaGlobalRef(ScopedJavaGlobalRef && other)180   ScopedJavaGlobalRef(ScopedJavaGlobalRef&& other)
181       : JavaRef<T>(other.Release()) {}
182 
~ScopedJavaGlobalRef()183   ~ScopedJavaGlobalRef() {
184     if (obj_ != nullptr)
185       AttachCurrentThreadIfNeeded()->DeleteGlobalRef(obj_);
186   }
187 
188   // Releases the reference to the caller. The caller *must* delete the
189   // reference when it is done with it. Note that calling a Java method
190   // is *not* a transfer of ownership and Release() should not be used.
Release()191   T Release() {
192     T obj = static_cast<T>(obj_);
193     obj_ = nullptr;
194     return obj;
195   }
196 
197  private:
198   RTC_DISALLOW_COPY_AND_ASSIGN(ScopedJavaGlobalRef);
199 };
200 
201 template <typename T>
static_java_ref_cast(JNIEnv * env,JavaRef<jobject> const & ref)202 inline ScopedJavaLocalRef<T> static_java_ref_cast(JNIEnv* env,
203                                                   JavaRef<jobject> const& ref) {
204   ScopedJavaLocalRef<jobject> owned_ref(env, ref);
205   return ScopedJavaLocalRef<T>(env, static_cast<T>(owned_ref.Release()));
206 }
207 
208 }  // namespace webrtc
209 
210 #endif  // SDK_ANDROID_NATIVE_API_JNI_SCOPED_JAVA_REF_H_
211