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/to_str.h" 25 #include "check_jni.h" 26 #include "indirect_reference_table.h" 27 #include "java_vm_ext.h" 28 #include "jni_internal.h" 29 #include "lock_word.h" 30 #include "mirror/object-inl.h" 31 #include "nth_caller_visitor.h" 32 #include "scoped_thread_state_change.h" 33 #include "thread-current-inl.h" 34 #include "thread_list.h" 35 36 namespace art { 37 38 using android::base::StringPrintf; 39 40 static constexpr size_t kMonitorsInitial = 32; // Arbitrary. 41 static constexpr size_t kMonitorsMax = 4096; // Arbitrary sanity check. 42 43 const JNINativeInterface* JNIEnvExt::table_override_ = nullptr; 44 45 bool JNIEnvExt::CheckLocalsValid(JNIEnvExt* in) NO_THREAD_SAFETY_ANALYSIS { 46 if (in == nullptr) { 47 return false; 48 } 49 return in->locals_.IsValid(); 50 } 51 52 jint 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 66 JNIEnvExt* 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)); 68 if (CheckLocalsValid(ret.get())) { 69 return ret.release(); 70 } 71 return nullptr; 72 } 73 74 JNIEnvExt::JNIEnvExt(Thread* self_in, JavaVMExt* vm_in, std::string* error_msg) 75 : 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) { 83 MutexLock mu(Thread::Current(), *Locks::jni_function_table_lock_); 84 check_jni_ = vm_in->IsCheckJniEnabled(); 85 functions = GetFunctionTable(check_jni_); 86 unchecked_functions_ = GetJniNativeInterface(); 87 } 88 89 void JNIEnvExt::SetFunctionsToRuntimeShutdownFunctions() { 90 functions = GetRuntimeShutdownNativeInterface(); 91 runtime_deleted_ = true; 92 } 93 94 JNIEnvExt::~JNIEnvExt() { 95 } 96 97 jobject JNIEnvExt::NewLocalRef(mirror::Object* obj) { 98 if (obj == nullptr) { 99 return nullptr; 100 } 101 std::string error_msg; 102 jobject ref = reinterpret_cast<jobject>(locals_.Add(local_ref_cookie_, obj, &error_msg)); 103 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; 109 } 110 111 void JNIEnvExt::DeleteLocalRef(jobject obj) { 112 if (obj != nullptr) { 113 locals_.Remove(local_ref_cookie_, reinterpret_cast<IndirectRef>(obj)); 114 } 115 } 116 117 void JNIEnvExt::SetCheckJniEnabled(bool enabled) { 118 check_jni_ = 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 127 void JNIEnvExt::DumpReferenceTables(std::ostream& os) { 128 locals_.Dump(os); 129 monitors_.Dump(os); 130 } 131 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 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. 148 static size_t JNIEnvSize(size_t pointer_size) { 149 // A single pointer. 150 return pointer_size; 151 } 152 153 Offset 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 163 Offset JNIEnvExt::LocalRefCookieOffset(size_t pointer_size) { 164 return Offset(JNIEnvSize(pointer_size) + 165 2 * pointer_size); // Thread* self + JavaVMExt* vm 166 } 167 168 Offset JNIEnvExt::SelfOffset(size_t pointer_size) { 169 return Offset(JNIEnvSize(pointer_size)); 170 } 171 172 // Use some defining part of the caller's frame as the identifying mark for the JNI segment. 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 189 void JNIEnvExt::RecordMonitorEnter(jobject obj) { 190 locked_objects_.push_back(std::make_pair(GetJavaCallFrame(self_), obj)); 191 } 192 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 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 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 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 292 static 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 } 298 299 void 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 313 const 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 321 } // namespace art 322