blob: 5a3fafa7264e7ccea96cfc941ca9312e90d7b56b [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"
31#include "thread-inl.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070032
33namespace art {
34
Andreas Gampe46ee31b2016-12-14 10:11:49 -080035using android::base::StringPrintf;
36
Ian Rogers68d8b422014-07-17 11:09:10 -070037static constexpr size_t kMonitorsInitial = 32; // Arbitrary.
38static constexpr size_t kMonitorsMax = 4096; // Arbitrary sanity check.
39
Andreas Gampe3f5881f2015-04-08 10:26:16 -070040// Checking "locals" requires the mutator lock, but at creation time we're really only interested
41// in validity, which isn't changing. To avoid grabbing the mutator lock, factored out and tagged
42// with NO_THREAD_SAFETY_ANALYSIS.
43static bool CheckLocalsValid(JNIEnvExt* in) NO_THREAD_SAFETY_ANALYSIS {
44 if (in == nullptr) {
45 return false;
46 }
47 return in->locals.IsValid();
48}
49
Alex Light185d1342016-08-11 10:48:03 -070050jint JNIEnvExt::GetEnvHandler(JavaVMExt* vm, /*out*/void** env, jint version) {
51 UNUSED(vm);
52 // GetEnv always returns a JNIEnv* for the most current supported JNI version,
53 // and unlike other calls that take a JNI version doesn't care if you supply
54 // JNI_VERSION_1_1, which we don't otherwise support.
55 if (JavaVMExt::IsBadJniVersion(version) && version != JNI_VERSION_1_1) {
56 return JNI_EVERSION;
57 }
58 Thread* thread = Thread::Current();
59 CHECK(thread != nullptr);
60 *env = thread->GetJniEnv();
61 return JNI_OK;
62}
63
Richard Uhlerda0a69e2016-10-11 15:06:38 +010064JNIEnvExt* JNIEnvExt::Create(Thread* self_in, JavaVMExt* vm_in, std::string* error_msg) {
65 std::unique_ptr<JNIEnvExt> ret(new JNIEnvExt(self_in, vm_in, error_msg));
Andreas Gampe3f5881f2015-04-08 10:26:16 -070066 if (CheckLocalsValid(ret.get())) {
67 return ret.release();
68 }
69 return nullptr;
70}
71
Richard Uhlerda0a69e2016-10-11 15:06:38 +010072JNIEnvExt::JNIEnvExt(Thread* self_in, JavaVMExt* vm_in, std::string* error_msg)
Andreas Gampe277ccbd2014-11-03 21:36:10 -080073 : self(self_in),
74 vm(vm_in),
Andreas Gampee03662b2016-10-13 17:12:56 -070075 local_ref_cookie(kIRTFirstSegment),
Andreas Gampe9d7ef622016-10-24 19:35:19 -070076 locals(kLocalsInitial, kLocal, IndirectReferenceTable::ResizableCapacity::kYes, error_msg),
Ian Rogers68d8b422014-07-17 11:09:10 -070077 check_jni(false),
Mathieu Chartier4d87df62016-01-07 15:14:19 -080078 runtime_deleted(false),
Ian Rogers68d8b422014-07-17 11:09:10 -070079 critical(0),
80 monitors("monitors", kMonitorsInitial, kMonitorsMax) {
81 functions = unchecked_functions = GetJniNativeInterface();
82 if (vm->IsCheckJniEnabled()) {
83 SetCheckJniEnabled(true);
84 }
85}
86
Mathieu Chartier4d87df62016-01-07 15:14:19 -080087void JNIEnvExt::SetFunctionsToRuntimeShutdownFunctions() {
88 functions = GetRuntimeShutdownNativeInterface();
89 runtime_deleted = true;
90}
91
Ian Rogers68d8b422014-07-17 11:09:10 -070092JNIEnvExt::~JNIEnvExt() {
93}
94
Andreas Gampe5f4a09a2015-09-28 13:16:33 -070095jobject JNIEnvExt::NewLocalRef(mirror::Object* obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -070096 if (obj == nullptr) {
97 return nullptr;
98 }
99 return reinterpret_cast<jobject>(locals.Add(local_ref_cookie, obj));
100}
101
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700102void JNIEnvExt::DeleteLocalRef(jobject obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700103 if (obj != nullptr) {
104 locals.Remove(local_ref_cookie, reinterpret_cast<IndirectRef>(obj));
105 }
106}
107
108void JNIEnvExt::SetCheckJniEnabled(bool enabled) {
109 check_jni = enabled;
110 functions = enabled ? GetCheckJniNativeInterface() : GetJniNativeInterface();
111}
112
113void JNIEnvExt::DumpReferenceTables(std::ostream& os) {
114 locals.Dump(os);
115 monitors.Dump(os);
116}
117
Roland Levillain4b8f1ec2015-08-26 18:34:03 +0100118void JNIEnvExt::PushFrame(int capacity ATTRIBUTE_UNUSED) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700119 // TODO: take 'capacity' into account.
120 stacked_local_ref_cookies.push_back(local_ref_cookie);
121 local_ref_cookie = locals.GetSegmentState();
122}
123
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700124void JNIEnvExt::PopFrame() {
Ian Rogers68d8b422014-07-17 11:09:10 -0700125 locals.SetSegmentState(local_ref_cookie);
126 local_ref_cookie = stacked_local_ref_cookies.back();
127 stacked_local_ref_cookies.pop_back();
128}
129
Andreas Gampe4d98c842015-12-09 15:14:04 -0800130// Note: the offset code is brittle, as we can't use OFFSETOF_MEMBER or offsetof easily. Thus, there
131// are tests in jni_internal_test to match the results against the actual values.
132
133// This is encoding the knowledge of the structure and layout of JNIEnv fields.
134static size_t JNIEnvSize(size_t pointer_size) {
135 // A single pointer.
136 return pointer_size;
137}
138
139Offset JNIEnvExt::SegmentStateOffset(size_t pointer_size) {
140 size_t locals_offset = JNIEnvSize(pointer_size) +
141 2 * pointer_size + // Thread* self + JavaVMExt* vm.
142 4 + // local_ref_cookie.
143 (pointer_size - 4); // Padding.
144 size_t irt_segment_state_offset =
145 IndirectReferenceTable::SegmentStateOffset(pointer_size).Int32Value();
146 return Offset(locals_offset + irt_segment_state_offset);
147}
148
149Offset JNIEnvExt::LocalRefCookieOffset(size_t pointer_size) {
150 return Offset(JNIEnvSize(pointer_size) +
151 2 * pointer_size); // Thread* self + JavaVMExt* vm
152}
153
154Offset JNIEnvExt::SelfOffset(size_t pointer_size) {
155 return Offset(JNIEnvSize(pointer_size));
Ian Rogers68d8b422014-07-17 11:09:10 -0700156}
157
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700158// Use some defining part of the caller's frame as the identifying mark for the JNI segment.
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700159static uintptr_t GetJavaCallFrame(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700160 NthCallerVisitor zeroth_caller(self, 0, false);
161 zeroth_caller.WalkStack();
162 if (zeroth_caller.caller == nullptr) {
163 // No Java code, must be from pure native code.
164 return 0;
165 } else if (zeroth_caller.GetCurrentQuickFrame() == nullptr) {
166 // Shadow frame = interpreter. Use the actual shadow frame's address.
167 DCHECK(zeroth_caller.GetCurrentShadowFrame() != nullptr);
168 return reinterpret_cast<uintptr_t>(zeroth_caller.GetCurrentShadowFrame());
169 } else {
170 // Quick frame = compiled code. Use the bottom of the frame.
171 return reinterpret_cast<uintptr_t>(zeroth_caller.GetCurrentQuickFrame());
172 }
173}
174
175void JNIEnvExt::RecordMonitorEnter(jobject obj) {
176 locked_objects_.push_back(std::make_pair(GetJavaCallFrame(self), obj));
177}
178
179static std::string ComputeMonitorDescription(Thread* self,
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700180 jobject obj) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700181 ObjPtr<mirror::Object> o = self->DecodeJObject(obj);
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700182 if ((o->GetLockWord(false).GetState() == LockWord::kThinLocked) &&
183 Locks::mutator_lock_->IsExclusiveHeld(self)) {
184 // Getting the identity hashcode here would result in lock inflation and suspension of the
185 // current thread, which isn't safe if this is the only runnable thread.
186 return StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700187 reinterpret_cast<intptr_t>(o.Ptr()),
David Sehr709b0702016-10-13 09:12:37 -0700188 o->PrettyTypeOf().c_str());
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700189 } else {
190 // IdentityHashCode can cause thread suspension, which would invalidate o if it moved. So
191 // we get the pretty type before we call IdentityHashCode.
David Sehr709b0702016-10-13 09:12:37 -0700192 const std::string pretty_type(o->PrettyTypeOf());
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700193 return StringPrintf("<0x%08x> (a %s)", o->IdentityHashCode(), pretty_type.c_str());
194 }
195}
196
197static void RemoveMonitors(Thread* self,
198 uintptr_t frame,
199 ReferenceTable* monitors,
200 std::vector<std::pair<uintptr_t, jobject>>* locked_objects)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700201 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700202 auto kept_end = std::remove_if(
203 locked_objects->begin(),
204 locked_objects->end(),
205 [self, frame, monitors](const std::pair<uintptr_t, jobject>& pair)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700206 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700207 if (frame == pair.first) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700208 ObjPtr<mirror::Object> o = self->DecodeJObject(pair.second);
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700209 monitors->Remove(o);
210 return true;
211 }
212 return false;
213 });
214 locked_objects->erase(kept_end, locked_objects->end());
215}
216
217void JNIEnvExt::CheckMonitorRelease(jobject obj) {
218 uintptr_t current_frame = GetJavaCallFrame(self);
219 std::pair<uintptr_t, jobject> exact_pair = std::make_pair(current_frame, obj);
220 auto it = std::find(locked_objects_.begin(), locked_objects_.end(), exact_pair);
221 bool will_abort = false;
222 if (it != locked_objects_.end()) {
223 locked_objects_.erase(it);
224 } else {
225 // Check whether this monitor was locked in another JNI "session."
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700226 ObjPtr<mirror::Object> mirror_obj = self->DecodeJObject(obj);
Andreas Gampe5f4a09a2015-09-28 13:16:33 -0700227 for (std::pair<uintptr_t, jobject>& pair : locked_objects_) {
228 if (self->DecodeJObject(pair.second) == mirror_obj) {
229 std::string monitor_descr = ComputeMonitorDescription(self, pair.second);
230 vm->JniAbortF("<JNI MonitorExit>",
231 "Unlocking monitor that wasn't locked here: %s",
232 monitor_descr.c_str());
233 will_abort = true;
234 break;
235 }
236 }
237 }
238
239 // When we abort, also make sure that any locks from the current "session" are removed from
240 // the monitors table, otherwise we may visit local objects in GC during abort (which won't be
241 // valid anymore).
242 if (will_abort) {
243 RemoveMonitors(self, current_frame, &monitors, &locked_objects_);
244 }
245}
246
247void JNIEnvExt::CheckNoHeldMonitors() {
248 uintptr_t current_frame = GetJavaCallFrame(self);
249 // The locked_objects_ are grouped by their stack frame component, as this enforces structured
250 // locking, and the groups form a stack. So the current frame entries are at the end. Check
251 // whether the vector is empty, and when there are elements, whether the last element belongs
252 // to this call - this signals that there are unlocked monitors.
253 if (!locked_objects_.empty()) {
254 std::pair<uintptr_t, jobject>& pair = locked_objects_[locked_objects_.size() - 1];
255 if (pair.first == current_frame) {
256 std::string monitor_descr = ComputeMonitorDescription(self, pair.second);
257 vm->JniAbortF("<JNI End>",
258 "Still holding a locked object on JNI end: %s",
259 monitor_descr.c_str());
260 // When we abort, also make sure that any locks from the current "session" are removed from
261 // the monitors table, otherwise we may visit local objects in GC during abort.
262 RemoveMonitors(self, current_frame, &monitors, &locked_objects_);
263 } else if (kIsDebugBuild) {
264 // Make sure there are really no other entries and our checking worked as expected.
265 for (std::pair<uintptr_t, jobject>& check_pair : locked_objects_) {
266 CHECK_NE(check_pair.first, current_frame);
267 }
268 }
269 }
270}
271
Ian Rogers68d8b422014-07-17 11:09:10 -0700272} // namespace art