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