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