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