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