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