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