blob: efe43ee0e940fdfd5661296922a4f9b0cac2c7ea [file] [log] [blame]
Ian Rogers68d8b422014-07-17 11:09:10 -07001/*
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
Andreas Gampe5f4a09a2015-09-28 13:16:33 -070019#include <algorithm>
20#include <vector>
21
Andreas Gampe46ee31b2016-12-14 10:11:49 -080022#include "android-base/stringprintf.h"
23
Ian Rogers55256cb2017-12-21 17:07:11 -080024#include "base/to_str.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070025#include "check_jni.h"
26#include "indirect_reference_table.h"
27#include "java_vm_ext.h"
28#include "jni_internal.h"
Andreas Gampe5f4a09a2015-09-28 13:16:33 -070029#include "lock_word.h"
30#include "mirror/object-inl.h"
31#include "nth_caller_visitor.h"
Ian Rogers55256cb2017-12-21 17:07:11 -080032#include "scoped_thread_state_change.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070033#include "thread-current-inl.h"
Andreas Gampec8089542017-01-16 12:41:12 -080034#include "thread_list.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070035
36namespace art {
37
Andreas Gampe46ee31b2016-12-14 10:11:49 -080038using android::base::StringPrintf;
39
Ian Rogers68d8b422014-07-17 11:09:10 -070040static constexpr size_t kMonitorsInitial = 32; // Arbitrary.
41static constexpr size_t kMonitorsMax = 4096; // Arbitrary sanity check.
42
Andreas Gampec8089542017-01-16 12:41:12 -080043const JNINativeInterface* JNIEnvExt::table_override_ = nullptr;
44
Ian Rogers55256cb2017-12-21 17:07:11 -080045bool JNIEnvExt::CheckLocalsValid(JNIEnvExt* in) NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampe3f5881f2015-04-08 10:26:16 -070046 if (in == nullptr) {
47 return false;
48 }
Ian Rogers55256cb2017-12-21 17:07:11 -080049 return in->locals_.IsValid();
Andreas Gampe3f5881f2015-04-08 10:26:16 -070050}
51
Alex Light185d1342016-08-11 10:48:03 -070052jint JNIEnvExt::GetEnvHandler(JavaVMExt* vm, /*out*/void** env, jint version) {
53 UNUSED(vm);
54 // GetEnv always returns a JNIEnv* for the most current supported JNI version,
55 // and unlike other calls that take a JNI version doesn't care if you supply
56 // JNI_VERSION_1_1, which we don't otherwise support.
57 if (JavaVMExt::IsBadJniVersion(version) && version != JNI_VERSION_1_1) {
58 return JNI_EVERSION;
59 }
60 Thread* thread = Thread::Current();
61 CHECK(thread != nullptr);
62 *env = thread->GetJniEnv();
63 return JNI_OK;
64}
65
Richard Uhlerda0a69e2016-10-11 15:06:38 +010066JNIEnvExt* JNIEnvExt::Create(Thread* self_in, JavaVMExt* vm_in, std::string* error_msg) {
67 std::unique_ptr<JNIEnvExt> ret(new JNIEnvExt(self_in, vm_in, error_msg));
Andreas Gampe3f5881f2015-04-08 10:26:16 -070068 if (CheckLocalsValid(ret.get())) {
69 return ret.release();
70 }
71 return nullptr;
72}
73
Richard Uhlerda0a69e2016-10-11 15:06:38 +010074JNIEnvExt::JNIEnvExt(Thread* self_in, JavaVMExt* vm_in, std::string* error_msg)
Ian Rogers55256cb2017-12-21 17:07:11 -080075 : self_(self_in),
76 vm_(vm_in),
77 local_ref_cookie_(kIRTFirstSegment),
78 locals_(kLocalsInitial, kLocal, IndirectReferenceTable::ResizableCapacity::kYes, error_msg),
79 monitors_("monitors", kMonitorsInitial, kMonitorsMax),
80 critical_(0),
81 check_jni_(false),
82 runtime_deleted_(false) {
Andreas Gampec8089542017-01-16 12:41:12 -080083 MutexLock mu(Thread::Current(), *Locks::jni_function_table_lock_);
Ian Rogers55256cb2017-12-21 17:07:11 -080084 check_jni_ = vm_in->IsCheckJniEnabled();
85 functions = GetFunctionTable(check_jni_);
86 unchecked_functions_ = GetJniNativeInterface();
Ian Rogers68d8b422014-07-17 11:09:10 -070087}
88
Mathieu Chartier4d87df62016-01-07 15:14:19 -080089void JNIEnvExt::SetFunctionsToRuntimeShutdownFunctions() {
90 functions = GetRuntimeShutdownNativeInterface();
Ian Rogers55256cb2017-12-21 17:07:11 -080091 runtime_deleted_ = true;
Mathieu Chartier4d87df62016-01-07 15:14:19 -080092}
93
Ian Rogers68d8b422014-07-17 11:09:10 -070094JNIEnvExt::~JNIEnvExt() {
95}
96
Andreas Gampe5f4a09a2015-09-28 13:16:33 -070097jobject JNIEnvExt::NewLocalRef(mirror::Object* obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -070098 if (obj == nullptr) {
99 return nullptr;
100 }
Andreas Gampe25651122017-09-25 14:50:23 -0700101 std::string error_msg;
Ian Rogers55256cb2017-12-21 17:07:11 -0800102 jobject ref = reinterpret_cast<jobject>(locals_.Add(local_ref_cookie_, obj, &error_msg));
Andreas Gampe25651122017-09-25 14:50:23 -0700103 if (UNLIKELY(ref == nullptr)) {
104 // This is really unexpected if we allow resizing local IRTs...
105 LOG(FATAL) << error_msg;
106 UNREACHABLE();
107 }
108 return ref;
Ian Rogers68d8b422014-07-17 11:09:10 -0700109}
110
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700111void JNIEnvExt::DeleteLocalRef(jobject obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700112 if (obj != nullptr) {
Ian Rogers55256cb2017-12-21 17:07:11 -0800113 locals_.Remove(local_ref_cookie_, reinterpret_cast<IndirectRef>(obj));
Ian Rogers68d8b422014-07-17 11:09:10 -0700114 }
115}
116
117void JNIEnvExt::SetCheckJniEnabled(bool enabled) {
Ian Rogers55256cb2017-12-21 17:07:11 -0800118 check_jni_ = enabled;
Andreas Gampec8089542017-01-16 12:41:12 -0800119 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 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700125}
126
127void JNIEnvExt::DumpReferenceTables(std::ostream& os) {
Ian Rogers55256cb2017-12-21 17:07:11 -0800128 locals_.Dump(os);
129 monitors_.Dump(os);
Ian Rogers68d8b422014-07-17 11:09:10 -0700130}
131
Andreas Gampe88831082017-05-31 19:46:03 -0700132void JNIEnvExt::PushFrame(int capacity) {
Ian Rogers55256cb2017-12-21 17:07:11 -0800133 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();
Ian Rogers68d8b422014-07-17 11:09:10 -0700136}
137
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700138void JNIEnvExt::PopFrame() {
Ian Rogers55256cb2017-12-21 17:07:11 -0800139 locals_.SetSegmentState(local_ref_cookie_);
140 local_ref_cookie_ = stacked_local_ref_cookies_.back();
141 stacked_local_ref_cookies_.pop_back();
Ian Rogers68d8b422014-07-17 11:09:10 -0700142}
143
Andreas Gampe4d98c842015-12-09 15:14:04 -0800144// 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.
148static size_t JNIEnvSize(size_t pointer_size) {
149 // A single pointer.
150 return pointer_size;
151}
152
153Offset 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 IndirectReferenceTable::SegmentStateOffset(pointer_size).Int32Value();
160 return Offset(locals_offset + irt_segment_state_offset);
161}
162
163Offset JNIEnvExt::LocalRefCookieOffset(size_t pointer_size) {
164 return Offset(JNIEnvSize(pointer_size) +
165 2 * pointer_size); // Thread* self + JavaVMExt* vm
166}
167
168Offset JNIEnvExt::SelfOffset(size_t pointer_size) {
169 return Offset(JNIEnvSize(pointer_size));
Ian Rogers68d8b422014-07-17 11:09:10 -0700170}
171
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700172// Use some defining part of the caller's frame as the identifying mark for the JNI segment.
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700173static uintptr_t GetJavaCallFrame(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700174 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
189void JNIEnvExt::RecordMonitorEnter(jobject obj) {
Ian Rogers55256cb2017-12-21 17:07:11 -0800190 locked_objects_.push_back(std::make_pair(GetJavaCallFrame(self_), obj));
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700191}
192
193static std::string ComputeMonitorDescription(Thread* self,
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700194 jobject obj) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700195 ObjPtr<mirror::Object> o = self->DecodeJObject(obj);
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700196 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)",
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700201 reinterpret_cast<intptr_t>(o.Ptr()),
David Sehr709b0702016-10-13 09:12:37 -0700202 o->PrettyTypeOf().c_str());
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700203 } 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.
David Sehr709b0702016-10-13 09:12:37 -0700206 const std::string pretty_type(o->PrettyTypeOf());
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700207 return StringPrintf("<0x%08x> (a %s)", o->IdentityHashCode(), pretty_type.c_str());
208 }
209}
210
211static void RemoveMonitors(Thread* self,
212 uintptr_t frame,
213 ReferenceTable* monitors,
214 std::vector<std::pair<uintptr_t, jobject>>* locked_objects)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700215 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700216 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)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700220 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700221 if (frame == pair.first) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700222 ObjPtr<mirror::Object> o = self->DecodeJObject(pair.second);
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700223 monitors->Remove(o);
224 return true;
225 }
226 return false;
227 });
228 locked_objects->erase(kept_end, locked_objects->end());
229}
230
231void JNIEnvExt::CheckMonitorRelease(jobject obj) {
Ian Rogers55256cb2017-12-21 17:07:11 -0800232 uintptr_t current_frame = GetJavaCallFrame(self_);
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700233 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."
Ian Rogers55256cb2017-12-21 17:07:11 -0800240 ObjPtr<mirror::Object> mirror_obj = self_->DecodeJObject(obj);
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700241 for (std::pair<uintptr_t, jobject>& pair : locked_objects_) {
Ian Rogers55256cb2017-12-21 17:07:11 -0800242 if (self_->DecodeJObject(pair.second) == mirror_obj) {
243 std::string monitor_descr = ComputeMonitorDescription(self_, pair.second);
244 vm_->JniAbortF("<JNI MonitorExit>",
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700245 "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) {
Ian Rogers55256cb2017-12-21 17:07:11 -0800257 RemoveMonitors(self_, current_frame, &monitors_, &locked_objects_);
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700258 }
259}
260
261void JNIEnvExt::CheckNoHeldMonitors() {
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700262 // 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()) {
Ian Rogers55256cb2017-12-21 17:07:11 -0800267 uintptr_t current_frame = GetJavaCallFrame(self_);
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700268 std::pair<uintptr_t, jobject>& pair = locked_objects_[locked_objects_.size() - 1];
269 if (pair.first == current_frame) {
Ian Rogers55256cb2017-12-21 17:07:11 -0800270 std::string monitor_descr = ComputeMonitorDescription(self_, pair.second);
271 vm_->JniAbortF("<JNI End>",
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700272 "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.
Ian Rogers55256cb2017-12-21 17:07:11 -0800276 RemoveMonitors(self_, current_frame, &monitors_, &locked_objects_);
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700277 } 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 }
Ian Rogers55256cb2017-12-21 17:07:11 -0800284 // 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 }
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700290}
291
Andreas Gampec8089542017-01-16 12:41:12 -0800292static void ThreadResetFunctionTable(Thread* thread, void* arg ATTRIBUTE_UNUSED)
293 REQUIRES(Locks::jni_function_table_lock_) {
294 JNIEnvExt* env = thread->GetJniEnv();
Ian Rogers55256cb2017-12-21 17:07:11 -0800295 bool check_jni = env->IsCheckJniEnabled();
Andreas Gampec8089542017-01-16 12:41:12 -0800296 env->functions = JNIEnvExt::GetFunctionTable(check_jni);
297}
298
299void JNIEnvExt::SetTableOverride(const JNINativeInterface* table_override) {
300 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
301 MutexLock mu2(Thread::Current(), *Locks::jni_function_table_lock_);
302
303 JNIEnvExt::table_override_ = table_override;
304
305 // See if we have a runtime. Note: we cannot run other code (like JavaVMExt's CheckJNI install
306 // code), as we'd have to recursively lock the mutex.
307 Runtime* runtime = Runtime::Current();
308 if (runtime != nullptr) {
309 runtime->GetThreadList()->ForEach(ThreadResetFunctionTable, nullptr);
310 }
311}
312
313const JNINativeInterface* JNIEnvExt::GetFunctionTable(bool check_jni) {
314 const JNINativeInterface* override = JNIEnvExt::table_override_;
315 if (override != nullptr) {
316 return override;
317 }
318 return check_jni ? GetCheckJniNativeInterface() : GetJniNativeInterface();
319}
320
Ian Rogers68d8b422014-07-17 11:09:10 -0700321} // namespace art