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