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