thread.cc revision eb1680f0365a5b2dd10dd38982cf716ac6fd8c84
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#include "thread.h" 18 19#include <pthread.h> 20#include <signal.h> 21#include <sys/resource.h> 22#include <sys/time.h> 23 24#include <algorithm> 25#include <bitset> 26#include <cerrno> 27#include <iostream> 28#include <list> 29#include <sstream> 30 31#include "arch/context.h" 32#include "art_field-inl.h" 33#include "art_method-inl.h" 34#include "base/bit_utils.h" 35#include "base/memory_tool.h" 36#include "base/mutex.h" 37#include "base/timing_logger.h" 38#include "base/to_str.h" 39#include "base/systrace.h" 40#include "class_linker-inl.h" 41#include "debugger.h" 42#include "dex_file-inl.h" 43#include "entrypoints/entrypoint_utils.h" 44#include "entrypoints/quick/quick_alloc_entrypoints.h" 45#include "gc/accounting/card_table-inl.h" 46#include "gc/accounting/heap_bitmap-inl.h" 47#include "gc/allocator/rosalloc.h" 48#include "gc/heap.h" 49#include "gc/space/space-inl.h" 50#include "handle_scope-inl.h" 51#include "indirect_reference_table-inl.h" 52#include "jni_internal.h" 53#include "mirror/class_loader.h" 54#include "mirror/class-inl.h" 55#include "mirror/object_array-inl.h" 56#include "mirror/stack_trace_element.h" 57#include "monitor.h" 58#include "native_stack_dump.h" 59#include "nth_caller_visitor.h" 60#include "oat_quick_method_header.h" 61#include "object_lock.h" 62#include "quick_exception_handler.h" 63#include "quick/quick_method_frame_info.h" 64#include "reflection.h" 65#include "runtime.h" 66#include "scoped_thread_state_change.h" 67#include "ScopedLocalRef.h" 68#include "ScopedUtfChars.h" 69#include "stack.h" 70#include "stack_map.h" 71#include "thread_list.h" 72#include "thread-inl.h" 73#include "utils.h" 74#include "verifier/method_verifier.h" 75#include "verify_object-inl.h" 76#include "well_known_classes.h" 77#include "interpreter/interpreter.h" 78 79#if ART_USE_FUTEXES 80#include "linux/futex.h" 81#include "sys/syscall.h" 82#ifndef SYS_futex 83#define SYS_futex __NR_futex 84#endif 85#endif // ART_USE_FUTEXES 86 87namespace art { 88 89extern "C" NO_RETURN void artDeoptimize(Thread* self); 90 91bool Thread::is_started_ = false; 92pthread_key_t Thread::pthread_key_self_; 93ConditionVariable* Thread::resume_cond_ = nullptr; 94const size_t Thread::kStackOverflowImplicitCheckSize = GetStackOverflowReservedBytes(kRuntimeISA); 95bool (*Thread::is_sensitive_thread_hook_)() = nullptr; 96Thread* Thread::jit_sensitive_thread_ = nullptr; 97 98static constexpr bool kVerifyImageObjectsMarked = kIsDebugBuild; 99 100// For implicit overflow checks we reserve an extra piece of memory at the bottom 101// of the stack (lowest memory). The higher portion of the memory 102// is protected against reads and the lower is available for use while 103// throwing the StackOverflow exception. 104constexpr size_t kStackOverflowProtectedSize = 4 * kMemoryToolStackGuardSizeScale * KB; 105 106static const char* kThreadNameDuringStartup = "<native thread without managed peer>"; 107 108void Thread::InitCardTable() { 109 tlsPtr_.card_table = Runtime::Current()->GetHeap()->GetCardTable()->GetBiasedBegin(); 110} 111 112static void UnimplementedEntryPoint() { 113 UNIMPLEMENTED(FATAL); 114} 115 116void InitEntryPoints(JniEntryPoints* jpoints, QuickEntryPoints* qpoints); 117 118void Thread::InitTlsEntryPoints() { 119 // Insert a placeholder so we can easily tell if we call an unimplemented entry point. 120 uintptr_t* begin = reinterpret_cast<uintptr_t*>(&tlsPtr_.jni_entrypoints); 121 uintptr_t* end = reinterpret_cast<uintptr_t*>(reinterpret_cast<uint8_t*>(&tlsPtr_.quick_entrypoints) + 122 sizeof(tlsPtr_.quick_entrypoints)); 123 for (uintptr_t* it = begin; it != end; ++it) { 124 *it = reinterpret_cast<uintptr_t>(UnimplementedEntryPoint); 125 } 126 InitEntryPoints(&tlsPtr_.jni_entrypoints, &tlsPtr_.quick_entrypoints); 127} 128 129void Thread::InitStringEntryPoints() { 130 ScopedObjectAccess soa(this); 131 QuickEntryPoints* qpoints = &tlsPtr_.quick_entrypoints; 132 qpoints->pNewEmptyString = reinterpret_cast<void(*)()>( 133 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newEmptyString)); 134 qpoints->pNewStringFromBytes_B = reinterpret_cast<void(*)()>( 135 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromBytes_B)); 136 qpoints->pNewStringFromBytes_BI = reinterpret_cast<void(*)()>( 137 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromBytes_BI)); 138 qpoints->pNewStringFromBytes_BII = reinterpret_cast<void(*)()>( 139 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromBytes_BII)); 140 qpoints->pNewStringFromBytes_BIII = reinterpret_cast<void(*)()>( 141 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromBytes_BIII)); 142 qpoints->pNewStringFromBytes_BIIString = reinterpret_cast<void(*)()>( 143 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromBytes_BIIString)); 144 qpoints->pNewStringFromBytes_BString = reinterpret_cast<void(*)()>( 145 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromBytes_BString)); 146 qpoints->pNewStringFromBytes_BIICharset = reinterpret_cast<void(*)()>( 147 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromBytes_BIICharset)); 148 qpoints->pNewStringFromBytes_BCharset = reinterpret_cast<void(*)()>( 149 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromBytes_BCharset)); 150 qpoints->pNewStringFromChars_C = reinterpret_cast<void(*)()>( 151 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromChars_C)); 152 qpoints->pNewStringFromChars_CII = reinterpret_cast<void(*)()>( 153 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromChars_CII)); 154 qpoints->pNewStringFromChars_IIC = reinterpret_cast<void(*)()>( 155 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromChars_IIC)); 156 qpoints->pNewStringFromCodePoints = reinterpret_cast<void(*)()>( 157 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromCodePoints)); 158 qpoints->pNewStringFromString = reinterpret_cast<void(*)()>( 159 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromString)); 160 qpoints->pNewStringFromStringBuffer = reinterpret_cast<void(*)()>( 161 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromStringBuffer)); 162 qpoints->pNewStringFromStringBuilder = reinterpret_cast<void(*)()>( 163 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromStringBuilder)); 164} 165 166void Thread::ResetQuickAllocEntryPointsForThread() { 167 ResetQuickAllocEntryPoints(&tlsPtr_.quick_entrypoints); 168} 169 170class DeoptimizationContextRecord { 171 public: 172 DeoptimizationContextRecord(const JValue& ret_val, 173 bool is_reference, 174 bool from_code, 175 mirror::Throwable* pending_exception, 176 DeoptimizationContextRecord* link) 177 : ret_val_(ret_val), 178 is_reference_(is_reference), 179 from_code_(from_code), 180 pending_exception_(pending_exception), 181 link_(link) {} 182 183 JValue GetReturnValue() const { return ret_val_; } 184 bool IsReference() const { return is_reference_; } 185 bool GetFromCode() const { return from_code_; } 186 mirror::Throwable* GetPendingException() const { return pending_exception_; } 187 DeoptimizationContextRecord* GetLink() const { return link_; } 188 mirror::Object** GetReturnValueAsGCRoot() { 189 DCHECK(is_reference_); 190 return ret_val_.GetGCRoot(); 191 } 192 mirror::Object** GetPendingExceptionAsGCRoot() { 193 return reinterpret_cast<mirror::Object**>(&pending_exception_); 194 } 195 196 private: 197 // The value returned by the method at the top of the stack before deoptimization. 198 JValue ret_val_; 199 200 // Indicates whether the returned value is a reference. If so, the GC will visit it. 201 const bool is_reference_; 202 203 // Whether the context was created from an explicit deoptimization in the code. 204 const bool from_code_; 205 206 // The exception that was pending before deoptimization (or null if there was no pending 207 // exception). 208 mirror::Throwable* pending_exception_; 209 210 // A link to the previous DeoptimizationContextRecord. 211 DeoptimizationContextRecord* const link_; 212 213 DISALLOW_COPY_AND_ASSIGN(DeoptimizationContextRecord); 214}; 215 216class StackedShadowFrameRecord { 217 public: 218 StackedShadowFrameRecord(ShadowFrame* shadow_frame, 219 StackedShadowFrameType type, 220 StackedShadowFrameRecord* link) 221 : shadow_frame_(shadow_frame), 222 type_(type), 223 link_(link) {} 224 225 ShadowFrame* GetShadowFrame() const { return shadow_frame_; } 226 StackedShadowFrameType GetType() const { return type_; } 227 StackedShadowFrameRecord* GetLink() const { return link_; } 228 229 private: 230 ShadowFrame* const shadow_frame_; 231 const StackedShadowFrameType type_; 232 StackedShadowFrameRecord* const link_; 233 234 DISALLOW_COPY_AND_ASSIGN(StackedShadowFrameRecord); 235}; 236 237void Thread::PushDeoptimizationContext(const JValue& return_value, 238 bool is_reference, 239 bool from_code, 240 mirror::Throwable* exception) { 241 DeoptimizationContextRecord* record = new DeoptimizationContextRecord( 242 return_value, 243 is_reference, 244 from_code, 245 exception, 246 tlsPtr_.deoptimization_context_stack); 247 tlsPtr_.deoptimization_context_stack = record; 248} 249 250void Thread::PopDeoptimizationContext(JValue* result, 251 mirror::Throwable** exception, 252 bool* from_code) { 253 AssertHasDeoptimizationContext(); 254 DeoptimizationContextRecord* record = tlsPtr_.deoptimization_context_stack; 255 tlsPtr_.deoptimization_context_stack = record->GetLink(); 256 result->SetJ(record->GetReturnValue().GetJ()); 257 *exception = record->GetPendingException(); 258 *from_code = record->GetFromCode(); 259 delete record; 260} 261 262void Thread::AssertHasDeoptimizationContext() { 263 CHECK(tlsPtr_.deoptimization_context_stack != nullptr) 264 << "No deoptimization context for thread " << *this; 265} 266 267void Thread::PushStackedShadowFrame(ShadowFrame* sf, StackedShadowFrameType type) { 268 StackedShadowFrameRecord* record = new StackedShadowFrameRecord( 269 sf, type, tlsPtr_.stacked_shadow_frame_record); 270 tlsPtr_.stacked_shadow_frame_record = record; 271} 272 273ShadowFrame* Thread::PopStackedShadowFrame(StackedShadowFrameType type, bool must_be_present) { 274 StackedShadowFrameRecord* record = tlsPtr_.stacked_shadow_frame_record; 275 if (must_be_present) { 276 DCHECK(record != nullptr); 277 } else { 278 if (record == nullptr || record->GetType() != type) { 279 return nullptr; 280 } 281 } 282 tlsPtr_.stacked_shadow_frame_record = record->GetLink(); 283 ShadowFrame* shadow_frame = record->GetShadowFrame(); 284 delete record; 285 return shadow_frame; 286} 287 288class FrameIdToShadowFrame { 289 public: 290 static FrameIdToShadowFrame* Create(size_t frame_id, 291 ShadowFrame* shadow_frame, 292 FrameIdToShadowFrame* next, 293 size_t num_vregs) { 294 // Append a bool array at the end to keep track of what vregs are updated by the debugger. 295 uint8_t* memory = new uint8_t[sizeof(FrameIdToShadowFrame) + sizeof(bool) * num_vregs]; 296 return new (memory) FrameIdToShadowFrame(frame_id, shadow_frame, next); 297 } 298 299 static void Delete(FrameIdToShadowFrame* f) { 300 uint8_t* memory = reinterpret_cast<uint8_t*>(f); 301 delete[] memory; 302 } 303 304 size_t GetFrameId() const { return frame_id_; } 305 ShadowFrame* GetShadowFrame() const { return shadow_frame_; } 306 FrameIdToShadowFrame* GetNext() const { return next_; } 307 void SetNext(FrameIdToShadowFrame* next) { next_ = next; } 308 bool* GetUpdatedVRegFlags() { 309 return updated_vreg_flags_; 310 } 311 312 private: 313 FrameIdToShadowFrame(size_t frame_id, 314 ShadowFrame* shadow_frame, 315 FrameIdToShadowFrame* next) 316 : frame_id_(frame_id), 317 shadow_frame_(shadow_frame), 318 next_(next) {} 319 320 const size_t frame_id_; 321 ShadowFrame* const shadow_frame_; 322 FrameIdToShadowFrame* next_; 323 bool updated_vreg_flags_[0]; 324 325 DISALLOW_COPY_AND_ASSIGN(FrameIdToShadowFrame); 326}; 327 328static FrameIdToShadowFrame* FindFrameIdToShadowFrame(FrameIdToShadowFrame* head, 329 size_t frame_id) { 330 FrameIdToShadowFrame* found = nullptr; 331 for (FrameIdToShadowFrame* record = head; record != nullptr; record = record->GetNext()) { 332 if (record->GetFrameId() == frame_id) { 333 if (kIsDebugBuild) { 334 // Sanity check we have at most one record for this frame. 335 CHECK(found == nullptr) << "Multiple records for the frame " << frame_id; 336 found = record; 337 } else { 338 return record; 339 } 340 } 341 } 342 return found; 343} 344 345ShadowFrame* Thread::FindDebuggerShadowFrame(size_t frame_id) { 346 FrameIdToShadowFrame* record = FindFrameIdToShadowFrame( 347 tlsPtr_.frame_id_to_shadow_frame, frame_id); 348 if (record != nullptr) { 349 return record->GetShadowFrame(); 350 } 351 return nullptr; 352} 353 354// Must only be called when FindDebuggerShadowFrame(frame_id) returns non-nullptr. 355bool* Thread::GetUpdatedVRegFlags(size_t frame_id) { 356 FrameIdToShadowFrame* record = FindFrameIdToShadowFrame( 357 tlsPtr_.frame_id_to_shadow_frame, frame_id); 358 CHECK(record != nullptr); 359 return record->GetUpdatedVRegFlags(); 360} 361 362ShadowFrame* Thread::FindOrCreateDebuggerShadowFrame(size_t frame_id, 363 uint32_t num_vregs, 364 ArtMethod* method, 365 uint32_t dex_pc) { 366 ShadowFrame* shadow_frame = FindDebuggerShadowFrame(frame_id); 367 if (shadow_frame != nullptr) { 368 return shadow_frame; 369 } 370 VLOG(deopt) << "Create pre-deopted ShadowFrame for " << PrettyMethod(method); 371 shadow_frame = ShadowFrame::CreateDeoptimizedFrame(num_vregs, nullptr, method, dex_pc); 372 FrameIdToShadowFrame* record = FrameIdToShadowFrame::Create(frame_id, 373 shadow_frame, 374 tlsPtr_.frame_id_to_shadow_frame, 375 num_vregs); 376 for (uint32_t i = 0; i < num_vregs; i++) { 377 // Do this to clear all references for root visitors. 378 shadow_frame->SetVRegReference(i, nullptr); 379 // This flag will be changed to true if the debugger modifies the value. 380 record->GetUpdatedVRegFlags()[i] = false; 381 } 382 tlsPtr_.frame_id_to_shadow_frame = record; 383 return shadow_frame; 384} 385 386void Thread::RemoveDebuggerShadowFrameMapping(size_t frame_id) { 387 FrameIdToShadowFrame* head = tlsPtr_.frame_id_to_shadow_frame; 388 if (head->GetFrameId() == frame_id) { 389 tlsPtr_.frame_id_to_shadow_frame = head->GetNext(); 390 FrameIdToShadowFrame::Delete(head); 391 return; 392 } 393 FrameIdToShadowFrame* prev = head; 394 for (FrameIdToShadowFrame* record = head->GetNext(); 395 record != nullptr; 396 prev = record, record = record->GetNext()) { 397 if (record->GetFrameId() == frame_id) { 398 prev->SetNext(record->GetNext()); 399 FrameIdToShadowFrame::Delete(record); 400 return; 401 } 402 } 403 LOG(FATAL) << "No shadow frame for frame " << frame_id; 404 UNREACHABLE(); 405} 406 407void Thread::InitTid() { 408 tls32_.tid = ::art::GetTid(); 409} 410 411void Thread::InitAfterFork() { 412 // One thread (us) survived the fork, but we have a new tid so we need to 413 // update the value stashed in this Thread*. 414 InitTid(); 415} 416 417void* Thread::CreateCallback(void* arg) { 418 Thread* self = reinterpret_cast<Thread*>(arg); 419 Runtime* runtime = Runtime::Current(); 420 if (runtime == nullptr) { 421 LOG(ERROR) << "Thread attaching to non-existent runtime: " << *self; 422 return nullptr; 423 } 424 { 425 // TODO: pass self to MutexLock - requires self to equal Thread::Current(), which is only true 426 // after self->Init(). 427 MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_); 428 // Check that if we got here we cannot be shutting down (as shutdown should never have started 429 // while threads are being born). 430 CHECK(!runtime->IsShuttingDownLocked()); 431 // Note: given that the JNIEnv is created in the parent thread, the only failure point here is 432 // a mess in InitStackHwm. We do not have a reasonable way to recover from that, so abort 433 // the runtime in such a case. In case this ever changes, we need to make sure here to 434 // delete the tmp_jni_env, as we own it at this point. 435 CHECK(self->Init(runtime->GetThreadList(), runtime->GetJavaVM(), self->tlsPtr_.tmp_jni_env)); 436 self->tlsPtr_.tmp_jni_env = nullptr; 437 Runtime::Current()->EndThreadBirth(); 438 } 439 { 440 ScopedObjectAccess soa(self); 441 self->InitStringEntryPoints(); 442 443 // Copy peer into self, deleting global reference when done. 444 CHECK(self->tlsPtr_.jpeer != nullptr); 445 self->tlsPtr_.opeer = soa.Decode<mirror::Object*>(self->tlsPtr_.jpeer); 446 self->GetJniEnv()->DeleteGlobalRef(self->tlsPtr_.jpeer); 447 self->tlsPtr_.jpeer = nullptr; 448 self->SetThreadName(self->GetThreadName(soa)->ToModifiedUtf8().c_str()); 449 450 ArtField* priorityField = soa.DecodeField(WellKnownClasses::java_lang_Thread_priority); 451 self->SetNativePriority(priorityField->GetInt(self->tlsPtr_.opeer)); 452 Dbg::PostThreadStart(self); 453 454 // Invoke the 'run' method of our java.lang.Thread. 455 mirror::Object* receiver = self->tlsPtr_.opeer; 456 jmethodID mid = WellKnownClasses::java_lang_Thread_run; 457 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(receiver)); 458 InvokeVirtualOrInterfaceWithJValues(soa, ref.get(), mid, nullptr); 459 } 460 // Detach and delete self. 461 Runtime::Current()->GetThreadList()->Unregister(self); 462 463 return nullptr; 464} 465 466Thread* Thread::FromManagedThread(const ScopedObjectAccessAlreadyRunnable& soa, 467 mirror::Object* thread_peer) { 468 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_nativePeer); 469 Thread* result = reinterpret_cast<Thread*>(static_cast<uintptr_t>(f->GetLong(thread_peer))); 470 // Sanity check that if we have a result it is either suspended or we hold the thread_list_lock_ 471 // to stop it from going away. 472 if (kIsDebugBuild) { 473 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_); 474 if (result != nullptr && !result->IsSuspended()) { 475 Locks::thread_list_lock_->AssertHeld(soa.Self()); 476 } 477 } 478 return result; 479} 480 481Thread* Thread::FromManagedThread(const ScopedObjectAccessAlreadyRunnable& soa, 482 jobject java_thread) { 483 return FromManagedThread(soa, soa.Decode<mirror::Object*>(java_thread)); 484} 485 486static size_t FixStackSize(size_t stack_size) { 487 // A stack size of zero means "use the default". 488 if (stack_size == 0) { 489 stack_size = Runtime::Current()->GetDefaultStackSize(); 490 } 491 492 // Dalvik used the bionic pthread default stack size for native threads, 493 // so include that here to support apps that expect large native stacks. 494 stack_size += 1 * MB; 495 496 // It's not possible to request a stack smaller than the system-defined PTHREAD_STACK_MIN. 497 if (stack_size < PTHREAD_STACK_MIN) { 498 stack_size = PTHREAD_STACK_MIN; 499 } 500 501 if (Runtime::Current()->ExplicitStackOverflowChecks()) { 502 // It's likely that callers are trying to ensure they have at least a certain amount of 503 // stack space, so we should add our reserved space on top of what they requested, rather 504 // than implicitly take it away from them. 505 stack_size += GetStackOverflowReservedBytes(kRuntimeISA); 506 } else { 507 // If we are going to use implicit stack checks, allocate space for the protected 508 // region at the bottom of the stack. 509 stack_size += Thread::kStackOverflowImplicitCheckSize + 510 GetStackOverflowReservedBytes(kRuntimeISA); 511 } 512 513 // Some systems require the stack size to be a multiple of the system page size, so round up. 514 stack_size = RoundUp(stack_size, kPageSize); 515 516 return stack_size; 517} 518 519// Return the nearest page-aligned address below the current stack top. 520NO_INLINE 521static uint8_t* FindStackTop() { 522 return reinterpret_cast<uint8_t*>( 523 AlignDown(__builtin_frame_address(0), kPageSize)); 524} 525 526// Install a protected region in the stack. This is used to trigger a SIGSEGV if a stack 527// overflow is detected. It is located right below the stack_begin_. 528ATTRIBUTE_NO_SANITIZE_ADDRESS 529void Thread::InstallImplicitProtection() { 530 uint8_t* pregion = tlsPtr_.stack_begin - kStackOverflowProtectedSize; 531 // Page containing current top of stack. 532 uint8_t* stack_top = FindStackTop(); 533 534 // Try to directly protect the stack. 535 VLOG(threads) << "installing stack protected region at " << std::hex << 536 static_cast<void*>(pregion) << " to " << 537 static_cast<void*>(pregion + kStackOverflowProtectedSize - 1); 538 if (ProtectStack(/* fatal_on_error */ false)) { 539 // Tell the kernel that we won't be needing these pages any more. 540 // NB. madvise will probably write zeroes into the memory (on linux it does). 541 uint32_t unwanted_size = stack_top - pregion - kPageSize; 542 madvise(pregion, unwanted_size, MADV_DONTNEED); 543 return; 544 } 545 546 // There is a little complexity here that deserves a special mention. On some 547 // architectures, the stack is created using a VM_GROWSDOWN flag 548 // to prevent memory being allocated when it's not needed. This flag makes the 549 // kernel only allocate memory for the stack by growing down in memory. Because we 550 // want to put an mprotected region far away from that at the stack top, we need 551 // to make sure the pages for the stack are mapped in before we call mprotect. 552 // 553 // The failed mprotect in UnprotectStack is an indication of a thread with VM_GROWSDOWN 554 // with a non-mapped stack (usually only the main thread). 555 // 556 // We map in the stack by reading every page from the stack bottom (highest address) 557 // to the stack top. (We then madvise this away.) This must be done by reading from the 558 // current stack pointer downwards. Any access more than a page below the current SP 559 // might cause a segv. 560 // TODO: This comment may be out of date. It seems possible to speed this up. As 561 // this is normally done once in the zygote on startup, ignore for now. 562 // 563 // AddressSanitizer does not like the part of this functions that reads every stack page. 564 // Looks a lot like an out-of-bounds access. 565 566 // (Defensively) first remove the protection on the protected region as will want to read 567 // and write it. Ignore errors. 568 UnprotectStack(); 569 570 VLOG(threads) << "Need to map in stack for thread at " << std::hex << 571 static_cast<void*>(pregion); 572 573 // Read every page from the high address to the low. 574 volatile uint8_t dont_optimize_this; 575 UNUSED(dont_optimize_this); 576 for (uint8_t* p = stack_top; p >= pregion; p -= kPageSize) { 577 dont_optimize_this = *p; 578 } 579 580 VLOG(threads) << "(again) installing stack protected region at " << std::hex << 581 static_cast<void*>(pregion) << " to " << 582 static_cast<void*>(pregion + kStackOverflowProtectedSize - 1); 583 584 // Protect the bottom of the stack to prevent read/write to it. 585 ProtectStack(/* fatal_on_error */ true); 586 587 // Tell the kernel that we won't be needing these pages any more. 588 // NB. madvise will probably write zeroes into the memory (on linux it does). 589 uint32_t unwanted_size = stack_top - pregion - kPageSize; 590 madvise(pregion, unwanted_size, MADV_DONTNEED); 591} 592 593void Thread::CreateNativeThread(JNIEnv* env, jobject java_peer, size_t stack_size, bool is_daemon) { 594 CHECK(java_peer != nullptr); 595 Thread* self = static_cast<JNIEnvExt*>(env)->self; 596 597 if (VLOG_IS_ON(threads)) { 598 ScopedObjectAccess soa(env); 599 600 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_name); 601 mirror::String* java_name = reinterpret_cast<mirror::String*>(f->GetObject( 602 soa.Decode<mirror::Object*>(java_peer))); 603 std::string thread_name; 604 if (java_name != nullptr) { 605 thread_name = java_name->ToModifiedUtf8(); 606 } else { 607 thread_name = "(Unnamed)"; 608 } 609 610 VLOG(threads) << "Creating native thread for " << thread_name; 611 self->Dump(LOG(INFO)); 612 } 613 614 Runtime* runtime = Runtime::Current(); 615 616 // Atomically start the birth of the thread ensuring the runtime isn't shutting down. 617 bool thread_start_during_shutdown = false; 618 { 619 MutexLock mu(self, *Locks::runtime_shutdown_lock_); 620 if (runtime->IsShuttingDownLocked()) { 621 thread_start_during_shutdown = true; 622 } else { 623 runtime->StartThreadBirth(); 624 } 625 } 626 if (thread_start_during_shutdown) { 627 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/InternalError")); 628 env->ThrowNew(error_class.get(), "Thread starting during runtime shutdown"); 629 return; 630 } 631 632 Thread* child_thread = new Thread(is_daemon); 633 // Use global JNI ref to hold peer live while child thread starts. 634 child_thread->tlsPtr_.jpeer = env->NewGlobalRef(java_peer); 635 stack_size = FixStackSize(stack_size); 636 637 // Thread.start is synchronized, so we know that nativePeer is 0, and know that we're not racing to 638 // assign it. 639 env->SetLongField(java_peer, WellKnownClasses::java_lang_Thread_nativePeer, 640 reinterpret_cast<jlong>(child_thread)); 641 642 // Try to allocate a JNIEnvExt for the thread. We do this here as we might be out of memory and 643 // do not have a good way to report this on the child's side. 644 std::unique_ptr<JNIEnvExt> child_jni_env_ext( 645 JNIEnvExt::Create(child_thread, Runtime::Current()->GetJavaVM())); 646 647 int pthread_create_result = 0; 648 if (child_jni_env_ext.get() != nullptr) { 649 pthread_t new_pthread; 650 pthread_attr_t attr; 651 child_thread->tlsPtr_.tmp_jni_env = child_jni_env_ext.get(); 652 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread"); 653 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), 654 "PTHREAD_CREATE_DETACHED"); 655 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size); 656 pthread_create_result = pthread_create(&new_pthread, 657 &attr, 658 Thread::CreateCallback, 659 child_thread); 660 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread"); 661 662 if (pthread_create_result == 0) { 663 // pthread_create started the new thread. The child is now responsible for managing the 664 // JNIEnvExt we created. 665 // Note: we can't check for tmp_jni_env == nullptr, as that would require synchronization 666 // between the threads. 667 child_jni_env_ext.release(); 668 return; 669 } 670 } 671 672 // Either JNIEnvExt::Create or pthread_create(3) failed, so clean up. 673 { 674 MutexLock mu(self, *Locks::runtime_shutdown_lock_); 675 runtime->EndThreadBirth(); 676 } 677 // Manually delete the global reference since Thread::Init will not have been run. 678 env->DeleteGlobalRef(child_thread->tlsPtr_.jpeer); 679 child_thread->tlsPtr_.jpeer = nullptr; 680 delete child_thread; 681 child_thread = nullptr; 682 // TODO: remove from thread group? 683 env->SetLongField(java_peer, WellKnownClasses::java_lang_Thread_nativePeer, 0); 684 { 685 std::string msg(child_jni_env_ext.get() == nullptr ? 686 "Could not allocate JNI Env" : 687 StringPrintf("pthread_create (%s stack) failed: %s", 688 PrettySize(stack_size).c_str(), strerror(pthread_create_result))); 689 ScopedObjectAccess soa(env); 690 soa.Self()->ThrowOutOfMemoryError(msg.c_str()); 691 } 692} 693 694bool Thread::Init(ThreadList* thread_list, JavaVMExt* java_vm, JNIEnvExt* jni_env_ext) { 695 // This function does all the initialization that must be run by the native thread it applies to. 696 // (When we create a new thread from managed code, we allocate the Thread* in Thread::Create so 697 // we can handshake with the corresponding native thread when it's ready.) Check this native 698 // thread hasn't been through here already... 699 CHECK(Thread::Current() == nullptr); 700 701 // Set pthread_self_ ahead of pthread_setspecific, that makes Thread::Current function, this 702 // avoids pthread_self_ ever being invalid when discovered from Thread::Current(). 703 tlsPtr_.pthread_self = pthread_self(); 704 CHECK(is_started_); 705 706 SetUpAlternateSignalStack(); 707 if (!InitStackHwm()) { 708 return false; 709 } 710 InitCpu(); 711 InitTlsEntryPoints(); 712 RemoveSuspendTrigger(); 713 InitCardTable(); 714 InitTid(); 715 interpreter::InitInterpreterTls(this); 716 717#ifdef ART_TARGET_ANDROID 718 __get_tls()[TLS_SLOT_ART_THREAD_SELF] = this; 719#else 720 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach self"); 721#endif 722 DCHECK_EQ(Thread::Current(), this); 723 724 tls32_.thin_lock_thread_id = thread_list->AllocThreadId(this); 725 726 if (jni_env_ext != nullptr) { 727 DCHECK_EQ(jni_env_ext->vm, java_vm); 728 DCHECK_EQ(jni_env_ext->self, this); 729 tlsPtr_.jni_env = jni_env_ext; 730 } else { 731 tlsPtr_.jni_env = JNIEnvExt::Create(this, java_vm); 732 if (tlsPtr_.jni_env == nullptr) { 733 return false; 734 } 735 } 736 737 thread_list->Register(this); 738 return true; 739} 740 741Thread* Thread::Attach(const char* thread_name, bool as_daemon, jobject thread_group, 742 bool create_peer) { 743 Runtime* runtime = Runtime::Current(); 744 if (runtime == nullptr) { 745 LOG(ERROR) << "Thread attaching to non-existent runtime: " << thread_name; 746 return nullptr; 747 } 748 Thread* self; 749 { 750 MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_); 751 if (runtime->IsShuttingDownLocked()) { 752 LOG(WARNING) << "Thread attaching while runtime is shutting down: " << thread_name; 753 return nullptr; 754 } else { 755 Runtime::Current()->StartThreadBirth(); 756 self = new Thread(as_daemon); 757 bool init_success = self->Init(runtime->GetThreadList(), runtime->GetJavaVM()); 758 Runtime::Current()->EndThreadBirth(); 759 if (!init_success) { 760 delete self; 761 return nullptr; 762 } 763 } 764 } 765 766 self->InitStringEntryPoints(); 767 768 CHECK_NE(self->GetState(), kRunnable); 769 self->SetState(kNative); 770 771 // If we're the main thread, ClassLinker won't be created until after we're attached, 772 // so that thread needs a two-stage attach. Regular threads don't need this hack. 773 // In the compiler, all threads need this hack, because no-one's going to be getting 774 // a native peer! 775 if (create_peer) { 776 self->CreatePeer(thread_name, as_daemon, thread_group); 777 if (self->IsExceptionPending()) { 778 // We cannot keep the exception around, as we're deleting self. Try to be helpful and log it. 779 { 780 ScopedObjectAccess soa(self); 781 LOG(ERROR) << "Exception creating thread peer:"; 782 LOG(ERROR) << self->GetException()->Dump(); 783 self->ClearException(); 784 } 785 runtime->GetThreadList()->Unregister(self); 786 // Unregister deletes self, no need to do this here. 787 return nullptr; 788 } 789 } else { 790 // These aren't necessary, but they improve diagnostics for unit tests & command-line tools. 791 if (thread_name != nullptr) { 792 self->tlsPtr_.name->assign(thread_name); 793 ::art::SetThreadName(thread_name); 794 } else if (self->GetJniEnv()->check_jni) { 795 LOG(WARNING) << *Thread::Current() << " attached without supplying a name"; 796 } 797 } 798 799 if (VLOG_IS_ON(threads)) { 800 if (thread_name != nullptr) { 801 VLOG(threads) << "Attaching thread " << thread_name; 802 } else { 803 VLOG(threads) << "Attaching unnamed thread."; 804 } 805 ScopedObjectAccess soa(self); 806 self->Dump(LOG(INFO)); 807 } 808 809 { 810 ScopedObjectAccess soa(self); 811 Dbg::PostThreadStart(self); 812 } 813 814 return self; 815} 816 817void Thread::CreatePeer(const char* name, bool as_daemon, jobject thread_group) { 818 Runtime* runtime = Runtime::Current(); 819 CHECK(runtime->IsStarted()); 820 JNIEnv* env = tlsPtr_.jni_env; 821 822 if (thread_group == nullptr) { 823 thread_group = runtime->GetMainThreadGroup(); 824 } 825 ScopedLocalRef<jobject> thread_name(env, env->NewStringUTF(name)); 826 // Add missing null check in case of OOM b/18297817 827 if (name != nullptr && thread_name.get() == nullptr) { 828 CHECK(IsExceptionPending()); 829 return; 830 } 831 jint thread_priority = GetNativePriority(); 832 jboolean thread_is_daemon = as_daemon; 833 834 ScopedLocalRef<jobject> peer(env, env->AllocObject(WellKnownClasses::java_lang_Thread)); 835 if (peer.get() == nullptr) { 836 CHECK(IsExceptionPending()); 837 return; 838 } 839 { 840 ScopedObjectAccess soa(this); 841 tlsPtr_.opeer = soa.Decode<mirror::Object*>(peer.get()); 842 } 843 env->CallNonvirtualVoidMethod(peer.get(), 844 WellKnownClasses::java_lang_Thread, 845 WellKnownClasses::java_lang_Thread_init, 846 thread_group, thread_name.get(), thread_priority, thread_is_daemon); 847 if (IsExceptionPending()) { 848 return; 849 } 850 851 Thread* self = this; 852 DCHECK_EQ(self, Thread::Current()); 853 env->SetLongField(peer.get(), WellKnownClasses::java_lang_Thread_nativePeer, 854 reinterpret_cast<jlong>(self)); 855 856 ScopedObjectAccess soa(self); 857 StackHandleScope<1> hs(self); 858 MutableHandle<mirror::String> peer_thread_name(hs.NewHandle(GetThreadName(soa))); 859 if (peer_thread_name.Get() == nullptr) { 860 // The Thread constructor should have set the Thread.name to a 861 // non-null value. However, because we can run without code 862 // available (in the compiler, in tests), we manually assign the 863 // fields the constructor should have set. 864 if (runtime->IsActiveTransaction()) { 865 InitPeer<true>(soa, thread_is_daemon, thread_group, thread_name.get(), thread_priority); 866 } else { 867 InitPeer<false>(soa, thread_is_daemon, thread_group, thread_name.get(), thread_priority); 868 } 869 peer_thread_name.Assign(GetThreadName(soa)); 870 } 871 // 'thread_name' may have been null, so don't trust 'peer_thread_name' to be non-null. 872 if (peer_thread_name.Get() != nullptr) { 873 SetThreadName(peer_thread_name->ToModifiedUtf8().c_str()); 874 } 875} 876 877template<bool kTransactionActive> 878void Thread::InitPeer(ScopedObjectAccess& soa, jboolean thread_is_daemon, jobject thread_group, 879 jobject thread_name, jint thread_priority) { 880 soa.DecodeField(WellKnownClasses::java_lang_Thread_daemon)-> 881 SetBoolean<kTransactionActive>(tlsPtr_.opeer, thread_is_daemon); 882 soa.DecodeField(WellKnownClasses::java_lang_Thread_group)-> 883 SetObject<kTransactionActive>(tlsPtr_.opeer, soa.Decode<mirror::Object*>(thread_group)); 884 soa.DecodeField(WellKnownClasses::java_lang_Thread_name)-> 885 SetObject<kTransactionActive>(tlsPtr_.opeer, soa.Decode<mirror::Object*>(thread_name)); 886 soa.DecodeField(WellKnownClasses::java_lang_Thread_priority)-> 887 SetInt<kTransactionActive>(tlsPtr_.opeer, thread_priority); 888} 889 890void Thread::SetThreadName(const char* name) { 891 tlsPtr_.name->assign(name); 892 ::art::SetThreadName(name); 893 Dbg::DdmSendThreadNotification(this, CHUNK_TYPE("THNM")); 894} 895 896bool Thread::InitStackHwm() { 897 void* read_stack_base; 898 size_t read_stack_size; 899 size_t read_guard_size; 900 GetThreadStack(tlsPtr_.pthread_self, &read_stack_base, &read_stack_size, &read_guard_size); 901 902 tlsPtr_.stack_begin = reinterpret_cast<uint8_t*>(read_stack_base); 903 tlsPtr_.stack_size = read_stack_size; 904 905 // The minimum stack size we can cope with is the overflow reserved bytes (typically 906 // 8K) + the protected region size (4K) + another page (4K). Typically this will 907 // be 8+4+4 = 16K. The thread won't be able to do much with this stack even the GC takes 908 // between 8K and 12K. 909 uint32_t min_stack = GetStackOverflowReservedBytes(kRuntimeISA) + kStackOverflowProtectedSize 910 + 4 * KB; 911 if (read_stack_size <= min_stack) { 912 // Note, as we know the stack is small, avoid operations that could use a lot of stack. 913 LogMessage::LogLineLowStack(__PRETTY_FUNCTION__, __LINE__, ERROR, 914 "Attempt to attach a thread with a too-small stack"); 915 return false; 916 } 917 918 // This is included in the SIGQUIT output, but it's useful here for thread debugging. 919 VLOG(threads) << StringPrintf("Native stack is at %p (%s with %s guard)", 920 read_stack_base, 921 PrettySize(read_stack_size).c_str(), 922 PrettySize(read_guard_size).c_str()); 923 924 // Set stack_end_ to the bottom of the stack saving space of stack overflows 925 926 Runtime* runtime = Runtime::Current(); 927 bool implicit_stack_check = !runtime->ExplicitStackOverflowChecks() && !runtime->IsAotCompiler(); 928 929 // Valgrind on arm doesn't give the right values here. Do not install the guard page, and 930 // effectively disable stack overflow checks (we'll get segfaults, potentially) by setting 931 // stack_begin to 0. 932 const bool valgrind_on_arm = 933 (kRuntimeISA == kArm || kRuntimeISA == kArm64) && 934 kMemoryToolIsValgrind && 935 RUNNING_ON_MEMORY_TOOL != 0; 936 if (valgrind_on_arm) { 937 tlsPtr_.stack_begin = nullptr; 938 } 939 940 ResetDefaultStackEnd(); 941 942 // Install the protected region if we are doing implicit overflow checks. 943 if (implicit_stack_check && !valgrind_on_arm) { 944 // The thread might have protected region at the bottom. We need 945 // to install our own region so we need to move the limits 946 // of the stack to make room for it. 947 948 tlsPtr_.stack_begin += read_guard_size + kStackOverflowProtectedSize; 949 tlsPtr_.stack_end += read_guard_size + kStackOverflowProtectedSize; 950 tlsPtr_.stack_size -= read_guard_size; 951 952 InstallImplicitProtection(); 953 } 954 955 // Sanity check. 956 CHECK_GT(FindStackTop(), reinterpret_cast<void*>(tlsPtr_.stack_end)); 957 958 return true; 959} 960 961void Thread::ShortDump(std::ostream& os) const { 962 os << "Thread["; 963 if (GetThreadId() != 0) { 964 // If we're in kStarting, we won't have a thin lock id or tid yet. 965 os << GetThreadId() 966 << ",tid=" << GetTid() << ','; 967 } 968 os << GetState() 969 << ",Thread*=" << this 970 << ",peer=" << tlsPtr_.opeer 971 << ",\"" << (tlsPtr_.name != nullptr ? *tlsPtr_.name : "null") << "\"" 972 << "]"; 973} 974 975void Thread::Dump(std::ostream& os, bool dump_native_stack, BacktraceMap* backtrace_map) const { 976 DumpState(os); 977 DumpStack(os, dump_native_stack, backtrace_map); 978} 979 980mirror::String* Thread::GetThreadName(const ScopedObjectAccessAlreadyRunnable& soa) const { 981 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_name); 982 return (tlsPtr_.opeer != nullptr) ? 983 reinterpret_cast<mirror::String*>(f->GetObject(tlsPtr_.opeer)) : nullptr; 984} 985 986void Thread::GetThreadName(std::string& name) const { 987 name.assign(*tlsPtr_.name); 988} 989 990uint64_t Thread::GetCpuMicroTime() const { 991#if defined(__linux__) 992 clockid_t cpu_clock_id; 993 pthread_getcpuclockid(tlsPtr_.pthread_self, &cpu_clock_id); 994 timespec now; 995 clock_gettime(cpu_clock_id, &now); 996 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_nsec / UINT64_C(1000); 997#else // __APPLE__ 998 UNIMPLEMENTED(WARNING); 999 return -1; 1000#endif 1001} 1002 1003// Attempt to rectify locks so that we dump thread list with required locks before exiting. 1004static void UnsafeLogFatalForSuspendCount(Thread* self, Thread* thread) NO_THREAD_SAFETY_ANALYSIS { 1005 LOG(ERROR) << *thread << " suspend count already zero."; 1006 Locks::thread_suspend_count_lock_->Unlock(self); 1007 if (!Locks::mutator_lock_->IsSharedHeld(self)) { 1008 Locks::mutator_lock_->SharedTryLock(self); 1009 if (!Locks::mutator_lock_->IsSharedHeld(self)) { 1010 LOG(WARNING) << "Dumping thread list without holding mutator_lock_"; 1011 } 1012 } 1013 if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) { 1014 Locks::thread_list_lock_->TryLock(self); 1015 if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) { 1016 LOG(WARNING) << "Dumping thread list without holding thread_list_lock_"; 1017 } 1018 } 1019 std::ostringstream ss; 1020 Runtime::Current()->GetThreadList()->Dump(ss); 1021 LOG(FATAL) << ss.str(); 1022} 1023 1024bool Thread::ModifySuspendCount(Thread* self, int delta, AtomicInteger* suspend_barrier, 1025 bool for_debugger) { 1026 if (kIsDebugBuild) { 1027 DCHECK(delta == -1 || delta == +1 || delta == -tls32_.debug_suspend_count) 1028 << delta << " " << tls32_.debug_suspend_count << " " << this; 1029 DCHECK_GE(tls32_.suspend_count, tls32_.debug_suspend_count) << this; 1030 Locks::thread_suspend_count_lock_->AssertHeld(self); 1031 if (this != self && !IsSuspended()) { 1032 Locks::thread_list_lock_->AssertHeld(self); 1033 } 1034 } 1035 if (UNLIKELY(delta < 0 && tls32_.suspend_count <= 0)) { 1036 UnsafeLogFatalForSuspendCount(self, this); 1037 return false; 1038 } 1039 1040 uint16_t flags = kSuspendRequest; 1041 if (delta > 0 && suspend_barrier != nullptr) { 1042 uint32_t available_barrier = kMaxSuspendBarriers; 1043 for (uint32_t i = 0; i < kMaxSuspendBarriers; ++i) { 1044 if (tlsPtr_.active_suspend_barriers[i] == nullptr) { 1045 available_barrier = i; 1046 break; 1047 } 1048 } 1049 if (available_barrier == kMaxSuspendBarriers) { 1050 // No barrier spaces available, we can't add another. 1051 return false; 1052 } 1053 tlsPtr_.active_suspend_barriers[available_barrier] = suspend_barrier; 1054 flags |= kActiveSuspendBarrier; 1055 } 1056 1057 tls32_.suspend_count += delta; 1058 if (for_debugger) { 1059 tls32_.debug_suspend_count += delta; 1060 } 1061 1062 if (tls32_.suspend_count == 0) { 1063 AtomicClearFlag(kSuspendRequest); 1064 } else { 1065 // Two bits might be set simultaneously. 1066 tls32_.state_and_flags.as_atomic_int.FetchAndOrSequentiallyConsistent(flags); 1067 TriggerSuspend(); 1068 } 1069 return true; 1070} 1071 1072bool Thread::PassActiveSuspendBarriers(Thread* self) { 1073 // Grab the suspend_count lock and copy the current set of 1074 // barriers. Then clear the list and the flag. The ModifySuspendCount 1075 // function requires the lock so we prevent a race between setting 1076 // the kActiveSuspendBarrier flag and clearing it. 1077 AtomicInteger* pass_barriers[kMaxSuspendBarriers]; 1078 { 1079 MutexLock mu(self, *Locks::thread_suspend_count_lock_); 1080 if (!ReadFlag(kActiveSuspendBarrier)) { 1081 // quick exit test: the barriers have already been claimed - this is 1082 // possible as there may be a race to claim and it doesn't matter 1083 // who wins. 1084 // All of the callers of this function (except the SuspendAllInternal) 1085 // will first test the kActiveSuspendBarrier flag without lock. Here 1086 // double-check whether the barrier has been passed with the 1087 // suspend_count lock. 1088 return false; 1089 } 1090 1091 for (uint32_t i = 0; i < kMaxSuspendBarriers; ++i) { 1092 pass_barriers[i] = tlsPtr_.active_suspend_barriers[i]; 1093 tlsPtr_.active_suspend_barriers[i] = nullptr; 1094 } 1095 AtomicClearFlag(kActiveSuspendBarrier); 1096 } 1097 1098 uint32_t barrier_count = 0; 1099 for (uint32_t i = 0; i < kMaxSuspendBarriers; i++) { 1100 AtomicInteger* pending_threads = pass_barriers[i]; 1101 if (pending_threads != nullptr) { 1102 bool done = false; 1103 do { 1104 int32_t cur_val = pending_threads->LoadRelaxed(); 1105 CHECK_GT(cur_val, 0) << "Unexpected value for PassActiveSuspendBarriers(): " << cur_val; 1106 // Reduce value by 1. 1107 done = pending_threads->CompareExchangeWeakRelaxed(cur_val, cur_val - 1); 1108#if ART_USE_FUTEXES 1109 if (done && (cur_val - 1) == 0) { // Weak CAS may fail spuriously. 1110 futex(pending_threads->Address(), FUTEX_WAKE, -1, nullptr, nullptr, 0); 1111 } 1112#endif 1113 } while (!done); 1114 ++barrier_count; 1115 } 1116 } 1117 CHECK_GT(barrier_count, 0U); 1118 return true; 1119} 1120 1121void Thread::ClearSuspendBarrier(AtomicInteger* target) { 1122 CHECK(ReadFlag(kActiveSuspendBarrier)); 1123 bool clear_flag = true; 1124 for (uint32_t i = 0; i < kMaxSuspendBarriers; ++i) { 1125 AtomicInteger* ptr = tlsPtr_.active_suspend_barriers[i]; 1126 if (ptr == target) { 1127 tlsPtr_.active_suspend_barriers[i] = nullptr; 1128 } else if (ptr != nullptr) { 1129 clear_flag = false; 1130 } 1131 } 1132 if (LIKELY(clear_flag)) { 1133 AtomicClearFlag(kActiveSuspendBarrier); 1134 } 1135} 1136 1137void Thread::RunCheckpointFunction() { 1138 bool done = false; 1139 do { 1140 // Grab the suspend_count lock and copy the checkpoints one by one. When the last checkpoint is 1141 // copied, clear the list and the flag. The RequestCheckpoint function will also grab this lock 1142 // to prevent a race between setting the kCheckpointRequest flag and clearing it. 1143 Closure* checkpoint = nullptr; 1144 { 1145 MutexLock mu(this, *Locks::thread_suspend_count_lock_); 1146 if (tlsPtr_.checkpoint_function != nullptr) { 1147 checkpoint = tlsPtr_.checkpoint_function; 1148 if (!checkpoint_overflow_.empty()) { 1149 // Overflow list not empty, copy the first one out and continue. 1150 tlsPtr_.checkpoint_function = checkpoint_overflow_.front(); 1151 checkpoint_overflow_.pop_front(); 1152 } else { 1153 // No overflow checkpoints, this means that we are on the last pending checkpoint. 1154 tlsPtr_.checkpoint_function = nullptr; 1155 AtomicClearFlag(kCheckpointRequest); 1156 done = true; 1157 } 1158 } else { 1159 LOG(FATAL) << "Checkpoint flag set without pending checkpoint"; 1160 } 1161 } 1162 1163 // Outside the lock, run the checkpoint functions that we collected. 1164 ScopedTrace trace("Run checkpoint function"); 1165 DCHECK(checkpoint != nullptr); 1166 checkpoint->Run(this); 1167 } while (!done); 1168} 1169 1170bool Thread::RequestCheckpoint(Closure* function) { 1171 union StateAndFlags old_state_and_flags; 1172 old_state_and_flags.as_int = tls32_.state_and_flags.as_int; 1173 if (old_state_and_flags.as_struct.state != kRunnable) { 1174 return false; // Fail, thread is suspended and so can't run a checkpoint. 1175 } 1176 1177 // We must be runnable to request a checkpoint. 1178 DCHECK_EQ(old_state_and_flags.as_struct.state, kRunnable); 1179 union StateAndFlags new_state_and_flags; 1180 new_state_and_flags.as_int = old_state_and_flags.as_int; 1181 new_state_and_flags.as_struct.flags |= kCheckpointRequest; 1182 bool success = tls32_.state_and_flags.as_atomic_int.CompareExchangeStrongSequentiallyConsistent( 1183 old_state_and_flags.as_int, new_state_and_flags.as_int); 1184 if (success) { 1185 // Succeeded setting checkpoint flag, now insert the actual checkpoint. 1186 if (tlsPtr_.checkpoint_function == nullptr) { 1187 tlsPtr_.checkpoint_function = function; 1188 } else { 1189 checkpoint_overflow_.push_back(function); 1190 } 1191 CHECK_EQ(ReadFlag(kCheckpointRequest), true); 1192 TriggerSuspend(); 1193 } 1194 return success; 1195} 1196 1197Closure* Thread::GetFlipFunction() { 1198 Atomic<Closure*>* atomic_func = reinterpret_cast<Atomic<Closure*>*>(&tlsPtr_.flip_function); 1199 Closure* func; 1200 do { 1201 func = atomic_func->LoadRelaxed(); 1202 if (func == nullptr) { 1203 return nullptr; 1204 } 1205 } while (!atomic_func->CompareExchangeWeakSequentiallyConsistent(func, nullptr)); 1206 DCHECK(func != nullptr); 1207 return func; 1208} 1209 1210void Thread::SetFlipFunction(Closure* function) { 1211 CHECK(function != nullptr); 1212 Atomic<Closure*>* atomic_func = reinterpret_cast<Atomic<Closure*>*>(&tlsPtr_.flip_function); 1213 atomic_func->StoreSequentiallyConsistent(function); 1214} 1215 1216void Thread::FullSuspendCheck() { 1217 ScopedTrace trace(__FUNCTION__); 1218 VLOG(threads) << this << " self-suspending"; 1219 // Make thread appear suspended to other threads, release mutator_lock_. 1220 // Transition to suspended and back to runnable, re-acquire share on mutator_lock_. 1221 ScopedThreadSuspension(this, kSuspended); 1222 VLOG(threads) << this << " self-reviving"; 1223} 1224 1225void Thread::DumpState(std::ostream& os, const Thread* thread, pid_t tid) { 1226 std::string group_name; 1227 int priority; 1228 bool is_daemon = false; 1229 Thread* self = Thread::Current(); 1230 1231 // If flip_function is not null, it means we have run a checkpoint 1232 // before the thread wakes up to execute the flip function and the 1233 // thread roots haven't been forwarded. So the following access to 1234 // the roots (opeer or methods in the frames) would be bad. Run it 1235 // here. TODO: clean up. 1236 if (thread != nullptr) { 1237 ScopedObjectAccessUnchecked soa(self); 1238 Thread* this_thread = const_cast<Thread*>(thread); 1239 Closure* flip_func = this_thread->GetFlipFunction(); 1240 if (flip_func != nullptr) { 1241 flip_func->Run(this_thread); 1242 } 1243 } 1244 1245 // Don't do this if we are aborting since the GC may have all the threads suspended. This will 1246 // cause ScopedObjectAccessUnchecked to deadlock. 1247 if (gAborting == 0 && self != nullptr && thread != nullptr && thread->tlsPtr_.opeer != nullptr) { 1248 ScopedObjectAccessUnchecked soa(self); 1249 priority = soa.DecodeField(WellKnownClasses::java_lang_Thread_priority) 1250 ->GetInt(thread->tlsPtr_.opeer); 1251 is_daemon = soa.DecodeField(WellKnownClasses::java_lang_Thread_daemon) 1252 ->GetBoolean(thread->tlsPtr_.opeer); 1253 1254 mirror::Object* thread_group = 1255 soa.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(thread->tlsPtr_.opeer); 1256 1257 if (thread_group != nullptr) { 1258 ArtField* group_name_field = 1259 soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_name); 1260 mirror::String* group_name_string = 1261 reinterpret_cast<mirror::String*>(group_name_field->GetObject(thread_group)); 1262 group_name = (group_name_string != nullptr) ? group_name_string->ToModifiedUtf8() : "<null>"; 1263 } 1264 } else { 1265 priority = GetNativePriority(); 1266 } 1267 1268 std::string scheduler_group_name(GetSchedulerGroupName(tid)); 1269 if (scheduler_group_name.empty()) { 1270 scheduler_group_name = "default"; 1271 } 1272 1273 if (thread != nullptr) { 1274 os << '"' << *thread->tlsPtr_.name << '"'; 1275 if (is_daemon) { 1276 os << " daemon"; 1277 } 1278 os << " prio=" << priority 1279 << " tid=" << thread->GetThreadId() 1280 << " " << thread->GetState(); 1281 if (thread->IsStillStarting()) { 1282 os << " (still starting up)"; 1283 } 1284 os << "\n"; 1285 } else { 1286 os << '"' << ::art::GetThreadName(tid) << '"' 1287 << " prio=" << priority 1288 << " (not attached)\n"; 1289 } 1290 1291 if (thread != nullptr) { 1292 MutexLock mu(self, *Locks::thread_suspend_count_lock_); 1293 os << " | group=\"" << group_name << "\"" 1294 << " sCount=" << thread->tls32_.suspend_count 1295 << " dsCount=" << thread->tls32_.debug_suspend_count 1296 << " obj=" << reinterpret_cast<void*>(thread->tlsPtr_.opeer) 1297 << " self=" << reinterpret_cast<const void*>(thread) << "\n"; 1298 } 1299 1300 os << " | sysTid=" << tid 1301 << " nice=" << getpriority(PRIO_PROCESS, tid) 1302 << " cgrp=" << scheduler_group_name; 1303 if (thread != nullptr) { 1304 int policy; 1305 sched_param sp; 1306 CHECK_PTHREAD_CALL(pthread_getschedparam, (thread->tlsPtr_.pthread_self, &policy, &sp), 1307 __FUNCTION__); 1308 os << " sched=" << policy << "/" << sp.sched_priority 1309 << " handle=" << reinterpret_cast<void*>(thread->tlsPtr_.pthread_self); 1310 } 1311 os << "\n"; 1312 1313 // Grab the scheduler stats for this thread. 1314 std::string scheduler_stats; 1315 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", tid), &scheduler_stats)) { 1316 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'. 1317 } else { 1318 scheduler_stats = "0 0 0"; 1319 } 1320 1321 char native_thread_state = '?'; 1322 int utime = 0; 1323 int stime = 0; 1324 int task_cpu = 0; 1325 GetTaskStats(tid, &native_thread_state, &utime, &stime, &task_cpu); 1326 1327 os << " | state=" << native_thread_state 1328 << " schedstat=( " << scheduler_stats << " )" 1329 << " utm=" << utime 1330 << " stm=" << stime 1331 << " core=" << task_cpu 1332 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n"; 1333 if (thread != nullptr) { 1334 os << " | stack=" << reinterpret_cast<void*>(thread->tlsPtr_.stack_begin) << "-" 1335 << reinterpret_cast<void*>(thread->tlsPtr_.stack_end) << " stackSize=" 1336 << PrettySize(thread->tlsPtr_.stack_size) << "\n"; 1337 // Dump the held mutexes. 1338 os << " | held mutexes="; 1339 for (size_t i = 0; i < kLockLevelCount; ++i) { 1340 if (i != kMonitorLock) { 1341 BaseMutex* mutex = thread->GetHeldMutex(static_cast<LockLevel>(i)); 1342 if (mutex != nullptr) { 1343 os << " \"" << mutex->GetName() << "\""; 1344 if (mutex->IsReaderWriterMutex()) { 1345 ReaderWriterMutex* rw_mutex = down_cast<ReaderWriterMutex*>(mutex); 1346 if (rw_mutex->GetExclusiveOwnerTid() == static_cast<uint64_t>(tid)) { 1347 os << "(exclusive held)"; 1348 } else { 1349 os << "(shared held)"; 1350 } 1351 } 1352 } 1353 } 1354 } 1355 os << "\n"; 1356 } 1357} 1358 1359void Thread::DumpState(std::ostream& os) const { 1360 Thread::DumpState(os, this, GetTid()); 1361} 1362 1363struct StackDumpVisitor : public StackVisitor { 1364 StackDumpVisitor(std::ostream& os_in, Thread* thread_in, Context* context, bool can_allocate_in) 1365 REQUIRES_SHARED(Locks::mutator_lock_) 1366 : StackVisitor(thread_in, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames), 1367 os(os_in), 1368 can_allocate(can_allocate_in), 1369 last_method(nullptr), 1370 last_line_number(0), 1371 repetition_count(0), 1372 frame_count(0) {} 1373 1374 virtual ~StackDumpVisitor() { 1375 if (frame_count == 0) { 1376 os << " (no managed stack frames)\n"; 1377 } 1378 } 1379 1380 bool VisitFrame() REQUIRES_SHARED(Locks::mutator_lock_) { 1381 ArtMethod* m = GetMethod(); 1382 if (m->IsRuntimeMethod()) { 1383 return true; 1384 } 1385 m = m->GetInterfaceMethodIfProxy(kRuntimePointerSize); 1386 const int kMaxRepetition = 3; 1387 mirror::Class* c = m->GetDeclaringClass(); 1388 mirror::DexCache* dex_cache = c->GetDexCache(); 1389 int line_number = -1; 1390 if (dex_cache != nullptr) { // be tolerant of bad input 1391 const DexFile& dex_file = *dex_cache->GetDexFile(); 1392 line_number = dex_file.GetLineNumFromPC(m, GetDexPc(false)); 1393 } 1394 if (line_number == last_line_number && last_method == m) { 1395 ++repetition_count; 1396 } else { 1397 if (repetition_count >= kMaxRepetition) { 1398 os << " ... repeated " << (repetition_count - kMaxRepetition) << " times\n"; 1399 } 1400 repetition_count = 0; 1401 last_line_number = line_number; 1402 last_method = m; 1403 } 1404 if (repetition_count < kMaxRepetition) { 1405 os << " at " << PrettyMethod(m, false); 1406 if (m->IsNative()) { 1407 os << "(Native method)"; 1408 } else { 1409 const char* source_file(m->GetDeclaringClassSourceFile()); 1410 os << "(" << (source_file != nullptr ? source_file : "unavailable") 1411 << ":" << line_number << ")"; 1412 } 1413 os << "\n"; 1414 if (frame_count == 0) { 1415 Monitor::DescribeWait(os, GetThread()); 1416 } 1417 if (can_allocate) { 1418 // Visit locks, but do not abort on errors. This would trigger a nested abort. 1419 Monitor::VisitLocks(this, DumpLockedObject, &os, false); 1420 } 1421 } 1422 1423 ++frame_count; 1424 return true; 1425 } 1426 1427 static void DumpLockedObject(mirror::Object* o, void* context) 1428 REQUIRES_SHARED(Locks::mutator_lock_) { 1429 std::ostream& os = *reinterpret_cast<std::ostream*>(context); 1430 os << " - locked "; 1431 if (o == nullptr) { 1432 os << "an unknown object"; 1433 } else { 1434 if (kUseReadBarrier && Thread::Current()->GetIsGcMarking()) { 1435 // We may call Thread::Dump() in the middle of the CC thread flip and this thread's stack 1436 // may have not been flipped yet and "o" may be a from-space (stale) ref, in which case the 1437 // IdentityHashCode call below will crash. So explicitly mark/forward it here. 1438 o = ReadBarrier::Mark(o); 1439 } 1440 if ((o->GetLockWord(false).GetState() == LockWord::kThinLocked) && 1441 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) { 1442 // Getting the identity hashcode here would result in lock inflation and suspension of the 1443 // current thread, which isn't safe if this is the only runnable thread. 1444 os << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)", reinterpret_cast<intptr_t>(o), 1445 PrettyTypeOf(o).c_str()); 1446 } else { 1447 // IdentityHashCode can cause thread suspension, which would invalidate o if it moved. So 1448 // we get the pretty type beofre we call IdentityHashCode. 1449 const std::string pretty_type(PrettyTypeOf(o)); 1450 os << StringPrintf("<0x%08x> (a %s)", o->IdentityHashCode(), pretty_type.c_str()); 1451 } 1452 } 1453 os << "\n"; 1454 } 1455 1456 std::ostream& os; 1457 const bool can_allocate; 1458 ArtMethod* last_method; 1459 int last_line_number; 1460 int repetition_count; 1461 int frame_count; 1462}; 1463 1464static bool ShouldShowNativeStack(const Thread* thread) 1465 REQUIRES_SHARED(Locks::mutator_lock_) { 1466 ThreadState state = thread->GetState(); 1467 1468 // In native code somewhere in the VM (one of the kWaitingFor* states)? That's interesting. 1469 if (state > kWaiting && state < kStarting) { 1470 return true; 1471 } 1472 1473 // In an Object.wait variant or Thread.sleep? That's not interesting. 1474 if (state == kTimedWaiting || state == kSleeping || state == kWaiting) { 1475 return false; 1476 } 1477 1478 // Threads with no managed stack frames should be shown. 1479 const ManagedStack* managed_stack = thread->GetManagedStack(); 1480 if (managed_stack == nullptr || (managed_stack->GetTopQuickFrame() == nullptr && 1481 managed_stack->GetTopShadowFrame() == nullptr)) { 1482 return true; 1483 } 1484 1485 // In some other native method? That's interesting. 1486 // We don't just check kNative because native methods will be in state kSuspended if they're 1487 // calling back into the VM, or kBlocked if they're blocked on a monitor, or one of the 1488 // thread-startup states if it's early enough in their life cycle (http://b/7432159). 1489 ArtMethod* current_method = thread->GetCurrentMethod(nullptr); 1490 return current_method != nullptr && current_method->IsNative(); 1491} 1492 1493void Thread::DumpJavaStack(std::ostream& os) const { 1494 // If flip_function is not null, it means we have run a checkpoint 1495 // before the thread wakes up to execute the flip function and the 1496 // thread roots haven't been forwarded. So the following access to 1497 // the roots (locks or methods in the frames) would be bad. Run it 1498 // here. TODO: clean up. 1499 { 1500 Thread* this_thread = const_cast<Thread*>(this); 1501 Closure* flip_func = this_thread->GetFlipFunction(); 1502 if (flip_func != nullptr) { 1503 flip_func->Run(this_thread); 1504 } 1505 } 1506 1507 // Dumping the Java stack involves the verifier for locks. The verifier operates under the 1508 // assumption that there is no exception pending on entry. Thus, stash any pending exception. 1509 // Thread::Current() instead of this in case a thread is dumping the stack of another suspended 1510 // thread. 1511 StackHandleScope<1> scope(Thread::Current()); 1512 Handle<mirror::Throwable> exc; 1513 bool have_exception = false; 1514 if (IsExceptionPending()) { 1515 exc = scope.NewHandle(GetException()); 1516 const_cast<Thread*>(this)->ClearException(); 1517 have_exception = true; 1518 } 1519 1520 std::unique_ptr<Context> context(Context::Create()); 1521 StackDumpVisitor dumper(os, const_cast<Thread*>(this), context.get(), 1522 !tls32_.throwing_OutOfMemoryError); 1523 dumper.WalkStack(); 1524 1525 if (have_exception) { 1526 const_cast<Thread*>(this)->SetException(exc.Get()); 1527 } 1528} 1529 1530void Thread::DumpStack(std::ostream& os, 1531 bool dump_native_stack, 1532 BacktraceMap* backtrace_map) const { 1533 // TODO: we call this code when dying but may not have suspended the thread ourself. The 1534 // IsSuspended check is therefore racy with the use for dumping (normally we inhibit 1535 // the race with the thread_suspend_count_lock_). 1536 bool dump_for_abort = (gAborting > 0); 1537 bool safe_to_dump = (this == Thread::Current() || IsSuspended()); 1538 if (!kIsDebugBuild) { 1539 // We always want to dump the stack for an abort, however, there is no point dumping another 1540 // thread's stack in debug builds where we'll hit the not suspended check in the stack walk. 1541 safe_to_dump = (safe_to_dump || dump_for_abort); 1542 } 1543 if (safe_to_dump) { 1544 // If we're currently in native code, dump that stack before dumping the managed stack. 1545 if (dump_native_stack && (dump_for_abort || ShouldShowNativeStack(this))) { 1546 DumpKernelStack(os, GetTid(), " kernel: ", false); 1547 ArtMethod* method = GetCurrentMethod(nullptr, !dump_for_abort); 1548 DumpNativeStack(os, GetTid(), backtrace_map, " native: ", method); 1549 } 1550 DumpJavaStack(os); 1551 } else { 1552 os << "Not able to dump stack of thread that isn't suspended"; 1553 } 1554} 1555 1556void Thread::ThreadExitCallback(void* arg) { 1557 Thread* self = reinterpret_cast<Thread*>(arg); 1558 if (self->tls32_.thread_exit_check_count == 0) { 1559 LOG(WARNING) << "Native thread exiting without having called DetachCurrentThread (maybe it's " 1560 "going to use a pthread_key_create destructor?): " << *self; 1561 CHECK(is_started_); 1562#ifdef ART_TARGET_ANDROID 1563 __get_tls()[TLS_SLOT_ART_THREAD_SELF] = self; 1564#else 1565 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, self), "reattach self"); 1566#endif 1567 self->tls32_.thread_exit_check_count = 1; 1568 } else { 1569 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self; 1570 } 1571} 1572 1573void Thread::Startup() { 1574 CHECK(!is_started_); 1575 is_started_ = true; 1576 { 1577 // MutexLock to keep annotalysis happy. 1578 // 1579 // Note we use null for the thread because Thread::Current can 1580 // return garbage since (is_started_ == true) and 1581 // Thread::pthread_key_self_ is not yet initialized. 1582 // This was seen on glibc. 1583 MutexLock mu(nullptr, *Locks::thread_suspend_count_lock_); 1584 resume_cond_ = new ConditionVariable("Thread resumption condition variable", 1585 *Locks::thread_suspend_count_lock_); 1586 } 1587 1588 // Allocate a TLS slot. 1589 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), 1590 "self key"); 1591 1592 // Double-check the TLS slot allocation. 1593 if (pthread_getspecific(pthread_key_self_) != nullptr) { 1594 LOG(FATAL) << "Newly-created pthread TLS slot is not nullptr"; 1595 } 1596} 1597 1598void Thread::FinishStartup() { 1599 Runtime* runtime = Runtime::Current(); 1600 CHECK(runtime->IsStarted()); 1601 1602 // Finish attaching the main thread. 1603 ScopedObjectAccess soa(Thread::Current()); 1604 Thread::Current()->CreatePeer("main", false, runtime->GetMainThreadGroup()); 1605 Thread::Current()->AssertNoPendingException(); 1606 1607 Runtime::Current()->GetClassLinker()->RunRootClinits(); 1608} 1609 1610void Thread::Shutdown() { 1611 CHECK(is_started_); 1612 is_started_ = false; 1613 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key"); 1614 MutexLock mu(Thread::Current(), *Locks::thread_suspend_count_lock_); 1615 if (resume_cond_ != nullptr) { 1616 delete resume_cond_; 1617 resume_cond_ = nullptr; 1618 } 1619} 1620 1621Thread::Thread(bool daemon) : tls32_(daemon), wait_monitor_(nullptr), interrupted_(false) { 1622 wait_mutex_ = new Mutex("a thread wait mutex"); 1623 wait_cond_ = new ConditionVariable("a thread wait condition variable", *wait_mutex_); 1624 tlsPtr_.instrumentation_stack = new std::deque<instrumentation::InstrumentationStackFrame>; 1625 tlsPtr_.name = new std::string(kThreadNameDuringStartup); 1626 tlsPtr_.nested_signal_state = static_cast<jmp_buf*>(malloc(sizeof(jmp_buf))); 1627 1628 static_assert((sizeof(Thread) % 4) == 0U, 1629 "art::Thread has a size which is not a multiple of 4."); 1630 tls32_.state_and_flags.as_struct.flags = 0; 1631 tls32_.state_and_flags.as_struct.state = kNative; 1632 memset(&tlsPtr_.held_mutexes[0], 0, sizeof(tlsPtr_.held_mutexes)); 1633 std::fill(tlsPtr_.rosalloc_runs, 1634 tlsPtr_.rosalloc_runs + kNumRosAllocThreadLocalSizeBracketsInThread, 1635 gc::allocator::RosAlloc::GetDedicatedFullRun()); 1636 tlsPtr_.checkpoint_function = nullptr; 1637 for (uint32_t i = 0; i < kMaxSuspendBarriers; ++i) { 1638 tlsPtr_.active_suspend_barriers[i] = nullptr; 1639 } 1640 tlsPtr_.flip_function = nullptr; 1641 tlsPtr_.thread_local_mark_stack = nullptr; 1642 tls32_.is_transitioning_to_runnable = false; 1643} 1644 1645bool Thread::IsStillStarting() const { 1646 // You might think you can check whether the state is kStarting, but for much of thread startup, 1647 // the thread is in kNative; it might also be in kVmWait. 1648 // You might think you can check whether the peer is null, but the peer is actually created and 1649 // assigned fairly early on, and needs to be. 1650 // It turns out that the last thing to change is the thread name; that's a good proxy for "has 1651 // this thread _ever_ entered kRunnable". 1652 return (tlsPtr_.jpeer == nullptr && tlsPtr_.opeer == nullptr) || 1653 (*tlsPtr_.name == kThreadNameDuringStartup); 1654} 1655 1656void Thread::AssertPendingException() const { 1657 CHECK(IsExceptionPending()) << "Pending exception expected."; 1658} 1659 1660void Thread::AssertPendingOOMException() const { 1661 AssertPendingException(); 1662 auto* e = GetException(); 1663 CHECK_EQ(e->GetClass(), DecodeJObject(WellKnownClasses::java_lang_OutOfMemoryError)->AsClass()) 1664 << e->Dump(); 1665} 1666 1667void Thread::AssertNoPendingException() const { 1668 if (UNLIKELY(IsExceptionPending())) { 1669 ScopedObjectAccess soa(Thread::Current()); 1670 mirror::Throwable* exception = GetException(); 1671 LOG(FATAL) << "No pending exception expected: " << exception->Dump(); 1672 } 1673} 1674 1675void Thread::AssertNoPendingExceptionForNewException(const char* msg) const { 1676 if (UNLIKELY(IsExceptionPending())) { 1677 ScopedObjectAccess soa(Thread::Current()); 1678 mirror::Throwable* exception = GetException(); 1679 LOG(FATAL) << "Throwing new exception '" << msg << "' with unexpected pending exception: " 1680 << exception->Dump(); 1681 } 1682} 1683 1684class MonitorExitVisitor : public SingleRootVisitor { 1685 public: 1686 explicit MonitorExitVisitor(Thread* self) : self_(self) { } 1687 1688 // NO_THREAD_SAFETY_ANALYSIS due to MonitorExit. 1689 void VisitRoot(mirror::Object* entered_monitor, const RootInfo& info ATTRIBUTE_UNUSED) 1690 OVERRIDE NO_THREAD_SAFETY_ANALYSIS { 1691 if (self_->HoldsLock(entered_monitor)) { 1692 LOG(WARNING) << "Calling MonitorExit on object " 1693 << entered_monitor << " (" << PrettyTypeOf(entered_monitor) << ")" 1694 << " left locked by native thread " 1695 << *Thread::Current() << " which is detaching"; 1696 entered_monitor->MonitorExit(self_); 1697 } 1698 } 1699 1700 private: 1701 Thread* const self_; 1702}; 1703 1704void Thread::Destroy() { 1705 Thread* self = this; 1706 DCHECK_EQ(self, Thread::Current()); 1707 1708 if (tlsPtr_.jni_env != nullptr) { 1709 { 1710 ScopedObjectAccess soa(self); 1711 MonitorExitVisitor visitor(self); 1712 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited. 1713 tlsPtr_.jni_env->monitors.VisitRoots(&visitor, RootInfo(kRootVMInternal)); 1714 } 1715 // Release locally held global references which releasing may require the mutator lock. 1716 if (tlsPtr_.jpeer != nullptr) { 1717 // If pthread_create fails we don't have a jni env here. 1718 tlsPtr_.jni_env->DeleteGlobalRef(tlsPtr_.jpeer); 1719 tlsPtr_.jpeer = nullptr; 1720 } 1721 if (tlsPtr_.class_loader_override != nullptr) { 1722 tlsPtr_.jni_env->DeleteGlobalRef(tlsPtr_.class_loader_override); 1723 tlsPtr_.class_loader_override = nullptr; 1724 } 1725 } 1726 1727 if (tlsPtr_.opeer != nullptr) { 1728 ScopedObjectAccess soa(self); 1729 // We may need to call user-supplied managed code, do this before final clean-up. 1730 HandleUncaughtExceptions(soa); 1731 RemoveFromThreadGroup(soa); 1732 1733 // this.nativePeer = 0; 1734 if (Runtime::Current()->IsActiveTransaction()) { 1735 soa.DecodeField(WellKnownClasses::java_lang_Thread_nativePeer) 1736 ->SetLong<true>(tlsPtr_.opeer, 0); 1737 } else { 1738 soa.DecodeField(WellKnownClasses::java_lang_Thread_nativePeer) 1739 ->SetLong<false>(tlsPtr_.opeer, 0); 1740 } 1741 Dbg::PostThreadDeath(self); 1742 1743 // Thread.join() is implemented as an Object.wait() on the Thread.lock object. Signal anyone 1744 // who is waiting. 1745 mirror::Object* lock = 1746 soa.DecodeField(WellKnownClasses::java_lang_Thread_lock)->GetObject(tlsPtr_.opeer); 1747 // (This conditional is only needed for tests, where Thread.lock won't have been set.) 1748 if (lock != nullptr) { 1749 StackHandleScope<1> hs(self); 1750 Handle<mirror::Object> h_obj(hs.NewHandle(lock)); 1751 ObjectLock<mirror::Object> locker(self, h_obj); 1752 locker.NotifyAll(); 1753 } 1754 tlsPtr_.opeer = nullptr; 1755 } 1756 1757 { 1758 ScopedObjectAccess soa(self); 1759 Runtime::Current()->GetHeap()->RevokeThreadLocalBuffers(this); 1760 if (kUseReadBarrier) { 1761 Runtime::Current()->GetHeap()->ConcurrentCopyingCollector()->RevokeThreadLocalMarkStack(this); 1762 } 1763 } 1764} 1765 1766Thread::~Thread() { 1767 CHECK(tlsPtr_.class_loader_override == nullptr); 1768 CHECK(tlsPtr_.jpeer == nullptr); 1769 CHECK(tlsPtr_.opeer == nullptr); 1770 bool initialized = (tlsPtr_.jni_env != nullptr); // Did Thread::Init run? 1771 if (initialized) { 1772 delete tlsPtr_.jni_env; 1773 tlsPtr_.jni_env = nullptr; 1774 } 1775 CHECK_NE(GetState(), kRunnable); 1776 CHECK_NE(ReadFlag(kCheckpointRequest), true); 1777 CHECK(tlsPtr_.checkpoint_function == nullptr); 1778 CHECK_EQ(checkpoint_overflow_.size(), 0u); 1779 CHECK(tlsPtr_.flip_function == nullptr); 1780 CHECK_EQ(tls32_.is_transitioning_to_runnable, false); 1781 1782 // Make sure we processed all deoptimization requests. 1783 CHECK(tlsPtr_.deoptimization_context_stack == nullptr) << "Missed deoptimization"; 1784 CHECK(tlsPtr_.frame_id_to_shadow_frame == nullptr) << 1785 "Not all deoptimized frames have been consumed by the debugger."; 1786 1787 // We may be deleting a still born thread. 1788 SetStateUnsafe(kTerminated); 1789 1790 delete wait_cond_; 1791 delete wait_mutex_; 1792 1793 if (tlsPtr_.long_jump_context != nullptr) { 1794 delete tlsPtr_.long_jump_context; 1795 } 1796 1797 if (initialized) { 1798 CleanupCpu(); 1799 } 1800 1801 if (tlsPtr_.single_step_control != nullptr) { 1802 delete tlsPtr_.single_step_control; 1803 } 1804 delete tlsPtr_.instrumentation_stack; 1805 delete tlsPtr_.name; 1806 delete tlsPtr_.stack_trace_sample; 1807 free(tlsPtr_.nested_signal_state); 1808 1809 Runtime::Current()->GetHeap()->AssertThreadLocalBuffersAreRevoked(this); 1810 1811 TearDownAlternateSignalStack(); 1812} 1813 1814void Thread::HandleUncaughtExceptions(ScopedObjectAccess& soa) { 1815 if (!IsExceptionPending()) { 1816 return; 1817 } 1818 ScopedLocalRef<jobject> peer(tlsPtr_.jni_env, soa.AddLocalReference<jobject>(tlsPtr_.opeer)); 1819 ScopedThreadStateChange tsc(this, kNative); 1820 1821 // Get and clear the exception. 1822 ScopedLocalRef<jthrowable> exception(tlsPtr_.jni_env, tlsPtr_.jni_env->ExceptionOccurred()); 1823 tlsPtr_.jni_env->ExceptionClear(); 1824 1825 // Call the Thread instance's dispatchUncaughtException(Throwable) 1826 tlsPtr_.jni_env->CallVoidMethod(peer.get(), 1827 WellKnownClasses::java_lang_Thread_dispatchUncaughtException, 1828 exception.get()); 1829 1830 // If the dispatchUncaughtException threw, clear that exception too. 1831 tlsPtr_.jni_env->ExceptionClear(); 1832} 1833 1834void Thread::RemoveFromThreadGroup(ScopedObjectAccess& soa) { 1835 // this.group.removeThread(this); 1836 // group can be null if we're in the compiler or a test. 1837 mirror::Object* ogroup = soa.DecodeField(WellKnownClasses::java_lang_Thread_group) 1838 ->GetObject(tlsPtr_.opeer); 1839 if (ogroup != nullptr) { 1840 ScopedLocalRef<jobject> group(soa.Env(), soa.AddLocalReference<jobject>(ogroup)); 1841 ScopedLocalRef<jobject> peer(soa.Env(), soa.AddLocalReference<jobject>(tlsPtr_.opeer)); 1842 ScopedThreadStateChange tsc(soa.Self(), kNative); 1843 tlsPtr_.jni_env->CallVoidMethod(group.get(), 1844 WellKnownClasses::java_lang_ThreadGroup_removeThread, 1845 peer.get()); 1846 } 1847} 1848 1849size_t Thread::NumHandleReferences() { 1850 size_t count = 0; 1851 for (HandleScope* cur = tlsPtr_.top_handle_scope; cur != nullptr; cur = cur->GetLink()) { 1852 count += cur->NumberOfReferences(); 1853 } 1854 return count; 1855} 1856 1857bool Thread::HandleScopeContains(jobject obj) const { 1858 StackReference<mirror::Object>* hs_entry = 1859 reinterpret_cast<StackReference<mirror::Object>*>(obj); 1860 for (HandleScope* cur = tlsPtr_.top_handle_scope; cur!= nullptr; cur = cur->GetLink()) { 1861 if (cur->Contains(hs_entry)) { 1862 return true; 1863 } 1864 } 1865 // JNI code invoked from portable code uses shadow frames rather than the handle scope. 1866 return tlsPtr_.managed_stack.ShadowFramesContain(hs_entry); 1867} 1868 1869void Thread::HandleScopeVisitRoots(RootVisitor* visitor, uint32_t thread_id) { 1870 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor( 1871 visitor, RootInfo(kRootNativeStack, thread_id)); 1872 for (HandleScope* cur = tlsPtr_.top_handle_scope; cur; cur = cur->GetLink()) { 1873 for (size_t j = 0, count = cur->NumberOfReferences(); j < count; ++j) { 1874 // GetReference returns a pointer to the stack reference within the handle scope. If this 1875 // needs to be updated, it will be done by the root visitor. 1876 buffered_visitor.VisitRootIfNonNull(cur->GetHandle(j).GetReference()); 1877 } 1878 } 1879} 1880 1881mirror::Object* Thread::DecodeJObject(jobject obj) const { 1882 if (obj == nullptr) { 1883 return nullptr; 1884 } 1885 IndirectRef ref = reinterpret_cast<IndirectRef>(obj); 1886 IndirectRefKind kind = GetIndirectRefKind(ref); 1887 mirror::Object* result; 1888 bool expect_null = false; 1889 // The "kinds" below are sorted by the frequency we expect to encounter them. 1890 if (kind == kLocal) { 1891 IndirectReferenceTable& locals = tlsPtr_.jni_env->locals; 1892 // Local references do not need a read barrier. 1893 result = locals.Get<kWithoutReadBarrier>(ref); 1894 } else if (kind == kHandleScopeOrInvalid) { 1895 // TODO: make stack indirect reference table lookup more efficient. 1896 // Check if this is a local reference in the handle scope. 1897 if (LIKELY(HandleScopeContains(obj))) { 1898 // Read from handle scope. 1899 result = reinterpret_cast<StackReference<mirror::Object>*>(obj)->AsMirrorPtr(); 1900 VerifyObject(result); 1901 } else { 1902 tlsPtr_.jni_env->vm->JniAbortF(nullptr, "use of invalid jobject %p", obj); 1903 expect_null = true; 1904 result = nullptr; 1905 } 1906 } else if (kind == kGlobal) { 1907 result = tlsPtr_.jni_env->vm->DecodeGlobal(ref); 1908 } else { 1909 DCHECK_EQ(kind, kWeakGlobal); 1910 result = tlsPtr_.jni_env->vm->DecodeWeakGlobal(const_cast<Thread*>(this), ref); 1911 if (Runtime::Current()->IsClearedJniWeakGlobal(result)) { 1912 // This is a special case where it's okay to return null. 1913 expect_null = true; 1914 result = nullptr; 1915 } 1916 } 1917 1918 if (UNLIKELY(!expect_null && result == nullptr)) { 1919 tlsPtr_.jni_env->vm->JniAbortF(nullptr, "use of deleted %s %p", 1920 ToStr<IndirectRefKind>(kind).c_str(), obj); 1921 } 1922 return result; 1923} 1924 1925bool Thread::IsJWeakCleared(jweak obj) const { 1926 CHECK(obj != nullptr); 1927 IndirectRef ref = reinterpret_cast<IndirectRef>(obj); 1928 IndirectRefKind kind = GetIndirectRefKind(ref); 1929 CHECK_EQ(kind, kWeakGlobal); 1930 return tlsPtr_.jni_env->vm->IsWeakGlobalCleared(const_cast<Thread*>(this), ref); 1931} 1932 1933// Implements java.lang.Thread.interrupted. 1934bool Thread::Interrupted() { 1935 MutexLock mu(Thread::Current(), *wait_mutex_); 1936 bool interrupted = IsInterruptedLocked(); 1937 SetInterruptedLocked(false); 1938 return interrupted; 1939} 1940 1941// Implements java.lang.Thread.isInterrupted. 1942bool Thread::IsInterrupted() { 1943 MutexLock mu(Thread::Current(), *wait_mutex_); 1944 return IsInterruptedLocked(); 1945} 1946 1947void Thread::Interrupt(Thread* self) { 1948 MutexLock mu(self, *wait_mutex_); 1949 if (interrupted_) { 1950 return; 1951 } 1952 interrupted_ = true; 1953 NotifyLocked(self); 1954} 1955 1956void Thread::Notify() { 1957 Thread* self = Thread::Current(); 1958 MutexLock mu(self, *wait_mutex_); 1959 NotifyLocked(self); 1960} 1961 1962void Thread::NotifyLocked(Thread* self) { 1963 if (wait_monitor_ != nullptr) { 1964 wait_cond_->Signal(self); 1965 } 1966} 1967 1968void Thread::SetClassLoaderOverride(jobject class_loader_override) { 1969 if (tlsPtr_.class_loader_override != nullptr) { 1970 GetJniEnv()->DeleteGlobalRef(tlsPtr_.class_loader_override); 1971 } 1972 tlsPtr_.class_loader_override = GetJniEnv()->NewGlobalRef(class_loader_override); 1973} 1974 1975class CountStackDepthVisitor : public StackVisitor { 1976 public: 1977 explicit CountStackDepthVisitor(Thread* thread) 1978 REQUIRES_SHARED(Locks::mutator_lock_) 1979 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames), 1980 depth_(0), skip_depth_(0), skipping_(true) {} 1981 1982 bool VisitFrame() REQUIRES_SHARED(Locks::mutator_lock_) { 1983 // We want to skip frames up to and including the exception's constructor. 1984 // Note we also skip the frame if it doesn't have a method (namely the callee 1985 // save frame) 1986 ArtMethod* m = GetMethod(); 1987 if (skipping_ && !m->IsRuntimeMethod() && 1988 !mirror::Throwable::GetJavaLangThrowable()->IsAssignableFrom(m->GetDeclaringClass())) { 1989 skipping_ = false; 1990 } 1991 if (!skipping_) { 1992 if (!m->IsRuntimeMethod()) { // Ignore runtime frames (in particular callee save). 1993 ++depth_; 1994 } 1995 } else { 1996 ++skip_depth_; 1997 } 1998 return true; 1999 } 2000 2001 int GetDepth() const { 2002 return depth_; 2003 } 2004 2005 int GetSkipDepth() const { 2006 return skip_depth_; 2007 } 2008 2009 private: 2010 uint32_t depth_; 2011 uint32_t skip_depth_; 2012 bool skipping_; 2013 2014 DISALLOW_COPY_AND_ASSIGN(CountStackDepthVisitor); 2015}; 2016 2017template<bool kTransactionActive> 2018class BuildInternalStackTraceVisitor : public StackVisitor { 2019 public: 2020 BuildInternalStackTraceVisitor(Thread* self, Thread* thread, int skip_depth) 2021 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames), 2022 self_(self), 2023 skip_depth_(skip_depth), 2024 count_(0), 2025 trace_(nullptr), 2026 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()) {} 2027 2028 bool Init(int depth) REQUIRES_SHARED(Locks::mutator_lock_) ACQUIRE(Roles::uninterruptible_) { 2029 // Allocate method trace as an object array where the first element is a pointer array that 2030 // contains the ArtMethod pointers and dex PCs. The rest of the elements are the declaring 2031 // class of the ArtMethod pointers. 2032 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 2033 StackHandleScope<1> hs(self_); 2034 mirror::Class* array_class = class_linker->GetClassRoot(ClassLinker::kObjectArrayClass); 2035 // The first element is the methods and dex pc array, the other elements are declaring classes 2036 // for the methods to ensure classes in the stack trace don't get unloaded. 2037 Handle<mirror::ObjectArray<mirror::Object>> trace( 2038 hs.NewHandle( 2039 mirror::ObjectArray<mirror::Object>::Alloc(hs.Self(), array_class, depth + 1))); 2040 if (trace.Get() == nullptr) { 2041 // Acquire uninterruptible_ in all paths. 2042 self_->StartAssertNoThreadSuspension("Building internal stack trace"); 2043 self_->AssertPendingOOMException(); 2044 return false; 2045 } 2046 mirror::PointerArray* methods_and_pcs = class_linker->AllocPointerArray(self_, depth * 2); 2047 const char* last_no_suspend_cause = 2048 self_->StartAssertNoThreadSuspension("Building internal stack trace"); 2049 if (methods_and_pcs == nullptr) { 2050 self_->AssertPendingOOMException(); 2051 return false; 2052 } 2053 trace->Set(0, methods_and_pcs); 2054 trace_ = trace.Get(); 2055 // If We are called from native, use non-transactional mode. 2056 CHECK(last_no_suspend_cause == nullptr) << last_no_suspend_cause; 2057 return true; 2058 } 2059 2060 virtual ~BuildInternalStackTraceVisitor() RELEASE(Roles::uninterruptible_) { 2061 self_->EndAssertNoThreadSuspension(nullptr); 2062 } 2063 2064 bool VisitFrame() REQUIRES_SHARED(Locks::mutator_lock_) { 2065 if (trace_ == nullptr) { 2066 return true; // We're probably trying to fillInStackTrace for an OutOfMemoryError. 2067 } 2068 if (skip_depth_ > 0) { 2069 skip_depth_--; 2070 return true; 2071 } 2072 ArtMethod* m = GetMethod(); 2073 if (m->IsRuntimeMethod()) { 2074 return true; // Ignore runtime frames (in particular callee save). 2075 } 2076 mirror::PointerArray* trace_methods_and_pcs = GetTraceMethodsAndPCs(); 2077 trace_methods_and_pcs->SetElementPtrSize<kTransactionActive>(count_, m, pointer_size_); 2078 trace_methods_and_pcs->SetElementPtrSize<kTransactionActive>( 2079 trace_methods_and_pcs->GetLength() / 2 + count_, 2080 m->IsProxyMethod() ? DexFile::kDexNoIndex : GetDexPc(), 2081 pointer_size_); 2082 // Save the declaring class of the method to ensure that the declaring classes of the methods 2083 // do not get unloaded while the stack trace is live. 2084 trace_->Set(count_ + 1, m->GetDeclaringClass()); 2085 ++count_; 2086 return true; 2087 } 2088 2089 mirror::PointerArray* GetTraceMethodsAndPCs() const REQUIRES_SHARED(Locks::mutator_lock_) { 2090 return down_cast<mirror::PointerArray*>(trace_->Get(0)); 2091 } 2092 2093 mirror::ObjectArray<mirror::Object>* GetInternalStackTrace() const { 2094 return trace_; 2095 } 2096 2097 private: 2098 Thread* const self_; 2099 // How many more frames to skip. 2100 int32_t skip_depth_; 2101 // Current position down stack trace. 2102 uint32_t count_; 2103 // An object array where the first element is a pointer array that contains the ArtMethod 2104 // pointers on the stack and dex PCs. The rest of the elements are the declaring 2105 // class of the ArtMethod pointers. trace_[i+1] contains the declaring class of the ArtMethod of 2106 // the i'th frame. 2107 mirror::ObjectArray<mirror::Object>* trace_; 2108 // For cross compilation. 2109 const PointerSize pointer_size_; 2110 2111 DISALLOW_COPY_AND_ASSIGN(BuildInternalStackTraceVisitor); 2112}; 2113 2114template<bool kTransactionActive> 2115jobject Thread::CreateInternalStackTrace(const ScopedObjectAccessAlreadyRunnable& soa) const { 2116 // Compute depth of stack 2117 CountStackDepthVisitor count_visitor(const_cast<Thread*>(this)); 2118 count_visitor.WalkStack(); 2119 int32_t depth = count_visitor.GetDepth(); 2120 int32_t skip_depth = count_visitor.GetSkipDepth(); 2121 2122 // Build internal stack trace. 2123 BuildInternalStackTraceVisitor<kTransactionActive> build_trace_visitor(soa.Self(), 2124 const_cast<Thread*>(this), 2125 skip_depth); 2126 if (!build_trace_visitor.Init(depth)) { 2127 return nullptr; // Allocation failed. 2128 } 2129 build_trace_visitor.WalkStack(); 2130 mirror::ObjectArray<mirror::Object>* trace = build_trace_visitor.GetInternalStackTrace(); 2131 if (kIsDebugBuild) { 2132 mirror::PointerArray* trace_methods = build_trace_visitor.GetTraceMethodsAndPCs(); 2133 // Second half of trace_methods is dex PCs. 2134 for (uint32_t i = 0; i < static_cast<uint32_t>(trace_methods->GetLength() / 2); ++i) { 2135 auto* method = trace_methods->GetElementPtrSize<ArtMethod*>( 2136 i, Runtime::Current()->GetClassLinker()->GetImagePointerSize()); 2137 CHECK(method != nullptr); 2138 } 2139 } 2140 return soa.AddLocalReference<jobject>(trace); 2141} 2142template jobject Thread::CreateInternalStackTrace<false>( 2143 const ScopedObjectAccessAlreadyRunnable& soa) const; 2144template jobject Thread::CreateInternalStackTrace<true>( 2145 const ScopedObjectAccessAlreadyRunnable& soa) const; 2146 2147bool Thread::IsExceptionThrownByCurrentMethod(mirror::Throwable* exception) const { 2148 CountStackDepthVisitor count_visitor(const_cast<Thread*>(this)); 2149 count_visitor.WalkStack(); 2150 return count_visitor.GetDepth() == exception->GetStackDepth(); 2151} 2152 2153jobjectArray Thread::InternalStackTraceToStackTraceElementArray( 2154 const ScopedObjectAccessAlreadyRunnable& soa, 2155 jobject internal, 2156 jobjectArray output_array, 2157 int* stack_depth) { 2158 // Decode the internal stack trace into the depth, method trace and PC trace. 2159 // Subtract one for the methods and PC trace. 2160 int32_t depth = soa.Decode<mirror::Array*>(internal)->GetLength() - 1; 2161 DCHECK_GE(depth, 0); 2162 2163 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker(); 2164 2165 jobjectArray result; 2166 2167 if (output_array != nullptr) { 2168 // Reuse the array we were given. 2169 result = output_array; 2170 // ...adjusting the number of frames we'll write to not exceed the array length. 2171 const int32_t traces_length = 2172 soa.Decode<mirror::ObjectArray<mirror::StackTraceElement>*>(result)->GetLength(); 2173 depth = std::min(depth, traces_length); 2174 } else { 2175 // Create java_trace array and place in local reference table 2176 mirror::ObjectArray<mirror::StackTraceElement>* java_traces = 2177 class_linker->AllocStackTraceElementArray(soa.Self(), depth); 2178 if (java_traces == nullptr) { 2179 return nullptr; 2180 } 2181 result = soa.AddLocalReference<jobjectArray>(java_traces); 2182 } 2183 2184 if (stack_depth != nullptr) { 2185 *stack_depth = depth; 2186 } 2187 2188 for (int32_t i = 0; i < depth; ++i) { 2189 mirror::ObjectArray<mirror::Object>* decoded_traces = 2190 soa.Decode<mirror::Object*>(internal)->AsObjectArray<mirror::Object>(); 2191 // Methods and dex PC trace is element 0. 2192 DCHECK(decoded_traces->Get(0)->IsIntArray() || decoded_traces->Get(0)->IsLongArray()); 2193 mirror::PointerArray* const method_trace = 2194 down_cast<mirror::PointerArray*>(decoded_traces->Get(0)); 2195 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line) 2196 ArtMethod* method = method_trace->GetElementPtrSize<ArtMethod*>(i, kRuntimePointerSize); 2197 uint32_t dex_pc = method_trace->GetElementPtrSize<uint32_t>( 2198 i + method_trace->GetLength() / 2, kRuntimePointerSize); 2199 int32_t line_number; 2200 StackHandleScope<3> hs(soa.Self()); 2201 auto class_name_object(hs.NewHandle<mirror::String>(nullptr)); 2202 auto source_name_object(hs.NewHandle<mirror::String>(nullptr)); 2203 if (method->IsProxyMethod()) { 2204 line_number = -1; 2205 class_name_object.Assign(method->GetDeclaringClass()->GetName()); 2206 // source_name_object intentionally left null for proxy methods 2207 } else { 2208 line_number = method->GetLineNumFromDexPC(dex_pc); 2209 // Allocate element, potentially triggering GC 2210 // TODO: reuse class_name_object via Class::name_? 2211 const char* descriptor = method->GetDeclaringClassDescriptor(); 2212 CHECK(descriptor != nullptr); 2213 std::string class_name(PrettyDescriptor(descriptor)); 2214 class_name_object.Assign( 2215 mirror::String::AllocFromModifiedUtf8(soa.Self(), class_name.c_str())); 2216 if (class_name_object.Get() == nullptr) { 2217 soa.Self()->AssertPendingOOMException(); 2218 return nullptr; 2219 } 2220 const char* source_file = method->GetDeclaringClassSourceFile(); 2221 if (source_file != nullptr) { 2222 source_name_object.Assign(mirror::String::AllocFromModifiedUtf8(soa.Self(), source_file)); 2223 if (source_name_object.Get() == nullptr) { 2224 soa.Self()->AssertPendingOOMException(); 2225 return nullptr; 2226 } 2227 } 2228 } 2229 const char* method_name = method->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName(); 2230 CHECK(method_name != nullptr); 2231 Handle<mirror::String> method_name_object( 2232 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(soa.Self(), method_name))); 2233 if (method_name_object.Get() == nullptr) { 2234 return nullptr; 2235 } 2236 mirror::StackTraceElement* obj = mirror::StackTraceElement::Alloc( 2237 soa.Self(), class_name_object, method_name_object, source_name_object, line_number); 2238 if (obj == nullptr) { 2239 return nullptr; 2240 } 2241 // We are called from native: use non-transactional mode. 2242 soa.Decode<mirror::ObjectArray<mirror::StackTraceElement>*>(result)->Set<false>(i, obj); 2243 } 2244 return result; 2245} 2246 2247void Thread::ThrowNewExceptionF(const char* exception_class_descriptor, const char* fmt, ...) { 2248 va_list args; 2249 va_start(args, fmt); 2250 ThrowNewExceptionV(exception_class_descriptor, fmt, args); 2251 va_end(args); 2252} 2253 2254void Thread::ThrowNewExceptionV(const char* exception_class_descriptor, 2255 const char* fmt, va_list ap) { 2256 std::string msg; 2257 StringAppendV(&msg, fmt, ap); 2258 ThrowNewException(exception_class_descriptor, msg.c_str()); 2259} 2260 2261void Thread::ThrowNewException(const char* exception_class_descriptor, 2262 const char* msg) { 2263 // Callers should either clear or call ThrowNewWrappedException. 2264 AssertNoPendingExceptionForNewException(msg); 2265 ThrowNewWrappedException(exception_class_descriptor, msg); 2266} 2267 2268static mirror::ClassLoader* GetCurrentClassLoader(Thread* self) 2269 REQUIRES_SHARED(Locks::mutator_lock_) { 2270 ArtMethod* method = self->GetCurrentMethod(nullptr); 2271 return method != nullptr 2272 ? method->GetDeclaringClass()->GetClassLoader() 2273 : nullptr; 2274} 2275 2276void Thread::ThrowNewWrappedException(const char* exception_class_descriptor, 2277 const char* msg) { 2278 DCHECK_EQ(this, Thread::Current()); 2279 ScopedObjectAccessUnchecked soa(this); 2280 StackHandleScope<3> hs(soa.Self()); 2281 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(GetCurrentClassLoader(soa.Self()))); 2282 ScopedLocalRef<jobject> cause(GetJniEnv(), soa.AddLocalReference<jobject>(GetException())); 2283 ClearException(); 2284 Runtime* runtime = Runtime::Current(); 2285 auto* cl = runtime->GetClassLinker(); 2286 Handle<mirror::Class> exception_class( 2287 hs.NewHandle(cl->FindClass(this, exception_class_descriptor, class_loader))); 2288 if (UNLIKELY(exception_class.Get() == nullptr)) { 2289 CHECK(IsExceptionPending()); 2290 LOG(ERROR) << "No exception class " << PrettyDescriptor(exception_class_descriptor); 2291 return; 2292 } 2293 2294 if (UNLIKELY(!runtime->GetClassLinker()->EnsureInitialized(soa.Self(), exception_class, true, 2295 true))) { 2296 DCHECK(IsExceptionPending()); 2297 return; 2298 } 2299 DCHECK(!runtime->IsStarted() || exception_class->IsThrowableClass()); 2300 Handle<mirror::Throwable> exception( 2301 hs.NewHandle(down_cast<mirror::Throwable*>(exception_class->AllocObject(this)))); 2302 2303 // If we couldn't allocate the exception, throw the pre-allocated out of memory exception. 2304 if (exception.Get() == nullptr) { 2305 SetException(Runtime::Current()->GetPreAllocatedOutOfMemoryError()); 2306 return; 2307 } 2308 2309 // Choose an appropriate constructor and set up the arguments. 2310 const char* signature; 2311 ScopedLocalRef<jstring> msg_string(GetJniEnv(), nullptr); 2312 if (msg != nullptr) { 2313 // Ensure we remember this and the method over the String allocation. 2314 msg_string.reset( 2315 soa.AddLocalReference<jstring>(mirror::String::AllocFromModifiedUtf8(this, msg))); 2316 if (UNLIKELY(msg_string.get() == nullptr)) { 2317 CHECK(IsExceptionPending()); // OOME. 2318 return; 2319 } 2320 if (cause.get() == nullptr) { 2321 signature = "(Ljava/lang/String;)V"; 2322 } else { 2323 signature = "(Ljava/lang/String;Ljava/lang/Throwable;)V"; 2324 } 2325 } else { 2326 if (cause.get() == nullptr) { 2327 signature = "()V"; 2328 } else { 2329 signature = "(Ljava/lang/Throwable;)V"; 2330 } 2331 } 2332 ArtMethod* exception_init_method = 2333 exception_class->FindDeclaredDirectMethod("<init>", signature, cl->GetImagePointerSize()); 2334 2335 CHECK(exception_init_method != nullptr) << "No <init>" << signature << " in " 2336 << PrettyDescriptor(exception_class_descriptor); 2337 2338 if (UNLIKELY(!runtime->IsStarted())) { 2339 // Something is trying to throw an exception without a started runtime, which is the common 2340 // case in the compiler. We won't be able to invoke the constructor of the exception, so set 2341 // the exception fields directly. 2342 if (msg != nullptr) { 2343 exception->SetDetailMessage(down_cast<mirror::String*>(DecodeJObject(msg_string.get()))); 2344 } 2345 if (cause.get() != nullptr) { 2346 exception->SetCause(down_cast<mirror::Throwable*>(DecodeJObject(cause.get()))); 2347 } 2348 ScopedLocalRef<jobject> trace(GetJniEnv(), 2349 Runtime::Current()->IsActiveTransaction() 2350 ? CreateInternalStackTrace<true>(soa) 2351 : CreateInternalStackTrace<false>(soa)); 2352 if (trace.get() != nullptr) { 2353 exception->SetStackState(down_cast<mirror::Throwable*>(DecodeJObject(trace.get()))); 2354 } 2355 SetException(exception.Get()); 2356 } else { 2357 jvalue jv_args[2]; 2358 size_t i = 0; 2359 2360 if (msg != nullptr) { 2361 jv_args[i].l = msg_string.get(); 2362 ++i; 2363 } 2364 if (cause.get() != nullptr) { 2365 jv_args[i].l = cause.get(); 2366 ++i; 2367 } 2368 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(exception.Get())); 2369 InvokeWithJValues(soa, ref.get(), soa.EncodeMethod(exception_init_method), jv_args); 2370 if (LIKELY(!IsExceptionPending())) { 2371 SetException(exception.Get()); 2372 } 2373 } 2374} 2375 2376void Thread::ThrowOutOfMemoryError(const char* msg) { 2377 LOG(WARNING) << StringPrintf("Throwing OutOfMemoryError \"%s\"%s", 2378 msg, (tls32_.throwing_OutOfMemoryError ? " (recursive case)" : "")); 2379 if (!tls32_.throwing_OutOfMemoryError) { 2380 tls32_.throwing_OutOfMemoryError = true; 2381 ThrowNewException("Ljava/lang/OutOfMemoryError;", msg); 2382 tls32_.throwing_OutOfMemoryError = false; 2383 } else { 2384 Dump(LOG(WARNING)); // The pre-allocated OOME has no stack, so help out and log one. 2385 SetException(Runtime::Current()->GetPreAllocatedOutOfMemoryError()); 2386 } 2387} 2388 2389Thread* Thread::CurrentFromGdb() { 2390 return Thread::Current(); 2391} 2392 2393void Thread::DumpFromGdb() const { 2394 std::ostringstream ss; 2395 Dump(ss); 2396 std::string str(ss.str()); 2397 // log to stderr for debugging command line processes 2398 std::cerr << str; 2399#ifdef ART_TARGET_ANDROID 2400 // log to logcat for debugging frameworks processes 2401 LOG(INFO) << str; 2402#endif 2403} 2404 2405// Explicitly instantiate 32 and 64bit thread offset dumping support. 2406template 2407void Thread::DumpThreadOffset<PointerSize::k32>(std::ostream& os, uint32_t offset); 2408template 2409void Thread::DumpThreadOffset<PointerSize::k64>(std::ostream& os, uint32_t offset); 2410 2411template<PointerSize ptr_size> 2412void Thread::DumpThreadOffset(std::ostream& os, uint32_t offset) { 2413#define DO_THREAD_OFFSET(x, y) \ 2414 if (offset == (x).Uint32Value()) { \ 2415 os << (y); \ 2416 return; \ 2417 } 2418 DO_THREAD_OFFSET(ThreadFlagsOffset<ptr_size>(), "state_and_flags") 2419 DO_THREAD_OFFSET(CardTableOffset<ptr_size>(), "card_table") 2420 DO_THREAD_OFFSET(ExceptionOffset<ptr_size>(), "exception") 2421 DO_THREAD_OFFSET(PeerOffset<ptr_size>(), "peer"); 2422 DO_THREAD_OFFSET(JniEnvOffset<ptr_size>(), "jni_env") 2423 DO_THREAD_OFFSET(SelfOffset<ptr_size>(), "self") 2424 DO_THREAD_OFFSET(StackEndOffset<ptr_size>(), "stack_end") 2425 DO_THREAD_OFFSET(ThinLockIdOffset<ptr_size>(), "thin_lock_thread_id") 2426 DO_THREAD_OFFSET(TopOfManagedStackOffset<ptr_size>(), "top_quick_frame_method") 2427 DO_THREAD_OFFSET(TopShadowFrameOffset<ptr_size>(), "top_shadow_frame") 2428 DO_THREAD_OFFSET(TopHandleScopeOffset<ptr_size>(), "top_handle_scope") 2429 DO_THREAD_OFFSET(ThreadSuspendTriggerOffset<ptr_size>(), "suspend_trigger") 2430#undef DO_THREAD_OFFSET 2431 2432#define JNI_ENTRY_POINT_INFO(x) \ 2433 if (JNI_ENTRYPOINT_OFFSET(ptr_size, x).Uint32Value() == offset) { \ 2434 os << #x; \ 2435 return; \ 2436 } 2437 JNI_ENTRY_POINT_INFO(pDlsymLookup) 2438#undef JNI_ENTRY_POINT_INFO 2439 2440#define QUICK_ENTRY_POINT_INFO(x) \ 2441 if (QUICK_ENTRYPOINT_OFFSET(ptr_size, x).Uint32Value() == offset) { \ 2442 os << #x; \ 2443 return; \ 2444 } 2445 QUICK_ENTRY_POINT_INFO(pAllocArray) 2446 QUICK_ENTRY_POINT_INFO(pAllocArrayResolved) 2447 QUICK_ENTRY_POINT_INFO(pAllocArrayWithAccessCheck) 2448 QUICK_ENTRY_POINT_INFO(pAllocObject) 2449 QUICK_ENTRY_POINT_INFO(pAllocObjectResolved) 2450 QUICK_ENTRY_POINT_INFO(pAllocObjectInitialized) 2451 QUICK_ENTRY_POINT_INFO(pAllocObjectWithAccessCheck) 2452 QUICK_ENTRY_POINT_INFO(pCheckAndAllocArray) 2453 QUICK_ENTRY_POINT_INFO(pCheckAndAllocArrayWithAccessCheck) 2454 QUICK_ENTRY_POINT_INFO(pAllocStringFromBytes) 2455 QUICK_ENTRY_POINT_INFO(pAllocStringFromChars) 2456 QUICK_ENTRY_POINT_INFO(pAllocStringFromString) 2457 QUICK_ENTRY_POINT_INFO(pInstanceofNonTrivial) 2458 QUICK_ENTRY_POINT_INFO(pCheckCast) 2459 QUICK_ENTRY_POINT_INFO(pInitializeStaticStorage) 2460 QUICK_ENTRY_POINT_INFO(pInitializeTypeAndVerifyAccess) 2461 QUICK_ENTRY_POINT_INFO(pInitializeType) 2462 QUICK_ENTRY_POINT_INFO(pResolveString) 2463 QUICK_ENTRY_POINT_INFO(pSet8Instance) 2464 QUICK_ENTRY_POINT_INFO(pSet8Static) 2465 QUICK_ENTRY_POINT_INFO(pSet16Instance) 2466 QUICK_ENTRY_POINT_INFO(pSet16Static) 2467 QUICK_ENTRY_POINT_INFO(pSet32Instance) 2468 QUICK_ENTRY_POINT_INFO(pSet32Static) 2469 QUICK_ENTRY_POINT_INFO(pSet64Instance) 2470 QUICK_ENTRY_POINT_INFO(pSet64Static) 2471 QUICK_ENTRY_POINT_INFO(pSetObjInstance) 2472 QUICK_ENTRY_POINT_INFO(pSetObjStatic) 2473 QUICK_ENTRY_POINT_INFO(pGetByteInstance) 2474 QUICK_ENTRY_POINT_INFO(pGetBooleanInstance) 2475 QUICK_ENTRY_POINT_INFO(pGetByteStatic) 2476 QUICK_ENTRY_POINT_INFO(pGetBooleanStatic) 2477 QUICK_ENTRY_POINT_INFO(pGetShortInstance) 2478 QUICK_ENTRY_POINT_INFO(pGetCharInstance) 2479 QUICK_ENTRY_POINT_INFO(pGetShortStatic) 2480 QUICK_ENTRY_POINT_INFO(pGetCharStatic) 2481 QUICK_ENTRY_POINT_INFO(pGet32Instance) 2482 QUICK_ENTRY_POINT_INFO(pGet32Static) 2483 QUICK_ENTRY_POINT_INFO(pGet64Instance) 2484 QUICK_ENTRY_POINT_INFO(pGet64Static) 2485 QUICK_ENTRY_POINT_INFO(pGetObjInstance) 2486 QUICK_ENTRY_POINT_INFO(pGetObjStatic) 2487 QUICK_ENTRY_POINT_INFO(pAputObjectWithNullAndBoundCheck) 2488 QUICK_ENTRY_POINT_INFO(pAputObjectWithBoundCheck) 2489 QUICK_ENTRY_POINT_INFO(pAputObject) 2490 QUICK_ENTRY_POINT_INFO(pHandleFillArrayData) 2491 QUICK_ENTRY_POINT_INFO(pJniMethodStart) 2492 QUICK_ENTRY_POINT_INFO(pJniMethodStartSynchronized) 2493 QUICK_ENTRY_POINT_INFO(pJniMethodEnd) 2494 QUICK_ENTRY_POINT_INFO(pJniMethodEndSynchronized) 2495 QUICK_ENTRY_POINT_INFO(pJniMethodEndWithReference) 2496 QUICK_ENTRY_POINT_INFO(pJniMethodEndWithReferenceSynchronized) 2497 QUICK_ENTRY_POINT_INFO(pQuickGenericJniTrampoline) 2498 QUICK_ENTRY_POINT_INFO(pLockObject) 2499 QUICK_ENTRY_POINT_INFO(pUnlockObject) 2500 QUICK_ENTRY_POINT_INFO(pCmpgDouble) 2501 QUICK_ENTRY_POINT_INFO(pCmpgFloat) 2502 QUICK_ENTRY_POINT_INFO(pCmplDouble) 2503 QUICK_ENTRY_POINT_INFO(pCmplFloat) 2504 QUICK_ENTRY_POINT_INFO(pCos) 2505 QUICK_ENTRY_POINT_INFO(pSin) 2506 QUICK_ENTRY_POINT_INFO(pAcos) 2507 QUICK_ENTRY_POINT_INFO(pAsin) 2508 QUICK_ENTRY_POINT_INFO(pAtan) 2509 QUICK_ENTRY_POINT_INFO(pAtan2) 2510 QUICK_ENTRY_POINT_INFO(pCbrt) 2511 QUICK_ENTRY_POINT_INFO(pCosh) 2512 QUICK_ENTRY_POINT_INFO(pExp) 2513 QUICK_ENTRY_POINT_INFO(pExpm1) 2514 QUICK_ENTRY_POINT_INFO(pHypot) 2515 QUICK_ENTRY_POINT_INFO(pLog) 2516 QUICK_ENTRY_POINT_INFO(pLog10) 2517 QUICK_ENTRY_POINT_INFO(pNextAfter) 2518 QUICK_ENTRY_POINT_INFO(pSinh) 2519 QUICK_ENTRY_POINT_INFO(pTan) 2520 QUICK_ENTRY_POINT_INFO(pTanh) 2521 QUICK_ENTRY_POINT_INFO(pFmod) 2522 QUICK_ENTRY_POINT_INFO(pL2d) 2523 QUICK_ENTRY_POINT_INFO(pFmodf) 2524 QUICK_ENTRY_POINT_INFO(pL2f) 2525 QUICK_ENTRY_POINT_INFO(pD2iz) 2526 QUICK_ENTRY_POINT_INFO(pF2iz) 2527 QUICK_ENTRY_POINT_INFO(pIdivmod) 2528 QUICK_ENTRY_POINT_INFO(pD2l) 2529 QUICK_ENTRY_POINT_INFO(pF2l) 2530 QUICK_ENTRY_POINT_INFO(pLdiv) 2531 QUICK_ENTRY_POINT_INFO(pLmod) 2532 QUICK_ENTRY_POINT_INFO(pLmul) 2533 QUICK_ENTRY_POINT_INFO(pShlLong) 2534 QUICK_ENTRY_POINT_INFO(pShrLong) 2535 QUICK_ENTRY_POINT_INFO(pUshrLong) 2536 QUICK_ENTRY_POINT_INFO(pIndexOf) 2537 QUICK_ENTRY_POINT_INFO(pStringCompareTo) 2538 QUICK_ENTRY_POINT_INFO(pMemcpy) 2539 QUICK_ENTRY_POINT_INFO(pQuickImtConflictTrampoline) 2540 QUICK_ENTRY_POINT_INFO(pQuickResolutionTrampoline) 2541 QUICK_ENTRY_POINT_INFO(pQuickToInterpreterBridge) 2542 QUICK_ENTRY_POINT_INFO(pInvokeDirectTrampolineWithAccessCheck) 2543 QUICK_ENTRY_POINT_INFO(pInvokeInterfaceTrampolineWithAccessCheck) 2544 QUICK_ENTRY_POINT_INFO(pInvokeStaticTrampolineWithAccessCheck) 2545 QUICK_ENTRY_POINT_INFO(pInvokeSuperTrampolineWithAccessCheck) 2546 QUICK_ENTRY_POINT_INFO(pInvokeVirtualTrampolineWithAccessCheck) 2547 QUICK_ENTRY_POINT_INFO(pTestSuspend) 2548 QUICK_ENTRY_POINT_INFO(pDeliverException) 2549 QUICK_ENTRY_POINT_INFO(pThrowArrayBounds) 2550 QUICK_ENTRY_POINT_INFO(pThrowDivZero) 2551 QUICK_ENTRY_POINT_INFO(pThrowNoSuchMethod) 2552 QUICK_ENTRY_POINT_INFO(pThrowNullPointer) 2553 QUICK_ENTRY_POINT_INFO(pThrowStackOverflow) 2554 QUICK_ENTRY_POINT_INFO(pDeoptimize) 2555 QUICK_ENTRY_POINT_INFO(pA64Load) 2556 QUICK_ENTRY_POINT_INFO(pA64Store) 2557 QUICK_ENTRY_POINT_INFO(pNewEmptyString) 2558 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_B) 2559 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BI) 2560 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BII) 2561 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BIII) 2562 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BIIString) 2563 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BString) 2564 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BIICharset) 2565 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BCharset) 2566 QUICK_ENTRY_POINT_INFO(pNewStringFromChars_C) 2567 QUICK_ENTRY_POINT_INFO(pNewStringFromChars_CII) 2568 QUICK_ENTRY_POINT_INFO(pNewStringFromChars_IIC) 2569 QUICK_ENTRY_POINT_INFO(pNewStringFromCodePoints) 2570 QUICK_ENTRY_POINT_INFO(pNewStringFromString) 2571 QUICK_ENTRY_POINT_INFO(pNewStringFromStringBuffer) 2572 QUICK_ENTRY_POINT_INFO(pNewStringFromStringBuilder) 2573 QUICK_ENTRY_POINT_INFO(pReadBarrierJni) 2574 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg00) 2575 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg01) 2576 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg02) 2577 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg03) 2578 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg04) 2579 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg05) 2580 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg06) 2581 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg07) 2582 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg08) 2583 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg09) 2584 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg10) 2585 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg11) 2586 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg12) 2587 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg13) 2588 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg14) 2589 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg15) 2590 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg16) 2591 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg17) 2592 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg18) 2593 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg19) 2594 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg20) 2595 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg21) 2596 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg22) 2597 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg23) 2598 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg24) 2599 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg25) 2600 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg26) 2601 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg27) 2602 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg28) 2603 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg29) 2604 QUICK_ENTRY_POINT_INFO(pReadBarrierSlow) 2605 QUICK_ENTRY_POINT_INFO(pReadBarrierForRootSlow) 2606 2607 QUICK_ENTRY_POINT_INFO(pJniMethodFastStart) 2608 QUICK_ENTRY_POINT_INFO(pJniMethodFastEnd) 2609#undef QUICK_ENTRY_POINT_INFO 2610 2611 os << offset; 2612} 2613 2614void Thread::QuickDeliverException() { 2615 // Get exception from thread. 2616 mirror::Throwable* exception = GetException(); 2617 CHECK(exception != nullptr); 2618 if (exception == GetDeoptimizationException()) { 2619 artDeoptimize(this); 2620 UNREACHABLE(); 2621 } 2622 2623 // This is a real exception: let the instrumentation know about it. 2624 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation(); 2625 if (instrumentation->HasExceptionCaughtListeners() && 2626 IsExceptionThrownByCurrentMethod(exception)) { 2627 // Instrumentation may cause GC so keep the exception object safe. 2628 StackHandleScope<1> hs(this); 2629 HandleWrapper<mirror::Throwable> h_exception(hs.NewHandleWrapper(&exception)); 2630 instrumentation->ExceptionCaughtEvent(this, exception); 2631 } 2632 // Does instrumentation need to deoptimize the stack? 2633 // Note: we do this *after* reporting the exception to instrumentation in case it 2634 // now requires deoptimization. It may happen if a debugger is attached and requests 2635 // new events (single-step, breakpoint, ...) when the exception is reported. 2636 if (Dbg::IsForcedInterpreterNeededForException(this)) { 2637 NthCallerVisitor visitor(this, 0, false); 2638 visitor.WalkStack(); 2639 if (Runtime::Current()->IsDeoptimizeable(visitor.caller_pc)) { 2640 // Save the exception into the deoptimization context so it can be restored 2641 // before entering the interpreter. 2642 PushDeoptimizationContext( 2643 JValue(), /*is_reference */ false, /* from_code */ false, exception); 2644 artDeoptimize(this); 2645 UNREACHABLE(); 2646 } 2647 } 2648 2649 // Don't leave exception visible while we try to find the handler, which may cause class 2650 // resolution. 2651 ClearException(); 2652 QuickExceptionHandler exception_handler(this, false); 2653 exception_handler.FindCatch(exception); 2654 exception_handler.UpdateInstrumentationStack(); 2655 exception_handler.DoLongJump(); 2656} 2657 2658Context* Thread::GetLongJumpContext() { 2659 Context* result = tlsPtr_.long_jump_context; 2660 if (result == nullptr) { 2661 result = Context::Create(); 2662 } else { 2663 tlsPtr_.long_jump_context = nullptr; // Avoid context being shared. 2664 result->Reset(); 2665 } 2666 return result; 2667} 2668 2669// Note: this visitor may return with a method set, but dex_pc_ being DexFile:kDexNoIndex. This is 2670// so we don't abort in a special situation (thinlocked monitor) when dumping the Java stack. 2671struct CurrentMethodVisitor FINAL : public StackVisitor { 2672 CurrentMethodVisitor(Thread* thread, Context* context, bool abort_on_error) 2673 REQUIRES_SHARED(Locks::mutator_lock_) 2674 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames), 2675 this_object_(nullptr), 2676 method_(nullptr), 2677 dex_pc_(0), 2678 abort_on_error_(abort_on_error) {} 2679 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) { 2680 ArtMethod* m = GetMethod(); 2681 if (m->IsRuntimeMethod()) { 2682 // Continue if this is a runtime method. 2683 return true; 2684 } 2685 if (context_ != nullptr) { 2686 this_object_ = GetThisObject(); 2687 } 2688 method_ = m; 2689 dex_pc_ = GetDexPc(abort_on_error_); 2690 return false; 2691 } 2692 mirror::Object* this_object_; 2693 ArtMethod* method_; 2694 uint32_t dex_pc_; 2695 const bool abort_on_error_; 2696}; 2697 2698ArtMethod* Thread::GetCurrentMethod(uint32_t* dex_pc, bool abort_on_error) const { 2699 CurrentMethodVisitor visitor(const_cast<Thread*>(this), nullptr, abort_on_error); 2700 visitor.WalkStack(false); 2701 if (dex_pc != nullptr) { 2702 *dex_pc = visitor.dex_pc_; 2703 } 2704 return visitor.method_; 2705} 2706 2707bool Thread::HoldsLock(mirror::Object* object) const { 2708 if (object == nullptr) { 2709 return false; 2710 } 2711 return object->GetLockOwnerThreadId() == GetThreadId(); 2712} 2713 2714// RootVisitor parameters are: (const Object* obj, size_t vreg, const StackVisitor* visitor). 2715template <typename RootVisitor> 2716class ReferenceMapVisitor : public StackVisitor { 2717 public: 2718 ReferenceMapVisitor(Thread* thread, Context* context, RootVisitor& visitor) 2719 REQUIRES_SHARED(Locks::mutator_lock_) 2720 // We are visiting the references in compiled frames, so we do not need 2721 // to know the inlined frames. 2722 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kSkipInlinedFrames), 2723 visitor_(visitor) {} 2724 2725 bool VisitFrame() REQUIRES_SHARED(Locks::mutator_lock_) { 2726 if (false) { 2727 LOG(INFO) << "Visiting stack roots in " << PrettyMethod(GetMethod()) 2728 << StringPrintf("@ PC:%04x", GetDexPc()); 2729 } 2730 ShadowFrame* shadow_frame = GetCurrentShadowFrame(); 2731 if (shadow_frame != nullptr) { 2732 VisitShadowFrame(shadow_frame); 2733 } else { 2734 VisitQuickFrame(); 2735 } 2736 return true; 2737 } 2738 2739 void VisitShadowFrame(ShadowFrame* shadow_frame) REQUIRES_SHARED(Locks::mutator_lock_) { 2740 ArtMethod* m = shadow_frame->GetMethod(); 2741 VisitDeclaringClass(m); 2742 DCHECK(m != nullptr); 2743 size_t num_regs = shadow_frame->NumberOfVRegs(); 2744 DCHECK(m->IsNative() || shadow_frame->HasReferenceArray()); 2745 // handle scope for JNI or References for interpreter. 2746 for (size_t reg = 0; reg < num_regs; ++reg) { 2747 mirror::Object* ref = shadow_frame->GetVRegReference(reg); 2748 if (ref != nullptr) { 2749 mirror::Object* new_ref = ref; 2750 visitor_(&new_ref, reg, this); 2751 if (new_ref != ref) { 2752 shadow_frame->SetVRegReference(reg, new_ref); 2753 } 2754 } 2755 } 2756 // Mark lock count map required for structured locking checks. 2757 shadow_frame->GetLockCountData().VisitMonitors(visitor_, -1, this); 2758 } 2759 2760 private: 2761 // Visiting the declaring class is necessary so that we don't unload the class of a method that 2762 // is executing. We need to ensure that the code stays mapped. NO_THREAD_SAFETY_ANALYSIS since 2763 // the threads do not all hold the heap bitmap lock for parallel GC. 2764 void VisitDeclaringClass(ArtMethod* method) 2765 REQUIRES_SHARED(Locks::mutator_lock_) 2766 NO_THREAD_SAFETY_ANALYSIS { 2767 mirror::Class* klass = method->GetDeclaringClassUnchecked<kWithoutReadBarrier>(); 2768 // klass can be null for runtime methods. 2769 if (klass != nullptr) { 2770 if (kVerifyImageObjectsMarked) { 2771 gc::Heap* const heap = Runtime::Current()->GetHeap(); 2772 gc::space::ContinuousSpace* space = heap->FindContinuousSpaceFromObject(klass, 2773 /*fail_ok*/true); 2774 if (space != nullptr && space->IsImageSpace()) { 2775 bool failed = false; 2776 if (!space->GetLiveBitmap()->Test(klass)) { 2777 failed = true; 2778 LOG(INTERNAL_FATAL) << "Unmarked object in image " << *space; 2779 } else if (!heap->GetLiveBitmap()->Test(klass)) { 2780 failed = true; 2781 LOG(INTERNAL_FATAL) << "Unmarked object in image through live bitmap " << *space; 2782 } 2783 if (failed) { 2784 GetThread()->Dump(LOG(INTERNAL_FATAL)); 2785 space->AsImageSpace()->DumpSections(LOG(INTERNAL_FATAL)); 2786 LOG(INTERNAL_FATAL) << "Method@" << method->GetDexMethodIndex() << ":" << method 2787 << " klass@" << klass; 2788 // Pretty info last in case it crashes. 2789 LOG(FATAL) << "Method " << PrettyMethod(method) << " klass " << PrettyClass(klass); 2790 } 2791 } 2792 } 2793 mirror::Object* new_ref = klass; 2794 visitor_(&new_ref, -1, this); 2795 if (new_ref != klass) { 2796 method->CASDeclaringClass(klass, new_ref->AsClass()); 2797 } 2798 } 2799 } 2800 2801 void VisitQuickFrame() REQUIRES_SHARED(Locks::mutator_lock_) { 2802 ArtMethod** cur_quick_frame = GetCurrentQuickFrame(); 2803 DCHECK(cur_quick_frame != nullptr); 2804 ArtMethod* m = *cur_quick_frame; 2805 VisitDeclaringClass(m); 2806 2807 // Process register map (which native and runtime methods don't have) 2808 if (!m->IsNative() && !m->IsRuntimeMethod() && (!m->IsProxyMethod() || m->IsConstructor())) { 2809 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader(); 2810 DCHECK(method_header->IsOptimized()); 2811 auto* vreg_base = reinterpret_cast<StackReference<mirror::Object>*>( 2812 reinterpret_cast<uintptr_t>(cur_quick_frame)); 2813 uintptr_t native_pc_offset = method_header->NativeQuickPcOffset(GetCurrentQuickFramePc()); 2814 CodeInfo code_info = method_header->GetOptimizedCodeInfo(); 2815 CodeInfoEncoding encoding = code_info.ExtractEncoding(); 2816 StackMap map = code_info.GetStackMapForNativePcOffset(native_pc_offset, encoding); 2817 DCHECK(map.IsValid()); 2818 // Visit stack entries that hold pointers. 2819 size_t number_of_bits = map.GetNumberOfStackMaskBits(encoding.stack_map_encoding); 2820 for (size_t i = 0; i < number_of_bits; ++i) { 2821 if (map.GetStackMaskBit(encoding.stack_map_encoding, i)) { 2822 auto* ref_addr = vreg_base + i; 2823 mirror::Object* ref = ref_addr->AsMirrorPtr(); 2824 if (ref != nullptr) { 2825 mirror::Object* new_ref = ref; 2826 visitor_(&new_ref, -1, this); 2827 if (ref != new_ref) { 2828 ref_addr->Assign(new_ref); 2829 } 2830 } 2831 } 2832 } 2833 // Visit callee-save registers that hold pointers. 2834 uint32_t register_mask = map.GetRegisterMask(encoding.stack_map_encoding); 2835 for (size_t i = 0; i < BitSizeOf<uint32_t>(); ++i) { 2836 if (register_mask & (1 << i)) { 2837 mirror::Object** ref_addr = reinterpret_cast<mirror::Object**>(GetGPRAddress(i)); 2838 if (kIsDebugBuild && ref_addr == nullptr) { 2839 std::string thread_name; 2840 GetThread()->GetThreadName(thread_name); 2841 LOG(INTERNAL_FATAL) << "On thread " << thread_name; 2842 DescribeStack(GetThread()); 2843 LOG(FATAL) << "Found an unsaved callee-save register " << i << " (null GPRAddress) " 2844 << "set in register_mask=" << register_mask << " at " << DescribeLocation(); 2845 } 2846 if (*ref_addr != nullptr) { 2847 visitor_(ref_addr, -1, this); 2848 } 2849 } 2850 } 2851 } 2852 } 2853 2854 // Visitor for when we visit a root. 2855 RootVisitor& visitor_; 2856}; 2857 2858class RootCallbackVisitor { 2859 public: 2860 RootCallbackVisitor(RootVisitor* visitor, uint32_t tid) : visitor_(visitor), tid_(tid) {} 2861 2862 void operator()(mirror::Object** obj, size_t vreg, const StackVisitor* stack_visitor) const 2863 REQUIRES_SHARED(Locks::mutator_lock_) { 2864 visitor_->VisitRoot(obj, JavaFrameRootInfo(tid_, stack_visitor, vreg)); 2865 } 2866 2867 private: 2868 RootVisitor* const visitor_; 2869 const uint32_t tid_; 2870}; 2871 2872void Thread::VisitRoots(RootVisitor* visitor) { 2873 const uint32_t thread_id = GetThreadId(); 2874 visitor->VisitRootIfNonNull(&tlsPtr_.opeer, RootInfo(kRootThreadObject, thread_id)); 2875 if (tlsPtr_.exception != nullptr && tlsPtr_.exception != GetDeoptimizationException()) { 2876 visitor->VisitRoot(reinterpret_cast<mirror::Object**>(&tlsPtr_.exception), 2877 RootInfo(kRootNativeStack, thread_id)); 2878 } 2879 visitor->VisitRootIfNonNull(&tlsPtr_.monitor_enter_object, RootInfo(kRootNativeStack, thread_id)); 2880 tlsPtr_.jni_env->locals.VisitRoots(visitor, RootInfo(kRootJNILocal, thread_id)); 2881 tlsPtr_.jni_env->monitors.VisitRoots(visitor, RootInfo(kRootJNIMonitor, thread_id)); 2882 HandleScopeVisitRoots(visitor, thread_id); 2883 if (tlsPtr_.debug_invoke_req != nullptr) { 2884 tlsPtr_.debug_invoke_req->VisitRoots(visitor, RootInfo(kRootDebugger, thread_id)); 2885 } 2886 // Visit roots for deoptimization. 2887 if (tlsPtr_.stacked_shadow_frame_record != nullptr) { 2888 RootCallbackVisitor visitor_to_callback(visitor, thread_id); 2889 ReferenceMapVisitor<RootCallbackVisitor> mapper(this, nullptr, visitor_to_callback); 2890 for (StackedShadowFrameRecord* record = tlsPtr_.stacked_shadow_frame_record; 2891 record != nullptr; 2892 record = record->GetLink()) { 2893 for (ShadowFrame* shadow_frame = record->GetShadowFrame(); 2894 shadow_frame != nullptr; 2895 shadow_frame = shadow_frame->GetLink()) { 2896 mapper.VisitShadowFrame(shadow_frame); 2897 } 2898 } 2899 } 2900 for (DeoptimizationContextRecord* record = tlsPtr_.deoptimization_context_stack; 2901 record != nullptr; 2902 record = record->GetLink()) { 2903 if (record->IsReference()) { 2904 visitor->VisitRootIfNonNull(record->GetReturnValueAsGCRoot(), 2905 RootInfo(kRootThreadObject, thread_id)); 2906 } 2907 visitor->VisitRootIfNonNull(record->GetPendingExceptionAsGCRoot(), 2908 RootInfo(kRootThreadObject, thread_id)); 2909 } 2910 if (tlsPtr_.frame_id_to_shadow_frame != nullptr) { 2911 RootCallbackVisitor visitor_to_callback(visitor, thread_id); 2912 ReferenceMapVisitor<RootCallbackVisitor> mapper(this, nullptr, visitor_to_callback); 2913 for (FrameIdToShadowFrame* record = tlsPtr_.frame_id_to_shadow_frame; 2914 record != nullptr; 2915 record = record->GetNext()) { 2916 mapper.VisitShadowFrame(record->GetShadowFrame()); 2917 } 2918 } 2919 for (auto* verifier = tlsPtr_.method_verifier; verifier != nullptr; verifier = verifier->link_) { 2920 verifier->VisitRoots(visitor, RootInfo(kRootNativeStack, thread_id)); 2921 } 2922 // Visit roots on this thread's stack 2923 Context* context = GetLongJumpContext(); 2924 RootCallbackVisitor visitor_to_callback(visitor, thread_id); 2925 ReferenceMapVisitor<RootCallbackVisitor> mapper(this, context, visitor_to_callback); 2926 mapper.WalkStack(); 2927 ReleaseLongJumpContext(context); 2928 for (instrumentation::InstrumentationStackFrame& frame : *GetInstrumentationStack()) { 2929 visitor->VisitRootIfNonNull(&frame.this_object_, RootInfo(kRootVMInternal, thread_id)); 2930 } 2931} 2932 2933class VerifyRootVisitor : public SingleRootVisitor { 2934 public: 2935 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED) 2936 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) { 2937 VerifyObject(root); 2938 } 2939}; 2940 2941void Thread::VerifyStackImpl() { 2942 VerifyRootVisitor visitor; 2943 std::unique_ptr<Context> context(Context::Create()); 2944 RootCallbackVisitor visitor_to_callback(&visitor, GetThreadId()); 2945 ReferenceMapVisitor<RootCallbackVisitor> mapper(this, context.get(), visitor_to_callback); 2946 mapper.WalkStack(); 2947} 2948 2949// Set the stack end to that to be used during a stack overflow 2950void Thread::SetStackEndForStackOverflow() { 2951 // During stack overflow we allow use of the full stack. 2952 if (tlsPtr_.stack_end == tlsPtr_.stack_begin) { 2953 // However, we seem to have already extended to use the full stack. 2954 LOG(ERROR) << "Need to increase kStackOverflowReservedBytes (currently " 2955 << GetStackOverflowReservedBytes(kRuntimeISA) << ")?"; 2956 DumpStack(LOG(ERROR)); 2957 LOG(FATAL) << "Recursive stack overflow."; 2958 } 2959 2960 tlsPtr_.stack_end = tlsPtr_.stack_begin; 2961 2962 // Remove the stack overflow protection if is it set up. 2963 bool implicit_stack_check = !Runtime::Current()->ExplicitStackOverflowChecks(); 2964 if (implicit_stack_check) { 2965 if (!UnprotectStack()) { 2966 LOG(ERROR) << "Unable to remove stack protection for stack overflow"; 2967 } 2968 } 2969} 2970 2971void Thread::SetTlab(uint8_t* start, uint8_t* end) { 2972 DCHECK_LE(start, end); 2973 tlsPtr_.thread_local_start = start; 2974 tlsPtr_.thread_local_pos = tlsPtr_.thread_local_start; 2975 tlsPtr_.thread_local_end = end; 2976 tlsPtr_.thread_local_objects = 0; 2977} 2978 2979bool Thread::HasTlab() const { 2980 bool has_tlab = tlsPtr_.thread_local_pos != nullptr; 2981 if (has_tlab) { 2982 DCHECK(tlsPtr_.thread_local_start != nullptr && tlsPtr_.thread_local_end != nullptr); 2983 } else { 2984 DCHECK(tlsPtr_.thread_local_start == nullptr && tlsPtr_.thread_local_end == nullptr); 2985 } 2986 return has_tlab; 2987} 2988 2989std::ostream& operator<<(std::ostream& os, const Thread& thread) { 2990 thread.ShortDump(os); 2991 return os; 2992} 2993 2994bool Thread::ProtectStack(bool fatal_on_error) { 2995 void* pregion = tlsPtr_.stack_begin - kStackOverflowProtectedSize; 2996 VLOG(threads) << "Protecting stack at " << pregion; 2997 if (mprotect(pregion, kStackOverflowProtectedSize, PROT_NONE) == -1) { 2998 if (fatal_on_error) { 2999 LOG(FATAL) << "Unable to create protected region in stack for implicit overflow check. " 3000 "Reason: " 3001 << strerror(errno) << " size: " << kStackOverflowProtectedSize; 3002 } 3003 return false; 3004 } 3005 return true; 3006} 3007 3008bool Thread::UnprotectStack() { 3009 void* pregion = tlsPtr_.stack_begin - kStackOverflowProtectedSize; 3010 VLOG(threads) << "Unprotecting stack at " << pregion; 3011 return mprotect(pregion, kStackOverflowProtectedSize, PROT_READ|PROT_WRITE) == 0; 3012} 3013 3014void Thread::ActivateSingleStepControl(SingleStepControl* ssc) { 3015 CHECK(Dbg::IsDebuggerActive()); 3016 CHECK(GetSingleStepControl() == nullptr) << "Single step already active in thread " << *this; 3017 CHECK(ssc != nullptr); 3018 tlsPtr_.single_step_control = ssc; 3019} 3020 3021void Thread::DeactivateSingleStepControl() { 3022 CHECK(Dbg::IsDebuggerActive()); 3023 CHECK(GetSingleStepControl() != nullptr) << "Single step not active in thread " << *this; 3024 SingleStepControl* ssc = GetSingleStepControl(); 3025 tlsPtr_.single_step_control = nullptr; 3026 delete ssc; 3027} 3028 3029void Thread::SetDebugInvokeReq(DebugInvokeReq* req) { 3030 CHECK(Dbg::IsDebuggerActive()); 3031 CHECK(GetInvokeReq() == nullptr) << "Debug invoke req already active in thread " << *this; 3032 CHECK(Thread::Current() != this) << "Debug invoke can't be dispatched by the thread itself"; 3033 CHECK(req != nullptr); 3034 tlsPtr_.debug_invoke_req = req; 3035} 3036 3037void Thread::ClearDebugInvokeReq() { 3038 CHECK(GetInvokeReq() != nullptr) << "Debug invoke req not active in thread " << *this; 3039 CHECK(Thread::Current() == this) << "Debug invoke must be finished by the thread itself"; 3040 DebugInvokeReq* req = tlsPtr_.debug_invoke_req; 3041 tlsPtr_.debug_invoke_req = nullptr; 3042 delete req; 3043} 3044 3045void Thread::PushVerifier(verifier::MethodVerifier* verifier) { 3046 verifier->link_ = tlsPtr_.method_verifier; 3047 tlsPtr_.method_verifier = verifier; 3048} 3049 3050void Thread::PopVerifier(verifier::MethodVerifier* verifier) { 3051 CHECK_EQ(tlsPtr_.method_verifier, verifier); 3052 tlsPtr_.method_verifier = verifier->link_; 3053} 3054 3055size_t Thread::NumberOfHeldMutexes() const { 3056 size_t count = 0; 3057 for (BaseMutex* mu : tlsPtr_.held_mutexes) { 3058 count += mu != nullptr ? 1 : 0; 3059 } 3060 return count; 3061} 3062 3063void Thread::DeoptimizeWithDeoptimizationException(JValue* result) { 3064 DCHECK_EQ(GetException(), Thread::GetDeoptimizationException()); 3065 ClearException(); 3066 ShadowFrame* shadow_frame = 3067 PopStackedShadowFrame(StackedShadowFrameType::kDeoptimizationShadowFrame); 3068 mirror::Throwable* pending_exception = nullptr; 3069 bool from_code = false; 3070 PopDeoptimizationContext(result, &pending_exception, &from_code); 3071 SetTopOfStack(nullptr); 3072 SetTopOfShadowStack(shadow_frame); 3073 3074 // Restore the exception that was pending before deoptimization then interpret the 3075 // deoptimized frames. 3076 if (pending_exception != nullptr) { 3077 SetException(pending_exception); 3078 } 3079 interpreter::EnterInterpreterFromDeoptimize(this, shadow_frame, from_code, result); 3080} 3081 3082void Thread::SetException(mirror::Throwable* new_exception) { 3083 CHECK(new_exception != nullptr); 3084 // TODO: DCHECK(!IsExceptionPending()); 3085 tlsPtr_.exception = new_exception; 3086 // LOG(ERROR) << new_exception->Dump(); 3087} 3088 3089} // namespace art 3090