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