blob: 8352657f28e65d271388bbcd06c10196920dda8b [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 Rogers68d8b422014-07-17 11:09:10 -070024#include "check_jni.h"
25#include "indirect_reference_table.h"
26#include "java_vm_ext.h"
27#include "jni_internal.h"
Andreas Gampe5f4a09a2015-09-28 13:16:33 -070028#include "lock_word.h"
29#include "mirror/object-inl.h"
30#include "nth_caller_visitor.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070031#include "thread-current-inl.h"
Andreas Gampec8089542017-01-16 12:41:12 -080032#include "thread_list.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070033
34namespace art {
35
Andreas Gampe46ee31b2016-12-14 10:11:49 -080036using android::base::StringPrintf;
37
Ian Rogers68d8b422014-07-17 11:09:10 -070038static constexpr size_t kMonitorsInitial = 32; // Arbitrary.
39static constexpr size_t kMonitorsMax = 4096; // Arbitrary sanity check.
40
Andreas Gampec8089542017-01-16 12:41:12 -080041const JNINativeInterface* JNIEnvExt::table_override_ = nullptr;
42
Andreas Gampe3f5881f2015-04-08 10:26:16 -070043// Checking "locals" requires the mutator lock, but at creation time we're really only interested
44// in validity, which isn't changing. To avoid grabbing the mutator lock, factored out and tagged
45// with NO_THREAD_SAFETY_ANALYSIS.
46static bool CheckLocalsValid(JNIEnvExt* in) NO_THREAD_SAFETY_ANALYSIS {
47 if (in == nullptr) {
48 return false;
49 }
50 return in->locals.IsValid();
51}
52
Alex Light185d1342016-08-11 10:48:03 -070053jint JNIEnvExt::GetEnvHandler(JavaVMExt* vm, /*out*/void** env, jint version) {
54 UNUSED(vm);
55 // GetEnv always returns a JNIEnv* for the most current supported JNI version,
56 // and unlike other calls that take a JNI version doesn't care if you supply
57 // JNI_VERSION_1_1, which we don't otherwise support.
58 if (JavaVMExt::IsBadJniVersion(version) && version != JNI_VERSION_1_1) {
59 return JNI_EVERSION;
60 }
61 Thread* thread = Thread::Current();
62 CHECK(thread != nullptr);
63 *env = thread->GetJniEnv();
64 return JNI_OK;
65}
66
Richard Uhlerda0a69e2016-10-11 15:06:38 +010067JNIEnvExt* JNIEnvExt::Create(Thread* self_in, JavaVMExt* vm_in, std::string* error_msg) {
68 std::unique_ptr<JNIEnvExt> ret(new JNIEnvExt(self_in, vm_in, error_msg));
Andreas Gampe3f5881f2015-04-08 10:26:16 -070069 if (CheckLocalsValid(ret.get())) {
70 return ret.release();
71 }
72 return nullptr;
73}
74
Richard Uhlerda0a69e2016-10-11 15:06:38 +010075JNIEnvExt::JNIEnvExt(Thread* self_in, JavaVMExt* vm_in, std::string* error_msg)
Andreas Gampe277ccbd2014-11-03 21:36:10 -080076 : self(self_in),
77 vm(vm_in),
Andreas Gampee03662b2016-10-13 17:12:56 -070078 local_ref_cookie(kIRTFirstSegment),
Andreas Gampe9d7ef622016-10-24 19:35:19 -070079 locals(kLocalsInitial, kLocal, IndirectReferenceTable::ResizableCapacity::kYes, error_msg),
Ian Rogers68d8b422014-07-17 11:09:10 -070080 check_jni(false),
Mathieu Chartier4d87df62016-01-07 15:14:19 -080081 runtime_deleted(false),
Ian Rogers68d8b422014-07-17 11:09:10 -070082 critical(0),
83 monitors("monitors", kMonitorsInitial, kMonitorsMax) {
Andreas Gampec8089542017-01-16 12:41:12 -080084 MutexLock mu(Thread::Current(), *Locks::jni_function_table_lock_);
85 check_jni = vm->IsCheckJniEnabled();
86 functions = GetFunctionTable(check_jni);
87 unchecked_functions = GetJniNativeInterface();
Ian Rogers68d8b422014-07-17 11:09:10 -070088}
89
Mathieu Chartier4d87df62016-01-07 15:14:19 -080090void JNIEnvExt::SetFunctionsToRuntimeShutdownFunctions() {
91 functions = GetRuntimeShutdownNativeInterface();
92 runtime_deleted = true;
93}
94
Ian Rogers68d8b422014-07-17 11:09:10 -070095JNIEnvExt::~JNIEnvExt() {
96}
97
Andreas Gampe5f4a09a2015-09-28 13:16:33 -070098jobject JNIEnvExt::NewLocalRef(mirror::Object* obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -070099 if (obj == nullptr) {
100 return nullptr;
101 }
Andreas Gampe25651122017-09-25 14:50:23 -0700102 std::string error_msg;
103 jobject ref = reinterpret_cast<jobject>(locals.Add(local_ref_cookie, obj, &error_msg));
104 if (UNLIKELY(ref == nullptr)) {
105 // This is really unexpected if we allow resizing local IRTs...
106 LOG(FATAL) << error_msg;
107 UNREACHABLE();
108 }
109 return ref;
Ian Rogers68d8b422014-07-17 11:09:10 -0700110}
111
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700112void JNIEnvExt::DeleteLocalRef(jobject obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700113 if (obj != nullptr) {
114 locals.Remove(local_ref_cookie, reinterpret_cast<IndirectRef>(obj));
115 }
116}
117
118void JNIEnvExt::SetCheckJniEnabled(bool enabled) {
119 check_jni = enabled;
Andreas Gampec8089542017-01-16 12:41:12 -0800120 MutexLock mu(Thread::Current(), *Locks::jni_function_table_lock_);
121 functions = GetFunctionTable(enabled);
122 // Check whether this is a no-op because of override.
123 if (enabled && JNIEnvExt::table_override_ != nullptr) {
124 LOG(WARNING) << "Enabling CheckJNI after a JNIEnv function table override is not functional.";
125 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700126}
127
128void JNIEnvExt::DumpReferenceTables(std::ostream& os) {
129 locals.Dump(os);
130 monitors.Dump(os);
131}
132
Andreas Gampe88831082017-05-31 19:46:03 -0700133void JNIEnvExt::PushFrame(int capacity) {
134 DCHECK_GE(locals.FreeCapacity(), static_cast<size_t>(capacity));
Ian Rogers68d8b422014-07-17 11:09:10 -0700135 stacked_local_ref_cookies.push_back(local_ref_cookie);
136 local_ref_cookie = locals.GetSegmentState();
137}
138
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700139void JNIEnvExt::PopFrame() {
Ian Rogers68d8b422014-07-17 11:09:10 -0700140 locals.SetSegmentState(local_ref_cookie);
141 local_ref_cookie = stacked_local_ref_cookies.back();
142 stacked_local_ref_cookies.pop_back();
143}
144
Andreas Gampe4d98c842015-12-09 15:14:04 -0800145// Note: the offset code is brittle, as we can't use OFFSETOF_MEMBER or offsetof easily. Thus, there
146// are tests in jni_internal_test to match the results against the actual values.
147
148// This is encoding the knowledge of the structure and layout of JNIEnv fields.
149static size_t JNIEnvSize(size_t pointer_size) {
150 // A single pointer.
151 return pointer_size;
152}
153
154Offset JNIEnvExt::SegmentStateOffset(size_t pointer_size) {
155 size_t locals_offset = JNIEnvSize(pointer_size) +
156 2 * pointer_size + // Thread* self + JavaVMExt* vm.
157 4 + // local_ref_cookie.
158 (pointer_size - 4); // Padding.
159 size_t irt_segment_state_offset =
160 IndirectReferenceTable::SegmentStateOffset(pointer_size).Int32Value();
161 return Offset(locals_offset + irt_segment_state_offset);
162}
163
164Offset JNIEnvExt::LocalRefCookieOffset(size_t pointer_size) {
165 return Offset(JNIEnvSize(pointer_size) +
166 2 * pointer_size); // Thread* self + JavaVMExt* vm
167}
168
169Offset JNIEnvExt::SelfOffset(size_t pointer_size) {
170 return Offset(JNIEnvSize(pointer_size));
Ian Rogers68d8b422014-07-17 11:09:10 -0700171}
172
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700173// Use some defining part of the caller's frame as the identifying mark for the JNI segment.
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700174static uintptr_t GetJavaCallFrame(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700175 NthCallerVisitor zeroth_caller(self, 0, false);
176 zeroth_caller.WalkStack();
177 if (zeroth_caller.caller == nullptr) {
178 // No Java code, must be from pure native code.
179 return 0;
180 } else if (zeroth_caller.GetCurrentQuickFrame() == nullptr) {
181 // Shadow frame = interpreter. Use the actual shadow frame's address.
182 DCHECK(zeroth_caller.GetCurrentShadowFrame() != nullptr);
183 return reinterpret_cast<uintptr_t>(zeroth_caller.GetCurrentShadowFrame());
184 } else {
185 // Quick frame = compiled code. Use the bottom of the frame.
186 return reinterpret_cast<uintptr_t>(zeroth_caller.GetCurrentQuickFrame());
187 }
188}
189
190void JNIEnvExt::RecordMonitorEnter(jobject obj) {
191 locked_objects_.push_back(std::make_pair(GetJavaCallFrame(self), obj));
192}
193
194static std::string ComputeMonitorDescription(Thread* self,
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700195 jobject obj) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700196 ObjPtr<mirror::Object> o = self->DecodeJObject(obj);
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700197 if ((o->GetLockWord(false).GetState() == LockWord::kThinLocked) &&
198 Locks::mutator_lock_->IsExclusiveHeld(self)) {
199 // Getting the identity hashcode here would result in lock inflation and suspension of the
200 // current thread, which isn't safe if this is the only runnable thread.
201 return StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700202 reinterpret_cast<intptr_t>(o.Ptr()),
David Sehr709b0702016-10-13 09:12:37 -0700203 o->PrettyTypeOf().c_str());
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700204 } else {
205 // IdentityHashCode can cause thread suspension, which would invalidate o if it moved. So
206 // we get the pretty type before we call IdentityHashCode.
David Sehr709b0702016-10-13 09:12:37 -0700207 const std::string pretty_type(o->PrettyTypeOf());
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700208 return StringPrintf("<0x%08x> (a %s)", o->IdentityHashCode(), pretty_type.c_str());
209 }
210}
211
212static void RemoveMonitors(Thread* self,
213 uintptr_t frame,
214 ReferenceTable* monitors,
215 std::vector<std::pair<uintptr_t, jobject>>* locked_objects)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700216 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700217 auto kept_end = std::remove_if(
218 locked_objects->begin(),
219 locked_objects->end(),
220 [self, frame, monitors](const std::pair<uintptr_t, jobject>& pair)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700221 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700222 if (frame == pair.first) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700223 ObjPtr<mirror::Object> o = self->DecodeJObject(pair.second);
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700224 monitors->Remove(o);
225 return true;
226 }
227 return false;
228 });
229 locked_objects->erase(kept_end, locked_objects->end());
230}
231
232void JNIEnvExt::CheckMonitorRelease(jobject obj) {
233 uintptr_t current_frame = GetJavaCallFrame(self);
234 std::pair<uintptr_t, jobject> exact_pair = std::make_pair(current_frame, obj);
235 auto it = std::find(locked_objects_.begin(), locked_objects_.end(), exact_pair);
236 bool will_abort = false;
237 if (it != locked_objects_.end()) {
238 locked_objects_.erase(it);
239 } else {
240 // Check whether this monitor was locked in another JNI "session."
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700241 ObjPtr<mirror::Object> mirror_obj = self->DecodeJObject(obj);
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700242 for (std::pair<uintptr_t, jobject>& pair : locked_objects_) {
243 if (self->DecodeJObject(pair.second) == mirror_obj) {
244 std::string monitor_descr = ComputeMonitorDescription(self, pair.second);
245 vm->JniAbortF("<JNI MonitorExit>",
246 "Unlocking monitor that wasn't locked here: %s",
247 monitor_descr.c_str());
248 will_abort = true;
249 break;
250 }
251 }
252 }
253
254 // When we abort, also make sure that any locks from the current "session" are removed from
255 // the monitors table, otherwise we may visit local objects in GC during abort (which won't be
256 // valid anymore).
257 if (will_abort) {
258 RemoveMonitors(self, current_frame, &monitors, &locked_objects_);
259 }
260}
261
262void JNIEnvExt::CheckNoHeldMonitors() {
263 uintptr_t current_frame = GetJavaCallFrame(self);
264 // The locked_objects_ are grouped by their stack frame component, as this enforces structured
265 // locking, and the groups form a stack. So the current frame entries are at the end. Check
266 // whether the vector is empty, and when there are elements, whether the last element belongs
267 // to this call - this signals that there are unlocked monitors.
268 if (!locked_objects_.empty()) {
269 std::pair<uintptr_t, jobject>& pair = locked_objects_[locked_objects_.size() - 1];
270 if (pair.first == current_frame) {
271 std::string monitor_descr = ComputeMonitorDescription(self, pair.second);
272 vm->JniAbortF("<JNI End>",
273 "Still holding a locked object on JNI end: %s",
274 monitor_descr.c_str());
275 // When we abort, also make sure that any locks from the current "session" are removed from
276 // the monitors table, otherwise we may visit local objects in GC during abort.
277 RemoveMonitors(self, current_frame, &monitors, &locked_objects_);
278 } else if (kIsDebugBuild) {
279 // Make sure there are really no other entries and our checking worked as expected.
280 for (std::pair<uintptr_t, jobject>& check_pair : locked_objects_) {
281 CHECK_NE(check_pair.first, current_frame);
282 }
283 }
284 }
285}
286
Andreas Gampec8089542017-01-16 12:41:12 -0800287static void ThreadResetFunctionTable(Thread* thread, void* arg ATTRIBUTE_UNUSED)
288 REQUIRES(Locks::jni_function_table_lock_) {
289 JNIEnvExt* env = thread->GetJniEnv();
290 bool check_jni = env->check_jni;
291 env->functions = JNIEnvExt::GetFunctionTable(check_jni);
292}
293
294void JNIEnvExt::SetTableOverride(const JNINativeInterface* table_override) {
295 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
296 MutexLock mu2(Thread::Current(), *Locks::jni_function_table_lock_);
297
298 JNIEnvExt::table_override_ = table_override;
299
300 // See if we have a runtime. Note: we cannot run other code (like JavaVMExt's CheckJNI install
301 // code), as we'd have to recursively lock the mutex.
302 Runtime* runtime = Runtime::Current();
303 if (runtime != nullptr) {
304 runtime->GetThreadList()->ForEach(ThreadResetFunctionTable, nullptr);
305 }
306}
307
308const JNINativeInterface* JNIEnvExt::GetFunctionTable(bool check_jni) {
309 const JNINativeInterface* override = JNIEnvExt::table_override_;
310 if (override != nullptr) {
311 return override;
312 }
313 return check_jni ? GetCheckJniNativeInterface() : GetJniNativeInterface();
314}
315
Ian Rogers68d8b422014-07-17 11:09:10 -0700316} // namespace art