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