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