• 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 #include "jni_env_ext.h"
18 
19 #include <algorithm>
20 #include <vector>
21 
22 #include "android-base/stringprintf.h"
23 
24 #include "base/mutex.h"
25 #include "base/to_str.h"
26 #include "check_jni.h"
27 #include "hidden_api.h"
28 #include "indirect_reference_table.h"
29 #include "java_vm_ext.h"
30 #include "jni_internal.h"
31 #include "lock_word.h"
32 #include "mirror/object-inl.h"
33 #include "nth_caller_visitor.h"
34 #include "scoped_thread_state_change.h"
35 #include "thread-current-inl.h"
36 #include "thread-inl.h"
37 #include "thread_list.h"
38 
39 namespace art HIDDEN {
40 
41 using android::base::StringPrintf;
42 
43 static constexpr size_t kMonitorsInitial = 32;  // Arbitrary.
44 static constexpr size_t kMonitorsMax = 4096;  // Maximum number of monitors held by JNI code.
45 
46 const JNINativeInterface* JNIEnvExt::table_override_ = nullptr;
47 
GetEnvHandler(JavaVMExt * vm,void ** env,jint version)48 jint JNIEnvExt::GetEnvHandler(JavaVMExt* vm, /*out*/void** env, jint version) {
49   UNUSED(vm);
50   // GetEnv always returns a JNIEnv* for the most current supported JNI version,
51   // and unlike other calls that take a JNI version doesn't care if you supply
52   // JNI_VERSION_1_1, which we don't otherwise support.
53   if (JavaVMExt::IsBadJniVersion(version) && version != JNI_VERSION_1_1) {
54     return JNI_EVERSION;
55   }
56   Thread* thread = Thread::Current();
57   CHECK(thread != nullptr);
58   *env = thread->GetJniEnv();
59   return JNI_OK;
60 }
61 
Create(Thread * self_in,JavaVMExt * vm_in,std::string * error_msg)62 JNIEnvExt* JNIEnvExt::Create(Thread* self_in, JavaVMExt* vm_in, std::string* error_msg) {
63   std::unique_ptr<JNIEnvExt> ret(new JNIEnvExt(self_in, vm_in));
64   if (!ret->Initialize(error_msg)) {
65     return nullptr;
66   }
67   return ret.release();
68 }
69 
JNIEnvExt(Thread * self_in,JavaVMExt * vm_in)70 JNIEnvExt::JNIEnvExt(Thread* self_in, JavaVMExt* vm_in)
71     : self_(self_in),
72       vm_(vm_in),
73       locals_(vm_in->IsCheckJniEnabled()),
74       monitors_("monitors", kMonitorsInitial, kMonitorsMax),
75       critical_(0),
76       check_jni_(false),
77       runtime_deleted_(false) {
78   MutexLock mu(Thread::Current(), *Locks::jni_function_table_lock_);
79   check_jni_ = vm_in->IsCheckJniEnabled();
80   functions = GetFunctionTable(check_jni_);
81   unchecked_functions_ = GetJniNativeInterface();
82 }
83 
Initialize(std::string * error_msg)84 bool JNIEnvExt::Initialize(std::string* error_msg) {
85   return locals_.Initialize(/*max_count=*/ 1u, error_msg);
86 }
87 
SetFunctionsToRuntimeShutdownFunctions()88 void JNIEnvExt::SetFunctionsToRuntimeShutdownFunctions() {
89   functions = GetRuntimeShutdownNativeInterface();
90 }
91 
~JNIEnvExt()92 JNIEnvExt::~JNIEnvExt() {
93 }
94 
NewLocalRef(mirror::Object * obj)95 jobject JNIEnvExt::NewLocalRef(mirror::Object* obj) {
96   if (obj == nullptr) {
97     return nullptr;
98   }
99   std::string error_msg;
100   jobject ref = reinterpret_cast<jobject>(locals_.Add(obj, &error_msg));
101   if (UNLIKELY(ref == nullptr)) {
102     // This is really unexpected if we allow resizing LRTs...
103     LOG(FATAL) << error_msg;
104     UNREACHABLE();
105   }
106   return ref;
107 }
108 
DeleteLocalRef(jobject obj)109 void JNIEnvExt::DeleteLocalRef(jobject obj) {
110   if (obj != nullptr) {
111     locals_.Remove(reinterpret_cast<IndirectRef>(obj));
112   }
113 }
114 
SetCheckJniEnabled(bool enabled)115 void JNIEnvExt::SetCheckJniEnabled(bool enabled) {
116   check_jni_ = enabled;
117   locals_.SetCheckJniEnabled(enabled);
118   MutexLock mu(Thread::Current(), *Locks::jni_function_table_lock_);
119   functions = GetFunctionTable(enabled);
120   // Check whether this is a no-op because of override.
121   if (enabled && JNIEnvExt::table_override_ != nullptr) {
122     LOG(WARNING) << "Enabling CheckJNI after a JNIEnv function table override is not functional.";
123   }
124 }
125 
DumpReferenceTables(std::ostream & os)126 void JNIEnvExt::DumpReferenceTables(std::ostream& os) {
127   locals_.Dump(os);
128   monitors_.Dump(os);
129 }
130 
PushFrame(int capacity)131 void JNIEnvExt::PushFrame(int capacity) {
132   DCHECK_GE(locals_.FreeCapacity(), static_cast<size_t>(capacity));
133   stacked_local_ref_cookies_.push_back(PushLocalReferenceFrame());
134 }
135 
PopFrame()136 void JNIEnvExt::PopFrame() {
137   PopLocalReferenceFrame(stacked_local_ref_cookies_.back());
138   stacked_local_ref_cookies_.pop_back();
139 }
140 
141 // Note: the offset code is brittle, as we can't use OFFSETOF_MEMBER or offsetof easily. Thus, there
142 //       are tests in jni_internal_test to match the results against the actual values.
143 
144 // This is encoding the knowledge of the structure and layout of JNIEnv fields.
JNIEnvSize(PointerSize pointer_size)145 static size_t JNIEnvSize(PointerSize pointer_size) {
146   // A single pointer.
147   return static_cast<size_t>(pointer_size);
148 }
149 
LocalReferenceTableOffset(PointerSize pointer_size)150 inline MemberOffset JNIEnvExt::LocalReferenceTableOffset(PointerSize pointer_size) {
151   return MemberOffset(JNIEnvSize(pointer_size) +
152                       2 * static_cast<size_t>(pointer_size));  // Thread* self + JavaVMExt* vm
153 }
154 
LrtSegmentStateOffset(PointerSize pointer_size)155 MemberOffset JNIEnvExt::LrtSegmentStateOffset(PointerSize pointer_size) {
156   return MemberOffset(LocalReferenceTableOffset(pointer_size).SizeValue() +
157                       jni::LocalReferenceTable::SegmentStateOffset().SizeValue());
158 }
159 
LrtPreviousStateOffset(PointerSize pointer_size)160 MemberOffset JNIEnvExt::LrtPreviousStateOffset(PointerSize pointer_size) {
161   return MemberOffset(LocalReferenceTableOffset(pointer_size).SizeValue() +
162                       jni::LocalReferenceTable::PreviousStateOffset().SizeValue());
163 }
164 
SelfOffset(PointerSize pointer_size)165 MemberOffset JNIEnvExt::SelfOffset(PointerSize pointer_size) {
166   return MemberOffset(JNIEnvSize(pointer_size));
167 }
168 
169 // Use some defining part of the caller's frame as the identifying mark for the JNI segment.
GetJavaCallFrame(Thread * self)170 static uintptr_t GetJavaCallFrame(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_) {
171   NthCallerVisitor zeroth_caller(self, 0, false);
172   zeroth_caller.WalkStack();
173   if (zeroth_caller.caller == nullptr) {
174     // No Java code, must be from pure native code.
175     return 0;
176   } else if (zeroth_caller.GetCurrentQuickFrame() == nullptr) {
177     // Shadow frame = interpreter. Use the actual shadow frame's address.
178     DCHECK(zeroth_caller.GetCurrentShadowFrame() != nullptr);
179     return reinterpret_cast<uintptr_t>(zeroth_caller.GetCurrentShadowFrame());
180   } else {
181     // Quick frame = compiled code. Use the bottom of the frame.
182     return reinterpret_cast<uintptr_t>(zeroth_caller.GetCurrentQuickFrame());
183   }
184 }
185 
RecordMonitorEnter(jobject obj)186 void JNIEnvExt::RecordMonitorEnter(jobject obj) {
187   locked_objects_.push_back(std::make_pair(GetJavaCallFrame(self_), obj));
188 }
189 
ComputeMonitorDescription(Thread * self,jobject obj)190 static std::string ComputeMonitorDescription(Thread* self,
191                                              jobject obj) REQUIRES_SHARED(Locks::mutator_lock_) {
192   ObjPtr<mirror::Object> o = self->DecodeJObject(obj);
193   if ((o->GetLockWord(false).GetState() == LockWord::kThinLocked) &&
194       Locks::mutator_lock_->IsExclusiveHeld(self)) {
195     // Getting the identity hashcode here would result in lock inflation and suspension of the
196     // current thread, which isn't safe if this is the only runnable thread.
197     return StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
198                         reinterpret_cast<intptr_t>(o.Ptr()),
199                         o->PrettyTypeOf().c_str());
200   } else {
201     // IdentityHashCode can cause thread suspension, which would invalidate o if it moved. So
202     // we get the pretty type before we call IdentityHashCode.
203     const std::string pretty_type(o->PrettyTypeOf());
204     return StringPrintf("<0x%08x> (a %s)", o->IdentityHashCode(), pretty_type.c_str());
205   }
206 }
207 
RemoveMonitors(Thread * self,uintptr_t frame,ReferenceTable * monitors,std::vector<std::pair<uintptr_t,jobject>> * locked_objects)208 static void RemoveMonitors(Thread* self,
209                            uintptr_t frame,
210                            ReferenceTable* monitors,
211                            std::vector<std::pair<uintptr_t, jobject>>* locked_objects)
212     REQUIRES_SHARED(Locks::mutator_lock_) {
213   auto kept_end = std::remove_if(
214       locked_objects->begin(),
215       locked_objects->end(),
216       [self, frame, monitors](const std::pair<uintptr_t, jobject>& pair)
217           REQUIRES_SHARED(Locks::mutator_lock_) {
218         if (frame == pair.first) {
219           ObjPtr<mirror::Object> o = self->DecodeJObject(pair.second);
220           monitors->Remove(o);
221           return true;
222         }
223         return false;
224       });
225   locked_objects->erase(kept_end, locked_objects->end());
226 }
227 
CheckMonitorRelease(jobject obj)228 void JNIEnvExt::CheckMonitorRelease(jobject obj) {
229   uintptr_t current_frame = GetJavaCallFrame(self_);
230   std::pair<uintptr_t, jobject> exact_pair = std::make_pair(current_frame, obj);
231   auto it = std::find(locked_objects_.begin(), locked_objects_.end(), exact_pair);
232   bool will_abort = false;
233   if (it != locked_objects_.end()) {
234     locked_objects_.erase(it);
235   } else {
236     // Check whether this monitor was locked in another JNI "session."
237     ObjPtr<mirror::Object> mirror_obj = self_->DecodeJObject(obj);
238     for (std::pair<uintptr_t, jobject>& pair : locked_objects_) {
239       if (self_->DecodeJObject(pair.second) == mirror_obj) {
240         std::string monitor_descr = ComputeMonitorDescription(self_, pair.second);
241         vm_->JniAbortF("<JNI MonitorExit>",
242                       "Unlocking monitor that wasn't locked here: %s",
243                       monitor_descr.c_str());
244         will_abort = true;
245         break;
246       }
247     }
248   }
249 
250   // When we abort, also make sure that any locks from the current "session" are removed from
251   // the monitors table, otherwise we may visit local objects in GC during abort (which won't be
252   // valid anymore).
253   if (will_abort) {
254     RemoveMonitors(self_, current_frame, &monitors_, &locked_objects_);
255   }
256 }
257 
CheckNoHeldMonitors()258 void JNIEnvExt::CheckNoHeldMonitors() {
259   // The locked_objects_ are grouped by their stack frame component, as this enforces structured
260   // locking, and the groups form a stack. So the current frame entries are at the end. Check
261   // whether the vector is empty, and when there are elements, whether the last element belongs
262   // to this call - this signals that there are unlocked monitors.
263   if (!locked_objects_.empty()) {
264     uintptr_t current_frame = GetJavaCallFrame(self_);
265     std::pair<uintptr_t, jobject>& pair = locked_objects_[locked_objects_.size() - 1];
266     if (pair.first == current_frame) {
267       std::string monitor_descr = ComputeMonitorDescription(self_, pair.second);
268       vm_->JniAbortF("<JNI End>",
269                     "Still holding a locked object on JNI end: %s",
270                     monitor_descr.c_str());
271       // When we abort, also make sure that any locks from the current "session" are removed from
272       // the monitors table, otherwise we may visit local objects in GC during abort.
273       RemoveMonitors(self_, current_frame, &monitors_, &locked_objects_);
274     } else if (kIsDebugBuild) {
275       // Make sure there are really no other entries and our checking worked as expected.
276       for (std::pair<uintptr_t, jobject>& check_pair : locked_objects_) {
277         CHECK_NE(check_pair.first, current_frame);
278       }
279     }
280   }
281   // Ensure critical locks aren't held when returning to Java.
282   if (critical_ > 0) {
283     vm_->JniAbortF("<JNI End>",
284                   "Critical lock held when returning to Java on thread %s",
285                   ToStr<Thread>(*self_).c_str());
286   }
287 }
288 
ThreadResetFunctionTable(Thread * thread,void * arg)289 void ThreadResetFunctionTable(Thread* thread, [[maybe_unused]] void* arg)
290     REQUIRES(Locks::jni_function_table_lock_) {
291   JNIEnvExt* env = thread->GetJniEnv();
292   bool check_jni = env->IsCheckJniEnabled();
293   env->functions = JNIEnvExt::GetFunctionTable(check_jni);
294   env->unchecked_functions_ = GetJniNativeInterface();
295 }
296 
SetTableOverride(const JNINativeInterface * table_override)297 void JNIEnvExt::SetTableOverride(const JNINativeInterface* table_override) {
298   MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
299   MutexLock mu2(Thread::Current(), *Locks::jni_function_table_lock_);
300 
301   JNIEnvExt::table_override_ = table_override;
302 
303   // See if we have a runtime. Note: we cannot run other code (like JavaVMExt's CheckJNI install
304   // code), as we'd have to recursively lock the mutex.
305   Runtime* runtime = Runtime::Current();
306   if (runtime != nullptr) {
307     runtime->GetThreadList()->ForEach(ThreadResetFunctionTable, nullptr);
308     // Core Platform API checks rely on stack walking and classifying the caller. If a table
309     // override is installed do not try to guess what semantics should be.
310     runtime->SetCorePlatformApiEnforcementPolicy(hiddenapi::EnforcementPolicy::kDisabled);
311   }
312 }
313 
GetFunctionTable(bool check_jni)314 const JNINativeInterface* JNIEnvExt::GetFunctionTable(bool check_jni) {
315   const JNINativeInterface* override = JNIEnvExt::table_override_;
316   if (override != nullptr) {
317     return override;
318   }
319   return check_jni ? GetCheckJniNativeInterface() : GetJniNativeInterface();
320 }
321 
ResetFunctionTable()322 void JNIEnvExt::ResetFunctionTable() {
323   MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
324   MutexLock mu2(Thread::Current(), *Locks::jni_function_table_lock_);
325   Runtime* runtime = Runtime::Current();
326   CHECK(runtime != nullptr);
327   runtime->GetThreadList()->ForEach(ThreadResetFunctionTable, nullptr);
328 }
329 
330 }  // namespace art
331