1 /*
2  * Copyright (C) 2011 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 ART_RUNTIME_JNI_JNI_ENV_EXT_H_
18 #define ART_RUNTIME_JNI_JNI_ENV_EXT_H_
19 
20 #include <jni.h>
21 
22 #include "base/locks.h"
23 #include "base/macros.h"
24 #include "indirect_reference_table.h"
25 #include "obj_ptr.h"
26 #include "reference_table.h"
27 
28 namespace art {
29 
30 class ArtMethod;
31 class ArtField;
32 class JavaVMExt;
33 class ScopedObjectAccess;
34 class ScopedObjectAccessAlreadyRunnable;
35 
36 namespace mirror {
37 class Object;
38 }  // namespace mirror
39 
40 // Number of local references in the indirect reference table. The value is arbitrary but
41 // low enough that it forces integrity checks.
42 static constexpr size_t kLocalsInitial = 512;
43 
44 class JNIEnvExt : public JNIEnv {
45  public:
46   // Creates a new JNIEnvExt. Returns null on error, in which case error_msg
47   // will contain a description of the error.
48   static JNIEnvExt* Create(Thread* self, JavaVMExt* vm, std::string* error_msg);
49   static Offset SegmentStateOffset(size_t pointer_size);
50   static Offset LocalRefCookieOffset(size_t pointer_size);
51   static Offset SelfOffset(size_t pointer_size);
52   static jint GetEnvHandler(JavaVMExt* vm, /*out*/void** out, jint version);
53 
54   ~JNIEnvExt();
55 
56   void DumpReferenceTables(std::ostream& os)
57       REQUIRES_SHARED(Locks::mutator_lock_)
58       REQUIRES(!Locks::alloc_tracker_lock_);
59 
60   void SetCheckJniEnabled(bool enabled) REQUIRES(!Locks::jni_function_table_lock_);
61 
62   void PushFrame(int capacity) REQUIRES_SHARED(Locks::mutator_lock_);
63   void PopFrame() REQUIRES_SHARED(Locks::mutator_lock_);
64 
65   template<typename T>
66   T AddLocalReference(ObjPtr<mirror::Object> obj)
67       REQUIRES_SHARED(Locks::mutator_lock_)
68       REQUIRES(!Locks::alloc_tracker_lock_);
69 
UpdateLocal(IndirectRef iref,ObjPtr<mirror::Object> obj)70   void UpdateLocal(IndirectRef iref, ObjPtr<mirror::Object> obj) REQUIRES_SHARED(Locks::mutator_lock_) {
71     locals_.Update(iref, obj);
72   }
73 
74   jobject NewLocalRef(mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_);
75   void DeleteLocalRef(jobject obj) REQUIRES_SHARED(Locks::mutator_lock_);
76 
TrimLocals()77   void TrimLocals() REQUIRES_SHARED(Locks::mutator_lock_) {
78     locals_.Trim();
79   }
AssertLocalsEmpty()80   void AssertLocalsEmpty() REQUIRES_SHARED(Locks::mutator_lock_) {
81     locals_.AssertEmpty();
82   }
GetLocalsCapacity()83   size_t GetLocalsCapacity() REQUIRES_SHARED(Locks::mutator_lock_) {
84     return locals_.Capacity();
85   }
86 
GetLocalRefCookie()87   IRTSegmentState GetLocalRefCookie() const { return local_ref_cookie_; }
SetLocalRefCookie(IRTSegmentState new_cookie)88   void SetLocalRefCookie(IRTSegmentState new_cookie) { local_ref_cookie_ = new_cookie; }
89 
GetLocalsSegmentState()90   IRTSegmentState GetLocalsSegmentState() const REQUIRES_SHARED(Locks::mutator_lock_) {
91     return locals_.GetSegmentState();
92   }
SetLocalSegmentState(IRTSegmentState new_state)93   void SetLocalSegmentState(IRTSegmentState new_state) REQUIRES_SHARED(Locks::mutator_lock_) {
94     locals_.SetSegmentState(new_state);
95   }
96 
VisitJniLocalRoots(RootVisitor * visitor,const RootInfo & root_info)97   void VisitJniLocalRoots(RootVisitor* visitor, const RootInfo& root_info)
98       REQUIRES_SHARED(Locks::mutator_lock_) {
99     locals_.VisitRoots(visitor, root_info);
100   }
101 
GetSelf()102   Thread* GetSelf() const { return self_; }
GetCritical()103   uint32_t GetCritical() const { return critical_; }
SetCritical(uint32_t new_critical)104   void SetCritical(uint32_t new_critical) { critical_ = new_critical; }
GetCriticalStartUs()105   uint64_t GetCriticalStartUs() const { return critical_start_us_; }
SetCriticalStartUs(uint64_t new_critical_start_us)106   void SetCriticalStartUs(uint64_t new_critical_start_us) {
107     critical_start_us_ = new_critical_start_us;
108   }
GetUncheckedFunctions()109   const JNINativeInterface* GetUncheckedFunctions() const {
110     return unchecked_functions_;
111   }
GetVm()112   JavaVMExt* GetVm() const { return vm_; }
113 
SetRuntimeDeleted()114   void SetRuntimeDeleted() { runtime_deleted_.store(true, std::memory_order_relaxed); }
IsRuntimeDeleted()115   bool IsRuntimeDeleted() const { return runtime_deleted_.load(std::memory_order_relaxed); }
IsCheckJniEnabled()116   bool IsCheckJniEnabled() const { return check_jni_; }
117 
118 
119   // Functions to keep track of monitor lock and unlock operations. Used to ensure proper locking
120   // rules in CheckJNI mode.
121 
122   // Record locking of a monitor.
123   void RecordMonitorEnter(jobject obj) REQUIRES_SHARED(Locks::mutator_lock_);
124 
125   // Check the release, that is, that the release is performed in the same JNI "segment."
126   void CheckMonitorRelease(jobject obj) REQUIRES_SHARED(Locks::mutator_lock_);
127 
128   // Check that no monitors are held that have been acquired in this JNI "segment."
129   void CheckNoHeldMonitors() REQUIRES_SHARED(Locks::mutator_lock_);
130 
VisitMonitorRoots(RootVisitor * visitor,const RootInfo & root_info)131   void VisitMonitorRoots(RootVisitor* visitor, const RootInfo& root_info)
132       REQUIRES_SHARED(Locks::mutator_lock_) {
133     monitors_.VisitRoots(visitor, root_info);
134   }
135 
136   // Set the functions to the runtime shutdown functions.
137   void SetFunctionsToRuntimeShutdownFunctions();
138 
139   // Set the functions to the new JNI functions based on Runtime::GetJniIdType.
140   void UpdateJniFunctionsPointer();
141 
142   // Set the function table override. This will install the override (or original table, if null)
143   // to all threads.
144   // Note: JNI function table overrides are sensitive to the order of operations wrt/ CheckJNI.
145   //       After overriding the JNI function table, CheckJNI toggling is ignored.
146   static void SetTableOverride(const JNINativeInterface* table_override)
147       REQUIRES(!Locks::thread_list_lock_, !Locks::jni_function_table_lock_);
148 
149   // Return either the regular, or the CheckJNI function table. Will return table_override_ instead
150   // if it is not null.
151   static const JNINativeInterface* GetFunctionTable(bool check_jni)
152       REQUIRES(Locks::jni_function_table_lock_);
153 
154   static void ResetFunctionTable()
155       REQUIRES(!Locks::thread_list_lock_, !Locks::jni_function_table_lock_);
156 
157  private:
158   // Checking "locals" requires the mutator lock, but at creation time we're
159   // really only interested in validity, which isn't changing. To avoid grabbing
160   // the mutator lock, factored out and tagged with NO_THREAD_SAFETY_ANALYSIS.
161   static bool CheckLocalsValid(JNIEnvExt* in) NO_THREAD_SAFETY_ANALYSIS;
162 
163   // Override of function tables. This applies to both default as well as instrumented (CheckJNI)
164   // function tables.
165   static const JNINativeInterface* table_override_ GUARDED_BY(Locks::jni_function_table_lock_);
166 
167   // The constructor should not be called directly. It may leave the object in an erroneous state,
168   // and the result needs to be checked.
169   JNIEnvExt(Thread* self, JavaVMExt* vm, std::string* error_msg)
170       REQUIRES(!Locks::jni_function_table_lock_);
171 
172   // Link to Thread::Current().
173   Thread* const self_;
174 
175   // The invocation interface JavaVM.
176   JavaVMExt* const vm_;
177 
178   // Cookie used when using the local indirect reference table.
179   IRTSegmentState local_ref_cookie_;
180 
181   // JNI local references.
182   IndirectReferenceTable locals_ GUARDED_BY(Locks::mutator_lock_);
183 
184   // Stack of cookies corresponding to PushLocalFrame/PopLocalFrame calls.
185   // TODO: to avoid leaks (and bugs), we need to clear this vector on entry (or return)
186   // to a native method.
187   std::vector<IRTSegmentState> stacked_local_ref_cookies_;
188 
189   // Entered JNI monitors, for bulk exit on thread detach.
190   ReferenceTable monitors_;
191 
192   // Used by -Xcheck:jni.
193   JNINativeInterface const* unchecked_functions_;
194 
195   // All locked objects, with the (Java caller) stack frame that locked them. Used in CheckJNI
196   // to ensure that only monitors locked in this native frame are being unlocked, and that at
197   // the end all are unlocked.
198   std::vector<std::pair<uintptr_t, jobject>> locked_objects_;
199 
200   // Start time of "critical" JNI calls to ensure that their use doesn't
201   // excessively block the VM with CheckJNI.
202   uint64_t critical_start_us_;
203 
204   // How many nested "critical" JNI calls are we in? Used by CheckJNI to ensure that criticals are
205   uint32_t critical_;
206 
207   // Frequently-accessed fields cached from JavaVM.
208   bool check_jni_;
209 
210   // If we are a JNI env for a daemon thread with a deleted runtime.
211   std::atomic<bool> runtime_deleted_;
212 
213   template<bool kEnableIndexIds> friend class JNI;
214   friend class ScopedJniEnvLocalRefState;
215   friend class Thread;
216   friend IndirectReferenceTable* GetIndirectReferenceTable(ScopedObjectAccess& soa,
217                                                            IndirectRefKind kind);
218   friend void ThreadResetFunctionTable(Thread* thread, void* arg);
219   ART_FRIEND_TEST(JniInternalTest, JNIEnvExtOffsets);
220 };
221 
222 // Used to save and restore the JNIEnvExt state when not going through code created by the JNI
223 // compiler.
224 class ScopedJniEnvLocalRefState {
225  public:
ScopedJniEnvLocalRefState(JNIEnvExt * env)226   explicit ScopedJniEnvLocalRefState(JNIEnvExt* env) :
227       env_(env),
228       saved_local_ref_cookie_(env->local_ref_cookie_) {
229     env->local_ref_cookie_ = env->locals_.GetSegmentState();
230   }
231 
~ScopedJniEnvLocalRefState()232   ~ScopedJniEnvLocalRefState() {
233     env_->locals_.SetSegmentState(env_->local_ref_cookie_);
234     env_->local_ref_cookie_ = saved_local_ref_cookie_;
235   }
236 
237  private:
238   JNIEnvExt* const env_;
239   const IRTSegmentState saved_local_ref_cookie_;
240 
241   DISALLOW_COPY_AND_ASSIGN(ScopedJniEnvLocalRefState);
242 };
243 
244 }  // namespace art
245 
246 #endif  // ART_RUNTIME_JNI_JNI_ENV_EXT_H_
247