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   } else {
550     // These aren't necessary, but they improve diagnostics for unit tests & command-line tools.
551     if (thread_name != nullptr) {
552       self->tlsPtr_.name->assign(thread_name);
553       ::art::SetThreadName(thread_name);
554     } else if (self->GetJniEnv()->check_jni) {
555       LOG(WARNING) << *Thread::Current() << " attached without supplying a name";
556     }
557   }
558 
559   {
560     ScopedObjectAccess soa(self);
561     Dbg::PostThreadStart(self);
562   }
563 
564   return self;
565 }
566 
CreatePeer(const char * name,bool as_daemon,jobject thread_group)567 void Thread::CreatePeer(const char* name, bool as_daemon, jobject thread_group) {
568   Runtime* runtime = Runtime::Current();
569   CHECK(runtime->IsStarted());
570   JNIEnv* env = tlsPtr_.jni_env;
571 
572   if (thread_group == nullptr) {
573     thread_group = runtime->GetMainThreadGroup();
574   }
575   ScopedLocalRef<jobject> thread_name(env, env->NewStringUTF(name));
576   // Add missing null check in case of OOM b/18297817
577   if (name != nullptr && thread_name.get() == nullptr) {
578     CHECK(IsExceptionPending());
579     return;
580   }
581   jint thread_priority = GetNativePriority();
582   jboolean thread_is_daemon = as_daemon;
583 
584   ScopedLocalRef<jobject> peer(env, env->AllocObject(WellKnownClasses::java_lang_Thread));
585   if (peer.get() == nullptr) {
586     CHECK(IsExceptionPending());
587     return;
588   }
589   {
590     ScopedObjectAccess soa(this);
591     tlsPtr_.opeer = soa.Decode<mirror::Object*>(peer.get());
592   }
593   env->CallNonvirtualVoidMethod(peer.get(),
594                                 WellKnownClasses::java_lang_Thread,
595                                 WellKnownClasses::java_lang_Thread_init,
596                                 thread_group, thread_name.get(), thread_priority, thread_is_daemon);
597   AssertNoPendingException();
598 
599   Thread* self = this;
600   DCHECK_EQ(self, Thread::Current());
601   env->SetLongField(peer.get(), WellKnownClasses::java_lang_Thread_nativePeer,
602                     reinterpret_cast<jlong>(self));
603 
604   ScopedObjectAccess soa(self);
605   StackHandleScope<1> hs(self);
606   MutableHandle<mirror::String> peer_thread_name(hs.NewHandle(GetThreadName(soa)));
607   if (peer_thread_name.Get() == nullptr) {
608     // The Thread constructor should have set the Thread.name to a
609     // non-null value. However, because we can run without code
610     // available (in the compiler, in tests), we manually assign the
611     // fields the constructor should have set.
612     if (runtime->IsActiveTransaction()) {
613       InitPeer<true>(soa, thread_is_daemon, thread_group, thread_name.get(), thread_priority);
614     } else {
615       InitPeer<false>(soa, thread_is_daemon, thread_group, thread_name.get(), thread_priority);
616     }
617     peer_thread_name.Assign(GetThreadName(soa));
618   }
619   // 'thread_name' may have been null, so don't trust 'peer_thread_name' to be non-null.
620   if (peer_thread_name.Get() != nullptr) {
621     SetThreadName(peer_thread_name->ToModifiedUtf8().c_str());
622   }
623 }
624 
625 template<bool kTransactionActive>
InitPeer(ScopedObjectAccess & soa,jboolean thread_is_daemon,jobject thread_group,jobject thread_name,jint thread_priority)626 void Thread::InitPeer(ScopedObjectAccess& soa, jboolean thread_is_daemon, jobject thread_group,
627                       jobject thread_name, jint thread_priority) {
628   soa.DecodeField(WellKnownClasses::java_lang_Thread_daemon)->
629       SetBoolean<kTransactionActive>(tlsPtr_.opeer, thread_is_daemon);
630   soa.DecodeField(WellKnownClasses::java_lang_Thread_group)->
631       SetObject<kTransactionActive>(tlsPtr_.opeer, soa.Decode<mirror::Object*>(thread_group));
632   soa.DecodeField(WellKnownClasses::java_lang_Thread_name)->
633       SetObject<kTransactionActive>(tlsPtr_.opeer, soa.Decode<mirror::Object*>(thread_name));
634   soa.DecodeField(WellKnownClasses::java_lang_Thread_priority)->
635       SetInt<kTransactionActive>(tlsPtr_.opeer, thread_priority);
636 }
637 
SetThreadName(const char * name)638 void Thread::SetThreadName(const char* name) {
639   tlsPtr_.name->assign(name);
640   ::art::SetThreadName(name);
641   Dbg::DdmSendThreadNotification(this, CHUNK_TYPE("THNM"));
642 }
643 
InitStackHwm()644 bool Thread::InitStackHwm() {
645   void* read_stack_base;
646   size_t read_stack_size;
647   size_t read_guard_size;
648   GetThreadStack(tlsPtr_.pthread_self, &read_stack_base, &read_stack_size, &read_guard_size);
649 
650   tlsPtr_.stack_begin = reinterpret_cast<uint8_t*>(read_stack_base);
651   tlsPtr_.stack_size = read_stack_size;
652 
653   // The minimum stack size we can cope with is the overflow reserved bytes (typically
654   // 8K) + the protected region size (4K) + another page (4K).  Typically this will
655   // be 8+4+4 = 16K.  The thread won't be able to do much with this stack even the GC takes
656   // between 8K and 12K.
657   uint32_t min_stack = GetStackOverflowReservedBytes(kRuntimeISA) + kStackOverflowProtectedSize
658     + 4 * KB;
659   if (read_stack_size <= min_stack) {
660     // Note, as we know the stack is small, avoid operations that could use a lot of stack.
661     LogMessage::LogLineLowStack(__PRETTY_FUNCTION__, __LINE__, ERROR,
662                                 "Attempt to attach a thread with a too-small stack");
663     return false;
664   }
665 
666   // This is included in the SIGQUIT output, but it's useful here for thread debugging.
667   VLOG(threads) << StringPrintf("Native stack is at %p (%s with %s guard)",
668                                 read_stack_base,
669                                 PrettySize(read_stack_size).c_str(),
670                                 PrettySize(read_guard_size).c_str());
671 
672   // Set stack_end_ to the bottom of the stack saving space of stack overflows
673 
674   Runtime* runtime = Runtime::Current();
675   bool implicit_stack_check = !runtime->ExplicitStackOverflowChecks() && !runtime->IsAotCompiler();
676   ResetDefaultStackEnd();
677 
678   // Install the protected region if we are doing implicit overflow checks.
679   if (implicit_stack_check) {
680     // The thread might have protected region at the bottom.  We need
681     // to install our own region so we need to move the limits
682     // of the stack to make room for it.
683 
684     tlsPtr_.stack_begin += read_guard_size + kStackOverflowProtectedSize;
685     tlsPtr_.stack_end += read_guard_size + kStackOverflowProtectedSize;
686     tlsPtr_.stack_size -= read_guard_size;
687 
688     InstallImplicitProtection();
689   }
690 
691   // Sanity check.
692   int stack_variable;
693   CHECK_GT(&stack_variable, reinterpret_cast<void*>(tlsPtr_.stack_end));
694 
695   return true;
696 }
697 
ShortDump(std::ostream & os) const698 void Thread::ShortDump(std::ostream& os) const {
699   os << "Thread[";
700   if (GetThreadId() != 0) {
701     // If we're in kStarting, we won't have a thin lock id or tid yet.
702     os << GetThreadId()
703        << ",tid=" << GetTid() << ',';
704   }
705   os << GetState()
706      << ",Thread*=" << this
707      << ",peer=" << tlsPtr_.opeer
708      << ",\"" << (tlsPtr_.name != nullptr ? *tlsPtr_.name : "null") << "\""
709      << "]";
710 }
711 
Dump(std::ostream & os) const712 void Thread::Dump(std::ostream& os) const {
713   DumpState(os);
714   DumpStack(os);
715 }
716 
GetThreadName(const ScopedObjectAccessAlreadyRunnable & soa) const717 mirror::String* Thread::GetThreadName(const ScopedObjectAccessAlreadyRunnable& soa) const {
718   ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
719   return (tlsPtr_.opeer != nullptr) ?
720       reinterpret_cast<mirror::String*>(f->GetObject(tlsPtr_.opeer)) : nullptr;
721 }
722 
GetThreadName(std::string & name) const723 void Thread::GetThreadName(std::string& name) const {
724   name.assign(*tlsPtr_.name);
725 }
726 
GetCpuMicroTime() const727 uint64_t Thread::GetCpuMicroTime() const {
728 #if defined(__linux__)
729   clockid_t cpu_clock_id;
730   pthread_getcpuclockid(tlsPtr_.pthread_self, &cpu_clock_id);
731   timespec now;
732   clock_gettime(cpu_clock_id, &now);
733   return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_nsec / UINT64_C(1000);
734 #else  // __APPLE__
735   UNIMPLEMENTED(WARNING);
736   return -1;
737 #endif
738 }
739 
740 // Attempt to rectify locks so that we dump thread list with required locks before exiting.
UnsafeLogFatalForSuspendCount(Thread * self,Thread * thread)741 static void UnsafeLogFatalForSuspendCount(Thread* self, Thread* thread) NO_THREAD_SAFETY_ANALYSIS {
742   LOG(ERROR) << *thread << " suspend count already zero.";
743   Locks::thread_suspend_count_lock_->Unlock(self);
744   if (!Locks::mutator_lock_->IsSharedHeld(self)) {
745     Locks::mutator_lock_->SharedTryLock(self);
746     if (!Locks::mutator_lock_->IsSharedHeld(self)) {
747       LOG(WARNING) << "Dumping thread list without holding mutator_lock_";
748     }
749   }
750   if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) {
751     Locks::thread_list_lock_->TryLock(self);
752     if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) {
753       LOG(WARNING) << "Dumping thread list without holding thread_list_lock_";
754     }
755   }
756   std::ostringstream ss;
757   Runtime::Current()->GetThreadList()->Dump(ss);
758   LOG(FATAL) << ss.str();
759 }
760 
ModifySuspendCount(Thread * self,int delta,bool for_debugger)761 void Thread::ModifySuspendCount(Thread* self, int delta, bool for_debugger) {
762   if (kIsDebugBuild) {
763     DCHECK(delta == -1 || delta == +1 || delta == -tls32_.debug_suspend_count)
764           << delta << " " << tls32_.debug_suspend_count << " " << this;
765     DCHECK_GE(tls32_.suspend_count, tls32_.debug_suspend_count) << this;
766     Locks::thread_suspend_count_lock_->AssertHeld(self);
767     if (this != self && !IsSuspended()) {
768       Locks::thread_list_lock_->AssertHeld(self);
769     }
770   }
771   if (UNLIKELY(delta < 0 && tls32_.suspend_count <= 0)) {
772     UnsafeLogFatalForSuspendCount(self, this);
773     return;
774   }
775 
776   tls32_.suspend_count += delta;
777   if (for_debugger) {
778     tls32_.debug_suspend_count += delta;
779   }
780 
781   if (tls32_.suspend_count == 0) {
782     AtomicClearFlag(kSuspendRequest);
783   } else {
784     AtomicSetFlag(kSuspendRequest);
785     TriggerSuspend();
786   }
787 }
788 
RunCheckpointFunction()789 void Thread::RunCheckpointFunction() {
790   Closure *checkpoints[kMaxCheckpoints];
791 
792   // Grab the suspend_count lock and copy the current set of
793   // checkpoints.  Then clear the list and the flag.  The RequestCheckpoint
794   // function will also grab this lock so we prevent a race between setting
795   // the kCheckpointRequest flag and clearing it.
796   {
797     MutexLock mu(this, *Locks::thread_suspend_count_lock_);
798     for (uint32_t i = 0; i < kMaxCheckpoints; ++i) {
799       checkpoints[i] = tlsPtr_.checkpoint_functions[i];
800       tlsPtr_.checkpoint_functions[i] = nullptr;
801     }
802     AtomicClearFlag(kCheckpointRequest);
803   }
804 
805   // Outside the lock, run all the checkpoint functions that
806   // we collected.
807   bool found_checkpoint = false;
808   for (uint32_t i = 0; i < kMaxCheckpoints; ++i) {
809     if (checkpoints[i] != nullptr) {
810       ATRACE_BEGIN("Checkpoint function");
811       checkpoints[i]->Run(this);
812       ATRACE_END();
813       found_checkpoint = true;
814     }
815   }
816   CHECK(found_checkpoint);
817 }
818 
RequestCheckpoint(Closure * function)819 bool Thread::RequestCheckpoint(Closure* function) {
820   union StateAndFlags old_state_and_flags;
821   old_state_and_flags.as_int = tls32_.state_and_flags.as_int;
822   if (old_state_and_flags.as_struct.state != kRunnable) {
823     return false;  // Fail, thread is suspended and so can't run a checkpoint.
824   }
825 
826   uint32_t available_checkpoint = kMaxCheckpoints;
827   for (uint32_t i = 0 ; i < kMaxCheckpoints; ++i) {
828     if (tlsPtr_.checkpoint_functions[i] == nullptr) {
829       available_checkpoint = i;
830       break;
831     }
832   }
833   if (available_checkpoint == kMaxCheckpoints) {
834     // No checkpoint functions available, we can't run a checkpoint
835     return false;
836   }
837   tlsPtr_.checkpoint_functions[available_checkpoint] = function;
838 
839   // Checkpoint function installed now install flag bit.
840   // We must be runnable to request a checkpoint.
841   DCHECK_EQ(old_state_and_flags.as_struct.state, kRunnable);
842   union StateAndFlags new_state_and_flags;
843   new_state_and_flags.as_int = old_state_and_flags.as_int;
844   new_state_and_flags.as_struct.flags |= kCheckpointRequest;
845   bool success = tls32_.state_and_flags.as_atomic_int.CompareExchangeStrongSequentiallyConsistent(
846       old_state_and_flags.as_int, new_state_and_flags.as_int);
847   if (UNLIKELY(!success)) {
848     // The thread changed state before the checkpoint was installed.
849     CHECK_EQ(tlsPtr_.checkpoint_functions[available_checkpoint], function);
850     tlsPtr_.checkpoint_functions[available_checkpoint] = nullptr;
851   } else {
852     CHECK_EQ(ReadFlag(kCheckpointRequest), true);
853     TriggerSuspend();
854   }
855   return success;
856 }
857 
GetFlipFunction()858 Closure* Thread::GetFlipFunction() {
859   Atomic<Closure*>* atomic_func = reinterpret_cast<Atomic<Closure*>*>(&tlsPtr_.flip_function);
860   Closure* func;
861   do {
862     func = atomic_func->LoadRelaxed();
863     if (func == nullptr) {
864       return nullptr;
865     }
866   } while (!atomic_func->CompareExchangeWeakSequentiallyConsistent(func, nullptr));
867   DCHECK(func != nullptr);
868   return func;
869 }
870 
SetFlipFunction(Closure * function)871 void Thread::SetFlipFunction(Closure* function) {
872   CHECK(function != nullptr);
873   Atomic<Closure*>* atomic_func = reinterpret_cast<Atomic<Closure*>*>(&tlsPtr_.flip_function);
874   atomic_func->StoreSequentiallyConsistent(function);
875 }
876 
FullSuspendCheck()877 void Thread::FullSuspendCheck() {
878   VLOG(threads) << this << " self-suspending";
879   ATRACE_BEGIN("Full suspend check");
880   // Make thread appear suspended to other threads, release mutator_lock_.
881   tls32_.suspended_at_suspend_check = true;
882   TransitionFromRunnableToSuspended(kSuspended);
883   // Transition back to runnable noting requests to suspend, re-acquire share on mutator_lock_.
884   TransitionFromSuspendedToRunnable();
885   tls32_.suspended_at_suspend_check = false;
886   ATRACE_END();
887   VLOG(threads) << this << " self-reviving";
888 }
889 
DumpState(std::ostream & os,const Thread * thread,pid_t tid)890 void Thread::DumpState(std::ostream& os, const Thread* thread, pid_t tid) {
891   std::string group_name;
892   int priority;
893   bool is_daemon = false;
894   Thread* self = Thread::Current();
895 
896   // If flip_function is not null, it means we have run a checkpoint
897   // before the thread wakes up to execute the flip function and the
898   // thread roots haven't been forwarded.  So the following access to
899   // the roots (opeer or methods in the frames) would be bad. Run it
900   // here. TODO: clean up.
901   if (thread != nullptr) {
902     ScopedObjectAccessUnchecked soa(self);
903     Thread* this_thread = const_cast<Thread*>(thread);
904     Closure* flip_func = this_thread->GetFlipFunction();
905     if (flip_func != nullptr) {
906       flip_func->Run(this_thread);
907     }
908   }
909 
910   // Don't do this if we are aborting since the GC may have all the threads suspended. This will
911   // cause ScopedObjectAccessUnchecked to deadlock.
912   if (gAborting == 0 && self != nullptr && thread != nullptr && thread->tlsPtr_.opeer != nullptr) {
913     ScopedObjectAccessUnchecked soa(self);
914     priority = soa.DecodeField(WellKnownClasses::java_lang_Thread_priority)
915         ->GetInt(thread->tlsPtr_.opeer);
916     is_daemon = soa.DecodeField(WellKnownClasses::java_lang_Thread_daemon)
917         ->GetBoolean(thread->tlsPtr_.opeer);
918 
919     mirror::Object* thread_group =
920         soa.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(thread->tlsPtr_.opeer);
921 
922     if (thread_group != nullptr) {
923       ArtField* group_name_field =
924           soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_name);
925       mirror::String* group_name_string =
926           reinterpret_cast<mirror::String*>(group_name_field->GetObject(thread_group));
927       group_name = (group_name_string != nullptr) ? group_name_string->ToModifiedUtf8() : "<null>";
928     }
929   } else {
930     priority = GetNativePriority();
931   }
932 
933   std::string scheduler_group_name(GetSchedulerGroupName(tid));
934   if (scheduler_group_name.empty()) {
935     scheduler_group_name = "default";
936   }
937 
938   if (thread != nullptr) {
939     os << '"' << *thread->tlsPtr_.name << '"';
940     if (is_daemon) {
941       os << " daemon";
942     }
943     os << " prio=" << priority
944        << " tid=" << thread->GetThreadId()
945        << " " << thread->GetState();
946     if (thread->IsStillStarting()) {
947       os << " (still starting up)";
948     }
949     os << "\n";
950   } else {
951     os << '"' << ::art::GetThreadName(tid) << '"'
952        << " prio=" << priority
953        << " (not attached)\n";
954   }
955 
956   if (thread != nullptr) {
957     MutexLock mu(self, *Locks::thread_suspend_count_lock_);
958     os << "  | group=\"" << group_name << "\""
959        << " sCount=" << thread->tls32_.suspend_count
960        << " dsCount=" << thread->tls32_.debug_suspend_count
961        << " obj=" << reinterpret_cast<void*>(thread->tlsPtr_.opeer)
962        << " self=" << reinterpret_cast<const void*>(thread) << "\n";
963   }
964 
965   os << "  | sysTid=" << tid
966      << " nice=" << getpriority(PRIO_PROCESS, tid)
967      << " cgrp=" << scheduler_group_name;
968   if (thread != nullptr) {
969     int policy;
970     sched_param sp;
971     CHECK_PTHREAD_CALL(pthread_getschedparam, (thread->tlsPtr_.pthread_self, &policy, &sp),
972                        __FUNCTION__);
973     os << " sched=" << policy << "/" << sp.sched_priority
974        << " handle=" << reinterpret_cast<void*>(thread->tlsPtr_.pthread_self);
975   }
976   os << "\n";
977 
978   // Grab the scheduler stats for this thread.
979   std::string scheduler_stats;
980   if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", tid), &scheduler_stats)) {
981     scheduler_stats.resize(scheduler_stats.size() - 1);  // Lose the trailing '\n'.
982   } else {
983     scheduler_stats = "0 0 0";
984   }
985 
986   char native_thread_state = '?';
987   int utime = 0;
988   int stime = 0;
989   int task_cpu = 0;
990   GetTaskStats(tid, &native_thread_state, &utime, &stime, &task_cpu);
991 
992   os << "  | state=" << native_thread_state
993      << " schedstat=( " << scheduler_stats << " )"
994      << " utm=" << utime
995      << " stm=" << stime
996      << " core=" << task_cpu
997      << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
998   if (thread != nullptr) {
999     os << "  | stack=" << reinterpret_cast<void*>(thread->tlsPtr_.stack_begin) << "-"
1000         << reinterpret_cast<void*>(thread->tlsPtr_.stack_end) << " stackSize="
1001         << PrettySize(thread->tlsPtr_.stack_size) << "\n";
1002     // Dump the held mutexes.
1003     os << "  | held mutexes=";
1004     for (size_t i = 0; i < kLockLevelCount; ++i) {
1005       if (i != kMonitorLock) {
1006         BaseMutex* mutex = thread->GetHeldMutex(static_cast<LockLevel>(i));
1007         if (mutex != nullptr) {
1008           os << " \"" << mutex->GetName() << "\"";
1009           if (mutex->IsReaderWriterMutex()) {
1010             ReaderWriterMutex* rw_mutex = down_cast<ReaderWriterMutex*>(mutex);
1011             if (rw_mutex->GetExclusiveOwnerTid() == static_cast<uint64_t>(tid)) {
1012               os << "(exclusive held)";
1013             } else {
1014               os << "(shared held)";
1015             }
1016           }
1017         }
1018       }
1019     }
1020     os << "\n";
1021   }
1022 }
1023 
DumpState(std::ostream & os) const1024 void Thread::DumpState(std::ostream& os) const {
1025   Thread::DumpState(os, this, GetTid());
1026 }
1027 
1028 struct StackDumpVisitor : public StackVisitor {
StackDumpVisitorart::StackDumpVisitor1029   StackDumpVisitor(std::ostream& os_in, Thread* thread_in, Context* context, bool can_allocate_in)
1030       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1031       : StackVisitor(thread_in, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
1032         os(os_in),
1033         thread(thread_in),
1034         can_allocate(can_allocate_in),
1035         last_method(nullptr),
1036         last_line_number(0),
1037         repetition_count(0),
1038         frame_count(0) {}
1039 
~StackDumpVisitorart::StackDumpVisitor1040   virtual ~StackDumpVisitor() {
1041     if (frame_count == 0) {
1042       os << "  (no managed stack frames)\n";
1043     }
1044   }
1045 
VisitFrameart::StackDumpVisitor1046   bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1047     ArtMethod* m = GetMethod();
1048     if (m->IsRuntimeMethod()) {
1049       return true;
1050     }
1051     m = m->GetInterfaceMethodIfProxy(sizeof(void*));
1052     const int kMaxRepetition = 3;
1053     mirror::Class* c = m->GetDeclaringClass();
1054     mirror::DexCache* dex_cache = c->GetDexCache();
1055     int line_number = -1;
1056     if (dex_cache != nullptr) {  // be tolerant of bad input
1057       const DexFile& dex_file = *dex_cache->GetDexFile();
1058       line_number = dex_file.GetLineNumFromPC(m, GetDexPc(false));
1059     }
1060     if (line_number == last_line_number && last_method == m) {
1061       ++repetition_count;
1062     } else {
1063       if (repetition_count >= kMaxRepetition) {
1064         os << "  ... repeated " << (repetition_count - kMaxRepetition) << " times\n";
1065       }
1066       repetition_count = 0;
1067       last_line_number = line_number;
1068       last_method = m;
1069     }
1070     if (repetition_count < kMaxRepetition) {
1071       os << "  at " << PrettyMethod(m, false);
1072       if (m->IsNative()) {
1073         os << "(Native method)";
1074       } else {
1075         const char* source_file(m->GetDeclaringClassSourceFile());
1076         os << "(" << (source_file != nullptr ? source_file : "unavailable")
1077            << ":" << line_number << ")";
1078       }
1079       os << "\n";
1080       if (frame_count == 0) {
1081         Monitor::DescribeWait(os, thread);
1082       }
1083       if (can_allocate) {
1084         // Visit locks, but do not abort on errors. This would trigger a nested abort.
1085         Monitor::VisitLocks(this, DumpLockedObject, &os, false);
1086       }
1087     }
1088 
1089     ++frame_count;
1090     return true;
1091   }
1092 
DumpLockedObjectart::StackDumpVisitor1093   static void DumpLockedObject(mirror::Object* o, void* context)
1094       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1095     std::ostream& os = *reinterpret_cast<std::ostream*>(context);
1096     os << "  - locked ";
1097     if (o == nullptr) {
1098       os << "an unknown object";
1099     } else {
1100       if ((o->GetLockWord(false).GetState() == LockWord::kThinLocked) &&
1101           Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
1102         // Getting the identity hashcode here would result in lock inflation and suspension of the
1103         // current thread, which isn't safe if this is the only runnable thread.
1104         os << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)", reinterpret_cast<intptr_t>(o),
1105                            PrettyTypeOf(o).c_str());
1106       } else {
1107         // IdentityHashCode can cause thread suspension, which would invalidate o if it moved. So
1108         // we get the pretty type beofre we call IdentityHashCode.
1109         const std::string pretty_type(PrettyTypeOf(o));
1110         os << StringPrintf("<0x%08x> (a %s)", o->IdentityHashCode(), pretty_type.c_str());
1111       }
1112     }
1113     os << "\n";
1114   }
1115 
1116   std::ostream& os;
1117   const Thread* thread;
1118   const bool can_allocate;
1119   ArtMethod* last_method;
1120   int last_line_number;
1121   int repetition_count;
1122   int frame_count;
1123 };
1124 
ShouldShowNativeStack(const Thread * thread)1125 static bool ShouldShowNativeStack(const Thread* thread)
1126     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1127   ThreadState state = thread->GetState();
1128 
1129   // In native code somewhere in the VM (one of the kWaitingFor* states)? That's interesting.
1130   if (state > kWaiting && state < kStarting) {
1131     return true;
1132   }
1133 
1134   // In an Object.wait variant or Thread.sleep? That's not interesting.
1135   if (state == kTimedWaiting || state == kSleeping || state == kWaiting) {
1136     return false;
1137   }
1138 
1139   // Threads with no managed stack frames should be shown.
1140   const ManagedStack* managed_stack = thread->GetManagedStack();
1141   if (managed_stack == nullptr || (managed_stack->GetTopQuickFrame() == nullptr &&
1142       managed_stack->GetTopShadowFrame() == nullptr)) {
1143     return true;
1144   }
1145 
1146   // In some other native method? That's interesting.
1147   // We don't just check kNative because native methods will be in state kSuspended if they're
1148   // calling back into the VM, or kBlocked if they're blocked on a monitor, or one of the
1149   // thread-startup states if it's early enough in their life cycle (http://b/7432159).
1150   ArtMethod* current_method = thread->GetCurrentMethod(nullptr);
1151   return current_method != nullptr && current_method->IsNative();
1152 }
1153 
DumpJavaStack(std::ostream & os) const1154 void Thread::DumpJavaStack(std::ostream& os) const {
1155   // If flip_function is not null, it means we have run a checkpoint
1156   // before the thread wakes up to execute the flip function and the
1157   // thread roots haven't been forwarded.  So the following access to
1158   // the roots (locks or methods in the frames) would be bad. Run it
1159   // here. TODO: clean up.
1160   {
1161     Thread* this_thread = const_cast<Thread*>(this);
1162     Closure* flip_func = this_thread->GetFlipFunction();
1163     if (flip_func != nullptr) {
1164       flip_func->Run(this_thread);
1165     }
1166   }
1167 
1168   // Dumping the Java stack involves the verifier for locks. The verifier operates under the
1169   // assumption that there is no exception pending on entry. Thus, stash any pending exception.
1170   // Thread::Current() instead of this in case a thread is dumping the stack of another suspended
1171   // thread.
1172   StackHandleScope<1> scope(Thread::Current());
1173   Handle<mirror::Throwable> exc;
1174   bool have_exception = false;
1175   if (IsExceptionPending()) {
1176     exc = scope.NewHandle(GetException());
1177     const_cast<Thread*>(this)->ClearException();
1178     have_exception = true;
1179   }
1180 
1181   std::unique_ptr<Context> context(Context::Create());
1182   StackDumpVisitor dumper(os, const_cast<Thread*>(this), context.get(),
1183                           !tls32_.throwing_OutOfMemoryError);
1184   dumper.WalkStack();
1185 
1186   if (have_exception) {
1187     const_cast<Thread*>(this)->SetException(exc.Get());
1188   }
1189 }
1190 
DumpStack(std::ostream & os) const1191 void Thread::DumpStack(std::ostream& os) const {
1192   // TODO: we call this code when dying but may not have suspended the thread ourself. The
1193   //       IsSuspended check is therefore racy with the use for dumping (normally we inhibit
1194   //       the race with the thread_suspend_count_lock_).
1195   bool dump_for_abort = (gAborting > 0);
1196   bool safe_to_dump = (this == Thread::Current() || IsSuspended());
1197   if (!kIsDebugBuild) {
1198     // We always want to dump the stack for an abort, however, there is no point dumping another
1199     // thread's stack in debug builds where we'll hit the not suspended check in the stack walk.
1200     safe_to_dump = (safe_to_dump || dump_for_abort);
1201   }
1202   if (safe_to_dump) {
1203     // If we're currently in native code, dump that stack before dumping the managed stack.
1204     if (dump_for_abort || ShouldShowNativeStack(this)) {
1205       DumpKernelStack(os, GetTid(), "  kernel: ", false);
1206       DumpNativeStack(os, GetTid(), "  native: ", GetCurrentMethod(nullptr, !dump_for_abort));
1207     }
1208     DumpJavaStack(os);
1209   } else {
1210     os << "Not able to dump stack of thread that isn't suspended";
1211   }
1212 }
1213 
ThreadExitCallback(void * arg)1214 void Thread::ThreadExitCallback(void* arg) {
1215   Thread* self = reinterpret_cast<Thread*>(arg);
1216   if (self->tls32_.thread_exit_check_count == 0) {
1217     LOG(WARNING) << "Native thread exiting without having called DetachCurrentThread (maybe it's "
1218         "going to use a pthread_key_create destructor?): " << *self;
1219     CHECK(is_started_);
1220     CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, self), "reattach self");
1221     self->tls32_.thread_exit_check_count = 1;
1222   } else {
1223     LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
1224   }
1225 }
1226 
Startup()1227 void Thread::Startup() {
1228   CHECK(!is_started_);
1229   is_started_ = true;
1230   {
1231     // MutexLock to keep annotalysis happy.
1232     //
1233     // Note we use null for the thread because Thread::Current can
1234     // return garbage since (is_started_ == true) and
1235     // Thread::pthread_key_self_ is not yet initialized.
1236     // This was seen on glibc.
1237     MutexLock mu(nullptr, *Locks::thread_suspend_count_lock_);
1238     resume_cond_ = new ConditionVariable("Thread resumption condition variable",
1239                                          *Locks::thread_suspend_count_lock_);
1240   }
1241 
1242   // Allocate a TLS slot.
1243   CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback),
1244                      "self key");
1245 
1246   // Double-check the TLS slot allocation.
1247   if (pthread_getspecific(pthread_key_self_) != nullptr) {
1248     LOG(FATAL) << "Newly-created pthread TLS slot is not nullptr";
1249   }
1250 }
1251 
FinishStartup()1252 void Thread::FinishStartup() {
1253   Runtime* runtime = Runtime::Current();
1254   CHECK(runtime->IsStarted());
1255 
1256   // Finish attaching the main thread.
1257   ScopedObjectAccess soa(Thread::Current());
1258   Thread::Current()->CreatePeer("main", false, runtime->GetMainThreadGroup());
1259 
1260   Runtime::Current()->GetClassLinker()->RunRootClinits();
1261 }
1262 
Shutdown()1263 void Thread::Shutdown() {
1264   CHECK(is_started_);
1265   is_started_ = false;
1266   CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
1267   MutexLock mu(Thread::Current(), *Locks::thread_suspend_count_lock_);
1268   if (resume_cond_ != nullptr) {
1269     delete resume_cond_;
1270     resume_cond_ = nullptr;
1271   }
1272 }
1273 
Thread(bool daemon)1274 Thread::Thread(bool daemon) : tls32_(daemon), wait_monitor_(nullptr), interrupted_(false) {
1275   wait_mutex_ = new Mutex("a thread wait mutex");
1276   wait_cond_ = new ConditionVariable("a thread wait condition variable", *wait_mutex_);
1277   tlsPtr_.instrumentation_stack = new std::deque<instrumentation::InstrumentationStackFrame>;
1278   tlsPtr_.name = new std::string(kThreadNameDuringStartup);
1279   tlsPtr_.nested_signal_state = static_cast<jmp_buf*>(malloc(sizeof(jmp_buf)));
1280 
1281   CHECK_EQ((sizeof(Thread) % 4), 0U) << sizeof(Thread);
1282   tls32_.state_and_flags.as_struct.flags = 0;
1283   tls32_.state_and_flags.as_struct.state = kNative;
1284   memset(&tlsPtr_.held_mutexes[0], 0, sizeof(tlsPtr_.held_mutexes));
1285   std::fill(tlsPtr_.rosalloc_runs,
1286             tlsPtr_.rosalloc_runs + kNumRosAllocThreadLocalSizeBrackets,
1287             gc::allocator::RosAlloc::GetDedicatedFullRun());
1288   for (uint32_t i = 0; i < kMaxCheckpoints; ++i) {
1289     tlsPtr_.checkpoint_functions[i] = nullptr;
1290   }
1291   tlsPtr_.flip_function = nullptr;
1292   tls32_.suspended_at_suspend_check = false;
1293 }
1294 
IsStillStarting() const1295 bool Thread::IsStillStarting() const {
1296   // You might think you can check whether the state is kStarting, but for much of thread startup,
1297   // the thread is in kNative; it might also be in kVmWait.
1298   // You might think you can check whether the peer is null, but the peer is actually created and
1299   // assigned fairly early on, and needs to be.
1300   // It turns out that the last thing to change is the thread name; that's a good proxy for "has
1301   // this thread _ever_ entered kRunnable".
1302   return (tlsPtr_.jpeer == nullptr && tlsPtr_.opeer == nullptr) ||
1303       (*tlsPtr_.name == kThreadNameDuringStartup);
1304 }
1305 
AssertPendingException() const1306 void Thread::AssertPendingException() const {
1307   CHECK(IsExceptionPending()) << "Pending exception expected.";
1308 }
1309 
AssertPendingOOMException() const1310 void Thread::AssertPendingOOMException() const {
1311   AssertPendingException();
1312   auto* e = GetException();
1313   CHECK_EQ(e->GetClass(), DecodeJObject(WellKnownClasses::java_lang_OutOfMemoryError)->AsClass())
1314       << e->Dump();
1315 }
1316 
AssertNoPendingException() const1317 void Thread::AssertNoPendingException() const {
1318   if (UNLIKELY(IsExceptionPending())) {
1319     ScopedObjectAccess soa(Thread::Current());
1320     mirror::Throwable* exception = GetException();
1321     LOG(FATAL) << "No pending exception expected: " << exception->Dump();
1322   }
1323 }
1324 
AssertNoPendingExceptionForNewException(const char * msg) const1325 void Thread::AssertNoPendingExceptionForNewException(const char* msg) const {
1326   if (UNLIKELY(IsExceptionPending())) {
1327     ScopedObjectAccess soa(Thread::Current());
1328     mirror::Throwable* exception = GetException();
1329     LOG(FATAL) << "Throwing new exception '" << msg << "' with unexpected pending exception: "
1330         << exception->Dump();
1331   }
1332 }
1333 
1334 class MonitorExitVisitor : public SingleRootVisitor {
1335  public:
MonitorExitVisitor(Thread * self)1336   explicit MonitorExitVisitor(Thread* self) : self_(self) { }
1337 
1338   // NO_THREAD_SAFETY_ANALYSIS due to MonitorExit.
VisitRoot(mirror::Object * entered_monitor,const RootInfo & info ATTRIBUTE_UNUSED)1339   void VisitRoot(mirror::Object* entered_monitor, const RootInfo& info ATTRIBUTE_UNUSED)
1340       OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
1341     if (self_->HoldsLock(entered_monitor)) {
1342       LOG(WARNING) << "Calling MonitorExit on object "
1343                    << entered_monitor << " (" << PrettyTypeOf(entered_monitor) << ")"
1344                    << " left locked by native thread "
1345                    << *Thread::Current() << " which is detaching";
1346       entered_monitor->MonitorExit(self_);
1347     }
1348   }
1349 
1350  private:
1351   Thread* const self_;
1352 };
1353 
Destroy()1354 void Thread::Destroy() {
1355   Thread* self = this;
1356   DCHECK_EQ(self, Thread::Current());
1357 
1358   if (tlsPtr_.jni_env != nullptr) {
1359     {
1360       ScopedObjectAccess soa(self);
1361       MonitorExitVisitor visitor(self);
1362       // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
1363       tlsPtr_.jni_env->monitors.VisitRoots(&visitor, RootInfo(kRootVMInternal));
1364     }
1365     // Release locally held global references which releasing may require the mutator lock.
1366     if (tlsPtr_.jpeer != nullptr) {
1367       // If pthread_create fails we don't have a jni env here.
1368       tlsPtr_.jni_env->DeleteGlobalRef(tlsPtr_.jpeer);
1369       tlsPtr_.jpeer = nullptr;
1370     }
1371     if (tlsPtr_.class_loader_override != nullptr) {
1372       tlsPtr_.jni_env->DeleteGlobalRef(tlsPtr_.class_loader_override);
1373       tlsPtr_.class_loader_override = nullptr;
1374     }
1375   }
1376 
1377   if (tlsPtr_.opeer != nullptr) {
1378     ScopedObjectAccess soa(self);
1379     // We may need to call user-supplied managed code, do this before final clean-up.
1380     HandleUncaughtExceptions(soa);
1381     RemoveFromThreadGroup(soa);
1382 
1383     // this.nativePeer = 0;
1384     if (Runtime::Current()->IsActiveTransaction()) {
1385       soa.DecodeField(WellKnownClasses::java_lang_Thread_nativePeer)
1386           ->SetLong<true>(tlsPtr_.opeer, 0);
1387     } else {
1388       soa.DecodeField(WellKnownClasses::java_lang_Thread_nativePeer)
1389           ->SetLong<false>(tlsPtr_.opeer, 0);
1390     }
1391     Dbg::PostThreadDeath(self);
1392 
1393     // Thread.join() is implemented as an Object.wait() on the Thread.lock object. Signal anyone
1394     // who is waiting.
1395     mirror::Object* lock =
1396         soa.DecodeField(WellKnownClasses::java_lang_Thread_lock)->GetObject(tlsPtr_.opeer);
1397     // (This conditional is only needed for tests, where Thread.lock won't have been set.)
1398     if (lock != nullptr) {
1399       StackHandleScope<1> hs(self);
1400       Handle<mirror::Object> h_obj(hs.NewHandle(lock));
1401       ObjectLock<mirror::Object> locker(self, h_obj);
1402       locker.NotifyAll();
1403     }
1404     tlsPtr_.opeer = nullptr;
1405   }
1406 
1407   {
1408     ScopedObjectAccess soa(self);
1409     Runtime::Current()->GetHeap()->RevokeThreadLocalBuffers(this);
1410   }
1411 }
1412 
~Thread()1413 Thread::~Thread() {
1414   CHECK(tlsPtr_.class_loader_override == nullptr);
1415   CHECK(tlsPtr_.jpeer == nullptr);
1416   CHECK(tlsPtr_.opeer == nullptr);
1417   bool initialized = (tlsPtr_.jni_env != nullptr);  // Did Thread::Init run?
1418   if (initialized) {
1419     delete tlsPtr_.jni_env;
1420     tlsPtr_.jni_env = nullptr;
1421   }
1422   CHECK_NE(GetState(), kRunnable);
1423   CHECK_NE(ReadFlag(kCheckpointRequest), true);
1424   CHECK(tlsPtr_.checkpoint_functions[0] == nullptr);
1425   CHECK(tlsPtr_.checkpoint_functions[1] == nullptr);
1426   CHECK(tlsPtr_.checkpoint_functions[2] == nullptr);
1427   CHECK(tlsPtr_.flip_function == nullptr);
1428   CHECK_EQ(tls32_.suspended_at_suspend_check, false);
1429 
1430   // We may be deleting a still born thread.
1431   SetStateUnsafe(kTerminated);
1432 
1433   delete wait_cond_;
1434   delete wait_mutex_;
1435 
1436   if (tlsPtr_.long_jump_context != nullptr) {
1437     delete tlsPtr_.long_jump_context;
1438   }
1439 
1440   if (initialized) {
1441     CleanupCpu();
1442   }
1443 
1444   if (tlsPtr_.single_step_control != nullptr) {
1445     delete tlsPtr_.single_step_control;
1446   }
1447   delete tlsPtr_.instrumentation_stack;
1448   delete tlsPtr_.name;
1449   delete tlsPtr_.stack_trace_sample;
1450   free(tlsPtr_.nested_signal_state);
1451 
1452   Runtime::Current()->GetHeap()->AssertThreadLocalBuffersAreRevoked(this);
1453 
1454   TearDownAlternateSignalStack();
1455 }
1456 
HandleUncaughtExceptions(ScopedObjectAccess & soa)1457 void Thread::HandleUncaughtExceptions(ScopedObjectAccess& soa) {
1458   if (!IsExceptionPending()) {
1459     return;
1460   }
1461   ScopedLocalRef<jobject> peer(tlsPtr_.jni_env, soa.AddLocalReference<jobject>(tlsPtr_.opeer));
1462   ScopedThreadStateChange tsc(this, kNative);
1463 
1464   // Get and clear the exception.
1465   ScopedLocalRef<jthrowable> exception(tlsPtr_.jni_env, tlsPtr_.jni_env->ExceptionOccurred());
1466   tlsPtr_.jni_env->ExceptionClear();
1467 
1468   // If the thread has its own handler, use that.
1469   ScopedLocalRef<jobject> handler(tlsPtr_.jni_env,
1470                                   tlsPtr_.jni_env->GetObjectField(peer.get(),
1471                                       WellKnownClasses::java_lang_Thread_uncaughtHandler));
1472   if (handler.get() == nullptr) {
1473     // Otherwise use the thread group's default handler.
1474     handler.reset(tlsPtr_.jni_env->GetObjectField(peer.get(),
1475                                                   WellKnownClasses::java_lang_Thread_group));
1476   }
1477 
1478   // Call the handler.
1479   tlsPtr_.jni_env->CallVoidMethod(handler.get(),
1480       WellKnownClasses::java_lang_Thread__UncaughtExceptionHandler_uncaughtException,
1481       peer.get(), exception.get());
1482 
1483   // If the handler threw, clear that exception too.
1484   tlsPtr_.jni_env->ExceptionClear();
1485 }
1486 
RemoveFromThreadGroup(ScopedObjectAccess & soa)1487 void Thread::RemoveFromThreadGroup(ScopedObjectAccess& soa) {
1488   // this.group.removeThread(this);
1489   // group can be null if we're in the compiler or a test.
1490   mirror::Object* ogroup = soa.DecodeField(WellKnownClasses::java_lang_Thread_group)
1491       ->GetObject(tlsPtr_.opeer);
1492   if (ogroup != nullptr) {
1493     ScopedLocalRef<jobject> group(soa.Env(), soa.AddLocalReference<jobject>(ogroup));
1494     ScopedLocalRef<jobject> peer(soa.Env(), soa.AddLocalReference<jobject>(tlsPtr_.opeer));
1495     ScopedThreadStateChange tsc(soa.Self(), kNative);
1496     tlsPtr_.jni_env->CallVoidMethod(group.get(),
1497                                     WellKnownClasses::java_lang_ThreadGroup_removeThread,
1498                                     peer.get());
1499   }
1500 }
1501 
NumHandleReferences()1502 size_t Thread::NumHandleReferences() {
1503   size_t count = 0;
1504   for (HandleScope* cur = tlsPtr_.top_handle_scope; cur != nullptr; cur = cur->GetLink()) {
1505     count += cur->NumberOfReferences();
1506   }
1507   return count;
1508 }
1509 
HandleScopeContains(jobject obj) const1510 bool Thread::HandleScopeContains(jobject obj) const {
1511   StackReference<mirror::Object>* hs_entry =
1512       reinterpret_cast<StackReference<mirror::Object>*>(obj);
1513   for (HandleScope* cur = tlsPtr_.top_handle_scope; cur!= nullptr; cur = cur->GetLink()) {
1514     if (cur->Contains(hs_entry)) {
1515       return true;
1516     }
1517   }
1518   // JNI code invoked from portable code uses shadow frames rather than the handle scope.
1519   return tlsPtr_.managed_stack.ShadowFramesContain(hs_entry);
1520 }
1521 
HandleScopeVisitRoots(RootVisitor * visitor,uint32_t thread_id)1522 void Thread::HandleScopeVisitRoots(RootVisitor* visitor, uint32_t thread_id) {
1523   BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(
1524       visitor, RootInfo(kRootNativeStack, thread_id));
1525   for (HandleScope* cur = tlsPtr_.top_handle_scope; cur; cur = cur->GetLink()) {
1526     for (size_t j = 0, count = cur->NumberOfReferences(); j < count; ++j) {
1527       // GetReference returns a pointer to the stack reference within the handle scope. If this
1528       // needs to be updated, it will be done by the root visitor.
1529       buffered_visitor.VisitRootIfNonNull(cur->GetHandle(j).GetReference());
1530     }
1531   }
1532 }
1533 
DecodeJObject(jobject obj) const1534 mirror::Object* Thread::DecodeJObject(jobject obj) const {
1535   if (obj == nullptr) {
1536     return nullptr;
1537   }
1538   IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
1539   IndirectRefKind kind = GetIndirectRefKind(ref);
1540   mirror::Object* result;
1541   bool expect_null = false;
1542   // The "kinds" below are sorted by the frequency we expect to encounter them.
1543   if (kind == kLocal) {
1544     IndirectReferenceTable& locals = tlsPtr_.jni_env->locals;
1545     // Local references do not need a read barrier.
1546     result = locals.Get<kWithoutReadBarrier>(ref);
1547   } else if (kind == kHandleScopeOrInvalid) {
1548     // TODO: make stack indirect reference table lookup more efficient.
1549     // Check if this is a local reference in the handle scope.
1550     if (LIKELY(HandleScopeContains(obj))) {
1551       // Read from handle scope.
1552       result = reinterpret_cast<StackReference<mirror::Object>*>(obj)->AsMirrorPtr();
1553       VerifyObject(result);
1554     } else {
1555       tlsPtr_.jni_env->vm->JniAbortF(nullptr, "use of invalid jobject %p", obj);
1556       expect_null = true;
1557       result = nullptr;
1558     }
1559   } else if (kind == kGlobal) {
1560     result = tlsPtr_.jni_env->vm->DecodeGlobal(const_cast<Thread*>(this), ref);
1561   } else {
1562     DCHECK_EQ(kind, kWeakGlobal);
1563     result = tlsPtr_.jni_env->vm->DecodeWeakGlobal(const_cast<Thread*>(this), ref);
1564     if (Runtime::Current()->IsClearedJniWeakGlobal(result)) {
1565       // This is a special case where it's okay to return null.
1566       expect_null = true;
1567       result = nullptr;
1568     }
1569   }
1570 
1571   if (UNLIKELY(!expect_null && result == nullptr)) {
1572     tlsPtr_.jni_env->vm->JniAbortF(nullptr, "use of deleted %s %p",
1573                                    ToStr<IndirectRefKind>(kind).c_str(), obj);
1574   }
1575   return result;
1576 }
1577 
1578 // Implements java.lang.Thread.interrupted.
Interrupted()1579 bool Thread::Interrupted() {
1580   MutexLock mu(Thread::Current(), *wait_mutex_);
1581   bool interrupted = IsInterruptedLocked();
1582   SetInterruptedLocked(false);
1583   return interrupted;
1584 }
1585 
1586 // Implements java.lang.Thread.isInterrupted.
IsInterrupted()1587 bool Thread::IsInterrupted() {
1588   MutexLock mu(Thread::Current(), *wait_mutex_);
1589   return IsInterruptedLocked();
1590 }
1591 
Interrupt(Thread * self)1592 void Thread::Interrupt(Thread* self) {
1593   MutexLock mu(self, *wait_mutex_);
1594   if (interrupted_) {
1595     return;
1596   }
1597   interrupted_ = true;
1598   NotifyLocked(self);
1599 }
1600 
Notify()1601 void Thread::Notify() {
1602   Thread* self = Thread::Current();
1603   MutexLock mu(self, *wait_mutex_);
1604   NotifyLocked(self);
1605 }
1606 
NotifyLocked(Thread * self)1607 void Thread::NotifyLocked(Thread* self) {
1608   if (wait_monitor_ != nullptr) {
1609     wait_cond_->Signal(self);
1610   }
1611 }
1612 
SetClassLoaderOverride(jobject class_loader_override)1613 void Thread::SetClassLoaderOverride(jobject class_loader_override) {
1614   if (tlsPtr_.class_loader_override != nullptr) {
1615     GetJniEnv()->DeleteGlobalRef(tlsPtr_.class_loader_override);
1616   }
1617   tlsPtr_.class_loader_override = GetJniEnv()->NewGlobalRef(class_loader_override);
1618 }
1619 
1620 class CountStackDepthVisitor : public StackVisitor {
1621  public:
1622   explicit CountStackDepthVisitor(Thread* thread)
SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)1623       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1624       : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
1625         depth_(0), skip_depth_(0), skipping_(true) {}
1626 
VisitFrame()1627   bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1628     // We want to skip frames up to and including the exception's constructor.
1629     // Note we also skip the frame if it doesn't have a method (namely the callee
1630     // save frame)
1631     ArtMethod* m = GetMethod();
1632     if (skipping_ && !m->IsRuntimeMethod() &&
1633         !mirror::Throwable::GetJavaLangThrowable()->IsAssignableFrom(m->GetDeclaringClass())) {
1634       skipping_ = false;
1635     }
1636     if (!skipping_) {
1637       if (!m->IsRuntimeMethod()) {  // Ignore runtime frames (in particular callee save).
1638         ++depth_;
1639       }
1640     } else {
1641       ++skip_depth_;
1642     }
1643     return true;
1644   }
1645 
GetDepth() const1646   int GetDepth() const {
1647     return depth_;
1648   }
1649 
GetSkipDepth() const1650   int GetSkipDepth() const {
1651     return skip_depth_;
1652   }
1653 
1654  private:
1655   uint32_t depth_;
1656   uint32_t skip_depth_;
1657   bool skipping_;
1658 };
1659 
1660 template<bool kTransactionActive>
1661 class BuildInternalStackTraceVisitor : public StackVisitor {
1662  public:
BuildInternalStackTraceVisitor(Thread * self,Thread * thread,int skip_depth)1663   explicit BuildInternalStackTraceVisitor(Thread* self, Thread* thread, int skip_depth)
1664       : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
1665         self_(self),
1666         skip_depth_(skip_depth),
1667         count_(0),
1668         trace_(nullptr),
1669         pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()) {}
1670 
Init(int depth)1671   bool Init(int depth)
1672       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1673     // Allocate method trace with format [method pointers][pcs].
1674     auto* cl = Runtime::Current()->GetClassLinker();
1675     trace_ = cl->AllocPointerArray(self_, depth * 2);
1676     if (trace_ == nullptr) {
1677       self_->AssertPendingOOMException();
1678       return false;
1679     }
1680     // If We are called from native, use non-transactional mode.
1681     const char* last_no_suspend_cause =
1682         self_->StartAssertNoThreadSuspension("Building internal stack trace");
1683     CHECK(last_no_suspend_cause == nullptr) << last_no_suspend_cause;
1684     return true;
1685   }
1686 
~BuildInternalStackTraceVisitor()1687   virtual ~BuildInternalStackTraceVisitor() {
1688     if (trace_ != nullptr) {
1689       self_->EndAssertNoThreadSuspension(nullptr);
1690     }
1691   }
1692 
VisitFrame()1693   bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1694     if (trace_ == nullptr) {
1695       return true;  // We're probably trying to fillInStackTrace for an OutOfMemoryError.
1696     }
1697     if (skip_depth_ > 0) {
1698       skip_depth_--;
1699       return true;
1700     }
1701     ArtMethod* m = GetMethod();
1702     if (m->IsRuntimeMethod()) {
1703       return true;  // Ignore runtime frames (in particular callee save).
1704     }
1705     trace_->SetElementPtrSize<kTransactionActive>(
1706         count_, m, pointer_size_);
1707     trace_->SetElementPtrSize<kTransactionActive>(
1708         trace_->GetLength() / 2 + count_, m->IsProxyMethod() ? DexFile::kDexNoIndex : GetDexPc(),
1709             pointer_size_);
1710     ++count_;
1711     return true;
1712   }
1713 
GetInternalStackTrace() const1714   mirror::PointerArray* GetInternalStackTrace() const {
1715     return trace_;
1716   }
1717 
1718  private:
1719   Thread* const self_;
1720   // How many more frames to skip.
1721   int32_t skip_depth_;
1722   // Current position down stack trace.
1723   uint32_t count_;
1724   // An array of the methods on the stack, the last entries are the dex PCs.
1725   mirror::PointerArray* trace_;
1726   // For cross compilation.
1727   size_t pointer_size_;
1728 };
1729 
1730 template<bool kTransactionActive>
CreateInternalStackTrace(const ScopedObjectAccessAlreadyRunnable & soa) const1731 jobject Thread::CreateInternalStackTrace(const ScopedObjectAccessAlreadyRunnable& soa) const {
1732   // Compute depth of stack
1733   CountStackDepthVisitor count_visitor(const_cast<Thread*>(this));
1734   count_visitor.WalkStack();
1735   int32_t depth = count_visitor.GetDepth();
1736   int32_t skip_depth = count_visitor.GetSkipDepth();
1737 
1738   // Build internal stack trace.
1739   BuildInternalStackTraceVisitor<kTransactionActive> build_trace_visitor(soa.Self(),
1740                                                                          const_cast<Thread*>(this),
1741                                                                          skip_depth);
1742   if (!build_trace_visitor.Init(depth)) {
1743     return nullptr;  // Allocation failed.
1744   }
1745   build_trace_visitor.WalkStack();
1746   mirror::PointerArray* trace = build_trace_visitor.GetInternalStackTrace();
1747   if (kIsDebugBuild) {
1748     // Second half is dex PCs.
1749     for (uint32_t i = 0; i < static_cast<uint32_t>(trace->GetLength() / 2); ++i) {
1750       auto* method = trace->GetElementPtrSize<ArtMethod*>(
1751           i, Runtime::Current()->GetClassLinker()->GetImagePointerSize());
1752       CHECK(method != nullptr);
1753     }
1754   }
1755   return soa.AddLocalReference<jobject>(trace);
1756 }
1757 template jobject Thread::CreateInternalStackTrace<false>(
1758     const ScopedObjectAccessAlreadyRunnable& soa) const;
1759 template jobject Thread::CreateInternalStackTrace<true>(
1760     const ScopedObjectAccessAlreadyRunnable& soa) const;
1761 
IsExceptionThrownByCurrentMethod(mirror::Throwable * exception) const1762 bool Thread::IsExceptionThrownByCurrentMethod(mirror::Throwable* exception) const {
1763   CountStackDepthVisitor count_visitor(const_cast<Thread*>(this));
1764   count_visitor.WalkStack();
1765   return count_visitor.GetDepth() == exception->GetStackDepth();
1766 }
1767 
InternalStackTraceToStackTraceElementArray(const ScopedObjectAccessAlreadyRunnable & soa,jobject internal,jobjectArray output_array,int * stack_depth)1768 jobjectArray Thread::InternalStackTraceToStackTraceElementArray(
1769     const ScopedObjectAccessAlreadyRunnable& soa, jobject internal, jobjectArray output_array,
1770     int* stack_depth) {
1771   // Decode the internal stack trace into the depth, method trace and PC trace
1772   int32_t depth = soa.Decode<mirror::PointerArray*>(internal)->GetLength() / 2;
1773 
1774   auto* cl = Runtime::Current()->GetClassLinker();
1775 
1776   jobjectArray result;
1777 
1778   if (output_array != nullptr) {
1779     // Reuse the array we were given.
1780     result = output_array;
1781     // ...adjusting the number of frames we'll write to not exceed the array length.
1782     const int32_t traces_length =
1783         soa.Decode<mirror::ObjectArray<mirror::StackTraceElement>*>(result)->GetLength();
1784     depth = std::min(depth, traces_length);
1785   } else {
1786     // Create java_trace array and place in local reference table
1787     mirror::ObjectArray<mirror::StackTraceElement>* java_traces =
1788         cl->AllocStackTraceElementArray(soa.Self(), depth);
1789     if (java_traces == nullptr) {
1790       return nullptr;
1791     }
1792     result = soa.AddLocalReference<jobjectArray>(java_traces);
1793   }
1794 
1795   if (stack_depth != nullptr) {
1796     *stack_depth = depth;
1797   }
1798 
1799   for (int32_t i = 0; i < depth; ++i) {
1800     auto* method_trace = soa.Decode<mirror::PointerArray*>(internal);
1801     // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1802     ArtMethod* method = method_trace->GetElementPtrSize<ArtMethod*>(i, sizeof(void*));
1803     uint32_t dex_pc = method_trace->GetElementPtrSize<uint32_t>(
1804         i + method_trace->GetLength() / 2, sizeof(void*));
1805     int32_t line_number;
1806     StackHandleScope<3> hs(soa.Self());
1807     auto class_name_object(hs.NewHandle<mirror::String>(nullptr));
1808     auto source_name_object(hs.NewHandle<mirror::String>(nullptr));
1809     if (method->IsProxyMethod()) {
1810       line_number = -1;
1811       class_name_object.Assign(method->GetDeclaringClass()->GetName());
1812       // source_name_object intentionally left null for proxy methods
1813     } else {
1814       line_number = method->GetLineNumFromDexPC(dex_pc);
1815       // Allocate element, potentially triggering GC
1816       // TODO: reuse class_name_object via Class::name_?
1817       const char* descriptor = method->GetDeclaringClassDescriptor();
1818       CHECK(descriptor != nullptr);
1819       std::string class_name(PrettyDescriptor(descriptor));
1820       class_name_object.Assign(
1821           mirror::String::AllocFromModifiedUtf8(soa.Self(), class_name.c_str()));
1822       if (class_name_object.Get() == nullptr) {
1823         soa.Self()->AssertPendingOOMException();
1824         return nullptr;
1825       }
1826       const char* source_file = method->GetDeclaringClassSourceFile();
1827       if (source_file != nullptr) {
1828         source_name_object.Assign(mirror::String::AllocFromModifiedUtf8(soa.Self(), source_file));
1829         if (source_name_object.Get() == nullptr) {
1830           soa.Self()->AssertPendingOOMException();
1831           return nullptr;
1832         }
1833       }
1834     }
1835     const char* method_name = method->GetInterfaceMethodIfProxy(sizeof(void*))->GetName();
1836     CHECK(method_name != nullptr);
1837     Handle<mirror::String> method_name_object(
1838         hs.NewHandle(mirror::String::AllocFromModifiedUtf8(soa.Self(), method_name)));
1839     if (method_name_object.Get() == nullptr) {
1840       return nullptr;
1841     }
1842     mirror::StackTraceElement* obj = mirror::StackTraceElement::Alloc(
1843         soa.Self(), class_name_object, method_name_object, source_name_object, line_number);
1844     if (obj == nullptr) {
1845       return nullptr;
1846     }
1847     // We are called from native: use non-transactional mode.
1848     soa.Decode<mirror::ObjectArray<mirror::StackTraceElement>*>(result)->Set<false>(i, obj);
1849   }
1850   return result;
1851 }
1852 
ThrowNewExceptionF(const char * exception_class_descriptor,const char * fmt,...)1853 void Thread::ThrowNewExceptionF(const char* exception_class_descriptor, const char* fmt, ...) {
1854   va_list args;
1855   va_start(args, fmt);
1856   ThrowNewExceptionV(exception_class_descriptor, fmt, args);
1857   va_end(args);
1858 }
1859 
ThrowNewExceptionV(const char * exception_class_descriptor,const char * fmt,va_list ap)1860 void Thread::ThrowNewExceptionV(const char* exception_class_descriptor,
1861                                 const char* fmt, va_list ap) {
1862   std::string msg;
1863   StringAppendV(&msg, fmt, ap);
1864   ThrowNewException(exception_class_descriptor, msg.c_str());
1865 }
1866 
ThrowNewException(const char * exception_class_descriptor,const char * msg)1867 void Thread::ThrowNewException(const char* exception_class_descriptor,
1868                                const char* msg) {
1869   // Callers should either clear or call ThrowNewWrappedException.
1870   AssertNoPendingExceptionForNewException(msg);
1871   ThrowNewWrappedException(exception_class_descriptor, msg);
1872 }
1873 
GetCurrentClassLoader(Thread * self)1874 static mirror::ClassLoader* GetCurrentClassLoader(Thread* self)
1875     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1876   ArtMethod* method = self->GetCurrentMethod(nullptr);
1877   return method != nullptr
1878       ? method->GetDeclaringClass()->GetClassLoader()
1879       : nullptr;
1880 }
1881 
ThrowNewWrappedException(const char * exception_class_descriptor,const char * msg)1882 void Thread::ThrowNewWrappedException(const char* exception_class_descriptor,
1883                                       const char* msg) {
1884   DCHECK_EQ(this, Thread::Current());
1885   ScopedObjectAccessUnchecked soa(this);
1886   StackHandleScope<3> hs(soa.Self());
1887   Handle<mirror::ClassLoader> class_loader(hs.NewHandle(GetCurrentClassLoader(soa.Self())));
1888   ScopedLocalRef<jobject> cause(GetJniEnv(), soa.AddLocalReference<jobject>(GetException()));
1889   ClearException();
1890   Runtime* runtime = Runtime::Current();
1891   auto* cl = runtime->GetClassLinker();
1892   Handle<mirror::Class> exception_class(
1893       hs.NewHandle(cl->FindClass(this, exception_class_descriptor, class_loader)));
1894   if (UNLIKELY(exception_class.Get() == nullptr)) {
1895     CHECK(IsExceptionPending());
1896     LOG(ERROR) << "No exception class " << PrettyDescriptor(exception_class_descriptor);
1897     return;
1898   }
1899 
1900   if (UNLIKELY(!runtime->GetClassLinker()->EnsureInitialized(soa.Self(), exception_class, true,
1901                                                              true))) {
1902     DCHECK(IsExceptionPending());
1903     return;
1904   }
1905   DCHECK(!runtime->IsStarted() || exception_class->IsThrowableClass());
1906   Handle<mirror::Throwable> exception(
1907       hs.NewHandle(down_cast<mirror::Throwable*>(exception_class->AllocObject(this))));
1908 
1909   // If we couldn't allocate the exception, throw the pre-allocated out of memory exception.
1910   if (exception.Get() == nullptr) {
1911     SetException(Runtime::Current()->GetPreAllocatedOutOfMemoryError());
1912     return;
1913   }
1914 
1915   // Choose an appropriate constructor and set up the arguments.
1916   const char* signature;
1917   ScopedLocalRef<jstring> msg_string(GetJniEnv(), nullptr);
1918   if (msg != nullptr) {
1919     // Ensure we remember this and the method over the String allocation.
1920     msg_string.reset(
1921         soa.AddLocalReference<jstring>(mirror::String::AllocFromModifiedUtf8(this, msg)));
1922     if (UNLIKELY(msg_string.get() == nullptr)) {
1923       CHECK(IsExceptionPending());  // OOME.
1924       return;
1925     }
1926     if (cause.get() == nullptr) {
1927       signature = "(Ljava/lang/String;)V";
1928     } else {
1929       signature = "(Ljava/lang/String;Ljava/lang/Throwable;)V";
1930     }
1931   } else {
1932     if (cause.get() == nullptr) {
1933       signature = "()V";
1934     } else {
1935       signature = "(Ljava/lang/Throwable;)V";
1936     }
1937   }
1938   ArtMethod* exception_init_method =
1939       exception_class->FindDeclaredDirectMethod("<init>", signature, cl->GetImagePointerSize());
1940 
1941   CHECK(exception_init_method != nullptr) << "No <init>" << signature << " in "
1942       << PrettyDescriptor(exception_class_descriptor);
1943 
1944   if (UNLIKELY(!runtime->IsStarted())) {
1945     // Something is trying to throw an exception without a started runtime, which is the common
1946     // case in the compiler. We won't be able to invoke the constructor of the exception, so set
1947     // the exception fields directly.
1948     if (msg != nullptr) {
1949       exception->SetDetailMessage(down_cast<mirror::String*>(DecodeJObject(msg_string.get())));
1950     }
1951     if (cause.get() != nullptr) {
1952       exception->SetCause(down_cast<mirror::Throwable*>(DecodeJObject(cause.get())));
1953     }
1954     ScopedLocalRef<jobject> trace(GetJniEnv(),
1955                                   Runtime::Current()->IsActiveTransaction()
1956                                       ? CreateInternalStackTrace<true>(soa)
1957                                       : CreateInternalStackTrace<false>(soa));
1958     if (trace.get() != nullptr) {
1959       exception->SetStackState(down_cast<mirror::Throwable*>(DecodeJObject(trace.get())));
1960     }
1961     SetException(exception.Get());
1962   } else {
1963     jvalue jv_args[2];
1964     size_t i = 0;
1965 
1966     if (msg != nullptr) {
1967       jv_args[i].l = msg_string.get();
1968       ++i;
1969     }
1970     if (cause.get() != nullptr) {
1971       jv_args[i].l = cause.get();
1972       ++i;
1973     }
1974     ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(exception.Get()));
1975     InvokeWithJValues(soa, ref.get(), soa.EncodeMethod(exception_init_method), jv_args);
1976     if (LIKELY(!IsExceptionPending())) {
1977       SetException(exception.Get());
1978     }
1979   }
1980 }
1981 
ThrowOutOfMemoryError(const char * msg)1982 void Thread::ThrowOutOfMemoryError(const char* msg) {
1983   LOG(WARNING) << StringPrintf("Throwing OutOfMemoryError \"%s\"%s",
1984       msg, (tls32_.throwing_OutOfMemoryError ? " (recursive case)" : ""));
1985   if (!tls32_.throwing_OutOfMemoryError) {
1986     tls32_.throwing_OutOfMemoryError = true;
1987     ThrowNewException("Ljava/lang/OutOfMemoryError;", msg);
1988     tls32_.throwing_OutOfMemoryError = false;
1989   } else {
1990     Dump(LOG(WARNING));  // The pre-allocated OOME has no stack, so help out and log one.
1991     SetException(Runtime::Current()->GetPreAllocatedOutOfMemoryError());
1992   }
1993 }
1994 
CurrentFromGdb()1995 Thread* Thread::CurrentFromGdb() {
1996   return Thread::Current();
1997 }
1998 
DumpFromGdb() const1999 void Thread::DumpFromGdb() const {
2000   std::ostringstream ss;
2001   Dump(ss);
2002   std::string str(ss.str());
2003   // log to stderr for debugging command line processes
2004   std::cerr << str;
2005 #ifdef HAVE_ANDROID_OS
2006   // log to logcat for debugging frameworks processes
2007   LOG(INFO) << str;
2008 #endif
2009 }
2010 
2011 // Explicitly instantiate 32 and 64bit thread offset dumping support.
2012 template void Thread::DumpThreadOffset<4>(std::ostream& os, uint32_t offset);
2013 template void Thread::DumpThreadOffset<8>(std::ostream& os, uint32_t offset);
2014 
2015 template<size_t ptr_size>
DumpThreadOffset(std::ostream & os,uint32_t offset)2016 void Thread::DumpThreadOffset(std::ostream& os, uint32_t offset) {
2017 #define DO_THREAD_OFFSET(x, y) \
2018     if (offset == x.Uint32Value()) { \
2019       os << y; \
2020       return; \
2021     }
2022   DO_THREAD_OFFSET(ThreadFlagsOffset<ptr_size>(), "state_and_flags")
2023   DO_THREAD_OFFSET(CardTableOffset<ptr_size>(), "card_table")
2024   DO_THREAD_OFFSET(ExceptionOffset<ptr_size>(), "exception")
2025   DO_THREAD_OFFSET(PeerOffset<ptr_size>(), "peer");
2026   DO_THREAD_OFFSET(JniEnvOffset<ptr_size>(), "jni_env")
2027   DO_THREAD_OFFSET(SelfOffset<ptr_size>(), "self")
2028   DO_THREAD_OFFSET(StackEndOffset<ptr_size>(), "stack_end")
2029   DO_THREAD_OFFSET(ThinLockIdOffset<ptr_size>(), "thin_lock_thread_id")
2030   DO_THREAD_OFFSET(TopOfManagedStackOffset<ptr_size>(), "top_quick_frame_method")
2031   DO_THREAD_OFFSET(TopShadowFrameOffset<ptr_size>(), "top_shadow_frame")
2032   DO_THREAD_OFFSET(TopHandleScopeOffset<ptr_size>(), "top_handle_scope")
2033   DO_THREAD_OFFSET(ThreadSuspendTriggerOffset<ptr_size>(), "suspend_trigger")
2034 #undef DO_THREAD_OFFSET
2035 
2036 #define INTERPRETER_ENTRY_POINT_INFO(x) \
2037     if (INTERPRETER_ENTRYPOINT_OFFSET(ptr_size, x).Uint32Value() == offset) { \
2038       os << #x; \
2039       return; \
2040     }
2041   INTERPRETER_ENTRY_POINT_INFO(pInterpreterToInterpreterBridge)
2042   INTERPRETER_ENTRY_POINT_INFO(pInterpreterToCompiledCodeBridge)
2043 #undef INTERPRETER_ENTRY_POINT_INFO
2044 
2045 #define JNI_ENTRY_POINT_INFO(x) \
2046     if (JNI_ENTRYPOINT_OFFSET(ptr_size, x).Uint32Value() == offset) { \
2047       os << #x; \
2048       return; \
2049     }
2050   JNI_ENTRY_POINT_INFO(pDlsymLookup)
2051 #undef JNI_ENTRY_POINT_INFO
2052 
2053 #define QUICK_ENTRY_POINT_INFO(x) \
2054     if (QUICK_ENTRYPOINT_OFFSET(ptr_size, x).Uint32Value() == offset) { \
2055       os << #x; \
2056       return; \
2057     }
2058   QUICK_ENTRY_POINT_INFO(pAllocArray)
2059   QUICK_ENTRY_POINT_INFO(pAllocArrayResolved)
2060   QUICK_ENTRY_POINT_INFO(pAllocArrayWithAccessCheck)
2061   QUICK_ENTRY_POINT_INFO(pAllocObject)
2062   QUICK_ENTRY_POINT_INFO(pAllocObjectResolved)
2063   QUICK_ENTRY_POINT_INFO(pAllocObjectInitialized)
2064   QUICK_ENTRY_POINT_INFO(pAllocObjectWithAccessCheck)
2065   QUICK_ENTRY_POINT_INFO(pCheckAndAllocArray)
2066   QUICK_ENTRY_POINT_INFO(pCheckAndAllocArrayWithAccessCheck)
2067   QUICK_ENTRY_POINT_INFO(pAllocStringFromBytes)
2068   QUICK_ENTRY_POINT_INFO(pAllocStringFromChars)
2069   QUICK_ENTRY_POINT_INFO(pAllocStringFromString)
2070   QUICK_ENTRY_POINT_INFO(pInstanceofNonTrivial)
2071   QUICK_ENTRY_POINT_INFO(pCheckCast)
2072   QUICK_ENTRY_POINT_INFO(pInitializeStaticStorage)
2073   QUICK_ENTRY_POINT_INFO(pInitializeTypeAndVerifyAccess)
2074   QUICK_ENTRY_POINT_INFO(pInitializeType)
2075   QUICK_ENTRY_POINT_INFO(pResolveString)
2076   QUICK_ENTRY_POINT_INFO(pSet8Instance)
2077   QUICK_ENTRY_POINT_INFO(pSet8Static)
2078   QUICK_ENTRY_POINT_INFO(pSet16Instance)
2079   QUICK_ENTRY_POINT_INFO(pSet16Static)
2080   QUICK_ENTRY_POINT_INFO(pSet32Instance)
2081   QUICK_ENTRY_POINT_INFO(pSet32Static)
2082   QUICK_ENTRY_POINT_INFO(pSet64Instance)
2083   QUICK_ENTRY_POINT_INFO(pSet64Static)
2084   QUICK_ENTRY_POINT_INFO(pSetObjInstance)
2085   QUICK_ENTRY_POINT_INFO(pSetObjStatic)
2086   QUICK_ENTRY_POINT_INFO(pGetByteInstance)
2087   QUICK_ENTRY_POINT_INFO(pGetBooleanInstance)
2088   QUICK_ENTRY_POINT_INFO(pGetByteStatic)
2089   QUICK_ENTRY_POINT_INFO(pGetBooleanStatic)
2090   QUICK_ENTRY_POINT_INFO(pGetShortInstance)
2091   QUICK_ENTRY_POINT_INFO(pGetCharInstance)
2092   QUICK_ENTRY_POINT_INFO(pGetShortStatic)
2093   QUICK_ENTRY_POINT_INFO(pGetCharStatic)
2094   QUICK_ENTRY_POINT_INFO(pGet32Instance)
2095   QUICK_ENTRY_POINT_INFO(pGet32Static)
2096   QUICK_ENTRY_POINT_INFO(pGet64Instance)
2097   QUICK_ENTRY_POINT_INFO(pGet64Static)
2098   QUICK_ENTRY_POINT_INFO(pGetObjInstance)
2099   QUICK_ENTRY_POINT_INFO(pGetObjStatic)
2100   QUICK_ENTRY_POINT_INFO(pAputObjectWithNullAndBoundCheck)
2101   QUICK_ENTRY_POINT_INFO(pAputObjectWithBoundCheck)
2102   QUICK_ENTRY_POINT_INFO(pAputObject)
2103   QUICK_ENTRY_POINT_INFO(pHandleFillArrayData)
2104   QUICK_ENTRY_POINT_INFO(pJniMethodStart)
2105   QUICK_ENTRY_POINT_INFO(pJniMethodStartSynchronized)
2106   QUICK_ENTRY_POINT_INFO(pJniMethodEnd)
2107   QUICK_ENTRY_POINT_INFO(pJniMethodEndSynchronized)
2108   QUICK_ENTRY_POINT_INFO(pJniMethodEndWithReference)
2109   QUICK_ENTRY_POINT_INFO(pJniMethodEndWithReferenceSynchronized)
2110   QUICK_ENTRY_POINT_INFO(pQuickGenericJniTrampoline)
2111   QUICK_ENTRY_POINT_INFO(pLockObject)
2112   QUICK_ENTRY_POINT_INFO(pUnlockObject)
2113   QUICK_ENTRY_POINT_INFO(pCmpgDouble)
2114   QUICK_ENTRY_POINT_INFO(pCmpgFloat)
2115   QUICK_ENTRY_POINT_INFO(pCmplDouble)
2116   QUICK_ENTRY_POINT_INFO(pCmplFloat)
2117   QUICK_ENTRY_POINT_INFO(pFmod)
2118   QUICK_ENTRY_POINT_INFO(pL2d)
2119   QUICK_ENTRY_POINT_INFO(pFmodf)
2120   QUICK_ENTRY_POINT_INFO(pL2f)
2121   QUICK_ENTRY_POINT_INFO(pD2iz)
2122   QUICK_ENTRY_POINT_INFO(pF2iz)
2123   QUICK_ENTRY_POINT_INFO(pIdivmod)
2124   QUICK_ENTRY_POINT_INFO(pD2l)
2125   QUICK_ENTRY_POINT_INFO(pF2l)
2126   QUICK_ENTRY_POINT_INFO(pLdiv)
2127   QUICK_ENTRY_POINT_INFO(pLmod)
2128   QUICK_ENTRY_POINT_INFO(pLmul)
2129   QUICK_ENTRY_POINT_INFO(pShlLong)
2130   QUICK_ENTRY_POINT_INFO(pShrLong)
2131   QUICK_ENTRY_POINT_INFO(pUshrLong)
2132   QUICK_ENTRY_POINT_INFO(pIndexOf)
2133   QUICK_ENTRY_POINT_INFO(pStringCompareTo)
2134   QUICK_ENTRY_POINT_INFO(pMemcpy)
2135   QUICK_ENTRY_POINT_INFO(pQuickImtConflictTrampoline)
2136   QUICK_ENTRY_POINT_INFO(pQuickResolutionTrampoline)
2137   QUICK_ENTRY_POINT_INFO(pQuickToInterpreterBridge)
2138   QUICK_ENTRY_POINT_INFO(pInvokeDirectTrampolineWithAccessCheck)
2139   QUICK_ENTRY_POINT_INFO(pInvokeInterfaceTrampolineWithAccessCheck)
2140   QUICK_ENTRY_POINT_INFO(pInvokeStaticTrampolineWithAccessCheck)
2141   QUICK_ENTRY_POINT_INFO(pInvokeSuperTrampolineWithAccessCheck)
2142   QUICK_ENTRY_POINT_INFO(pInvokeVirtualTrampolineWithAccessCheck)
2143   QUICK_ENTRY_POINT_INFO(pTestSuspend)
2144   QUICK_ENTRY_POINT_INFO(pDeliverException)
2145   QUICK_ENTRY_POINT_INFO(pThrowArrayBounds)
2146   QUICK_ENTRY_POINT_INFO(pThrowDivZero)
2147   QUICK_ENTRY_POINT_INFO(pThrowNoSuchMethod)
2148   QUICK_ENTRY_POINT_INFO(pThrowNullPointer)
2149   QUICK_ENTRY_POINT_INFO(pThrowStackOverflow)
2150   QUICK_ENTRY_POINT_INFO(pDeoptimize)
2151   QUICK_ENTRY_POINT_INFO(pA64Load)
2152   QUICK_ENTRY_POINT_INFO(pA64Store)
2153   QUICK_ENTRY_POINT_INFO(pNewEmptyString)
2154   QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_B)
2155   QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BI)
2156   QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BII)
2157   QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BIII)
2158   QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BIIString)
2159   QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BString)
2160   QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BIICharset)
2161   QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BCharset)
2162   QUICK_ENTRY_POINT_INFO(pNewStringFromChars_C)
2163   QUICK_ENTRY_POINT_INFO(pNewStringFromChars_CII)
2164   QUICK_ENTRY_POINT_INFO(pNewStringFromChars_IIC)
2165   QUICK_ENTRY_POINT_INFO(pNewStringFromCodePoints)
2166   QUICK_ENTRY_POINT_INFO(pNewStringFromString)
2167   QUICK_ENTRY_POINT_INFO(pNewStringFromStringBuffer)
2168   QUICK_ENTRY_POINT_INFO(pNewStringFromStringBuilder)
2169   QUICK_ENTRY_POINT_INFO(pReadBarrierJni)
2170 #undef QUICK_ENTRY_POINT_INFO
2171 
2172   os << offset;
2173 }
2174 
QuickDeliverException()2175 void Thread::QuickDeliverException() {
2176   // Get exception from thread.
2177   mirror::Throwable* exception = GetException();
2178   CHECK(exception != nullptr);
2179   // Don't leave exception visible while we try to find the handler, which may cause class
2180   // resolution.
2181   ClearException();
2182   bool is_deoptimization = (exception == GetDeoptimizationException());
2183   QuickExceptionHandler exception_handler(this, is_deoptimization);
2184   if (is_deoptimization) {
2185     exception_handler.DeoptimizeStack();
2186   } else {
2187     exception_handler.FindCatch(exception);
2188   }
2189   exception_handler.UpdateInstrumentationStack();
2190   exception_handler.DoLongJump();
2191 }
2192 
GetLongJumpContext()2193 Context* Thread::GetLongJumpContext() {
2194   Context* result = tlsPtr_.long_jump_context;
2195   if (result == nullptr) {
2196     result = Context::Create();
2197   } else {
2198     tlsPtr_.long_jump_context = nullptr;  // Avoid context being shared.
2199     result->Reset();
2200   }
2201   return result;
2202 }
2203 
2204 // Note: this visitor may return with a method set, but dex_pc_ being DexFile:kDexNoIndex. This is
2205 //       so we don't abort in a special situation (thinlocked monitor) when dumping the Java stack.
2206 struct CurrentMethodVisitor FINAL : public StackVisitor {
CurrentMethodVisitorart::FINAL2207   CurrentMethodVisitor(Thread* thread, Context* context, bool abort_on_error)
2208       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
2209       : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2210         this_object_(nullptr),
2211         method_(nullptr),
2212         dex_pc_(0),
2213         abort_on_error_(abort_on_error) {}
VisitFrameart::FINAL2214   bool VisitFrame() OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2215     ArtMethod* m = GetMethod();
2216     if (m->IsRuntimeMethod()) {
2217       // Continue if this is a runtime method.
2218       return true;
2219     }
2220     if (context_ != nullptr) {
2221       this_object_ = GetThisObject();
2222     }
2223     method_ = m;
2224     dex_pc_ = GetDexPc(abort_on_error_);
2225     return false;
2226   }
2227   mirror::Object* this_object_;
2228   ArtMethod* method_;
2229   uint32_t dex_pc_;
2230   const bool abort_on_error_;
2231 };
2232 
GetCurrentMethod(uint32_t * dex_pc,bool abort_on_error) const2233 ArtMethod* Thread::GetCurrentMethod(uint32_t* dex_pc, bool abort_on_error) const {
2234   CurrentMethodVisitor visitor(const_cast<Thread*>(this), nullptr, abort_on_error);
2235   visitor.WalkStack(false);
2236   if (dex_pc != nullptr) {
2237     *dex_pc = visitor.dex_pc_;
2238   }
2239   return visitor.method_;
2240 }
2241 
HoldsLock(mirror::Object * object) const2242 bool Thread::HoldsLock(mirror::Object* object) const {
2243   if (object == nullptr) {
2244     return false;
2245   }
2246   return object->GetLockOwnerThreadId() == GetThreadId();
2247 }
2248 
2249 // RootVisitor parameters are: (const Object* obj, size_t vreg, const StackVisitor* visitor).
2250 template <typename RootVisitor>
2251 class ReferenceMapVisitor : public StackVisitor {
2252  public:
ReferenceMapVisitor(Thread * thread,Context * context,RootVisitor & visitor)2253   ReferenceMapVisitor(Thread* thread, Context* context, RootVisitor& visitor)
2254       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
2255         // We are visiting the references in compiled frames, so we do not need
2256         // to know the inlined frames.
2257       : StackVisitor(thread, context, StackVisitor::StackWalkKind::kSkipInlinedFrames),
2258         visitor_(visitor) {}
2259 
VisitFrame()2260   bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2261     if (false) {
2262       LOG(INFO) << "Visiting stack roots in " << PrettyMethod(GetMethod())
2263                 << StringPrintf("@ PC:%04x", GetDexPc());
2264     }
2265     ShadowFrame* shadow_frame = GetCurrentShadowFrame();
2266     if (shadow_frame != nullptr) {
2267       VisitShadowFrame(shadow_frame);
2268     } else {
2269       VisitQuickFrame();
2270     }
2271     return true;
2272   }
2273 
VisitShadowFrame(ShadowFrame * shadow_frame)2274   void VisitShadowFrame(ShadowFrame* shadow_frame) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2275     ArtMethod* m = shadow_frame->GetMethod();
2276     DCHECK(m != nullptr);
2277     size_t num_regs = shadow_frame->NumberOfVRegs();
2278     if (m->IsNative() || shadow_frame->HasReferenceArray()) {
2279       // handle scope for JNI or References for interpreter.
2280       for (size_t reg = 0; reg < num_regs; ++reg) {
2281         mirror::Object* ref = shadow_frame->GetVRegReference(reg);
2282         if (ref != nullptr) {
2283           mirror::Object* new_ref = ref;
2284           visitor_(&new_ref, reg, this);
2285           if (new_ref != ref) {
2286             shadow_frame->SetVRegReference(reg, new_ref);
2287           }
2288         }
2289       }
2290     } else {
2291       // Java method.
2292       // Portable path use DexGcMap and store in Method.native_gc_map_.
2293       const uint8_t* gc_map = m->GetNativeGcMap(sizeof(void*));
2294       CHECK(gc_map != nullptr) << PrettyMethod(m);
2295       verifier::DexPcToReferenceMap dex_gc_map(gc_map);
2296       uint32_t dex_pc = shadow_frame->GetDexPC();
2297       const uint8_t* reg_bitmap = dex_gc_map.FindBitMap(dex_pc);
2298       DCHECK(reg_bitmap != nullptr);
2299       num_regs = std::min(dex_gc_map.RegWidth() * 8, num_regs);
2300       for (size_t reg = 0; reg < num_regs; ++reg) {
2301         if (TestBitmap(reg, reg_bitmap)) {
2302           mirror::Object* ref = shadow_frame->GetVRegReference(reg);
2303           if (ref != nullptr) {
2304             mirror::Object* new_ref = ref;
2305             visitor_(&new_ref, reg, this);
2306             if (new_ref != ref) {
2307               shadow_frame->SetVRegReference(reg, new_ref);
2308             }
2309           }
2310         }
2311       }
2312     }
2313   }
2314 
2315  private:
VisitQuickFrame()2316   void VisitQuickFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2317     auto* cur_quick_frame = GetCurrentQuickFrame();
2318     DCHECK(cur_quick_frame != nullptr);
2319     auto* m = *cur_quick_frame;
2320 
2321     // Process register map (which native and runtime methods don't have)
2322     if (!m->IsNative() && !m->IsRuntimeMethod() && !m->IsProxyMethod()) {
2323       if (m->IsOptimized(sizeof(void*))) {
2324         auto* vreg_base = reinterpret_cast<StackReference<mirror::Object>*>(
2325             reinterpret_cast<uintptr_t>(cur_quick_frame));
2326         Runtime* runtime = Runtime::Current();
2327         const void* entry_point = runtime->GetInstrumentation()->GetQuickCodeFor(m, sizeof(void*));
2328         uintptr_t native_pc_offset = m->NativeQuickPcOffset(GetCurrentQuickFramePc(), entry_point);
2329         CodeInfo code_info = m->GetOptimizedCodeInfo();
2330         StackMap map = code_info.GetStackMapForNativePcOffset(native_pc_offset);
2331         MemoryRegion mask = map.GetStackMask(code_info);
2332         // Visit stack entries that hold pointers.
2333         for (size_t i = 0; i < mask.size_in_bits(); ++i) {
2334           if (mask.LoadBit(i)) {
2335             auto* ref_addr = vreg_base + i;
2336             mirror::Object* ref = ref_addr->AsMirrorPtr();
2337             if (ref != nullptr) {
2338               mirror::Object* new_ref = ref;
2339               visitor_(&new_ref, -1, this);
2340               if (ref != new_ref) {
2341                 ref_addr->Assign(new_ref);
2342               }
2343             }
2344           }
2345         }
2346         // Visit callee-save registers that hold pointers.
2347         uint32_t register_mask = map.GetRegisterMask(code_info);
2348         for (size_t i = 0; i < BitSizeOf<uint32_t>(); ++i) {
2349           if (register_mask & (1 << i)) {
2350             mirror::Object** ref_addr = reinterpret_cast<mirror::Object**>(GetGPRAddress(i));
2351             if (*ref_addr != nullptr) {
2352               visitor_(ref_addr, -1, this);
2353             }
2354           }
2355         }
2356       } else {
2357         const uint8_t* native_gc_map = m->GetNativeGcMap(sizeof(void*));
2358         CHECK(native_gc_map != nullptr) << PrettyMethod(m);
2359         const DexFile::CodeItem* code_item = m->GetCodeItem();
2360         // Can't be null or how would we compile its instructions?
2361         DCHECK(code_item != nullptr) << PrettyMethod(m);
2362         NativePcOffsetToReferenceMap map(native_gc_map);
2363         size_t num_regs = std::min(map.RegWidth() * 8,
2364                                    static_cast<size_t>(code_item->registers_size_));
2365         if (num_regs > 0) {
2366           Runtime* runtime = Runtime::Current();
2367           const void* entry_point = runtime->GetInstrumentation()->GetQuickCodeFor(m, sizeof(void*));
2368           uintptr_t native_pc_offset = m->NativeQuickPcOffset(GetCurrentQuickFramePc(), entry_point);
2369           const uint8_t* reg_bitmap = map.FindBitMap(native_pc_offset);
2370           DCHECK(reg_bitmap != nullptr);
2371           const void* code_pointer = ArtMethod::EntryPointToCodePointer(entry_point);
2372           const VmapTable vmap_table(m->GetVmapTable(code_pointer, sizeof(void*)));
2373           QuickMethodFrameInfo frame_info = m->GetQuickFrameInfo(code_pointer);
2374           // For all dex registers in the bitmap
2375           DCHECK(cur_quick_frame != nullptr);
2376           for (size_t reg = 0; reg < num_regs; ++reg) {
2377             // Does this register hold a reference?
2378             if (TestBitmap(reg, reg_bitmap)) {
2379               uint32_t vmap_offset;
2380               if (vmap_table.IsInContext(reg, kReferenceVReg, &vmap_offset)) {
2381                 int vmap_reg = vmap_table.ComputeRegister(frame_info.CoreSpillMask(), vmap_offset,
2382                                                           kReferenceVReg);
2383                 // This is sound as spilled GPRs will be word sized (ie 32 or 64bit).
2384                 mirror::Object** ref_addr =
2385                     reinterpret_cast<mirror::Object**>(GetGPRAddress(vmap_reg));
2386                 if (*ref_addr != nullptr) {
2387                   visitor_(ref_addr, reg, this);
2388                 }
2389               } else {
2390                 StackReference<mirror::Object>* ref_addr =
2391                     reinterpret_cast<StackReference<mirror::Object>*>(GetVRegAddrFromQuickCode(
2392                         cur_quick_frame, code_item, frame_info.CoreSpillMask(),
2393                         frame_info.FpSpillMask(), frame_info.FrameSizeInBytes(), reg));
2394                 mirror::Object* ref = ref_addr->AsMirrorPtr();
2395                 if (ref != nullptr) {
2396                   mirror::Object* new_ref = ref;
2397                   visitor_(&new_ref, reg, this);
2398                   if (ref != new_ref) {
2399                     ref_addr->Assign(new_ref);
2400                   }
2401                 }
2402               }
2403             }
2404           }
2405         }
2406       }
2407     }
2408   }
2409 
2410   // Visitor for when we visit a root.
2411   RootVisitor& visitor_;
2412 };
2413 
2414 class RootCallbackVisitor {
2415  public:
RootCallbackVisitor(RootVisitor * visitor,uint32_t tid)2416   RootCallbackVisitor(RootVisitor* visitor, uint32_t tid) : visitor_(visitor), tid_(tid) {}
2417 
operator ()(mirror::Object ** obj,size_t vreg,const StackVisitor * stack_visitor) const2418   void operator()(mirror::Object** obj, size_t vreg, const StackVisitor* stack_visitor) const
2419       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2420     visitor_->VisitRoot(obj, JavaFrameRootInfo(tid_, stack_visitor, vreg));
2421   }
2422 
2423  private:
2424   RootVisitor* const visitor_;
2425   const uint32_t tid_;
2426 };
2427 
VisitRoots(RootVisitor * visitor)2428 void Thread::VisitRoots(RootVisitor* visitor) {
2429   const uint32_t thread_id = GetThreadId();
2430   visitor->VisitRootIfNonNull(&tlsPtr_.opeer, RootInfo(kRootThreadObject, thread_id));
2431   if (tlsPtr_.exception != nullptr && tlsPtr_.exception != GetDeoptimizationException()) {
2432     visitor->VisitRoot(reinterpret_cast<mirror::Object**>(&tlsPtr_.exception),
2433                    RootInfo(kRootNativeStack, thread_id));
2434   }
2435   visitor->VisitRootIfNonNull(&tlsPtr_.monitor_enter_object, RootInfo(kRootNativeStack, thread_id));
2436   tlsPtr_.jni_env->locals.VisitRoots(visitor, RootInfo(kRootJNILocal, thread_id));
2437   tlsPtr_.jni_env->monitors.VisitRoots(visitor, RootInfo(kRootJNIMonitor, thread_id));
2438   HandleScopeVisitRoots(visitor, thread_id);
2439   if (tlsPtr_.debug_invoke_req != nullptr) {
2440     tlsPtr_.debug_invoke_req->VisitRoots(visitor, RootInfo(kRootDebugger, thread_id));
2441   }
2442   if (tlsPtr_.stacked_shadow_frame_record != nullptr) {
2443     RootCallbackVisitor visitor_to_callback(visitor, thread_id);
2444     ReferenceMapVisitor<RootCallbackVisitor> mapper(this, nullptr, visitor_to_callback);
2445     for (StackedShadowFrameRecord* record = tlsPtr_.stacked_shadow_frame_record;
2446          record != nullptr;
2447          record = record->GetLink()) {
2448       for (ShadowFrame* shadow_frame = record->GetShadowFrame();
2449            shadow_frame != nullptr;
2450            shadow_frame = shadow_frame->GetLink()) {
2451         mapper.VisitShadowFrame(shadow_frame);
2452       }
2453     }
2454   }
2455   if (tlsPtr_.deoptimization_return_value_stack != nullptr) {
2456     for (DeoptimizationReturnValueRecord* record = tlsPtr_.deoptimization_return_value_stack;
2457          record != nullptr;
2458          record = record->GetLink()) {
2459       if (record->IsReference()) {
2460         visitor->VisitRootIfNonNull(record->GetGCRoot(),
2461             RootInfo(kRootThreadObject, thread_id));
2462       }
2463     }
2464   }
2465   for (auto* verifier = tlsPtr_.method_verifier; verifier != nullptr; verifier = verifier->link_) {
2466     verifier->VisitRoots(visitor, RootInfo(kRootNativeStack, thread_id));
2467   }
2468   // Visit roots on this thread's stack
2469   Context* context = GetLongJumpContext();
2470   RootCallbackVisitor visitor_to_callback(visitor, thread_id);
2471   ReferenceMapVisitor<RootCallbackVisitor> mapper(this, context, visitor_to_callback);
2472   mapper.WalkStack();
2473   ReleaseLongJumpContext(context);
2474   for (instrumentation::InstrumentationStackFrame& frame : *GetInstrumentationStack()) {
2475     visitor->VisitRootIfNonNull(&frame.this_object_, RootInfo(kRootVMInternal, thread_id));
2476   }
2477 }
2478 
2479 class VerifyRootVisitor : public SingleRootVisitor {
2480  public:
VisitRoot(mirror::Object * root,const RootInfo & info ATTRIBUTE_UNUSED)2481   void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
2482       OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2483     VerifyObject(root);
2484   }
2485 };
2486 
VerifyStackImpl()2487 void Thread::VerifyStackImpl() {
2488   VerifyRootVisitor visitor;
2489   std::unique_ptr<Context> context(Context::Create());
2490   RootCallbackVisitor visitor_to_callback(&visitor, GetThreadId());
2491   ReferenceMapVisitor<RootCallbackVisitor> mapper(this, context.get(), visitor_to_callback);
2492   mapper.WalkStack();
2493 }
2494 
2495 // Set the stack end to that to be used during a stack overflow
SetStackEndForStackOverflow()2496 void Thread::SetStackEndForStackOverflow() {
2497   // During stack overflow we allow use of the full stack.
2498   if (tlsPtr_.stack_end == tlsPtr_.stack_begin) {
2499     // However, we seem to have already extended to use the full stack.
2500     LOG(ERROR) << "Need to increase kStackOverflowReservedBytes (currently "
2501                << GetStackOverflowReservedBytes(kRuntimeISA) << ")?";
2502     DumpStack(LOG(ERROR));
2503     LOG(FATAL) << "Recursive stack overflow.";
2504   }
2505 
2506   tlsPtr_.stack_end = tlsPtr_.stack_begin;
2507 
2508   // Remove the stack overflow protection if is it set up.
2509   bool implicit_stack_check = !Runtime::Current()->ExplicitStackOverflowChecks();
2510   if (implicit_stack_check) {
2511     if (!UnprotectStack()) {
2512       LOG(ERROR) << "Unable to remove stack protection for stack overflow";
2513     }
2514   }
2515 }
2516 
SetTlab(uint8_t * start,uint8_t * end)2517 void Thread::SetTlab(uint8_t* start, uint8_t* end) {
2518   DCHECK_LE(start, end);
2519   tlsPtr_.thread_local_start = start;
2520   tlsPtr_.thread_local_pos  = tlsPtr_.thread_local_start;
2521   tlsPtr_.thread_local_end = end;
2522   tlsPtr_.thread_local_objects = 0;
2523 }
2524 
HasTlab() const2525 bool Thread::HasTlab() const {
2526   bool has_tlab = tlsPtr_.thread_local_pos != nullptr;
2527   if (has_tlab) {
2528     DCHECK(tlsPtr_.thread_local_start != nullptr && tlsPtr_.thread_local_end != nullptr);
2529   } else {
2530     DCHECK(tlsPtr_.thread_local_start == nullptr && tlsPtr_.thread_local_end == nullptr);
2531   }
2532   return has_tlab;
2533 }
2534 
operator <<(std::ostream & os,const Thread & thread)2535 std::ostream& operator<<(std::ostream& os, const Thread& thread) {
2536   thread.ShortDump(os);
2537   return os;
2538 }
2539 
ProtectStack()2540 void Thread::ProtectStack() {
2541   void* pregion = tlsPtr_.stack_begin - kStackOverflowProtectedSize;
2542   VLOG(threads) << "Protecting stack at " << pregion;
2543   if (mprotect(pregion, kStackOverflowProtectedSize, PROT_NONE) == -1) {
2544     LOG(FATAL) << "Unable to create protected region in stack for implicit overflow check. "
2545         "Reason: "
2546         << strerror(errno) << " size:  " << kStackOverflowProtectedSize;
2547   }
2548 }
2549 
UnprotectStack()2550 bool Thread::UnprotectStack() {
2551   void* pregion = tlsPtr_.stack_begin - kStackOverflowProtectedSize;
2552   VLOG(threads) << "Unprotecting stack at " << pregion;
2553   return mprotect(pregion, kStackOverflowProtectedSize, PROT_READ|PROT_WRITE) == 0;
2554 }
2555 
ActivateSingleStepControl(SingleStepControl * ssc)2556 void Thread::ActivateSingleStepControl(SingleStepControl* ssc) {
2557   CHECK(Dbg::IsDebuggerActive());
2558   CHECK(GetSingleStepControl() == nullptr) << "Single step already active in thread " << *this;
2559   CHECK(ssc != nullptr);
2560   tlsPtr_.single_step_control = ssc;
2561 }
2562 
DeactivateSingleStepControl()2563 void Thread::DeactivateSingleStepControl() {
2564   CHECK(Dbg::IsDebuggerActive());
2565   CHECK(GetSingleStepControl() != nullptr) << "Single step not active in thread " << *this;
2566   SingleStepControl* ssc = GetSingleStepControl();
2567   tlsPtr_.single_step_control = nullptr;
2568   delete ssc;
2569 }
2570 
SetDebugInvokeReq(DebugInvokeReq * req)2571 void Thread::SetDebugInvokeReq(DebugInvokeReq* req) {
2572   CHECK(Dbg::IsDebuggerActive());
2573   CHECK(GetInvokeReq() == nullptr) << "Debug invoke req already active in thread " << *this;
2574   CHECK(Thread::Current() != this) << "Debug invoke can't be dispatched by the thread itself";
2575   CHECK(req != nullptr);
2576   tlsPtr_.debug_invoke_req = req;
2577 }
2578 
ClearDebugInvokeReq()2579 void Thread::ClearDebugInvokeReq() {
2580   CHECK(GetInvokeReq() != nullptr) << "Debug invoke req not active in thread " << *this;
2581   CHECK(Thread::Current() == this) << "Debug invoke must be finished by the thread itself";
2582   DebugInvokeReq* req = tlsPtr_.debug_invoke_req;
2583   tlsPtr_.debug_invoke_req = nullptr;
2584   delete req;
2585 }
2586 
PushVerifier(verifier::MethodVerifier * verifier)2587 void Thread::PushVerifier(verifier::MethodVerifier* verifier) {
2588   verifier->link_ = tlsPtr_.method_verifier;
2589   tlsPtr_.method_verifier = verifier;
2590 }
2591 
PopVerifier(verifier::MethodVerifier * verifier)2592 void Thread::PopVerifier(verifier::MethodVerifier* verifier) {
2593   CHECK_EQ(tlsPtr_.method_verifier, verifier);
2594   tlsPtr_.method_verifier = verifier->link_;
2595 }
2596 
2597 }  // namespace art
2598