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