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