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