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