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