thread.cc revision 597c4f0aeafed2b6fa69e53ece4be4f53115d707
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#define ATRACE_TAG ATRACE_TAG_DALVIK 18 19#include "thread.h" 20 21#include <cutils/trace.h> 22#include <pthread.h> 23#include <signal.h> 24#include <sys/resource.h> 25#include <sys/time.h> 26 27#include <algorithm> 28#include <bitset> 29#include <cerrno> 30#include <iostream> 31#include <list> 32#include <sstream> 33 34#include "arch/context.h" 35#include "base/mutex.h" 36#include "base/timing_logger.h" 37#include "base/to_str.h" 38#include "class_linker-inl.h" 39#include "class_linker.h" 40#include "debugger.h" 41#include "dex_file-inl.h" 42#include "entrypoints/entrypoint_utils.h" 43#include "entrypoints/quick/quick_alloc_entrypoints.h" 44#include "gc_map.h" 45#include "gc/accounting/card_table-inl.h" 46#include "gc/allocator/rosalloc.h" 47#include "gc/heap.h" 48#include "gc/space/space.h" 49#include "handle_scope-inl.h" 50#include "handle_scope.h" 51#include "indirect_reference_table-inl.h" 52#include "jni_internal.h" 53#include "mirror/art_field-inl.h" 54#include "mirror/art_method-inl.h" 55#include "mirror/class_loader.h" 56#include "mirror/class-inl.h" 57#include "mirror/object_array-inl.h" 58#include "mirror/stack_trace_element.h" 59#include "monitor.h" 60#include "object_lock.h" 61#include "quick_exception_handler.h" 62#include "quick/quick_method_frame_info.h" 63#include "reflection.h" 64#include "runtime.h" 65#include "scoped_thread_state_change.h" 66#include "ScopedLocalRef.h" 67#include "ScopedUtfChars.h" 68#include "stack.h" 69#include "thread_list.h" 70#include "thread-inl.h" 71#include "utils.h" 72#include "verifier/dex_gc_map.h" 73#include "verify_object-inl.h" 74#include "vmap_table.h" 75#include "well_known_classes.h" 76 77namespace art { 78 79bool Thread::is_started_ = false; 80pthread_key_t Thread::pthread_key_self_; 81ConditionVariable* Thread::resume_cond_ = nullptr; 82const size_t Thread::kStackOverflowImplicitCheckSize = GetStackOverflowReservedBytes(kRuntimeISA); 83 84static const char* kThreadNameDuringStartup = "<native thread without managed peer>"; 85 86void Thread::InitCardTable() { 87 tlsPtr_.card_table = Runtime::Current()->GetHeap()->GetCardTable()->GetBiasedBegin(); 88} 89 90static void UnimplementedEntryPoint() { 91 UNIMPLEMENTED(FATAL); 92} 93 94void InitEntryPoints(InterpreterEntryPoints* ipoints, JniEntryPoints* jpoints, 95 QuickEntryPoints* qpoints); 96 97void Thread::InitTlsEntryPoints() { 98 // Insert a placeholder so we can easily tell if we call an unimplemented entry point. 99 uintptr_t* begin = reinterpret_cast<uintptr_t*>(&tlsPtr_.interpreter_entrypoints); 100 uintptr_t* end = reinterpret_cast<uintptr_t*>(reinterpret_cast<uint8_t*>(&tlsPtr_.quick_entrypoints) + 101 sizeof(tlsPtr_.quick_entrypoints)); 102 for (uintptr_t* it = begin; it != end; ++it) { 103 *it = reinterpret_cast<uintptr_t>(UnimplementedEntryPoint); 104 } 105 InitEntryPoints(&tlsPtr_.interpreter_entrypoints, &tlsPtr_.jni_entrypoints, 106 &tlsPtr_.quick_entrypoints); 107} 108 109void Thread::ResetQuickAllocEntryPointsForThread() { 110 ResetQuickAllocEntryPoints(&tlsPtr_.quick_entrypoints); 111} 112 113void Thread::SetDeoptimizationShadowFrame(ShadowFrame* sf) { 114 tlsPtr_.deoptimization_shadow_frame = sf; 115} 116 117void Thread::SetDeoptimizationReturnValue(const JValue& ret_val) { 118 tls64_.deoptimization_return_value.SetJ(ret_val.GetJ()); 119} 120 121ShadowFrame* Thread::GetAndClearDeoptimizationShadowFrame(JValue* ret_val) { 122 ShadowFrame* sf = tlsPtr_.deoptimization_shadow_frame; 123 tlsPtr_.deoptimization_shadow_frame = nullptr; 124 ret_val->SetJ(tls64_.deoptimization_return_value.GetJ()); 125 return sf; 126} 127 128void Thread::SetShadowFrameUnderConstruction(ShadowFrame* sf) { 129 sf->SetLink(tlsPtr_.shadow_frame_under_construction); 130 tlsPtr_.shadow_frame_under_construction = sf; 131} 132 133void Thread::ClearShadowFrameUnderConstruction() { 134 CHECK_NE(static_cast<ShadowFrame*>(nullptr), tlsPtr_.shadow_frame_under_construction); 135 tlsPtr_.shadow_frame_under_construction = tlsPtr_.shadow_frame_under_construction->GetLink(); 136} 137 138void Thread::InitTid() { 139 tls32_.tid = ::art::GetTid(); 140} 141 142void Thread::InitAfterFork() { 143 // One thread (us) survived the fork, but we have a new tid so we need to 144 // update the value stashed in this Thread*. 145 InitTid(); 146} 147 148void* Thread::CreateCallback(void* arg) { 149 Thread* self = reinterpret_cast<Thread*>(arg); 150 Runtime* runtime = Runtime::Current(); 151 if (runtime == nullptr) { 152 LOG(ERROR) << "Thread attaching to non-existent runtime: " << *self; 153 return nullptr; 154 } 155 { 156 // TODO: pass self to MutexLock - requires self to equal Thread::Current(), which is only true 157 // after self->Init(). 158 MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_); 159 // Check that if we got here we cannot be shutting down (as shutdown should never have started 160 // while threads are being born). 161 CHECK(!runtime->IsShuttingDownLocked()); 162 CHECK(self->Init(runtime->GetThreadList(), runtime->GetJavaVM())); 163 Runtime::Current()->EndThreadBirth(); 164 } 165 { 166 ScopedObjectAccess soa(self); 167 168 // Copy peer into self, deleting global reference when done. 169 CHECK(self->tlsPtr_.jpeer != nullptr); 170 self->tlsPtr_.opeer = soa.Decode<mirror::Object*>(self->tlsPtr_.jpeer); 171 self->GetJniEnv()->DeleteGlobalRef(self->tlsPtr_.jpeer); 172 self->tlsPtr_.jpeer = nullptr; 173 self->SetThreadName(self->GetThreadName(soa)->ToModifiedUtf8().c_str()); 174 175 mirror::ArtField* priorityField = soa.DecodeField(WellKnownClasses::java_lang_Thread_priority); 176 self->SetNativePriority(priorityField->GetInt(self->tlsPtr_.opeer)); 177 Dbg::PostThreadStart(self); 178 179 // Invoke the 'run' method of our java.lang.Thread. 180 mirror::Object* receiver = self->tlsPtr_.opeer; 181 jmethodID mid = WellKnownClasses::java_lang_Thread_run; 182 InvokeVirtualOrInterfaceWithJValues(soa, receiver, mid, nullptr); 183 } 184 // Detach and delete self. 185 Runtime::Current()->GetThreadList()->Unregister(self); 186 187 return nullptr; 188} 189 190Thread* Thread::FromManagedThread(const ScopedObjectAccessAlreadyRunnable& soa, 191 mirror::Object* thread_peer) { 192 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_nativePeer); 193 Thread* result = reinterpret_cast<Thread*>(static_cast<uintptr_t>(f->GetLong(thread_peer))); 194 // Sanity check that if we have a result it is either suspended or we hold the thread_list_lock_ 195 // to stop it from going away. 196 if (kIsDebugBuild) { 197 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_); 198 if (result != nullptr && !result->IsSuspended()) { 199 Locks::thread_list_lock_->AssertHeld(soa.Self()); 200 } 201 } 202 return result; 203} 204 205Thread* Thread::FromManagedThread(const ScopedObjectAccessAlreadyRunnable& soa, 206 jobject java_thread) { 207 return FromManagedThread(soa, soa.Decode<mirror::Object*>(java_thread)); 208} 209 210static size_t FixStackSize(size_t stack_size) { 211 // A stack size of zero means "use the default". 212 if (stack_size == 0) { 213 stack_size = Runtime::Current()->GetDefaultStackSize(); 214 } 215 216 // Dalvik used the bionic pthread default stack size for native threads, 217 // so include that here to support apps that expect large native stacks. 218 stack_size += 1 * MB; 219 220 // It's not possible to request a stack smaller than the system-defined PTHREAD_STACK_MIN. 221 if (stack_size < PTHREAD_STACK_MIN) { 222 stack_size = PTHREAD_STACK_MIN; 223 } 224 225 if (Runtime::Current()->ExplicitStackOverflowChecks()) { 226 // It's likely that callers are trying to ensure they have at least a certain amount of 227 // stack space, so we should add our reserved space on top of what they requested, rather 228 // than implicitly take it away from them. 229 stack_size += GetStackOverflowReservedBytes(kRuntimeISA); 230 } else { 231 // If we are going to use implicit stack checks, allocate space for the protected 232 // region at the bottom of the stack. 233 stack_size += Thread::kStackOverflowImplicitCheckSize + 234 GetStackOverflowReservedBytes(kRuntimeISA); 235 } 236 237 // Some systems require the stack size to be a multiple of the system page size, so round up. 238 stack_size = RoundUp(stack_size, kPageSize); 239 240 return stack_size; 241} 242 243// Global variable to prevent the compiler optimizing away the page reads for the stack. 244uint8_t dont_optimize_this; 245 246// Install a protected region in the stack. This is used to trigger a SIGSEGV if a stack 247// overflow is detected. It is located right below the stack_begin_. 248// 249// There is a little complexity here that deserves a special mention. On some 250// architectures, the stack created using a VM_GROWSDOWN flag 251// to prevent memory being allocated when it's not needed. This flag makes the 252// kernel only allocate memory for the stack by growing down in memory. Because we 253// want to put an mprotected region far away from that at the stack top, we need 254// to make sure the pages for the stack are mapped in before we call mprotect. We do 255// this by reading every page from the stack bottom (highest address) to the stack top. 256// We then madvise this away. 257void Thread::InstallImplicitProtection() { 258 uint8_t* pregion = tlsPtr_.stack_begin - kStackOverflowProtectedSize; 259 uint8_t* stack_himem = tlsPtr_.stack_end; 260 uint8_t* stack_top = reinterpret_cast<uint8_t*>(reinterpret_cast<uintptr_t>(&stack_himem) & 261 ~(kPageSize - 1)); // Page containing current top of stack. 262 263 // First remove the protection on the protected region as will want to read and 264 // write it. This may fail (on the first attempt when the stack is not mapped) 265 // but we ignore that. 266 UnprotectStack(); 267 268 // Map in the stack. This must be done by reading from the 269 // current stack pointer downwards as the stack may be mapped using VM_GROWSDOWN 270 // in the kernel. Any access more than a page below the current SP might cause 271 // a segv. 272 273 // Read every page from the high address to the low. 274 for (uint8_t* p = stack_top; p >= pregion; p -= kPageSize) { 275 dont_optimize_this = *p; 276 } 277 278 VLOG(threads) << "installing stack protected region at " << std::hex << 279 static_cast<void*>(pregion) << " to " << 280 static_cast<void*>(pregion + kStackOverflowProtectedSize - 1); 281 282 // Protect the bottom of the stack to prevent read/write to it. 283 ProtectStack(); 284 285 // Tell the kernel that we won't be needing these pages any more. 286 // NB. madvise will probably write zeroes into the memory (on linux it does). 287 uint32_t unwanted_size = stack_top - pregion - kPageSize; 288 madvise(pregion, unwanted_size, MADV_DONTNEED); 289} 290 291void Thread::CreateNativeThread(JNIEnv* env, jobject java_peer, size_t stack_size, bool is_daemon) { 292 CHECK(java_peer != nullptr); 293 Thread* self = static_cast<JNIEnvExt*>(env)->self; 294 Runtime* runtime = Runtime::Current(); 295 296 // Atomically start the birth of the thread ensuring the runtime isn't shutting down. 297 bool thread_start_during_shutdown = false; 298 { 299 MutexLock mu(self, *Locks::runtime_shutdown_lock_); 300 if (runtime->IsShuttingDownLocked()) { 301 thread_start_during_shutdown = true; 302 } else { 303 runtime->StartThreadBirth(); 304 } 305 } 306 if (thread_start_during_shutdown) { 307 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/InternalError")); 308 env->ThrowNew(error_class.get(), "Thread starting during runtime shutdown"); 309 return; 310 } 311 312 Thread* child_thread = new Thread(is_daemon); 313 // Use global JNI ref to hold peer live while child thread starts. 314 child_thread->tlsPtr_.jpeer = env->NewGlobalRef(java_peer); 315 stack_size = FixStackSize(stack_size); 316 317 // Thread.start is synchronized, so we know that nativePeer is 0, and know that we're not racing to 318 // assign it. 319 env->SetLongField(java_peer, WellKnownClasses::java_lang_Thread_nativePeer, 320 reinterpret_cast<jlong>(child_thread)); 321 322 pthread_t new_pthread; 323 pthread_attr_t attr; 324 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread"); 325 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED"); 326 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size); 327 int pthread_create_result = pthread_create(&new_pthread, &attr, Thread::CreateCallback, child_thread); 328 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread"); 329 330 if (pthread_create_result != 0) { 331 // pthread_create(3) failed, so clean up. 332 { 333 MutexLock mu(self, *Locks::runtime_shutdown_lock_); 334 runtime->EndThreadBirth(); 335 } 336 // Manually delete the global reference since Thread::Init will not have been run. 337 env->DeleteGlobalRef(child_thread->tlsPtr_.jpeer); 338 child_thread->tlsPtr_.jpeer = nullptr; 339 delete child_thread; 340 child_thread = nullptr; 341 // TODO: remove from thread group? 342 env->SetLongField(java_peer, WellKnownClasses::java_lang_Thread_nativePeer, 0); 343 { 344 std::string msg(StringPrintf("pthread_create (%s stack) failed: %s", 345 PrettySize(stack_size).c_str(), strerror(pthread_create_result))); 346 ScopedObjectAccess soa(env); 347 soa.Self()->ThrowOutOfMemoryError(msg.c_str()); 348 } 349 } 350} 351 352bool Thread::Init(ThreadList* thread_list, JavaVMExt* java_vm) { 353 // This function does all the initialization that must be run by the native thread it applies to. 354 // (When we create a new thread from managed code, we allocate the Thread* in Thread::Create so 355 // we can handshake with the corresponding native thread when it's ready.) Check this native 356 // thread hasn't been through here already... 357 CHECK(Thread::Current() == nullptr); 358 359 // Set pthread_self_ ahead of pthread_setspecific, that makes Thread::Current function, this 360 // avoids pthread_self_ ever being invalid when discovered from Thread::Current(). 361 tlsPtr_.pthread_self = pthread_self(); 362 CHECK(is_started_); 363 364 SetUpAlternateSignalStack(); 365 if (!InitStackHwm()) { 366 return false; 367 } 368 InitCpu(); 369 InitTlsEntryPoints(); 370 RemoveSuspendTrigger(); 371 InitCardTable(); 372 InitTid(); 373 374 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach self"); 375 DCHECK_EQ(Thread::Current(), this); 376 377 tls32_.thin_lock_thread_id = thread_list->AllocThreadId(this); 378 379 tlsPtr_.jni_env = new JNIEnvExt(this, java_vm); 380 thread_list->Register(this); 381 return true; 382} 383 384Thread* Thread::Attach(const char* thread_name, bool as_daemon, jobject thread_group, 385 bool create_peer) { 386 Runtime* runtime = Runtime::Current(); 387 if (runtime == nullptr) { 388 LOG(ERROR) << "Thread attaching to non-existent runtime: " << thread_name; 389 return nullptr; 390 } 391 Thread* self; 392 { 393 MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_); 394 if (runtime->IsShuttingDownLocked()) { 395 LOG(ERROR) << "Thread attaching while runtime is shutting down: " << thread_name; 396 return nullptr; 397 } else { 398 Runtime::Current()->StartThreadBirth(); 399 self = new Thread(as_daemon); 400 bool init_success = self->Init(runtime->GetThreadList(), runtime->GetJavaVM()); 401 Runtime::Current()->EndThreadBirth(); 402 if (!init_success) { 403 delete self; 404 return nullptr; 405 } 406 } 407 } 408 409 CHECK_NE(self->GetState(), kRunnable); 410 self->SetState(kNative); 411 412 // If we're the main thread, ClassLinker won't be created until after we're attached, 413 // so that thread needs a two-stage attach. Regular threads don't need this hack. 414 // In the compiler, all threads need this hack, because no-one's going to be getting 415 // a native peer! 416 if (create_peer) { 417 self->CreatePeer(thread_name, as_daemon, thread_group); 418 } else { 419 // These aren't necessary, but they improve diagnostics for unit tests & command-line tools. 420 if (thread_name != nullptr) { 421 self->tlsPtr_.name->assign(thread_name); 422 ::art::SetThreadName(thread_name); 423 } else if (self->GetJniEnv()->check_jni) { 424 LOG(WARNING) << *Thread::Current() << " attached without supplying a name"; 425 } 426 } 427 428 { 429 ScopedObjectAccess soa(self); 430 Dbg::PostThreadStart(self); 431 } 432 433 return self; 434} 435 436void Thread::CreatePeer(const char* name, bool as_daemon, jobject thread_group) { 437 Runtime* runtime = Runtime::Current(); 438 CHECK(runtime->IsStarted()); 439 JNIEnv* env = tlsPtr_.jni_env; 440 441 if (thread_group == nullptr) { 442 thread_group = runtime->GetMainThreadGroup(); 443 } 444 ScopedLocalRef<jobject> thread_name(env, env->NewStringUTF(name)); 445 // Add missing null check in case of OOM b/18297817 446 if (name != nullptr && thread_name.get() == nullptr) { 447 CHECK(IsExceptionPending()); 448 return; 449 } 450 jint thread_priority = GetNativePriority(); 451 jboolean thread_is_daemon = as_daemon; 452 453 ScopedLocalRef<jobject> peer(env, env->AllocObject(WellKnownClasses::java_lang_Thread)); 454 if (peer.get() == nullptr) { 455 CHECK(IsExceptionPending()); 456 return; 457 } 458 { 459 ScopedObjectAccess soa(this); 460 tlsPtr_.opeer = soa.Decode<mirror::Object*>(peer.get()); 461 } 462 env->CallNonvirtualVoidMethod(peer.get(), 463 WellKnownClasses::java_lang_Thread, 464 WellKnownClasses::java_lang_Thread_init, 465 thread_group, thread_name.get(), thread_priority, thread_is_daemon); 466 AssertNoPendingException(); 467 468 Thread* self = this; 469 DCHECK_EQ(self, Thread::Current()); 470 env->SetLongField(peer.get(), WellKnownClasses::java_lang_Thread_nativePeer, 471 reinterpret_cast<jlong>(self)); 472 473 ScopedObjectAccess soa(self); 474 StackHandleScope<1> hs(self); 475 MutableHandle<mirror::String> peer_thread_name(hs.NewHandle(GetThreadName(soa))); 476 if (peer_thread_name.Get() == nullptr) { 477 // The Thread constructor should have set the Thread.name to a 478 // non-null value. However, because we can run without code 479 // available (in the compiler, in tests), we manually assign the 480 // fields the constructor should have set. 481 if (runtime->IsActiveTransaction()) { 482 InitPeer<true>(soa, thread_is_daemon, thread_group, thread_name.get(), thread_priority); 483 } else { 484 InitPeer<false>(soa, thread_is_daemon, thread_group, thread_name.get(), thread_priority); 485 } 486 peer_thread_name.Assign(GetThreadName(soa)); 487 } 488 // 'thread_name' may have been null, so don't trust 'peer_thread_name' to be non-null. 489 if (peer_thread_name.Get() != nullptr) { 490 SetThreadName(peer_thread_name->ToModifiedUtf8().c_str()); 491 } 492} 493 494template<bool kTransactionActive> 495void Thread::InitPeer(ScopedObjectAccess& soa, jboolean thread_is_daemon, jobject thread_group, 496 jobject thread_name, jint thread_priority) { 497 soa.DecodeField(WellKnownClasses::java_lang_Thread_daemon)-> 498 SetBoolean<kTransactionActive>(tlsPtr_.opeer, thread_is_daemon); 499 soa.DecodeField(WellKnownClasses::java_lang_Thread_group)-> 500 SetObject<kTransactionActive>(tlsPtr_.opeer, soa.Decode<mirror::Object*>(thread_group)); 501 soa.DecodeField(WellKnownClasses::java_lang_Thread_name)-> 502 SetObject<kTransactionActive>(tlsPtr_.opeer, soa.Decode<mirror::Object*>(thread_name)); 503 soa.DecodeField(WellKnownClasses::java_lang_Thread_priority)-> 504 SetInt<kTransactionActive>(tlsPtr_.opeer, thread_priority); 505} 506 507void Thread::SetThreadName(const char* name) { 508 tlsPtr_.name->assign(name); 509 ::art::SetThreadName(name); 510 Dbg::DdmSendThreadNotification(this, CHUNK_TYPE("THNM")); 511} 512 513bool Thread::InitStackHwm() { 514 void* read_stack_base; 515 size_t read_stack_size; 516 size_t read_guard_size; 517 GetThreadStack(tlsPtr_.pthread_self, &read_stack_base, &read_stack_size, &read_guard_size); 518 519 tlsPtr_.stack_begin = reinterpret_cast<uint8_t*>(read_stack_base); 520 tlsPtr_.stack_size = read_stack_size; 521 522 // The minimum stack size we can cope with is the overflow reserved bytes (typically 523 // 8K) + the protected region size (4K) + another page (4K). Typically this will 524 // be 8+4+4 = 16K. The thread won't be able to do much with this stack even the GC takes 525 // between 8K and 12K. 526 uint32_t min_stack = GetStackOverflowReservedBytes(kRuntimeISA) + kStackOverflowProtectedSize 527 + 4 * KB; 528 if (read_stack_size <= min_stack) { 529 // Note, as we know the stack is small, avoid operations that could use a lot of stack. 530 LogMessage::LogLineLowStack(__PRETTY_FUNCTION__, __LINE__, ERROR, 531 "Attempt to attach a thread with a too-small stack"); 532 return false; 533 } 534 535 // This is included in the SIGQUIT output, but it's useful here for thread debugging. 536 VLOG(threads) << StringPrintf("Native stack is at %p (%s with %s guard)", 537 read_stack_base, 538 PrettySize(read_stack_size).c_str(), 539 PrettySize(read_guard_size).c_str()); 540 541 // Set stack_end_ to the bottom of the stack saving space of stack overflows 542 543 Runtime* runtime = Runtime::Current(); 544 bool implicit_stack_check = !runtime->ExplicitStackOverflowChecks() && !runtime->IsCompiler(); 545 ResetDefaultStackEnd(); 546 547 // Install the protected region if we are doing implicit overflow checks. 548 if (implicit_stack_check) { 549 // The thread might have protected region at the bottom. We need 550 // to install our own region so we need to move the limits 551 // of the stack to make room for it. 552 553 tlsPtr_.stack_begin += read_guard_size + kStackOverflowProtectedSize; 554 tlsPtr_.stack_end += read_guard_size + kStackOverflowProtectedSize; 555 tlsPtr_.stack_size -= read_guard_size; 556 557 InstallImplicitProtection(); 558 } 559 560 // Sanity check. 561 int stack_variable; 562 CHECK_GT(&stack_variable, reinterpret_cast<void*>(tlsPtr_.stack_end)); 563 564 return true; 565} 566 567void Thread::ShortDump(std::ostream& os) const { 568 os << "Thread["; 569 if (GetThreadId() != 0) { 570 // If we're in kStarting, we won't have a thin lock id or tid yet. 571 os << GetThreadId() 572 << ",tid=" << GetTid() << ','; 573 } 574 os << GetState() 575 << ",Thread*=" << this 576 << ",peer=" << tlsPtr_.opeer 577 << ",\"" << *tlsPtr_.name << "\"" 578 << "]"; 579} 580 581void Thread::Dump(std::ostream& os) const { 582 DumpState(os); 583 DumpStack(os); 584} 585 586mirror::String* Thread::GetThreadName(const ScopedObjectAccessAlreadyRunnable& soa) const { 587 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_name); 588 return (tlsPtr_.opeer != nullptr) ? reinterpret_cast<mirror::String*>(f->GetObject(tlsPtr_.opeer)) : nullptr; 589} 590 591void Thread::GetThreadName(std::string& name) const { 592 name.assign(*tlsPtr_.name); 593} 594 595uint64_t Thread::GetCpuMicroTime() const { 596#if defined(__linux__) 597 clockid_t cpu_clock_id; 598 pthread_getcpuclockid(tlsPtr_.pthread_self, &cpu_clock_id); 599 timespec now; 600 clock_gettime(cpu_clock_id, &now); 601 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_nsec / UINT64_C(1000); 602#else // __APPLE__ 603 UNIMPLEMENTED(WARNING); 604 return -1; 605#endif 606} 607 608// Attempt to rectify locks so that we dump thread list with required locks before exiting. 609static void UnsafeLogFatalForSuspendCount(Thread* self, Thread* thread) NO_THREAD_SAFETY_ANALYSIS { 610 LOG(ERROR) << *thread << " suspend count already zero."; 611 Locks::thread_suspend_count_lock_->Unlock(self); 612 if (!Locks::mutator_lock_->IsSharedHeld(self)) { 613 Locks::mutator_lock_->SharedTryLock(self); 614 if (!Locks::mutator_lock_->IsSharedHeld(self)) { 615 LOG(WARNING) << "Dumping thread list without holding mutator_lock_"; 616 } 617 } 618 if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) { 619 Locks::thread_list_lock_->TryLock(self); 620 if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) { 621 LOG(WARNING) << "Dumping thread list without holding thread_list_lock_"; 622 } 623 } 624 std::ostringstream ss; 625 Runtime::Current()->GetThreadList()->Dump(ss); 626 LOG(FATAL) << ss.str(); 627} 628 629void Thread::ModifySuspendCount(Thread* self, int delta, bool for_debugger) { 630 if (kIsDebugBuild) { 631 DCHECK(delta == -1 || delta == +1 || delta == -tls32_.debug_suspend_count) 632 << delta << " " << tls32_.debug_suspend_count << " " << this; 633 DCHECK_GE(tls32_.suspend_count, tls32_.debug_suspend_count) << this; 634 Locks::thread_suspend_count_lock_->AssertHeld(self); 635 if (this != self && !IsSuspended()) { 636 Locks::thread_list_lock_->AssertHeld(self); 637 } 638 } 639 if (UNLIKELY(delta < 0 && tls32_.suspend_count <= 0)) { 640 UnsafeLogFatalForSuspendCount(self, this); 641 return; 642 } 643 644 tls32_.suspend_count += delta; 645 if (for_debugger) { 646 tls32_.debug_suspend_count += delta; 647 } 648 649 if (tls32_.suspend_count == 0) { 650 AtomicClearFlag(kSuspendRequest); 651 } else { 652 AtomicSetFlag(kSuspendRequest); 653 TriggerSuspend(); 654 } 655} 656 657void Thread::RunCheckpointFunction() { 658 Closure *checkpoints[kMaxCheckpoints]; 659 660 // Grab the suspend_count lock and copy the current set of 661 // checkpoints. Then clear the list and the flag. The RequestCheckpoint 662 // function will also grab this lock so we prevent a race between setting 663 // the kCheckpointRequest flag and clearing it. 664 { 665 MutexLock mu(this, *Locks::thread_suspend_count_lock_); 666 for (uint32_t i = 0; i < kMaxCheckpoints; ++i) { 667 checkpoints[i] = tlsPtr_.checkpoint_functions[i]; 668 tlsPtr_.checkpoint_functions[i] = nullptr; 669 } 670 AtomicClearFlag(kCheckpointRequest); 671 } 672 673 // Outside the lock, run all the checkpoint functions that 674 // we collected. 675 bool found_checkpoint = false; 676 for (uint32_t i = 0; i < kMaxCheckpoints; ++i) { 677 if (checkpoints[i] != nullptr) { 678 ATRACE_BEGIN("Checkpoint function"); 679 checkpoints[i]->Run(this); 680 ATRACE_END(); 681 found_checkpoint = true; 682 } 683 } 684 CHECK(found_checkpoint); 685} 686 687bool Thread::RequestCheckpoint(Closure* function) { 688 union StateAndFlags old_state_and_flags; 689 old_state_and_flags.as_int = tls32_.state_and_flags.as_int; 690 if (old_state_and_flags.as_struct.state != kRunnable) { 691 return false; // Fail, thread is suspended and so can't run a checkpoint. 692 } 693 694 uint32_t available_checkpoint = kMaxCheckpoints; 695 for (uint32_t i = 0 ; i < kMaxCheckpoints; ++i) { 696 if (tlsPtr_.checkpoint_functions[i] == nullptr) { 697 available_checkpoint = i; 698 break; 699 } 700 } 701 if (available_checkpoint == kMaxCheckpoints) { 702 // No checkpoint functions available, we can't run a checkpoint 703 return false; 704 } 705 tlsPtr_.checkpoint_functions[available_checkpoint] = function; 706 707 // Checkpoint function installed now install flag bit. 708 // We must be runnable to request a checkpoint. 709 DCHECK_EQ(old_state_and_flags.as_struct.state, kRunnable); 710 union StateAndFlags new_state_and_flags; 711 new_state_and_flags.as_int = old_state_and_flags.as_int; 712 new_state_and_flags.as_struct.flags |= kCheckpointRequest; 713 bool success = 714 tls32_.state_and_flags.as_atomic_int.CompareExchangeStrongSequentiallyConsistent(old_state_and_flags.as_int, 715 new_state_and_flags.as_int); 716 if (UNLIKELY(!success)) { 717 // The thread changed state before the checkpoint was installed. 718 CHECK_EQ(tlsPtr_.checkpoint_functions[available_checkpoint], function); 719 tlsPtr_.checkpoint_functions[available_checkpoint] = nullptr; 720 } else { 721 CHECK_EQ(ReadFlag(kCheckpointRequest), true); 722 TriggerSuspend(); 723 } 724 return success; 725} 726 727Closure* Thread::GetFlipFunction() { 728 Atomic<Closure*>* atomic_func = reinterpret_cast<Atomic<Closure*>*>(&tlsPtr_.flip_function); 729 Closure* func; 730 do { 731 func = atomic_func->LoadRelaxed(); 732 if (func == nullptr) { 733 return nullptr; 734 } 735 } while (!atomic_func->CompareExchangeWeakSequentiallyConsistent(func, nullptr)); 736 DCHECK(func != nullptr); 737 return func; 738} 739 740void Thread::SetFlipFunction(Closure* function) { 741 CHECK(function != nullptr); 742 Atomic<Closure*>* atomic_func = reinterpret_cast<Atomic<Closure*>*>(&tlsPtr_.flip_function); 743 atomic_func->StoreSequentiallyConsistent(function); 744} 745 746void Thread::FullSuspendCheck() { 747 VLOG(threads) << this << " self-suspending"; 748 ATRACE_BEGIN("Full suspend check"); 749 // Make thread appear suspended to other threads, release mutator_lock_. 750 tls32_.suspended_at_suspend_check = true; 751 TransitionFromRunnableToSuspended(kSuspended); 752 // Transition back to runnable noting requests to suspend, re-acquire share on mutator_lock_. 753 TransitionFromSuspendedToRunnable(); 754 tls32_.suspended_at_suspend_check = false; 755 ATRACE_END(); 756 VLOG(threads) << this << " self-reviving"; 757} 758 759void Thread::DumpState(std::ostream& os, const Thread* thread, pid_t tid) { 760 std::string group_name; 761 int priority; 762 bool is_daemon = false; 763 Thread* self = Thread::Current(); 764 765 // If flip_function is not null, it means we have run a checkpoint 766 // before the thread wakes up to execute the flip function and the 767 // thread roots haven't been forwarded. So the following access to 768 // the roots (opeer or methods in the frames) would be bad. Run it 769 // here. TODO: clean up. 770 if (thread != nullptr) { 771 ScopedObjectAccessUnchecked soa(self); 772 Thread* this_thread = const_cast<Thread*>(thread); 773 Closure* flip_func = this_thread->GetFlipFunction(); 774 if (flip_func != nullptr) { 775 flip_func->Run(this_thread); 776 } 777 } 778 779 // Don't do this if we are aborting since the GC may have all the threads suspended. This will 780 // cause ScopedObjectAccessUnchecked to deadlock. 781 if (gAborting == 0 && self != nullptr && thread != nullptr && thread->tlsPtr_.opeer != nullptr) { 782 ScopedObjectAccessUnchecked soa(self); 783 priority = soa.DecodeField(WellKnownClasses::java_lang_Thread_priority) 784 ->GetInt(thread->tlsPtr_.opeer); 785 is_daemon = soa.DecodeField(WellKnownClasses::java_lang_Thread_daemon) 786 ->GetBoolean(thread->tlsPtr_.opeer); 787 788 mirror::Object* thread_group = 789 soa.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(thread->tlsPtr_.opeer); 790 791 if (thread_group != nullptr) { 792 mirror::ArtField* group_name_field = 793 soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_name); 794 mirror::String* group_name_string = 795 reinterpret_cast<mirror::String*>(group_name_field->GetObject(thread_group)); 796 group_name = (group_name_string != nullptr) ? group_name_string->ToModifiedUtf8() : "<null>"; 797 } 798 } else { 799 priority = GetNativePriority(); 800 } 801 802 std::string scheduler_group_name(GetSchedulerGroupName(tid)); 803 if (scheduler_group_name.empty()) { 804 scheduler_group_name = "default"; 805 } 806 807 if (thread != nullptr) { 808 os << '"' << *thread->tlsPtr_.name << '"'; 809 if (is_daemon) { 810 os << " daemon"; 811 } 812 os << " prio=" << priority 813 << " tid=" << thread->GetThreadId() 814 << " " << thread->GetState(); 815 if (thread->IsStillStarting()) { 816 os << " (still starting up)"; 817 } 818 os << "\n"; 819 } else { 820 os << '"' << ::art::GetThreadName(tid) << '"' 821 << " prio=" << priority 822 << " (not attached)\n"; 823 } 824 825 if (thread != nullptr) { 826 MutexLock mu(self, *Locks::thread_suspend_count_lock_); 827 os << " | group=\"" << group_name << "\"" 828 << " sCount=" << thread->tls32_.suspend_count 829 << " dsCount=" << thread->tls32_.debug_suspend_count 830 << " obj=" << reinterpret_cast<void*>(thread->tlsPtr_.opeer) 831 << " self=" << reinterpret_cast<const void*>(thread) << "\n"; 832 } 833 834 os << " | sysTid=" << tid 835 << " nice=" << getpriority(PRIO_PROCESS, tid) 836 << " cgrp=" << scheduler_group_name; 837 if (thread != nullptr) { 838 int policy; 839 sched_param sp; 840 CHECK_PTHREAD_CALL(pthread_getschedparam, (thread->tlsPtr_.pthread_self, &policy, &sp), 841 __FUNCTION__); 842 os << " sched=" << policy << "/" << sp.sched_priority 843 << " handle=" << reinterpret_cast<void*>(thread->tlsPtr_.pthread_self); 844 } 845 os << "\n"; 846 847 // Grab the scheduler stats for this thread. 848 std::string scheduler_stats; 849 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", tid), &scheduler_stats)) { 850 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'. 851 } else { 852 scheduler_stats = "0 0 0"; 853 } 854 855 char native_thread_state = '?'; 856 int utime = 0; 857 int stime = 0; 858 int task_cpu = 0; 859 GetTaskStats(tid, &native_thread_state, &utime, &stime, &task_cpu); 860 861 os << " | state=" << native_thread_state 862 << " schedstat=( " << scheduler_stats << " )" 863 << " utm=" << utime 864 << " stm=" << stime 865 << " core=" << task_cpu 866 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n"; 867 if (thread != nullptr) { 868 os << " | stack=" << reinterpret_cast<void*>(thread->tlsPtr_.stack_begin) << "-" 869 << reinterpret_cast<void*>(thread->tlsPtr_.stack_end) << " stackSize=" 870 << PrettySize(thread->tlsPtr_.stack_size) << "\n"; 871 // Dump the held mutexes. 872 os << " | held mutexes="; 873 for (size_t i = 0; i < kLockLevelCount; ++i) { 874 if (i != kMonitorLock) { 875 BaseMutex* mutex = thread->GetHeldMutex(static_cast<LockLevel>(i)); 876 if (mutex != nullptr) { 877 os << " \"" << mutex->GetName() << "\""; 878 if (mutex->IsReaderWriterMutex()) { 879 ReaderWriterMutex* rw_mutex = down_cast<ReaderWriterMutex*>(mutex); 880 if (rw_mutex->GetExclusiveOwnerTid() == static_cast<uint64_t>(tid)) { 881 os << "(exclusive held)"; 882 } else { 883 os << "(shared held)"; 884 } 885 } 886 } 887 } 888 } 889 os << "\n"; 890 } 891} 892 893void Thread::DumpState(std::ostream& os) const { 894 Thread::DumpState(os, this, GetTid()); 895} 896 897struct StackDumpVisitor : public StackVisitor { 898 StackDumpVisitor(std::ostream& os_in, Thread* thread_in, Context* context, bool can_allocate_in) 899 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 900 : StackVisitor(thread_in, context), os(os_in), thread(thread_in), 901 can_allocate(can_allocate_in), last_method(nullptr), last_line_number(0), 902 repetition_count(0), frame_count(0) { 903 } 904 905 virtual ~StackDumpVisitor() { 906 if (frame_count == 0) { 907 os << " (no managed stack frames)\n"; 908 } 909 } 910 911 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 912 mirror::ArtMethod* m = GetMethod(); 913 if (m->IsRuntimeMethod()) { 914 return true; 915 } 916 const int kMaxRepetition = 3; 917 mirror::Class* c = m->GetDeclaringClass(); 918 mirror::DexCache* dex_cache = c->GetDexCache(); 919 int line_number = -1; 920 if (dex_cache != nullptr) { // be tolerant of bad input 921 const DexFile& dex_file = *dex_cache->GetDexFile(); 922 line_number = dex_file.GetLineNumFromPC(m, GetDexPc(false)); 923 } 924 if (line_number == last_line_number && last_method == m) { 925 ++repetition_count; 926 } else { 927 if (repetition_count >= kMaxRepetition) { 928 os << " ... repeated " << (repetition_count - kMaxRepetition) << " times\n"; 929 } 930 repetition_count = 0; 931 last_line_number = line_number; 932 last_method = m; 933 } 934 if (repetition_count < kMaxRepetition) { 935 os << " at " << PrettyMethod(m, false); 936 if (m->IsNative()) { 937 os << "(Native method)"; 938 } else { 939 const char* source_file(m->GetDeclaringClassSourceFile()); 940 os << "(" << (source_file != nullptr ? source_file : "unavailable") 941 << ":" << line_number << ")"; 942 } 943 os << "\n"; 944 if (frame_count == 0) { 945 Monitor::DescribeWait(os, thread); 946 } 947 if (can_allocate) { 948 // Visit locks, but do not abort on errors. This would trigger a nested abort. 949 Monitor::VisitLocks(this, DumpLockedObject, &os, false); 950 } 951 } 952 953 ++frame_count; 954 return true; 955 } 956 957 static void DumpLockedObject(mirror::Object* o, void* context) 958 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 959 std::ostream& os = *reinterpret_cast<std::ostream*>(context); 960 os << " - locked "; 961 if (o == nullptr) { 962 os << "an unknown object"; 963 } else { 964 if ((o->GetLockWord(false).GetState() == LockWord::kThinLocked) && 965 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) { 966 // Getting the identity hashcode here would result in lock inflation and suspension of the 967 // current thread, which isn't safe if this is the only runnable thread. 968 os << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)", reinterpret_cast<intptr_t>(o), 969 PrettyTypeOf(o).c_str()); 970 } else { 971 // IdentityHashCode can cause thread suspension, which would invalidate o if it moved. So 972 // we get the pretty type beofre we call IdentityHashCode. 973 const std::string pretty_type(PrettyTypeOf(o)); 974 os << StringPrintf("<0x%08x> (a %s)", o->IdentityHashCode(), pretty_type.c_str()); 975 } 976 } 977 os << "\n"; 978 } 979 980 std::ostream& os; 981 const Thread* thread; 982 const bool can_allocate; 983 mirror::ArtMethod* last_method; 984 int last_line_number; 985 int repetition_count; 986 int frame_count; 987}; 988 989static bool ShouldShowNativeStack(const Thread* thread) 990 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 991 ThreadState state = thread->GetState(); 992 993 // In native code somewhere in the VM (one of the kWaitingFor* states)? That's interesting. 994 if (state > kWaiting && state < kStarting) { 995 return true; 996 } 997 998 // In an Object.wait variant or Thread.sleep? That's not interesting. 999 if (state == kTimedWaiting || state == kSleeping || state == kWaiting) { 1000 return false; 1001 } 1002 1003 // Threads with no managed stack frames should be shown. 1004 const ManagedStack* managed_stack = thread->GetManagedStack(); 1005 if (managed_stack == NULL || (managed_stack->GetTopQuickFrame() == NULL && 1006 managed_stack->GetTopShadowFrame() == NULL)) { 1007 return true; 1008 } 1009 1010 // In some other native method? That's interesting. 1011 // We don't just check kNative because native methods will be in state kSuspended if they're 1012 // calling back into the VM, or kBlocked if they're blocked on a monitor, or one of the 1013 // thread-startup states if it's early enough in their life cycle (http://b/7432159). 1014 mirror::ArtMethod* current_method = thread->GetCurrentMethod(nullptr); 1015 return current_method != nullptr && current_method->IsNative(); 1016} 1017 1018void Thread::DumpJavaStack(std::ostream& os) const { 1019 // If flip_function is not null, it means we have run a checkpoint 1020 // before the thread wakes up to execute the flip function and the 1021 // thread roots haven't been forwarded. So the following access to 1022 // the roots (locks or methods in the frames) would be bad. Run it 1023 // here. TODO: clean up. 1024 { 1025 Thread* this_thread = const_cast<Thread*>(this); 1026 Closure* flip_func = this_thread->GetFlipFunction(); 1027 if (flip_func != nullptr) { 1028 flip_func->Run(this_thread); 1029 } 1030 } 1031 1032 // Dumping the Java stack involves the verifier for locks. The verifier operates under the 1033 // assumption that there is no exception pending on entry. Thus, stash any pending exception. 1034 // Thread::Current() instead of this in case a thread is dumping the stack of another suspended 1035 // thread. 1036 StackHandleScope<3> scope(Thread::Current()); 1037 Handle<mirror::Throwable> exc; 1038 Handle<mirror::Object> throw_location_this_object; 1039 Handle<mirror::ArtMethod> throw_location_method; 1040 uint32_t throw_location_dex_pc; 1041 bool have_exception = false; 1042 if (IsExceptionPending()) { 1043 ThrowLocation exc_location; 1044 exc = scope.NewHandle(GetException(&exc_location)); 1045 throw_location_this_object = scope.NewHandle(exc_location.GetThis()); 1046 throw_location_method = scope.NewHandle(exc_location.GetMethod()); 1047 throw_location_dex_pc = exc_location.GetDexPc(); 1048 const_cast<Thread*>(this)->ClearException(); 1049 have_exception = true; 1050 } 1051 1052 std::unique_ptr<Context> context(Context::Create()); 1053 StackDumpVisitor dumper(os, const_cast<Thread*>(this), context.get(), 1054 !tls32_.throwing_OutOfMemoryError); 1055 dumper.WalkStack(); 1056 1057 if (have_exception) { 1058 ThrowLocation exc_location(throw_location_this_object.Get(), 1059 throw_location_method.Get(), 1060 throw_location_dex_pc); 1061 const_cast<Thread*>(this)->SetException(exc_location, exc.Get()); 1062 } 1063} 1064 1065void Thread::DumpStack(std::ostream& os) const { 1066 // TODO: we call this code when dying but may not have suspended the thread ourself. The 1067 // IsSuspended check is therefore racy with the use for dumping (normally we inhibit 1068 // the race with the thread_suspend_count_lock_). 1069 bool dump_for_abort = (gAborting > 0); 1070 bool safe_to_dump = (this == Thread::Current() || IsSuspended()); 1071 if (!kIsDebugBuild) { 1072 // We always want to dump the stack for an abort, however, there is no point dumping another 1073 // thread's stack in debug builds where we'll hit the not suspended check in the stack walk. 1074 safe_to_dump = (safe_to_dump || dump_for_abort); 1075 } 1076 if (safe_to_dump) { 1077 // If we're currently in native code, dump that stack before dumping the managed stack. 1078 if (dump_for_abort || ShouldShowNativeStack(this)) { 1079 DumpKernelStack(os, GetTid(), " kernel: ", false); 1080 DumpNativeStack(os, GetTid(), " native: ", GetCurrentMethod(nullptr, !dump_for_abort)); 1081 } 1082 DumpJavaStack(os); 1083 } else { 1084 os << "Not able to dump stack of thread that isn't suspended"; 1085 } 1086} 1087 1088void Thread::ThreadExitCallback(void* arg) { 1089 Thread* self = reinterpret_cast<Thread*>(arg); 1090 if (self->tls32_.thread_exit_check_count == 0) { 1091 LOG(WARNING) << "Native thread exiting without having called DetachCurrentThread (maybe it's " 1092 "going to use a pthread_key_create destructor?): " << *self; 1093 CHECK(is_started_); 1094 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, self), "reattach self"); 1095 self->tls32_.thread_exit_check_count = 1; 1096 } else { 1097 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self; 1098 } 1099} 1100 1101void Thread::Startup() { 1102 CHECK(!is_started_); 1103 is_started_ = true; 1104 { 1105 // MutexLock to keep annotalysis happy. 1106 // 1107 // Note we use nullptr for the thread because Thread::Current can 1108 // return garbage since (is_started_ == true) and 1109 // Thread::pthread_key_self_ is not yet initialized. 1110 // This was seen on glibc. 1111 MutexLock mu(nullptr, *Locks::thread_suspend_count_lock_); 1112 resume_cond_ = new ConditionVariable("Thread resumption condition variable", 1113 *Locks::thread_suspend_count_lock_); 1114 } 1115 1116 // Allocate a TLS slot. 1117 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), 1118 "self key"); 1119 1120 // Double-check the TLS slot allocation. 1121 if (pthread_getspecific(pthread_key_self_) != nullptr) { 1122 LOG(FATAL) << "Newly-created pthread TLS slot is not nullptr"; 1123 } 1124} 1125 1126void Thread::FinishStartup() { 1127 Runtime* runtime = Runtime::Current(); 1128 CHECK(runtime->IsStarted()); 1129 1130 // Finish attaching the main thread. 1131 ScopedObjectAccess soa(Thread::Current()); 1132 Thread::Current()->CreatePeer("main", false, runtime->GetMainThreadGroup()); 1133 1134 Runtime::Current()->GetClassLinker()->RunRootClinits(); 1135} 1136 1137void Thread::Shutdown() { 1138 CHECK(is_started_); 1139 is_started_ = false; 1140 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key"); 1141 MutexLock mu(Thread::Current(), *Locks::thread_suspend_count_lock_); 1142 if (resume_cond_ != nullptr) { 1143 delete resume_cond_; 1144 resume_cond_ = nullptr; 1145 } 1146} 1147 1148Thread::Thread(bool daemon) : tls32_(daemon), wait_monitor_(nullptr), interrupted_(false) { 1149 wait_mutex_ = new Mutex("a thread wait mutex"); 1150 wait_cond_ = new ConditionVariable("a thread wait condition variable", *wait_mutex_); 1151 tlsPtr_.debug_invoke_req = new DebugInvokeReq; 1152 tlsPtr_.single_step_control = nullptr; 1153 tlsPtr_.instrumentation_stack = new std::deque<instrumentation::InstrumentationStackFrame>; 1154 tlsPtr_.name = new std::string(kThreadNameDuringStartup); 1155 tlsPtr_.nested_signal_state = static_cast<jmp_buf*>(malloc(sizeof(jmp_buf))); 1156 1157 CHECK_EQ((sizeof(Thread) % 4), 0U) << sizeof(Thread); 1158 tls32_.state_and_flags.as_struct.flags = 0; 1159 tls32_.state_and_flags.as_struct.state = kNative; 1160 memset(&tlsPtr_.held_mutexes[0], 0, sizeof(tlsPtr_.held_mutexes)); 1161 std::fill(tlsPtr_.rosalloc_runs, 1162 tlsPtr_.rosalloc_runs + kNumRosAllocThreadLocalSizeBrackets, 1163 gc::allocator::RosAlloc::GetDedicatedFullRun()); 1164 for (uint32_t i = 0; i < kMaxCheckpoints; ++i) { 1165 tlsPtr_.checkpoint_functions[i] = nullptr; 1166 } 1167 tlsPtr_.flip_function = nullptr; 1168 tls32_.suspended_at_suspend_check = false; 1169} 1170 1171bool Thread::IsStillStarting() const { 1172 // You might think you can check whether the state is kStarting, but for much of thread startup, 1173 // the thread is in kNative; it might also be in kVmWait. 1174 // You might think you can check whether the peer is nullptr, but the peer is actually created and 1175 // assigned fairly early on, and needs to be. 1176 // It turns out that the last thing to change is the thread name; that's a good proxy for "has 1177 // this thread _ever_ entered kRunnable". 1178 return (tlsPtr_.jpeer == nullptr && tlsPtr_.opeer == nullptr) || 1179 (*tlsPtr_.name == kThreadNameDuringStartup); 1180} 1181 1182void Thread::AssertPendingException() const { 1183 if (UNLIKELY(!IsExceptionPending())) { 1184 LOG(FATAL) << "Pending exception expected."; 1185 } 1186} 1187 1188void Thread::AssertNoPendingException() const { 1189 if (UNLIKELY(IsExceptionPending())) { 1190 ScopedObjectAccess soa(Thread::Current()); 1191 mirror::Throwable* exception = GetException(nullptr); 1192 LOG(FATAL) << "No pending exception expected: " << exception->Dump(); 1193 } 1194} 1195 1196void Thread::AssertNoPendingExceptionForNewException(const char* msg) const { 1197 if (UNLIKELY(IsExceptionPending())) { 1198 ScopedObjectAccess soa(Thread::Current()); 1199 mirror::Throwable* exception = GetException(nullptr); 1200 LOG(FATAL) << "Throwing new exception '" << msg << "' with unexpected pending exception: " 1201 << exception->Dump(); 1202 } 1203} 1204 1205static void MonitorExitVisitor(mirror::Object** object, void* arg, const RootInfo& /*root_info*/) 1206 NO_THREAD_SAFETY_ANALYSIS { 1207 Thread* self = reinterpret_cast<Thread*>(arg); 1208 mirror::Object* entered_monitor = *object; 1209 if (self->HoldsLock(entered_monitor)) { 1210 LOG(WARNING) << "Calling MonitorExit on object " 1211 << object << " (" << PrettyTypeOf(entered_monitor) << ")" 1212 << " left locked by native thread " 1213 << *Thread::Current() << " which is detaching"; 1214 entered_monitor->MonitorExit(self); 1215 } 1216} 1217 1218void Thread::Destroy() { 1219 Thread* self = this; 1220 DCHECK_EQ(self, Thread::Current()); 1221 1222 if (tlsPtr_.jni_env != nullptr) { 1223 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited. 1224 tlsPtr_.jni_env->monitors.VisitRoots(MonitorExitVisitor, self, RootInfo(kRootVMInternal)); 1225 // Release locally held global references which releasing may require the mutator lock. 1226 if (tlsPtr_.jpeer != nullptr) { 1227 // If pthread_create fails we don't have a jni env here. 1228 tlsPtr_.jni_env->DeleteGlobalRef(tlsPtr_.jpeer); 1229 tlsPtr_.jpeer = nullptr; 1230 } 1231 if (tlsPtr_.class_loader_override != nullptr) { 1232 tlsPtr_.jni_env->DeleteGlobalRef(tlsPtr_.class_loader_override); 1233 tlsPtr_.class_loader_override = nullptr; 1234 } 1235 } 1236 1237 if (tlsPtr_.opeer != nullptr) { 1238 ScopedObjectAccess soa(self); 1239 // We may need to call user-supplied managed code, do this before final clean-up. 1240 HandleUncaughtExceptions(soa); 1241 RemoveFromThreadGroup(soa); 1242 1243 // this.nativePeer = 0; 1244 if (Runtime::Current()->IsActiveTransaction()) { 1245 soa.DecodeField(WellKnownClasses::java_lang_Thread_nativePeer) 1246 ->SetLong<true>(tlsPtr_.opeer, 0); 1247 } else { 1248 soa.DecodeField(WellKnownClasses::java_lang_Thread_nativePeer) 1249 ->SetLong<false>(tlsPtr_.opeer, 0); 1250 } 1251 Dbg::PostThreadDeath(self); 1252 1253 // Thread.join() is implemented as an Object.wait() on the Thread.lock object. Signal anyone 1254 // who is waiting. 1255 mirror::Object* lock = 1256 soa.DecodeField(WellKnownClasses::java_lang_Thread_lock)->GetObject(tlsPtr_.opeer); 1257 // (This conditional is only needed for tests, where Thread.lock won't have been set.) 1258 if (lock != nullptr) { 1259 StackHandleScope<1> hs(self); 1260 Handle<mirror::Object> h_obj(hs.NewHandle(lock)); 1261 ObjectLock<mirror::Object> locker(self, h_obj); 1262 locker.NotifyAll(); 1263 } 1264 tlsPtr_.opeer = nullptr; 1265 } 1266 1267 { 1268 ScopedObjectAccess soa(self); 1269 Runtime::Current()->GetHeap()->RevokeThreadLocalBuffers(this); 1270 } 1271} 1272 1273Thread::~Thread() { 1274 CHECK(tlsPtr_.class_loader_override == nullptr); 1275 CHECK(tlsPtr_.jpeer == nullptr); 1276 CHECK(tlsPtr_.opeer == nullptr); 1277 bool initialized = (tlsPtr_.jni_env != nullptr); // Did Thread::Init run? 1278 if (initialized) { 1279 delete tlsPtr_.jni_env; 1280 tlsPtr_.jni_env = nullptr; 1281 } 1282 CHECK_NE(GetState(), kRunnable); 1283 CHECK_NE(ReadFlag(kCheckpointRequest), true); 1284 CHECK(tlsPtr_.checkpoint_functions[0] == nullptr); 1285 CHECK(tlsPtr_.checkpoint_functions[1] == nullptr); 1286 CHECK(tlsPtr_.checkpoint_functions[2] == nullptr); 1287 CHECK(tlsPtr_.flip_function == nullptr); 1288 CHECK_EQ(tls32_.suspended_at_suspend_check, false); 1289 1290 // We may be deleting a still born thread. 1291 SetStateUnsafe(kTerminated); 1292 1293 delete wait_cond_; 1294 delete wait_mutex_; 1295 1296 if (tlsPtr_.long_jump_context != nullptr) { 1297 delete tlsPtr_.long_jump_context; 1298 } 1299 1300 if (initialized) { 1301 CleanupCpu(); 1302 } 1303 1304 delete tlsPtr_.debug_invoke_req; 1305 if (tlsPtr_.single_step_control != nullptr) { 1306 delete tlsPtr_.single_step_control; 1307 } 1308 delete tlsPtr_.instrumentation_stack; 1309 delete tlsPtr_.name; 1310 delete tlsPtr_.stack_trace_sample; 1311 free(tlsPtr_.nested_signal_state); 1312 1313 Runtime::Current()->GetHeap()->AssertThreadLocalBuffersAreRevoked(this); 1314 1315 TearDownAlternateSignalStack(); 1316} 1317 1318void Thread::HandleUncaughtExceptions(ScopedObjectAccess& soa) { 1319 if (!IsExceptionPending()) { 1320 return; 1321 } 1322 ScopedLocalRef<jobject> peer(tlsPtr_.jni_env, soa.AddLocalReference<jobject>(tlsPtr_.opeer)); 1323 ScopedThreadStateChange tsc(this, kNative); 1324 1325 // Get and clear the exception. 1326 ScopedLocalRef<jthrowable> exception(tlsPtr_.jni_env, tlsPtr_.jni_env->ExceptionOccurred()); 1327 tlsPtr_.jni_env->ExceptionClear(); 1328 1329 // If the thread has its own handler, use that. 1330 ScopedLocalRef<jobject> handler(tlsPtr_.jni_env, 1331 tlsPtr_.jni_env->GetObjectField(peer.get(), 1332 WellKnownClasses::java_lang_Thread_uncaughtHandler)); 1333 if (handler.get() == nullptr) { 1334 // Otherwise use the thread group's default handler. 1335 handler.reset(tlsPtr_.jni_env->GetObjectField(peer.get(), 1336 WellKnownClasses::java_lang_Thread_group)); 1337 } 1338 1339 // Call the handler. 1340 tlsPtr_.jni_env->CallVoidMethod(handler.get(), 1341 WellKnownClasses::java_lang_Thread__UncaughtExceptionHandler_uncaughtException, 1342 peer.get(), exception.get()); 1343 1344 // If the handler threw, clear that exception too. 1345 tlsPtr_.jni_env->ExceptionClear(); 1346} 1347 1348void Thread::RemoveFromThreadGroup(ScopedObjectAccess& soa) { 1349 // this.group.removeThread(this); 1350 // group can be null if we're in the compiler or a test. 1351 mirror::Object* ogroup = soa.DecodeField(WellKnownClasses::java_lang_Thread_group) 1352 ->GetObject(tlsPtr_.opeer); 1353 if (ogroup != nullptr) { 1354 ScopedLocalRef<jobject> group(soa.Env(), soa.AddLocalReference<jobject>(ogroup)); 1355 ScopedLocalRef<jobject> peer(soa.Env(), soa.AddLocalReference<jobject>(tlsPtr_.opeer)); 1356 ScopedThreadStateChange tsc(soa.Self(), kNative); 1357 tlsPtr_.jni_env->CallVoidMethod(group.get(), 1358 WellKnownClasses::java_lang_ThreadGroup_removeThread, 1359 peer.get()); 1360 } 1361} 1362 1363size_t Thread::NumHandleReferences() { 1364 size_t count = 0; 1365 for (HandleScope* cur = tlsPtr_.top_handle_scope; cur != nullptr; cur = cur->GetLink()) { 1366 count += cur->NumberOfReferences(); 1367 } 1368 return count; 1369} 1370 1371bool Thread::HandleScopeContains(jobject obj) const { 1372 StackReference<mirror::Object>* hs_entry = 1373 reinterpret_cast<StackReference<mirror::Object>*>(obj); 1374 for (HandleScope* cur = tlsPtr_.top_handle_scope; cur!= nullptr; cur = cur->GetLink()) { 1375 if (cur->Contains(hs_entry)) { 1376 return true; 1377 } 1378 } 1379 // JNI code invoked from portable code uses shadow frames rather than the handle scope. 1380 return tlsPtr_.managed_stack.ShadowFramesContain(hs_entry); 1381} 1382 1383void Thread::HandleScopeVisitRoots(RootCallback* visitor, void* arg, uint32_t thread_id) { 1384 for (HandleScope* cur = tlsPtr_.top_handle_scope; cur; cur = cur->GetLink()) { 1385 size_t num_refs = cur->NumberOfReferences(); 1386 for (size_t j = 0; j < num_refs; ++j) { 1387 mirror::Object* object = cur->GetReference(j); 1388 if (object != nullptr) { 1389 mirror::Object* old_obj = object; 1390 visitor(&object, arg, RootInfo(kRootNativeStack, thread_id)); 1391 if (old_obj != object) { 1392 cur->SetReference(j, object); 1393 } 1394 } 1395 } 1396 } 1397} 1398 1399mirror::Object* Thread::DecodeJObject(jobject obj) const { 1400 if (obj == nullptr) { 1401 return nullptr; 1402 } 1403 IndirectRef ref = reinterpret_cast<IndirectRef>(obj); 1404 IndirectRefKind kind = GetIndirectRefKind(ref); 1405 mirror::Object* result; 1406 bool expect_null = false; 1407 // The "kinds" below are sorted by the frequency we expect to encounter them. 1408 if (kind == kLocal) { 1409 IndirectReferenceTable& locals = tlsPtr_.jni_env->locals; 1410 // Local references do not need a read barrier. 1411 result = locals.Get<kWithoutReadBarrier>(ref); 1412 } else if (kind == kHandleScopeOrInvalid) { 1413 // TODO: make stack indirect reference table lookup more efficient. 1414 // Check if this is a local reference in the handle scope. 1415 if (LIKELY(HandleScopeContains(obj))) { 1416 // Read from handle scope. 1417 result = reinterpret_cast<StackReference<mirror::Object>*>(obj)->AsMirrorPtr(); 1418 VerifyObject(result); 1419 } else { 1420 tlsPtr_.jni_env->vm->JniAbortF(nullptr, "use of invalid jobject %p", obj); 1421 expect_null = true; 1422 result = nullptr; 1423 } 1424 } else if (kind == kGlobal) { 1425 result = tlsPtr_.jni_env->vm->DecodeGlobal(const_cast<Thread*>(this), ref); 1426 } else { 1427 DCHECK_EQ(kind, kWeakGlobal); 1428 result = tlsPtr_.jni_env->vm->DecodeWeakGlobal(const_cast<Thread*>(this), ref); 1429 if (Runtime::Current()->IsClearedJniWeakGlobal(result)) { 1430 // This is a special case where it's okay to return nullptr. 1431 expect_null = true; 1432 result = nullptr; 1433 } 1434 } 1435 1436 if (UNLIKELY(!expect_null && result == nullptr)) { 1437 tlsPtr_.jni_env->vm->JniAbortF(nullptr, "use of deleted %s %p", 1438 ToStr<IndirectRefKind>(kind).c_str(), obj); 1439 } 1440 return result; 1441} 1442 1443// Implements java.lang.Thread.interrupted. 1444bool Thread::Interrupted() { 1445 MutexLock mu(Thread::Current(), *wait_mutex_); 1446 bool interrupted = IsInterruptedLocked(); 1447 SetInterruptedLocked(false); 1448 return interrupted; 1449} 1450 1451// Implements java.lang.Thread.isInterrupted. 1452bool Thread::IsInterrupted() { 1453 MutexLock mu(Thread::Current(), *wait_mutex_); 1454 return IsInterruptedLocked(); 1455} 1456 1457void Thread::Interrupt(Thread* self) { 1458 MutexLock mu(self, *wait_mutex_); 1459 if (interrupted_) { 1460 return; 1461 } 1462 interrupted_ = true; 1463 NotifyLocked(self); 1464} 1465 1466void Thread::Notify() { 1467 Thread* self = Thread::Current(); 1468 MutexLock mu(self, *wait_mutex_); 1469 NotifyLocked(self); 1470} 1471 1472void Thread::NotifyLocked(Thread* self) { 1473 if (wait_monitor_ != nullptr) { 1474 wait_cond_->Signal(self); 1475 } 1476} 1477 1478void Thread::SetClassLoaderOverride(jobject class_loader_override) { 1479 if (tlsPtr_.class_loader_override != nullptr) { 1480 GetJniEnv()->DeleteGlobalRef(tlsPtr_.class_loader_override); 1481 } 1482 tlsPtr_.class_loader_override = GetJniEnv()->NewGlobalRef(class_loader_override); 1483} 1484 1485class CountStackDepthVisitor : public StackVisitor { 1486 public: 1487 explicit CountStackDepthVisitor(Thread* thread) 1488 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 1489 : StackVisitor(thread, nullptr), 1490 depth_(0), skip_depth_(0), skipping_(true) {} 1491 1492 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 1493 // We want to skip frames up to and including the exception's constructor. 1494 // Note we also skip the frame if it doesn't have a method (namely the callee 1495 // save frame) 1496 mirror::ArtMethod* m = GetMethod(); 1497 if (skipping_ && !m->IsRuntimeMethod() && 1498 !mirror::Throwable::GetJavaLangThrowable()->IsAssignableFrom(m->GetDeclaringClass())) { 1499 skipping_ = false; 1500 } 1501 if (!skipping_) { 1502 if (!m->IsRuntimeMethod()) { // Ignore runtime frames (in particular callee save). 1503 ++depth_; 1504 } 1505 } else { 1506 ++skip_depth_; 1507 } 1508 return true; 1509 } 1510 1511 int GetDepth() const { 1512 return depth_; 1513 } 1514 1515 int GetSkipDepth() const { 1516 return skip_depth_; 1517 } 1518 1519 private: 1520 uint32_t depth_; 1521 uint32_t skip_depth_; 1522 bool skipping_; 1523}; 1524 1525template<bool kTransactionActive> 1526class BuildInternalStackTraceVisitor : public StackVisitor { 1527 public: 1528 explicit BuildInternalStackTraceVisitor(Thread* self, Thread* thread, int skip_depth) 1529 : StackVisitor(thread, nullptr), self_(self), 1530 skip_depth_(skip_depth), count_(0), dex_pc_trace_(nullptr), method_trace_(nullptr) {} 1531 1532 bool Init(int depth) 1533 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 1534 // Allocate method trace with an extra slot that will hold the PC trace 1535 StackHandleScope<1> hs(self_); 1536 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 1537 Handle<mirror::ObjectArray<mirror::Object>> method_trace( 1538 hs.NewHandle(class_linker->AllocObjectArray<mirror::Object>(self_, depth + 1))); 1539 if (method_trace.Get() == nullptr) { 1540 return false; 1541 } 1542 mirror::IntArray* dex_pc_trace = mirror::IntArray::Alloc(self_, depth); 1543 if (dex_pc_trace == nullptr) { 1544 return false; 1545 } 1546 // Save PC trace in last element of method trace, also places it into the 1547 // object graph. 1548 // We are called from native: use non-transactional mode. 1549 method_trace->Set<kTransactionActive>(depth, dex_pc_trace); 1550 // Set the Object*s and assert that no thread suspension is now possible. 1551 const char* last_no_suspend_cause = 1552 self_->StartAssertNoThreadSuspension("Building internal stack trace"); 1553 CHECK(last_no_suspend_cause == nullptr) << last_no_suspend_cause; 1554 method_trace_ = method_trace.Get(); 1555 dex_pc_trace_ = dex_pc_trace; 1556 return true; 1557 } 1558 1559 virtual ~BuildInternalStackTraceVisitor() { 1560 if (method_trace_ != nullptr) { 1561 self_->EndAssertNoThreadSuspension(nullptr); 1562 } 1563 } 1564 1565 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 1566 if (method_trace_ == nullptr || dex_pc_trace_ == nullptr) { 1567 return true; // We're probably trying to fillInStackTrace for an OutOfMemoryError. 1568 } 1569 if (skip_depth_ > 0) { 1570 skip_depth_--; 1571 return true; 1572 } 1573 mirror::ArtMethod* m = GetMethod(); 1574 if (m->IsRuntimeMethod()) { 1575 return true; // Ignore runtime frames (in particular callee save). 1576 } 1577 method_trace_->Set<kTransactionActive>(count_, m); 1578 dex_pc_trace_->Set<kTransactionActive>(count_, 1579 m->IsProxyMethod() ? DexFile::kDexNoIndex : GetDexPc()); 1580 ++count_; 1581 return true; 1582 } 1583 1584 mirror::ObjectArray<mirror::Object>* GetInternalStackTrace() const { 1585 return method_trace_; 1586 } 1587 1588 private: 1589 Thread* const self_; 1590 // How many more frames to skip. 1591 int32_t skip_depth_; 1592 // Current position down stack trace. 1593 uint32_t count_; 1594 // Array of dex PC values. 1595 mirror::IntArray* dex_pc_trace_; 1596 // An array of the methods on the stack, the last entry is a reference to the PC trace. 1597 mirror::ObjectArray<mirror::Object>* method_trace_; 1598}; 1599 1600template<bool kTransactionActive> 1601jobject Thread::CreateInternalStackTrace(const ScopedObjectAccessAlreadyRunnable& soa) const { 1602 // Compute depth of stack 1603 CountStackDepthVisitor count_visitor(const_cast<Thread*>(this)); 1604 count_visitor.WalkStack(); 1605 int32_t depth = count_visitor.GetDepth(); 1606 int32_t skip_depth = count_visitor.GetSkipDepth(); 1607 1608 // Build internal stack trace. 1609 BuildInternalStackTraceVisitor<kTransactionActive> build_trace_visitor(soa.Self(), 1610 const_cast<Thread*>(this), 1611 skip_depth); 1612 if (!build_trace_visitor.Init(depth)) { 1613 return nullptr; // Allocation failed. 1614 } 1615 build_trace_visitor.WalkStack(); 1616 mirror::ObjectArray<mirror::Object>* trace = build_trace_visitor.GetInternalStackTrace(); 1617 if (kIsDebugBuild) { 1618 for (int32_t i = 0; i < trace->GetLength(); ++i) { 1619 CHECK(trace->Get(i) != nullptr); 1620 } 1621 } 1622 return soa.AddLocalReference<jobjectArray>(trace); 1623} 1624template jobject Thread::CreateInternalStackTrace<false>( 1625 const ScopedObjectAccessAlreadyRunnable& soa) const; 1626template jobject Thread::CreateInternalStackTrace<true>( 1627 const ScopedObjectAccessAlreadyRunnable& soa) const; 1628 1629jobjectArray Thread::InternalStackTraceToStackTraceElementArray( 1630 const ScopedObjectAccessAlreadyRunnable& soa, jobject internal, jobjectArray output_array, 1631 int* stack_depth) { 1632 // Decode the internal stack trace into the depth, method trace and PC trace 1633 int32_t depth = soa.Decode<mirror::ObjectArray<mirror::Object>*>(internal)->GetLength() - 1; 1634 1635 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 1636 1637 jobjectArray result; 1638 1639 if (output_array != nullptr) { 1640 // Reuse the array we were given. 1641 result = output_array; 1642 // ...adjusting the number of frames we'll write to not exceed the array length. 1643 const int32_t traces_length = 1644 soa.Decode<mirror::ObjectArray<mirror::StackTraceElement>*>(result)->GetLength(); 1645 depth = std::min(depth, traces_length); 1646 } else { 1647 // Create java_trace array and place in local reference table 1648 mirror::ObjectArray<mirror::StackTraceElement>* java_traces = 1649 class_linker->AllocStackTraceElementArray(soa.Self(), depth); 1650 if (java_traces == nullptr) { 1651 return nullptr; 1652 } 1653 result = soa.AddLocalReference<jobjectArray>(java_traces); 1654 } 1655 1656 if (stack_depth != nullptr) { 1657 *stack_depth = depth; 1658 } 1659 1660 for (int32_t i = 0; i < depth; ++i) { 1661 mirror::ObjectArray<mirror::Object>* method_trace = 1662 soa.Decode<mirror::ObjectArray<mirror::Object>*>(internal); 1663 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line) 1664 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(method_trace->Get(i)); 1665 int32_t line_number; 1666 StackHandleScope<3> hs(soa.Self()); 1667 auto class_name_object(hs.NewHandle<mirror::String>(nullptr)); 1668 auto source_name_object(hs.NewHandle<mirror::String>(nullptr)); 1669 if (method->IsProxyMethod()) { 1670 line_number = -1; 1671 class_name_object.Assign(method->GetDeclaringClass()->GetName()); 1672 // source_name_object intentionally left null for proxy methods 1673 } else { 1674 mirror::IntArray* pc_trace = down_cast<mirror::IntArray*>(method_trace->Get(depth)); 1675 uint32_t dex_pc = pc_trace->Get(i); 1676 line_number = method->GetLineNumFromDexPC(dex_pc); 1677 // Allocate element, potentially triggering GC 1678 // TODO: reuse class_name_object via Class::name_? 1679 const char* descriptor = method->GetDeclaringClassDescriptor(); 1680 CHECK(descriptor != nullptr); 1681 std::string class_name(PrettyDescriptor(descriptor)); 1682 class_name_object.Assign(mirror::String::AllocFromModifiedUtf8(soa.Self(), class_name.c_str())); 1683 if (class_name_object.Get() == nullptr) { 1684 return nullptr; 1685 } 1686 const char* source_file = method->GetDeclaringClassSourceFile(); 1687 if (source_file != nullptr) { 1688 source_name_object.Assign(mirror::String::AllocFromModifiedUtf8(soa.Self(), source_file)); 1689 if (source_name_object.Get() == nullptr) { 1690 return nullptr; 1691 } 1692 } 1693 } 1694 const char* method_name = method->GetName(); 1695 CHECK(method_name != nullptr); 1696 Handle<mirror::String> method_name_object( 1697 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(soa.Self(), method_name))); 1698 if (method_name_object.Get() == nullptr) { 1699 return nullptr; 1700 } 1701 mirror::StackTraceElement* obj = mirror::StackTraceElement::Alloc( 1702 soa.Self(), class_name_object, method_name_object, source_name_object, line_number); 1703 if (obj == nullptr) { 1704 return nullptr; 1705 } 1706 // We are called from native: use non-transactional mode. 1707 soa.Decode<mirror::ObjectArray<mirror::StackTraceElement>*>(result)->Set<false>(i, obj); 1708 } 1709 return result; 1710} 1711 1712void Thread::ThrowNewExceptionF(const ThrowLocation& throw_location, 1713 const char* exception_class_descriptor, const char* fmt, ...) { 1714 va_list args; 1715 va_start(args, fmt); 1716 ThrowNewExceptionV(throw_location, exception_class_descriptor, 1717 fmt, args); 1718 va_end(args); 1719} 1720 1721void Thread::ThrowNewExceptionV(const ThrowLocation& throw_location, 1722 const char* exception_class_descriptor, 1723 const char* fmt, va_list ap) { 1724 std::string msg; 1725 StringAppendV(&msg, fmt, ap); 1726 ThrowNewException(throw_location, exception_class_descriptor, msg.c_str()); 1727} 1728 1729void Thread::ThrowNewException(const ThrowLocation& throw_location, 1730 const char* exception_class_descriptor, 1731 const char* msg) { 1732 // Callers should either clear or call ThrowNewWrappedException. 1733 AssertNoPendingExceptionForNewException(msg); 1734 ThrowNewWrappedException(throw_location, exception_class_descriptor, msg); 1735} 1736 1737void Thread::ThrowNewWrappedException(const ThrowLocation& throw_location, 1738 const char* exception_class_descriptor, 1739 const char* msg) { 1740 DCHECK_EQ(this, Thread::Current()); 1741 ScopedObjectAccessUnchecked soa(this); 1742 StackHandleScope<5> hs(soa.Self()); 1743 // Ensure we don't forget arguments over object allocation. 1744 Handle<mirror::Object> saved_throw_this(hs.NewHandle(throw_location.GetThis())); 1745 Handle<mirror::ArtMethod> saved_throw_method(hs.NewHandle(throw_location.GetMethod())); 1746 // Ignore the cause throw location. TODO: should we report this as a re-throw? 1747 ScopedLocalRef<jobject> cause(GetJniEnv(), soa.AddLocalReference<jobject>(GetException(nullptr))); 1748 bool is_exception_reported = IsExceptionReportedToInstrumentation(); 1749 ClearException(); 1750 Runtime* runtime = Runtime::Current(); 1751 1752 mirror::ClassLoader* cl = nullptr; 1753 if (saved_throw_method.Get() != nullptr) { 1754 cl = saved_throw_method.Get()->GetDeclaringClass()->GetClassLoader(); 1755 } 1756 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(cl)); 1757 Handle<mirror::Class> exception_class( 1758 hs.NewHandle(runtime->GetClassLinker()->FindClass(this, exception_class_descriptor, 1759 class_loader))); 1760 if (UNLIKELY(exception_class.Get() == nullptr)) { 1761 CHECK(IsExceptionPending()); 1762 LOG(ERROR) << "No exception class " << PrettyDescriptor(exception_class_descriptor); 1763 return; 1764 } 1765 1766 if (UNLIKELY(!runtime->GetClassLinker()->EnsureInitialized(soa.Self(), exception_class, true, 1767 true))) { 1768 DCHECK(IsExceptionPending()); 1769 return; 1770 } 1771 DCHECK(!runtime->IsStarted() || exception_class->IsThrowableClass()); 1772 Handle<mirror::Throwable> exception( 1773 hs.NewHandle(down_cast<mirror::Throwable*>(exception_class->AllocObject(this)))); 1774 1775 // If we couldn't allocate the exception, throw the pre-allocated out of memory exception. 1776 if (exception.Get() == nullptr) { 1777 ThrowLocation gc_safe_throw_location(saved_throw_this.Get(), saved_throw_method.Get(), 1778 throw_location.GetDexPc()); 1779 SetException(gc_safe_throw_location, Runtime::Current()->GetPreAllocatedOutOfMemoryError()); 1780 SetExceptionReportedToInstrumentation(is_exception_reported); 1781 return; 1782 } 1783 1784 // Choose an appropriate constructor and set up the arguments. 1785 const char* signature; 1786 ScopedLocalRef<jstring> msg_string(GetJniEnv(), nullptr); 1787 if (msg != nullptr) { 1788 // Ensure we remember this and the method over the String allocation. 1789 msg_string.reset( 1790 soa.AddLocalReference<jstring>(mirror::String::AllocFromModifiedUtf8(this, msg))); 1791 if (UNLIKELY(msg_string.get() == nullptr)) { 1792 CHECK(IsExceptionPending()); // OOME. 1793 return; 1794 } 1795 if (cause.get() == nullptr) { 1796 signature = "(Ljava/lang/String;)V"; 1797 } else { 1798 signature = "(Ljava/lang/String;Ljava/lang/Throwable;)V"; 1799 } 1800 } else { 1801 if (cause.get() == nullptr) { 1802 signature = "()V"; 1803 } else { 1804 signature = "(Ljava/lang/Throwable;)V"; 1805 } 1806 } 1807 mirror::ArtMethod* exception_init_method = 1808 exception_class->FindDeclaredDirectMethod("<init>", signature); 1809 1810 CHECK(exception_init_method != nullptr) << "No <init>" << signature << " in " 1811 << PrettyDescriptor(exception_class_descriptor); 1812 1813 if (UNLIKELY(!runtime->IsStarted())) { 1814 // Something is trying to throw an exception without a started runtime, which is the common 1815 // case in the compiler. We won't be able to invoke the constructor of the exception, so set 1816 // the exception fields directly. 1817 if (msg != nullptr) { 1818 exception->SetDetailMessage(down_cast<mirror::String*>(DecodeJObject(msg_string.get()))); 1819 } 1820 if (cause.get() != nullptr) { 1821 exception->SetCause(down_cast<mirror::Throwable*>(DecodeJObject(cause.get()))); 1822 } 1823 ScopedLocalRef<jobject> trace(GetJniEnv(), 1824 Runtime::Current()->IsActiveTransaction() 1825 ? CreateInternalStackTrace<true>(soa) 1826 : CreateInternalStackTrace<false>(soa)); 1827 if (trace.get() != nullptr) { 1828 exception->SetStackState(down_cast<mirror::Throwable*>(DecodeJObject(trace.get()))); 1829 } 1830 ThrowLocation gc_safe_throw_location(saved_throw_this.Get(), saved_throw_method.Get(), 1831 throw_location.GetDexPc()); 1832 SetException(gc_safe_throw_location, exception.Get()); 1833 SetExceptionReportedToInstrumentation(is_exception_reported); 1834 } else { 1835 jvalue jv_args[2]; 1836 size_t i = 0; 1837 1838 if (msg != nullptr) { 1839 jv_args[i].l = msg_string.get(); 1840 ++i; 1841 } 1842 if (cause.get() != nullptr) { 1843 jv_args[i].l = cause.get(); 1844 ++i; 1845 } 1846 InvokeWithJValues(soa, exception.Get(), soa.EncodeMethod(exception_init_method), jv_args); 1847 if (LIKELY(!IsExceptionPending())) { 1848 ThrowLocation gc_safe_throw_location(saved_throw_this.Get(), saved_throw_method.Get(), 1849 throw_location.GetDexPc()); 1850 SetException(gc_safe_throw_location, exception.Get()); 1851 SetExceptionReportedToInstrumentation(is_exception_reported); 1852 } 1853 } 1854} 1855 1856void Thread::ThrowOutOfMemoryError(const char* msg) { 1857 LOG(ERROR) << StringPrintf("Throwing OutOfMemoryError \"%s\"%s", 1858 msg, (tls32_.throwing_OutOfMemoryError ? " (recursive case)" : "")); 1859 ThrowLocation throw_location = GetCurrentLocationForThrow(); 1860 if (!tls32_.throwing_OutOfMemoryError) { 1861 tls32_.throwing_OutOfMemoryError = true; 1862 ThrowNewException(throw_location, "Ljava/lang/OutOfMemoryError;", msg); 1863 tls32_.throwing_OutOfMemoryError = false; 1864 } else { 1865 Dump(LOG(ERROR)); // The pre-allocated OOME has no stack, so help out and log one. 1866 SetException(throw_location, Runtime::Current()->GetPreAllocatedOutOfMemoryError()); 1867 } 1868} 1869 1870Thread* Thread::CurrentFromGdb() { 1871 return Thread::Current(); 1872} 1873 1874void Thread::DumpFromGdb() const { 1875 std::ostringstream ss; 1876 Dump(ss); 1877 std::string str(ss.str()); 1878 // log to stderr for debugging command line processes 1879 std::cerr << str; 1880#ifdef HAVE_ANDROID_OS 1881 // log to logcat for debugging frameworks processes 1882 LOG(INFO) << str; 1883#endif 1884} 1885 1886// Explicitly instantiate 32 and 64bit thread offset dumping support. 1887template void Thread::DumpThreadOffset<4>(std::ostream& os, uint32_t offset); 1888template void Thread::DumpThreadOffset<8>(std::ostream& os, uint32_t offset); 1889 1890template<size_t ptr_size> 1891void Thread::DumpThreadOffset(std::ostream& os, uint32_t offset) { 1892#define DO_THREAD_OFFSET(x, y) \ 1893 if (offset == x.Uint32Value()) { \ 1894 os << y; \ 1895 return; \ 1896 } 1897 DO_THREAD_OFFSET(ThreadFlagsOffset<ptr_size>(), "state_and_flags") 1898 DO_THREAD_OFFSET(CardTableOffset<ptr_size>(), "card_table") 1899 DO_THREAD_OFFSET(ExceptionOffset<ptr_size>(), "exception") 1900 DO_THREAD_OFFSET(PeerOffset<ptr_size>(), "peer"); 1901 DO_THREAD_OFFSET(JniEnvOffset<ptr_size>(), "jni_env") 1902 DO_THREAD_OFFSET(SelfOffset<ptr_size>(), "self") 1903 DO_THREAD_OFFSET(StackEndOffset<ptr_size>(), "stack_end") 1904 DO_THREAD_OFFSET(ThinLockIdOffset<ptr_size>(), "thin_lock_thread_id") 1905 DO_THREAD_OFFSET(TopOfManagedStackOffset<ptr_size>(), "top_quick_frame_method") 1906 DO_THREAD_OFFSET(TopShadowFrameOffset<ptr_size>(), "top_shadow_frame") 1907 DO_THREAD_OFFSET(TopHandleScopeOffset<ptr_size>(), "top_handle_scope") 1908 DO_THREAD_OFFSET(ThreadSuspendTriggerOffset<ptr_size>(), "suspend_trigger") 1909#undef DO_THREAD_OFFSET 1910 1911#define INTERPRETER_ENTRY_POINT_INFO(x) \ 1912 if (INTERPRETER_ENTRYPOINT_OFFSET(ptr_size, x).Uint32Value() == offset) { \ 1913 os << #x; \ 1914 return; \ 1915 } 1916 INTERPRETER_ENTRY_POINT_INFO(pInterpreterToInterpreterBridge) 1917 INTERPRETER_ENTRY_POINT_INFO(pInterpreterToCompiledCodeBridge) 1918#undef INTERPRETER_ENTRY_POINT_INFO 1919 1920#define JNI_ENTRY_POINT_INFO(x) \ 1921 if (JNI_ENTRYPOINT_OFFSET(ptr_size, x).Uint32Value() == offset) { \ 1922 os << #x; \ 1923 return; \ 1924 } 1925 JNI_ENTRY_POINT_INFO(pDlsymLookup) 1926#undef JNI_ENTRY_POINT_INFO 1927 1928#define QUICK_ENTRY_POINT_INFO(x) \ 1929 if (QUICK_ENTRYPOINT_OFFSET(ptr_size, x).Uint32Value() == offset) { \ 1930 os << #x; \ 1931 return; \ 1932 } 1933 QUICK_ENTRY_POINT_INFO(pAllocArray) 1934 QUICK_ENTRY_POINT_INFO(pAllocArrayResolved) 1935 QUICK_ENTRY_POINT_INFO(pAllocArrayWithAccessCheck) 1936 QUICK_ENTRY_POINT_INFO(pAllocObject) 1937 QUICK_ENTRY_POINT_INFO(pAllocObjectResolved) 1938 QUICK_ENTRY_POINT_INFO(pAllocObjectInitialized) 1939 QUICK_ENTRY_POINT_INFO(pAllocObjectWithAccessCheck) 1940 QUICK_ENTRY_POINT_INFO(pCheckAndAllocArray) 1941 QUICK_ENTRY_POINT_INFO(pCheckAndAllocArrayWithAccessCheck) 1942 QUICK_ENTRY_POINT_INFO(pInstanceofNonTrivial) 1943 QUICK_ENTRY_POINT_INFO(pCheckCast) 1944 QUICK_ENTRY_POINT_INFO(pInitializeStaticStorage) 1945 QUICK_ENTRY_POINT_INFO(pInitializeTypeAndVerifyAccess) 1946 QUICK_ENTRY_POINT_INFO(pInitializeType) 1947 QUICK_ENTRY_POINT_INFO(pResolveString) 1948 QUICK_ENTRY_POINT_INFO(pSet8Instance) 1949 QUICK_ENTRY_POINT_INFO(pSet8Static) 1950 QUICK_ENTRY_POINT_INFO(pSet16Instance) 1951 QUICK_ENTRY_POINT_INFO(pSet16Static) 1952 QUICK_ENTRY_POINT_INFO(pSet32Instance) 1953 QUICK_ENTRY_POINT_INFO(pSet32Static) 1954 QUICK_ENTRY_POINT_INFO(pSet64Instance) 1955 QUICK_ENTRY_POINT_INFO(pSet64Static) 1956 QUICK_ENTRY_POINT_INFO(pSetObjInstance) 1957 QUICK_ENTRY_POINT_INFO(pSetObjStatic) 1958 QUICK_ENTRY_POINT_INFO(pGetByteInstance) 1959 QUICK_ENTRY_POINT_INFO(pGetBooleanInstance) 1960 QUICK_ENTRY_POINT_INFO(pGetByteStatic) 1961 QUICK_ENTRY_POINT_INFO(pGetBooleanStatic) 1962 QUICK_ENTRY_POINT_INFO(pGetShortInstance) 1963 QUICK_ENTRY_POINT_INFO(pGetCharInstance) 1964 QUICK_ENTRY_POINT_INFO(pGetShortStatic) 1965 QUICK_ENTRY_POINT_INFO(pGetCharStatic) 1966 QUICK_ENTRY_POINT_INFO(pGet32Instance) 1967 QUICK_ENTRY_POINT_INFO(pGet32Static) 1968 QUICK_ENTRY_POINT_INFO(pGet64Instance) 1969 QUICK_ENTRY_POINT_INFO(pGet64Static) 1970 QUICK_ENTRY_POINT_INFO(pGetObjInstance) 1971 QUICK_ENTRY_POINT_INFO(pGetObjStatic) 1972 QUICK_ENTRY_POINT_INFO(pAputObjectWithNullAndBoundCheck) 1973 QUICK_ENTRY_POINT_INFO(pAputObjectWithBoundCheck) 1974 QUICK_ENTRY_POINT_INFO(pAputObject) 1975 QUICK_ENTRY_POINT_INFO(pHandleFillArrayData) 1976 QUICK_ENTRY_POINT_INFO(pJniMethodStart) 1977 QUICK_ENTRY_POINT_INFO(pJniMethodStartSynchronized) 1978 QUICK_ENTRY_POINT_INFO(pJniMethodEnd) 1979 QUICK_ENTRY_POINT_INFO(pJniMethodEndSynchronized) 1980 QUICK_ENTRY_POINT_INFO(pJniMethodEndWithReference) 1981 QUICK_ENTRY_POINT_INFO(pJniMethodEndWithReferenceSynchronized) 1982 QUICK_ENTRY_POINT_INFO(pQuickGenericJniTrampoline) 1983 QUICK_ENTRY_POINT_INFO(pLockObject) 1984 QUICK_ENTRY_POINT_INFO(pUnlockObject) 1985 QUICK_ENTRY_POINT_INFO(pCmpgDouble) 1986 QUICK_ENTRY_POINT_INFO(pCmpgFloat) 1987 QUICK_ENTRY_POINT_INFO(pCmplDouble) 1988 QUICK_ENTRY_POINT_INFO(pCmplFloat) 1989 QUICK_ENTRY_POINT_INFO(pFmod) 1990 QUICK_ENTRY_POINT_INFO(pL2d) 1991 QUICK_ENTRY_POINT_INFO(pFmodf) 1992 QUICK_ENTRY_POINT_INFO(pL2f) 1993 QUICK_ENTRY_POINT_INFO(pD2iz) 1994 QUICK_ENTRY_POINT_INFO(pF2iz) 1995 QUICK_ENTRY_POINT_INFO(pIdivmod) 1996 QUICK_ENTRY_POINT_INFO(pD2l) 1997 QUICK_ENTRY_POINT_INFO(pF2l) 1998 QUICK_ENTRY_POINT_INFO(pLdiv) 1999 QUICK_ENTRY_POINT_INFO(pLmod) 2000 QUICK_ENTRY_POINT_INFO(pLmul) 2001 QUICK_ENTRY_POINT_INFO(pShlLong) 2002 QUICK_ENTRY_POINT_INFO(pShrLong) 2003 QUICK_ENTRY_POINT_INFO(pUshrLong) 2004 QUICK_ENTRY_POINT_INFO(pIndexOf) 2005 QUICK_ENTRY_POINT_INFO(pStringCompareTo) 2006 QUICK_ENTRY_POINT_INFO(pMemcpy) 2007 QUICK_ENTRY_POINT_INFO(pQuickImtConflictTrampoline) 2008 QUICK_ENTRY_POINT_INFO(pQuickResolutionTrampoline) 2009 QUICK_ENTRY_POINT_INFO(pQuickToInterpreterBridge) 2010 QUICK_ENTRY_POINT_INFO(pInvokeDirectTrampolineWithAccessCheck) 2011 QUICK_ENTRY_POINT_INFO(pInvokeInterfaceTrampolineWithAccessCheck) 2012 QUICK_ENTRY_POINT_INFO(pInvokeStaticTrampolineWithAccessCheck) 2013 QUICK_ENTRY_POINT_INFO(pInvokeSuperTrampolineWithAccessCheck) 2014 QUICK_ENTRY_POINT_INFO(pInvokeVirtualTrampolineWithAccessCheck) 2015 QUICK_ENTRY_POINT_INFO(pTestSuspend) 2016 QUICK_ENTRY_POINT_INFO(pDeliverException) 2017 QUICK_ENTRY_POINT_INFO(pThrowArrayBounds) 2018 QUICK_ENTRY_POINT_INFO(pThrowDivZero) 2019 QUICK_ENTRY_POINT_INFO(pThrowNoSuchMethod) 2020 QUICK_ENTRY_POINT_INFO(pThrowNullPointer) 2021 QUICK_ENTRY_POINT_INFO(pThrowStackOverflow) 2022 QUICK_ENTRY_POINT_INFO(pA64Load) 2023 QUICK_ENTRY_POINT_INFO(pA64Store) 2024#undef QUICK_ENTRY_POINT_INFO 2025 2026 os << offset; 2027} 2028 2029void Thread::QuickDeliverException() { 2030 // Get exception from thread. 2031 ThrowLocation throw_location; 2032 mirror::Throwable* exception = GetException(&throw_location); 2033 CHECK(exception != nullptr); 2034 // Don't leave exception visible while we try to find the handler, which may cause class 2035 // resolution. 2036 bool is_exception_reported = IsExceptionReportedToInstrumentation(); 2037 ClearException(); 2038 bool is_deoptimization = (exception == GetDeoptimizationException()); 2039 QuickExceptionHandler exception_handler(this, is_deoptimization); 2040 if (is_deoptimization) { 2041 exception_handler.DeoptimizeStack(); 2042 } else { 2043 exception_handler.FindCatch(throw_location, exception, is_exception_reported); 2044 } 2045 exception_handler.UpdateInstrumentationStack(); 2046 exception_handler.DoLongJump(); 2047 LOG(FATAL) << "UNREACHABLE"; 2048 UNREACHABLE(); 2049} 2050 2051Context* Thread::GetLongJumpContext() { 2052 Context* result = tlsPtr_.long_jump_context; 2053 if (result == nullptr) { 2054 result = Context::Create(); 2055 } else { 2056 tlsPtr_.long_jump_context = nullptr; // Avoid context being shared. 2057 result->Reset(); 2058 } 2059 return result; 2060} 2061 2062// Note: this visitor may return with a method set, but dex_pc_ being DexFile:kDexNoIndex. This is 2063// so we don't abort in a special situation (thinlocked monitor) when dumping the Java stack. 2064struct CurrentMethodVisitor FINAL : public StackVisitor { 2065 CurrentMethodVisitor(Thread* thread, Context* context, bool abort_on_error) 2066 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 2067 : StackVisitor(thread, context), this_object_(nullptr), method_(nullptr), dex_pc_(0), 2068 abort_on_error_(abort_on_error) {} 2069 bool VisitFrame() OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 2070 mirror::ArtMethod* m = GetMethod(); 2071 if (m->IsRuntimeMethod()) { 2072 // Continue if this is a runtime method. 2073 return true; 2074 } 2075 if (context_ != nullptr) { 2076 this_object_ = GetThisObject(); 2077 } 2078 method_ = m; 2079 dex_pc_ = GetDexPc(abort_on_error_); 2080 return false; 2081 } 2082 mirror::Object* this_object_; 2083 mirror::ArtMethod* method_; 2084 uint32_t dex_pc_; 2085 const bool abort_on_error_; 2086}; 2087 2088mirror::ArtMethod* Thread::GetCurrentMethod(uint32_t* dex_pc, bool abort_on_error) const { 2089 CurrentMethodVisitor visitor(const_cast<Thread*>(this), nullptr, abort_on_error); 2090 visitor.WalkStack(false); 2091 if (dex_pc != nullptr) { 2092 *dex_pc = visitor.dex_pc_; 2093 } 2094 return visitor.method_; 2095} 2096 2097ThrowLocation Thread::GetCurrentLocationForThrow() { 2098 Context* context = GetLongJumpContext(); 2099 CurrentMethodVisitor visitor(this, context, true); 2100 visitor.WalkStack(false); 2101 ReleaseLongJumpContext(context); 2102 return ThrowLocation(visitor.this_object_, visitor.method_, visitor.dex_pc_); 2103} 2104 2105bool Thread::HoldsLock(mirror::Object* object) const { 2106 if (object == nullptr) { 2107 return false; 2108 } 2109 return object->GetLockOwnerThreadId() == GetThreadId(); 2110} 2111 2112// RootVisitor parameters are: (const Object* obj, size_t vreg, const StackVisitor* visitor). 2113template <typename RootVisitor> 2114class ReferenceMapVisitor : public StackVisitor { 2115 public: 2116 ReferenceMapVisitor(Thread* thread, Context* context, const RootVisitor& visitor) 2117 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 2118 : StackVisitor(thread, context), visitor_(visitor) {} 2119 2120 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 2121 if (false) { 2122 LOG(INFO) << "Visiting stack roots in " << PrettyMethod(GetMethod()) 2123 << StringPrintf("@ PC:%04x", GetDexPc()); 2124 } 2125 ShadowFrame* shadow_frame = GetCurrentShadowFrame(); 2126 if (shadow_frame != nullptr) { 2127 VisitShadowFrame(shadow_frame); 2128 } else { 2129 VisitQuickFrame(); 2130 } 2131 return true; 2132 } 2133 2134 void VisitShadowFrame(ShadowFrame* shadow_frame) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 2135 mirror::ArtMethod** method_addr = shadow_frame->GetMethodAddress(); 2136 visitor_(reinterpret_cast<mirror::Object**>(method_addr), 0 /*ignored*/, this); 2137 mirror::ArtMethod* m = *method_addr; 2138 DCHECK(m != nullptr); 2139 size_t num_regs = shadow_frame->NumberOfVRegs(); 2140 if (m->IsNative() || shadow_frame->HasReferenceArray()) { 2141 // handle scope for JNI or References for interpreter. 2142 for (size_t reg = 0; reg < num_regs; ++reg) { 2143 mirror::Object* ref = shadow_frame->GetVRegReference(reg); 2144 if (ref != nullptr) { 2145 mirror::Object* new_ref = ref; 2146 visitor_(&new_ref, reg, this); 2147 if (new_ref != ref) { 2148 shadow_frame->SetVRegReference(reg, new_ref); 2149 } 2150 } 2151 } 2152 } else { 2153 // Java method. 2154 // Portable path use DexGcMap and store in Method.native_gc_map_. 2155 const uint8_t* gc_map = m->GetNativeGcMap(sizeof(void*)); 2156 CHECK(gc_map != nullptr) << PrettyMethod(m); 2157 verifier::DexPcToReferenceMap dex_gc_map(gc_map); 2158 uint32_t dex_pc = shadow_frame->GetDexPC(); 2159 const uint8_t* reg_bitmap = dex_gc_map.FindBitMap(dex_pc); 2160 DCHECK(reg_bitmap != nullptr); 2161 num_regs = std::min(dex_gc_map.RegWidth() * 8, num_regs); 2162 for (size_t reg = 0; reg < num_regs; ++reg) { 2163 if (TestBitmap(reg, reg_bitmap)) { 2164 mirror::Object* ref = shadow_frame->GetVRegReference(reg); 2165 if (ref != nullptr) { 2166 mirror::Object* new_ref = ref; 2167 visitor_(&new_ref, reg, this); 2168 if (new_ref != ref) { 2169 shadow_frame->SetVRegReference(reg, new_ref); 2170 } 2171 } 2172 } 2173 } 2174 } 2175 } 2176 2177 private: 2178 void VisitQuickFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 2179 StackReference<mirror::ArtMethod>* cur_quick_frame = GetCurrentQuickFrame(); 2180 mirror::ArtMethod* m = cur_quick_frame->AsMirrorPtr(); 2181 mirror::ArtMethod* old_method = m; 2182 visitor_(reinterpret_cast<mirror::Object**>(&m), 0 /*ignored*/, this); 2183 if (m != old_method) { 2184 cur_quick_frame->Assign(m); 2185 } 2186 2187 // Process register map (which native and runtime methods don't have) 2188 if (!m->IsNative() && !m->IsRuntimeMethod() && !m->IsProxyMethod()) { 2189 if (m->IsOptimized(sizeof(void*))) { 2190 Runtime* runtime = Runtime::Current(); 2191 const void* entry_point = runtime->GetInstrumentation()->GetQuickCodeFor(m, sizeof(void*)); 2192 uintptr_t native_pc_offset = m->NativeQuickPcOffset(GetCurrentQuickFramePc(), entry_point); 2193 StackMap map = m->GetStackMap(native_pc_offset); 2194 MemoryRegion mask = map.GetStackMask(); 2195 // Visit stack entries that hold pointers. 2196 for (size_t i = 0; i < mask.size_in_bits(); ++i) { 2197 if (mask.LoadBit(i)) { 2198 StackReference<mirror::Object>* ref_addr = 2199 reinterpret_cast<StackReference<mirror::Object>*>(cur_quick_frame) + i; 2200 mirror::Object* ref = ref_addr->AsMirrorPtr(); 2201 if (ref != nullptr) { 2202 mirror::Object* new_ref = ref; 2203 visitor_(&new_ref, -1, this); 2204 if (ref != new_ref) { 2205 ref_addr->Assign(new_ref); 2206 } 2207 } 2208 } 2209 } 2210 // Visit callee-save registers that hold pointers. 2211 uint32_t register_mask = map.GetRegisterMask(); 2212 for (size_t i = 0; i < BitSizeOf<uint32_t>(); ++i) { 2213 if (register_mask & (1 << i)) { 2214 mirror::Object** ref_addr = reinterpret_cast<mirror::Object**>(GetGPRAddress(i)); 2215 if (*ref_addr != nullptr) { 2216 visitor_(ref_addr, -1, this); 2217 } 2218 } 2219 } 2220 } else { 2221 const uint8_t* native_gc_map = m->GetNativeGcMap(sizeof(void*)); 2222 CHECK(native_gc_map != nullptr) << PrettyMethod(m); 2223 const DexFile::CodeItem* code_item = m->GetCodeItem(); 2224 // Can't be nullptr or how would we compile its instructions? 2225 DCHECK(code_item != nullptr) << PrettyMethod(m); 2226 NativePcOffsetToReferenceMap map(native_gc_map); 2227 size_t num_regs = std::min(map.RegWidth() * 8, 2228 static_cast<size_t>(code_item->registers_size_)); 2229 if (num_regs > 0) { 2230 Runtime* runtime = Runtime::Current(); 2231 const void* entry_point = runtime->GetInstrumentation()->GetQuickCodeFor(m, sizeof(void*)); 2232 uintptr_t native_pc_offset = m->NativeQuickPcOffset(GetCurrentQuickFramePc(), entry_point); 2233 const uint8_t* reg_bitmap = map.FindBitMap(native_pc_offset); 2234 DCHECK(reg_bitmap != nullptr); 2235 const void* code_pointer = mirror::ArtMethod::EntryPointToCodePointer(entry_point); 2236 const VmapTable vmap_table(m->GetVmapTable(code_pointer, sizeof(void*))); 2237 QuickMethodFrameInfo frame_info = m->GetQuickFrameInfo(code_pointer); 2238 // For all dex registers in the bitmap 2239 DCHECK(cur_quick_frame != nullptr); 2240 for (size_t reg = 0; reg < num_regs; ++reg) { 2241 // Does this register hold a reference? 2242 if (TestBitmap(reg, reg_bitmap)) { 2243 uint32_t vmap_offset; 2244 if (vmap_table.IsInContext(reg, kReferenceVReg, &vmap_offset)) { 2245 int vmap_reg = vmap_table.ComputeRegister(frame_info.CoreSpillMask(), vmap_offset, 2246 kReferenceVReg); 2247 // This is sound as spilled GPRs will be word sized (ie 32 or 64bit). 2248 mirror::Object** ref_addr = 2249 reinterpret_cast<mirror::Object**>(GetGPRAddress(vmap_reg)); 2250 if (*ref_addr != nullptr) { 2251 visitor_(ref_addr, reg, this); 2252 } 2253 } else { 2254 StackReference<mirror::Object>* ref_addr = 2255 reinterpret_cast<StackReference<mirror::Object>*>( 2256 GetVRegAddr(cur_quick_frame, code_item, frame_info.CoreSpillMask(), 2257 frame_info.FpSpillMask(), frame_info.FrameSizeInBytes(), reg)); 2258 mirror::Object* ref = ref_addr->AsMirrorPtr(); 2259 if (ref != nullptr) { 2260 mirror::Object* new_ref = ref; 2261 visitor_(&new_ref, reg, this); 2262 if (ref != new_ref) { 2263 ref_addr->Assign(new_ref); 2264 } 2265 } 2266 } 2267 } 2268 } 2269 } 2270 } 2271 } 2272 } 2273 2274 static bool TestBitmap(size_t reg, const uint8_t* reg_vector) { 2275 return ((reg_vector[reg / kBitsPerByte] >> (reg % kBitsPerByte)) & 0x01) != 0; 2276 } 2277 2278 // Visitor for when we visit a root. 2279 const RootVisitor& visitor_; 2280}; 2281 2282class RootCallbackVisitor { 2283 public: 2284 RootCallbackVisitor(RootCallback* callback, void* arg, uint32_t tid) 2285 : callback_(callback), arg_(arg), tid_(tid) {} 2286 2287 void operator()(mirror::Object** obj, size_t vreg, const StackVisitor* stack_visitor) const { 2288 callback_(obj, arg_, JavaFrameRootInfo(tid_, stack_visitor, vreg)); 2289 } 2290 2291 private: 2292 RootCallback* const callback_; 2293 void* const arg_; 2294 const uint32_t tid_; 2295}; 2296 2297void Thread::VisitRoots(RootCallback* visitor, void* arg) { 2298 uint32_t thread_id = GetThreadId(); 2299 if (tlsPtr_.opeer != nullptr) { 2300 visitor(&tlsPtr_.opeer, arg, RootInfo(kRootThreadObject, thread_id)); 2301 } 2302 if (tlsPtr_.exception != nullptr && tlsPtr_.exception != GetDeoptimizationException()) { 2303 visitor(reinterpret_cast<mirror::Object**>(&tlsPtr_.exception), arg, 2304 RootInfo(kRootNativeStack, thread_id)); 2305 } 2306 tlsPtr_.throw_location.VisitRoots(visitor, arg); 2307 if (tlsPtr_.monitor_enter_object != nullptr) { 2308 visitor(&tlsPtr_.monitor_enter_object, arg, RootInfo(kRootNativeStack, thread_id)); 2309 } 2310 tlsPtr_.jni_env->locals.VisitRoots(visitor, arg, RootInfo(kRootJNILocal, thread_id)); 2311 tlsPtr_.jni_env->monitors.VisitRoots(visitor, arg, RootInfo(kRootJNIMonitor, thread_id)); 2312 HandleScopeVisitRoots(visitor, arg, thread_id); 2313 if (tlsPtr_.debug_invoke_req != nullptr) { 2314 tlsPtr_.debug_invoke_req->VisitRoots(visitor, arg, RootInfo(kRootDebugger, thread_id)); 2315 } 2316 if (tlsPtr_.single_step_control != nullptr) { 2317 tlsPtr_.single_step_control->VisitRoots(visitor, arg, RootInfo(kRootDebugger, thread_id)); 2318 } 2319 if (tlsPtr_.deoptimization_shadow_frame != nullptr) { 2320 RootCallbackVisitor visitorToCallback(visitor, arg, thread_id); 2321 ReferenceMapVisitor<RootCallbackVisitor> mapper(this, nullptr, visitorToCallback); 2322 for (ShadowFrame* shadow_frame = tlsPtr_.deoptimization_shadow_frame; shadow_frame != nullptr; 2323 shadow_frame = shadow_frame->GetLink()) { 2324 mapper.VisitShadowFrame(shadow_frame); 2325 } 2326 } 2327 if (tlsPtr_.shadow_frame_under_construction != nullptr) { 2328 RootCallbackVisitor visitor_to_callback(visitor, arg, thread_id); 2329 ReferenceMapVisitor<RootCallbackVisitor> mapper(this, nullptr, visitor_to_callback); 2330 for (ShadowFrame* shadow_frame = tlsPtr_.shadow_frame_under_construction; 2331 shadow_frame != nullptr; 2332 shadow_frame = shadow_frame->GetLink()) { 2333 mapper.VisitShadowFrame(shadow_frame); 2334 } 2335 } 2336 // Visit roots on this thread's stack 2337 Context* context = GetLongJumpContext(); 2338 RootCallbackVisitor visitor_to_callback(visitor, arg, thread_id); 2339 ReferenceMapVisitor<RootCallbackVisitor> mapper(this, context, visitor_to_callback); 2340 mapper.WalkStack(); 2341 ReleaseLongJumpContext(context); 2342 for (instrumentation::InstrumentationStackFrame& frame : *GetInstrumentationStack()) { 2343 if (frame.this_object_ != nullptr) { 2344 visitor(&frame.this_object_, arg, RootInfo(kRootVMInternal, thread_id)); 2345 } 2346 DCHECK(frame.method_ != nullptr); 2347 visitor(reinterpret_cast<mirror::Object**>(&frame.method_), arg, 2348 RootInfo(kRootVMInternal, thread_id)); 2349 } 2350} 2351 2352static void VerifyRoot(mirror::Object** root, void* /*arg*/, const RootInfo& /*root_info*/) 2353 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 2354 VerifyObject(*root); 2355} 2356 2357void Thread::VerifyStackImpl() { 2358 std::unique_ptr<Context> context(Context::Create()); 2359 RootCallbackVisitor visitorToCallback(VerifyRoot, Runtime::Current()->GetHeap(), GetThreadId()); 2360 ReferenceMapVisitor<RootCallbackVisitor> mapper(this, context.get(), visitorToCallback); 2361 mapper.WalkStack(); 2362} 2363 2364// Set the stack end to that to be used during a stack overflow 2365void Thread::SetStackEndForStackOverflow() { 2366 // During stack overflow we allow use of the full stack. 2367 if (tlsPtr_.stack_end == tlsPtr_.stack_begin) { 2368 // However, we seem to have already extended to use the full stack. 2369 LOG(ERROR) << "Need to increase kStackOverflowReservedBytes (currently " 2370 << GetStackOverflowReservedBytes(kRuntimeISA) << ")?"; 2371 DumpStack(LOG(ERROR)); 2372 LOG(FATAL) << "Recursive stack overflow."; 2373 } 2374 2375 tlsPtr_.stack_end = tlsPtr_.stack_begin; 2376 2377 // Remove the stack overflow protection if is it set up. 2378 bool implicit_stack_check = !Runtime::Current()->ExplicitStackOverflowChecks(); 2379 if (implicit_stack_check) { 2380 if (!UnprotectStack()) { 2381 LOG(ERROR) << "Unable to remove stack protection for stack overflow"; 2382 } 2383 } 2384} 2385 2386void Thread::SetTlab(uint8_t* start, uint8_t* end) { 2387 DCHECK_LE(start, end); 2388 tlsPtr_.thread_local_start = start; 2389 tlsPtr_.thread_local_pos = tlsPtr_.thread_local_start; 2390 tlsPtr_.thread_local_end = end; 2391 tlsPtr_.thread_local_objects = 0; 2392} 2393 2394bool Thread::HasTlab() const { 2395 bool has_tlab = tlsPtr_.thread_local_pos != nullptr; 2396 if (has_tlab) { 2397 DCHECK(tlsPtr_.thread_local_start != nullptr && tlsPtr_.thread_local_end != nullptr); 2398 } else { 2399 DCHECK(tlsPtr_.thread_local_start == nullptr && tlsPtr_.thread_local_end == nullptr); 2400 } 2401 return has_tlab; 2402} 2403 2404std::ostream& operator<<(std::ostream& os, const Thread& thread) { 2405 thread.ShortDump(os); 2406 return os; 2407} 2408 2409void Thread::ProtectStack() { 2410 void* pregion = tlsPtr_.stack_begin - kStackOverflowProtectedSize; 2411 VLOG(threads) << "Protecting stack at " << pregion; 2412 if (mprotect(pregion, kStackOverflowProtectedSize, PROT_NONE) == -1) { 2413 LOG(FATAL) << "Unable to create protected region in stack for implicit overflow check. " 2414 "Reason: " 2415 << strerror(errno) << " size: " << kStackOverflowProtectedSize; 2416 } 2417} 2418 2419bool Thread::UnprotectStack() { 2420 void* pregion = tlsPtr_.stack_begin - kStackOverflowProtectedSize; 2421 VLOG(threads) << "Unprotecting stack at " << pregion; 2422 return mprotect(pregion, kStackOverflowProtectedSize, PROT_READ|PROT_WRITE) == 0; 2423} 2424 2425void Thread::ActivateSingleStepControl(SingleStepControl* ssc) { 2426 CHECK(Dbg::IsDebuggerActive()); 2427 CHECK(GetSingleStepControl() == nullptr) << "Single step already active in thread " << *this; 2428 CHECK(ssc != nullptr); 2429 tlsPtr_.single_step_control = ssc; 2430} 2431 2432void Thread::DeactivateSingleStepControl() { 2433 CHECK(Dbg::IsDebuggerActive()); 2434 CHECK(GetSingleStepControl() != nullptr) << "Single step not active in thread " << *this; 2435 SingleStepControl* ssc = GetSingleStepControl(); 2436 tlsPtr_.single_step_control = nullptr; 2437 delete ssc; 2438} 2439 2440} // namespace art 2441