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 "check_jni.h"
23 #include "indirect_reference_table.h"
24 #include "java_vm_ext.h"
25 #include "jni_internal.h"
26 #include "lock_word.h"
27 #include "mirror/object-inl.h"
28 #include "nth_caller_visitor.h"
29 #include "thread-inl.h"
30
31 namespace art {
32
33 static constexpr size_t kMonitorsInitial = 32; // Arbitrary.
34 static constexpr size_t kMonitorsMax = 4096; // Arbitrary sanity check.
35
36 static constexpr size_t kLocalsInitial = 64; // Arbitrary.
37
38 // Checking "locals" requires the mutator lock, but at creation time we're really only interested
39 // in validity, which isn't changing. To avoid grabbing the mutator lock, factored out and tagged
40 // with NO_THREAD_SAFETY_ANALYSIS.
CheckLocalsValid(JNIEnvExt * in)41 static bool CheckLocalsValid(JNIEnvExt* in) NO_THREAD_SAFETY_ANALYSIS {
42 if (in == nullptr) {
43 return false;
44 }
45 return in->locals.IsValid();
46 }
47
Create(Thread * self_in,JavaVMExt * vm_in)48 JNIEnvExt* JNIEnvExt::Create(Thread* self_in, JavaVMExt* vm_in) {
49 std::unique_ptr<JNIEnvExt> ret(new JNIEnvExt(self_in, vm_in));
50 if (CheckLocalsValid(ret.get())) {
51 return ret.release();
52 }
53 return nullptr;
54 }
55
JNIEnvExt(Thread * self_in,JavaVMExt * vm_in)56 JNIEnvExt::JNIEnvExt(Thread* self_in, JavaVMExt* vm_in)
57 : self(self_in),
58 vm(vm_in),
59 local_ref_cookie(IRT_FIRST_SEGMENT),
60 locals(kLocalsInitial, kLocalsMax, kLocal, false),
61 check_jni(false),
62 runtime_deleted(false),
63 critical(0),
64 monitors("monitors", kMonitorsInitial, kMonitorsMax) {
65 functions = unchecked_functions = GetJniNativeInterface();
66 if (vm->IsCheckJniEnabled()) {
67 SetCheckJniEnabled(true);
68 }
69 }
70
SetFunctionsToRuntimeShutdownFunctions()71 void JNIEnvExt::SetFunctionsToRuntimeShutdownFunctions() {
72 functions = GetRuntimeShutdownNativeInterface();
73 runtime_deleted = true;
74 }
75
~JNIEnvExt()76 JNIEnvExt::~JNIEnvExt() {
77 }
78
NewLocalRef(mirror::Object * obj)79 jobject JNIEnvExt::NewLocalRef(mirror::Object* obj) {
80 if (obj == nullptr) {
81 return nullptr;
82 }
83 return reinterpret_cast<jobject>(locals.Add(local_ref_cookie, obj));
84 }
85
DeleteLocalRef(jobject obj)86 void JNIEnvExt::DeleteLocalRef(jobject obj) {
87 if (obj != nullptr) {
88 locals.Remove(local_ref_cookie, reinterpret_cast<IndirectRef>(obj));
89 }
90 }
91
SetCheckJniEnabled(bool enabled)92 void JNIEnvExt::SetCheckJniEnabled(bool enabled) {
93 check_jni = enabled;
94 functions = enabled ? GetCheckJniNativeInterface() : GetJniNativeInterface();
95 }
96
DumpReferenceTables(std::ostream & os)97 void JNIEnvExt::DumpReferenceTables(std::ostream& os) {
98 locals.Dump(os);
99 monitors.Dump(os);
100 }
101
PushFrame(int capacity ATTRIBUTE_UNUSED)102 void JNIEnvExt::PushFrame(int capacity ATTRIBUTE_UNUSED) {
103 // TODO: take 'capacity' into account.
104 stacked_local_ref_cookies.push_back(local_ref_cookie);
105 local_ref_cookie = locals.GetSegmentState();
106 }
107
PopFrame()108 void JNIEnvExt::PopFrame() {
109 locals.SetSegmentState(local_ref_cookie);
110 local_ref_cookie = stacked_local_ref_cookies.back();
111 stacked_local_ref_cookies.pop_back();
112 }
113
114 // Note: the offset code is brittle, as we can't use OFFSETOF_MEMBER or offsetof easily. Thus, there
115 // are tests in jni_internal_test to match the results against the actual values.
116
117 // This is encoding the knowledge of the structure and layout of JNIEnv fields.
JNIEnvSize(size_t pointer_size)118 static size_t JNIEnvSize(size_t pointer_size) {
119 // A single pointer.
120 return pointer_size;
121 }
122
SegmentStateOffset(size_t pointer_size)123 Offset JNIEnvExt::SegmentStateOffset(size_t pointer_size) {
124 size_t locals_offset = JNIEnvSize(pointer_size) +
125 2 * pointer_size + // Thread* self + JavaVMExt* vm.
126 4 + // local_ref_cookie.
127 (pointer_size - 4); // Padding.
128 size_t irt_segment_state_offset =
129 IndirectReferenceTable::SegmentStateOffset(pointer_size).Int32Value();
130 return Offset(locals_offset + irt_segment_state_offset);
131 }
132
LocalRefCookieOffset(size_t pointer_size)133 Offset JNIEnvExt::LocalRefCookieOffset(size_t pointer_size) {
134 return Offset(JNIEnvSize(pointer_size) +
135 2 * pointer_size); // Thread* self + JavaVMExt* vm
136 }
137
SelfOffset(size_t pointer_size)138 Offset JNIEnvExt::SelfOffset(size_t pointer_size) {
139 return Offset(JNIEnvSize(pointer_size));
140 }
141
142 // Use some defining part of the caller's frame as the identifying mark for the JNI segment.
GetJavaCallFrame(Thread * self)143 static uintptr_t GetJavaCallFrame(Thread* self) SHARED_REQUIRES(Locks::mutator_lock_) {
144 NthCallerVisitor zeroth_caller(self, 0, false);
145 zeroth_caller.WalkStack();
146 if (zeroth_caller.caller == nullptr) {
147 // No Java code, must be from pure native code.
148 return 0;
149 } else if (zeroth_caller.GetCurrentQuickFrame() == nullptr) {
150 // Shadow frame = interpreter. Use the actual shadow frame's address.
151 DCHECK(zeroth_caller.GetCurrentShadowFrame() != nullptr);
152 return reinterpret_cast<uintptr_t>(zeroth_caller.GetCurrentShadowFrame());
153 } else {
154 // Quick frame = compiled code. Use the bottom of the frame.
155 return reinterpret_cast<uintptr_t>(zeroth_caller.GetCurrentQuickFrame());
156 }
157 }
158
RecordMonitorEnter(jobject obj)159 void JNIEnvExt::RecordMonitorEnter(jobject obj) {
160 locked_objects_.push_back(std::make_pair(GetJavaCallFrame(self), obj));
161 }
162
ComputeMonitorDescription(Thread * self,jobject obj)163 static std::string ComputeMonitorDescription(Thread* self,
164 jobject obj) SHARED_REQUIRES(Locks::mutator_lock_) {
165 mirror::Object* o = self->DecodeJObject(obj);
166 if ((o->GetLockWord(false).GetState() == LockWord::kThinLocked) &&
167 Locks::mutator_lock_->IsExclusiveHeld(self)) {
168 // Getting the identity hashcode here would result in lock inflation and suspension of the
169 // current thread, which isn't safe if this is the only runnable thread.
170 return StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
171 reinterpret_cast<intptr_t>(o),
172 PrettyTypeOf(o).c_str());
173 } else {
174 // IdentityHashCode can cause thread suspension, which would invalidate o if it moved. So
175 // we get the pretty type before we call IdentityHashCode.
176 const std::string pretty_type(PrettyTypeOf(o));
177 return StringPrintf("<0x%08x> (a %s)", o->IdentityHashCode(), pretty_type.c_str());
178 }
179 }
180
RemoveMonitors(Thread * self,uintptr_t frame,ReferenceTable * monitors,std::vector<std::pair<uintptr_t,jobject>> * locked_objects)181 static void RemoveMonitors(Thread* self,
182 uintptr_t frame,
183 ReferenceTable* monitors,
184 std::vector<std::pair<uintptr_t, jobject>>* locked_objects)
185 SHARED_REQUIRES(Locks::mutator_lock_) {
186 auto kept_end = std::remove_if(
187 locked_objects->begin(),
188 locked_objects->end(),
189 [self, frame, monitors](const std::pair<uintptr_t, jobject>& pair)
190 SHARED_REQUIRES(Locks::mutator_lock_) {
191 if (frame == pair.first) {
192 mirror::Object* o = self->DecodeJObject(pair.second);
193 monitors->Remove(o);
194 return true;
195 }
196 return false;
197 });
198 locked_objects->erase(kept_end, locked_objects->end());
199 }
200
CheckMonitorRelease(jobject obj)201 void JNIEnvExt::CheckMonitorRelease(jobject obj) {
202 uintptr_t current_frame = GetJavaCallFrame(self);
203 std::pair<uintptr_t, jobject> exact_pair = std::make_pair(current_frame, obj);
204 auto it = std::find(locked_objects_.begin(), locked_objects_.end(), exact_pair);
205 bool will_abort = false;
206 if (it != locked_objects_.end()) {
207 locked_objects_.erase(it);
208 } else {
209 // Check whether this monitor was locked in another JNI "session."
210 mirror::Object* mirror_obj = self->DecodeJObject(obj);
211 for (std::pair<uintptr_t, jobject>& pair : locked_objects_) {
212 if (self->DecodeJObject(pair.second) == mirror_obj) {
213 std::string monitor_descr = ComputeMonitorDescription(self, pair.second);
214 vm->JniAbortF("<JNI MonitorExit>",
215 "Unlocking monitor that wasn't locked here: %s",
216 monitor_descr.c_str());
217 will_abort = true;
218 break;
219 }
220 }
221 }
222
223 // When we abort, also make sure that any locks from the current "session" are removed from
224 // the monitors table, otherwise we may visit local objects in GC during abort (which won't be
225 // valid anymore).
226 if (will_abort) {
227 RemoveMonitors(self, current_frame, &monitors, &locked_objects_);
228 }
229 }
230
CheckNoHeldMonitors()231 void JNIEnvExt::CheckNoHeldMonitors() {
232 uintptr_t current_frame = GetJavaCallFrame(self);
233 // The locked_objects_ are grouped by their stack frame component, as this enforces structured
234 // locking, and the groups form a stack. So the current frame entries are at the end. Check
235 // whether the vector is empty, and when there are elements, whether the last element belongs
236 // to this call - this signals that there are unlocked monitors.
237 if (!locked_objects_.empty()) {
238 std::pair<uintptr_t, jobject>& pair = locked_objects_[locked_objects_.size() - 1];
239 if (pair.first == current_frame) {
240 std::string monitor_descr = ComputeMonitorDescription(self, pair.second);
241 vm->JniAbortF("<JNI End>",
242 "Still holding a locked object on JNI end: %s",
243 monitor_descr.c_str());
244 // When we abort, also make sure that any locks from the current "session" are removed from
245 // the monitors table, otherwise we may visit local objects in GC during abort.
246 RemoveMonitors(self, current_frame, &monitors, &locked_objects_);
247 } else if (kIsDebugBuild) {
248 // Make sure there are really no other entries and our checking worked as expected.
249 for (std::pair<uintptr_t, jobject>& check_pair : locked_objects_) {
250 CHECK_NE(check_pair.first, current_frame);
251 }
252 }
253 }
254 }
255
256 } // namespace art
257