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