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 #include "thread.h"
18 
19 #include <limits.h>  // for INT_MAX
20 #include <pthread.h>
21 #include <signal.h>
22 #include <sys/resource.h>
23 #include <sys/time.h>
24 
25 #if __has_feature(hwaddress_sanitizer)
26 #include <sanitizer/hwasan_interface.h>
27 #else
28 #define __hwasan_tag_pointer(p, t) (p)
29 #endif
30 
31 #include <algorithm>
32 #include <bitset>
33 #include <cerrno>
34 #include <iostream>
35 #include <list>
36 #include <sstream>
37 
38 #include "android-base/file.h"
39 #include "android-base/stringprintf.h"
40 #include "android-base/strings.h"
41 
42 #include "arch/context-inl.h"
43 #include "arch/context.h"
44 #include "art_field-inl.h"
45 #include "art_method-inl.h"
46 #include "base/atomic.h"
47 #include "base/bit_utils.h"
48 #include "base/casts.h"
49 #include "arch/context.h"
50 #include "base/file_utils.h"
51 #include "base/memory_tool.h"
52 #include "base/mutex.h"
53 #include "base/stl_util.h"
54 #include "base/systrace.h"
55 #include "base/timing_logger.h"
56 #include "base/to_str.h"
57 #include "base/utils.h"
58 #include "class_linker-inl.h"
59 #include "class_root-inl.h"
60 #include "debugger.h"
61 #include "dex/descriptors_names.h"
62 #include "dex/dex_file-inl.h"
63 #include "dex/dex_file_annotations.h"
64 #include "dex/dex_file_types.h"
65 #include "entrypoints/entrypoint_utils.h"
66 #include "entrypoints/quick/quick_alloc_entrypoints.h"
67 #include "gc/accounting/card_table-inl.h"
68 #include "gc/accounting/heap_bitmap-inl.h"
69 #include "gc/allocator/rosalloc.h"
70 #include "gc/heap.h"
71 #include "gc/space/space-inl.h"
72 #include "gc_root.h"
73 #include "handle_scope-inl.h"
74 #include "indirect_reference_table-inl.h"
75 #include "instrumentation.h"
76 #include "interpreter/interpreter.h"
77 #include "interpreter/mterp/mterp.h"
78 #include "interpreter/shadow_frame-inl.h"
79 #include "java_frame_root_info.h"
80 #include "jni/java_vm_ext.h"
81 #include "jni/jni_internal.h"
82 #include "mirror/class-alloc-inl.h"
83 #include "mirror/class_loader.h"
84 #include "mirror/object_array-alloc-inl.h"
85 #include "mirror/object_array-inl.h"
86 #include "mirror/stack_trace_element.h"
87 #include "monitor.h"
88 #include "monitor_objects_stack_visitor.h"
89 #include "native_stack_dump.h"
90 #include "nativehelper/scoped_local_ref.h"
91 #include "nativehelper/scoped_utf_chars.h"
92 #include "nterp_helpers.h"
93 #include "nth_caller_visitor.h"
94 #include "oat_quick_method_header.h"
95 #include "obj_ptr-inl.h"
96 #include "object_lock.h"
97 #include "palette/palette.h"
98 #include "quick/quick_method_frame_info.h"
99 #include "quick_exception_handler.h"
100 #include "read_barrier-inl.h"
101 #include "reflection.h"
102 #include "reflective_handle_scope-inl.h"
103 #include "runtime-inl.h"
104 #include "runtime.h"
105 #include "runtime_callbacks.h"
106 #include "scoped_thread_state_change-inl.h"
107 #include "stack.h"
108 #include "stack_map.h"
109 #include "thread-inl.h"
110 #include "thread_list.h"
111 #include "verifier/method_verifier.h"
112 #include "verify_object.h"
113 #include "well_known_classes.h"
114 
115 #if ART_USE_FUTEXES
116 #include "linux/futex.h"
117 #include "sys/syscall.h"
118 #ifndef SYS_futex
119 #define SYS_futex __NR_futex
120 #endif
121 #endif  // ART_USE_FUTEXES
122 
123 namespace art {
124 
125 using android::base::StringAppendV;
126 using android::base::StringPrintf;
127 
128 extern "C" NO_RETURN void artDeoptimize(Thread* self);
129 
130 bool Thread::is_started_ = false;
131 pthread_key_t Thread::pthread_key_self_;
132 ConditionVariable* Thread::resume_cond_ = nullptr;
133 const size_t Thread::kStackOverflowImplicitCheckSize = GetStackOverflowReservedBytes(kRuntimeISA);
134 bool (*Thread::is_sensitive_thread_hook_)() = nullptr;
135 Thread* Thread::jit_sensitive_thread_ = nullptr;
136 #ifndef __BIONIC__
137 thread_local Thread* Thread::self_tls_ = nullptr;
138 #endif
139 
140 static constexpr bool kVerifyImageObjectsMarked = kIsDebugBuild;
141 
142 // For implicit overflow checks we reserve an extra piece of memory at the bottom
143 // of the stack (lowest memory).  The higher portion of the memory
144 // is protected against reads and the lower is available for use while
145 // throwing the StackOverflow exception.
146 constexpr size_t kStackOverflowProtectedSize = 4 * kMemoryToolStackGuardSizeScale * KB;
147 
148 static const char* kThreadNameDuringStartup = "<native thread without managed peer>";
149 
InitCardTable()150 void Thread::InitCardTable() {
151   tlsPtr_.card_table = Runtime::Current()->GetHeap()->GetCardTable()->GetBiasedBegin();
152 }
153 
UnimplementedEntryPoint()154 static void UnimplementedEntryPoint() {
155   UNIMPLEMENTED(FATAL);
156 }
157 
158 void InitEntryPoints(JniEntryPoints* jpoints, QuickEntryPoints* qpoints);
159 void UpdateReadBarrierEntrypoints(QuickEntryPoints* qpoints, bool is_active);
160 
SetIsGcMarkingAndUpdateEntrypoints(bool is_marking)161 void Thread::SetIsGcMarkingAndUpdateEntrypoints(bool is_marking) {
162   CHECK(kUseReadBarrier);
163   tls32_.is_gc_marking = is_marking;
164   UpdateReadBarrierEntrypoints(&tlsPtr_.quick_entrypoints, /* is_active= */ is_marking);
165 }
166 
InitTlsEntryPoints()167 void Thread::InitTlsEntryPoints() {
168   ScopedTrace trace("InitTlsEntryPoints");
169   // Insert a placeholder so we can easily tell if we call an unimplemented entry point.
170   uintptr_t* begin = reinterpret_cast<uintptr_t*>(&tlsPtr_.jni_entrypoints);
171   uintptr_t* end = reinterpret_cast<uintptr_t*>(
172       reinterpret_cast<uint8_t*>(&tlsPtr_.quick_entrypoints) + sizeof(tlsPtr_.quick_entrypoints));
173   for (uintptr_t* it = begin; it != end; ++it) {
174     *it = reinterpret_cast<uintptr_t>(UnimplementedEntryPoint);
175   }
176   InitEntryPoints(&tlsPtr_.jni_entrypoints, &tlsPtr_.quick_entrypoints);
177 }
178 
ResetQuickAllocEntryPointsForThread()179 void Thread::ResetQuickAllocEntryPointsForThread() {
180   ResetQuickAllocEntryPoints(&tlsPtr_.quick_entrypoints);
181 }
182 
183 class DeoptimizationContextRecord {
184  public:
DeoptimizationContextRecord(const JValue & ret_val,bool is_reference,bool from_code,ObjPtr<mirror::Throwable> pending_exception,DeoptimizationMethodType method_type,DeoptimizationContextRecord * link)185   DeoptimizationContextRecord(const JValue& ret_val,
186                               bool is_reference,
187                               bool from_code,
188                               ObjPtr<mirror::Throwable> pending_exception,
189                               DeoptimizationMethodType method_type,
190                               DeoptimizationContextRecord* link)
191       : ret_val_(ret_val),
192         is_reference_(is_reference),
193         from_code_(from_code),
194         pending_exception_(pending_exception.Ptr()),
195         deopt_method_type_(method_type),
196         link_(link) {}
197 
GetReturnValue() const198   JValue GetReturnValue() const { return ret_val_; }
IsReference() const199   bool IsReference() const { return is_reference_; }
GetFromCode() const200   bool GetFromCode() const { return from_code_; }
GetPendingException() const201   ObjPtr<mirror::Throwable> GetPendingException() const { return pending_exception_; }
GetLink() const202   DeoptimizationContextRecord* GetLink() const { return link_; }
GetReturnValueAsGCRoot()203   mirror::Object** GetReturnValueAsGCRoot() {
204     DCHECK(is_reference_);
205     return ret_val_.GetGCRoot();
206   }
GetPendingExceptionAsGCRoot()207   mirror::Object** GetPendingExceptionAsGCRoot() {
208     return reinterpret_cast<mirror::Object**>(&pending_exception_);
209   }
GetDeoptimizationMethodType() const210   DeoptimizationMethodType GetDeoptimizationMethodType() const {
211     return deopt_method_type_;
212   }
213 
214  private:
215   // The value returned by the method at the top of the stack before deoptimization.
216   JValue ret_val_;
217 
218   // Indicates whether the returned value is a reference. If so, the GC will visit it.
219   const bool is_reference_;
220 
221   // Whether the context was created from an explicit deoptimization in the code.
222   const bool from_code_;
223 
224   // The exception that was pending before deoptimization (or null if there was no pending
225   // exception).
226   mirror::Throwable* pending_exception_;
227 
228   // Whether the context was created for an (idempotent) runtime method.
229   const DeoptimizationMethodType deopt_method_type_;
230 
231   // A link to the previous DeoptimizationContextRecord.
232   DeoptimizationContextRecord* const link_;
233 
234   DISALLOW_COPY_AND_ASSIGN(DeoptimizationContextRecord);
235 };
236 
237 class StackedShadowFrameRecord {
238  public:
StackedShadowFrameRecord(ShadowFrame * shadow_frame,StackedShadowFrameType type,StackedShadowFrameRecord * link)239   StackedShadowFrameRecord(ShadowFrame* shadow_frame,
240                            StackedShadowFrameType type,
241                            StackedShadowFrameRecord* link)
242       : shadow_frame_(shadow_frame),
243         type_(type),
244         link_(link) {}
245 
GetShadowFrame() const246   ShadowFrame* GetShadowFrame() const { return shadow_frame_; }
GetType() const247   StackedShadowFrameType GetType() const { return type_; }
GetLink() const248   StackedShadowFrameRecord* GetLink() const { return link_; }
249 
250  private:
251   ShadowFrame* const shadow_frame_;
252   const StackedShadowFrameType type_;
253   StackedShadowFrameRecord* const link_;
254 
255   DISALLOW_COPY_AND_ASSIGN(StackedShadowFrameRecord);
256 };
257 
PushDeoptimizationContext(const JValue & return_value,bool is_reference,ObjPtr<mirror::Throwable> exception,bool from_code,DeoptimizationMethodType method_type)258 void Thread::PushDeoptimizationContext(const JValue& return_value,
259                                        bool is_reference,
260                                        ObjPtr<mirror::Throwable> exception,
261                                        bool from_code,
262                                        DeoptimizationMethodType method_type) {
263   DeoptimizationContextRecord* record = new DeoptimizationContextRecord(
264       return_value,
265       is_reference,
266       from_code,
267       exception,
268       method_type,
269       tlsPtr_.deoptimization_context_stack);
270   tlsPtr_.deoptimization_context_stack = record;
271 }
272 
PopDeoptimizationContext(JValue * result,ObjPtr<mirror::Throwable> * exception,bool * from_code,DeoptimizationMethodType * method_type)273 void Thread::PopDeoptimizationContext(JValue* result,
274                                       ObjPtr<mirror::Throwable>* exception,
275                                       bool* from_code,
276                                       DeoptimizationMethodType* method_type) {
277   AssertHasDeoptimizationContext();
278   DeoptimizationContextRecord* record = tlsPtr_.deoptimization_context_stack;
279   tlsPtr_.deoptimization_context_stack = record->GetLink();
280   result->SetJ(record->GetReturnValue().GetJ());
281   *exception = record->GetPendingException();
282   *from_code = record->GetFromCode();
283   *method_type = record->GetDeoptimizationMethodType();
284   delete record;
285 }
286 
AssertHasDeoptimizationContext()287 void Thread::AssertHasDeoptimizationContext() {
288   CHECK(tlsPtr_.deoptimization_context_stack != nullptr)
289       << "No deoptimization context for thread " << *this;
290 }
291 
292 enum {
293   kPermitAvailable = 0,  // Incrementing consumes the permit
294   kNoPermit = 1,  // Incrementing marks as waiter waiting
295   kNoPermitWaiterWaiting = 2
296 };
297 
Park(bool is_absolute,int64_t time)298 void Thread::Park(bool is_absolute, int64_t time) {
299   DCHECK(this == Thread::Current());
300 #if ART_USE_FUTEXES
301   // Consume the permit, or mark as waiting. This cannot cause park_state to go
302   // outside of its valid range (0, 1, 2), because in all cases where 2 is
303   // assigned it is set back to 1 before returning, and this method cannot run
304   // concurrently with itself since it operates on the current thread.
305   int old_state = tls32_.park_state_.fetch_add(1, std::memory_order_relaxed);
306   if (old_state == kNoPermit) {
307     // no permit was available. block thread until later.
308     Runtime::Current()->GetRuntimeCallbacks()->ThreadParkStart(is_absolute, time);
309     bool timed_out = false;
310     if (!is_absolute && time == 0) {
311       // Thread.getState() is documented to return waiting for untimed parks.
312       ScopedThreadSuspension sts(this, ThreadState::kWaiting);
313       DCHECK_EQ(NumberOfHeldMutexes(), 0u);
314       int result = futex(tls32_.park_state_.Address(),
315                      FUTEX_WAIT_PRIVATE,
316                      /* sleep if val = */ kNoPermitWaiterWaiting,
317                      /* timeout */ nullptr,
318                      nullptr,
319                      0);
320       // This errno check must happen before the scope is closed, to ensure that
321       // no destructors (such as ScopedThreadSuspension) overwrite errno.
322       if (result == -1) {
323         switch (errno) {
324           case EAGAIN:
325             FALLTHROUGH_INTENDED;
326           case EINTR: break;  // park() is allowed to spuriously return
327           default: PLOG(FATAL) << "Failed to park";
328         }
329       }
330     } else if (time > 0) {
331       // Only actually suspend and futex_wait if we're going to wait for some
332       // positive amount of time - the kernel will reject negative times with
333       // EINVAL, and a zero time will just noop.
334 
335       // Thread.getState() is documented to return timed wait for timed parks.
336       ScopedThreadSuspension sts(this, ThreadState::kTimedWaiting);
337       DCHECK_EQ(NumberOfHeldMutexes(), 0u);
338       timespec timespec;
339       int result = 0;
340       if (is_absolute) {
341         // Time is millis when scheduled for an absolute time
342         timespec.tv_nsec = (time % 1000) * 1000000;
343         timespec.tv_sec = time / 1000;
344         // This odd looking pattern is recommended by futex documentation to
345         // wait until an absolute deadline, with otherwise identical behavior to
346         // FUTEX_WAIT_PRIVATE. This also allows parkUntil() to return at the
347         // correct time when the system clock changes.
348         result = futex(tls32_.park_state_.Address(),
349                        FUTEX_WAIT_BITSET_PRIVATE | FUTEX_CLOCK_REALTIME,
350                        /* sleep if val = */ kNoPermitWaiterWaiting,
351                        &timespec,
352                        nullptr,
353                        FUTEX_BITSET_MATCH_ANY);
354       } else {
355         // Time is nanos when scheduled for a relative time
356         timespec.tv_sec = time / 1000000000;
357         timespec.tv_nsec = time % 1000000000;
358         result = futex(tls32_.park_state_.Address(),
359                        FUTEX_WAIT_PRIVATE,
360                        /* sleep if val = */ kNoPermitWaiterWaiting,
361                        &timespec,
362                        nullptr,
363                        0);
364       }
365       // This errno check must happen before the scope is closed, to ensure that
366       // no destructors (such as ScopedThreadSuspension) overwrite errno.
367       if (result == -1) {
368         switch (errno) {
369           case ETIMEDOUT:
370             timed_out = true;
371             FALLTHROUGH_INTENDED;
372           case EAGAIN:
373           case EINTR: break;  // park() is allowed to spuriously return
374           default: PLOG(FATAL) << "Failed to park";
375         }
376       }
377     }
378     // Mark as no longer waiting, and consume permit if there is one.
379     tls32_.park_state_.store(kNoPermit, std::memory_order_relaxed);
380     // TODO: Call to signal jvmti here
381     Runtime::Current()->GetRuntimeCallbacks()->ThreadParkFinished(timed_out);
382   } else {
383     // the fetch_add has consumed the permit. immediately return.
384     DCHECK_EQ(old_state, kPermitAvailable);
385   }
386 #else
387   #pragma clang diagnostic push
388   #pragma clang diagnostic warning "-W#warnings"
389   #warning "LockSupport.park/unpark implemented as noops without FUTEX support."
390   #pragma clang diagnostic pop
391   UNUSED(is_absolute, time);
392   UNIMPLEMENTED(WARNING);
393   sched_yield();
394 #endif
395 }
396 
Unpark()397 void Thread::Unpark() {
398 #if ART_USE_FUTEXES
399   // Set permit available; will be consumed either by fetch_add (when the thread
400   // tries to park) or store (when the parked thread is woken up)
401   if (tls32_.park_state_.exchange(kPermitAvailable, std::memory_order_relaxed)
402       == kNoPermitWaiterWaiting) {
403     int result = futex(tls32_.park_state_.Address(),
404                        FUTEX_WAKE_PRIVATE,
405                        /* number of waiters = */ 1,
406                        nullptr,
407                        nullptr,
408                        0);
409     if (result == -1) {
410       PLOG(FATAL) << "Failed to unpark";
411     }
412   }
413 #else
414   UNIMPLEMENTED(WARNING);
415 #endif
416 }
417 
PushStackedShadowFrame(ShadowFrame * sf,StackedShadowFrameType type)418 void Thread::PushStackedShadowFrame(ShadowFrame* sf, StackedShadowFrameType type) {
419   StackedShadowFrameRecord* record = new StackedShadowFrameRecord(
420       sf, type, tlsPtr_.stacked_shadow_frame_record);
421   tlsPtr_.stacked_shadow_frame_record = record;
422 }
423 
PopStackedShadowFrame(StackedShadowFrameType type,bool must_be_present)424 ShadowFrame* Thread::PopStackedShadowFrame(StackedShadowFrameType type, bool must_be_present) {
425   StackedShadowFrameRecord* record = tlsPtr_.stacked_shadow_frame_record;
426   if (must_be_present) {
427     DCHECK(record != nullptr);
428   } else {
429     if (record == nullptr || record->GetType() != type) {
430       return nullptr;
431     }
432   }
433   tlsPtr_.stacked_shadow_frame_record = record->GetLink();
434   ShadowFrame* shadow_frame = record->GetShadowFrame();
435   delete record;
436   return shadow_frame;
437 }
438 
439 class FrameIdToShadowFrame {
440  public:
Create(size_t frame_id,ShadowFrame * shadow_frame,FrameIdToShadowFrame * next,size_t num_vregs)441   static FrameIdToShadowFrame* Create(size_t frame_id,
442                                       ShadowFrame* shadow_frame,
443                                       FrameIdToShadowFrame* next,
444                                       size_t num_vregs) {
445     // Append a bool array at the end to keep track of what vregs are updated by the debugger.
446     uint8_t* memory = new uint8_t[sizeof(FrameIdToShadowFrame) + sizeof(bool) * num_vregs];
447     return new (memory) FrameIdToShadowFrame(frame_id, shadow_frame, next);
448   }
449 
Delete(FrameIdToShadowFrame * f)450   static void Delete(FrameIdToShadowFrame* f) {
451     uint8_t* memory = reinterpret_cast<uint8_t*>(f);
452     delete[] memory;
453   }
454 
GetFrameId() const455   size_t GetFrameId() const { return frame_id_; }
GetShadowFrame() const456   ShadowFrame* GetShadowFrame() const { return shadow_frame_; }
GetNext() const457   FrameIdToShadowFrame* GetNext() const { return next_; }
SetNext(FrameIdToShadowFrame * next)458   void SetNext(FrameIdToShadowFrame* next) { next_ = next; }
GetUpdatedVRegFlags()459   bool* GetUpdatedVRegFlags() {
460     return updated_vreg_flags_;
461   }
462 
463  private:
FrameIdToShadowFrame(size_t frame_id,ShadowFrame * shadow_frame,FrameIdToShadowFrame * next)464   FrameIdToShadowFrame(size_t frame_id,
465                        ShadowFrame* shadow_frame,
466                        FrameIdToShadowFrame* next)
467       : frame_id_(frame_id),
468         shadow_frame_(shadow_frame),
469         next_(next) {}
470 
471   const size_t frame_id_;
472   ShadowFrame* const shadow_frame_;
473   FrameIdToShadowFrame* next_;
474   bool updated_vreg_flags_[0];
475 
476   DISALLOW_COPY_AND_ASSIGN(FrameIdToShadowFrame);
477 };
478 
FindFrameIdToShadowFrame(FrameIdToShadowFrame * head,size_t frame_id)479 static FrameIdToShadowFrame* FindFrameIdToShadowFrame(FrameIdToShadowFrame* head,
480                                                       size_t frame_id) {
481   FrameIdToShadowFrame* found = nullptr;
482   for (FrameIdToShadowFrame* record = head; record != nullptr; record = record->GetNext()) {
483     if (record->GetFrameId() == frame_id) {
484       if (kIsDebugBuild) {
485         // Check we have at most one record for this frame.
486         CHECK(found == nullptr) << "Multiple records for the frame " << frame_id;
487         found = record;
488       } else {
489         return record;
490       }
491     }
492   }
493   return found;
494 }
495 
FindDebuggerShadowFrame(size_t frame_id)496 ShadowFrame* Thread::FindDebuggerShadowFrame(size_t frame_id) {
497   FrameIdToShadowFrame* record = FindFrameIdToShadowFrame(
498       tlsPtr_.frame_id_to_shadow_frame, frame_id);
499   if (record != nullptr) {
500     return record->GetShadowFrame();
501   }
502   return nullptr;
503 }
504 
505 // Must only be called when FindDebuggerShadowFrame(frame_id) returns non-nullptr.
GetUpdatedVRegFlags(size_t frame_id)506 bool* Thread::GetUpdatedVRegFlags(size_t frame_id) {
507   FrameIdToShadowFrame* record = FindFrameIdToShadowFrame(
508       tlsPtr_.frame_id_to_shadow_frame, frame_id);
509   CHECK(record != nullptr);
510   return record->GetUpdatedVRegFlags();
511 }
512 
FindOrCreateDebuggerShadowFrame(size_t frame_id,uint32_t num_vregs,ArtMethod * method,uint32_t dex_pc)513 ShadowFrame* Thread::FindOrCreateDebuggerShadowFrame(size_t frame_id,
514                                                      uint32_t num_vregs,
515                                                      ArtMethod* method,
516                                                      uint32_t dex_pc) {
517   ShadowFrame* shadow_frame = FindDebuggerShadowFrame(frame_id);
518   if (shadow_frame != nullptr) {
519     return shadow_frame;
520   }
521   VLOG(deopt) << "Create pre-deopted ShadowFrame for " << ArtMethod::PrettyMethod(method);
522   shadow_frame = ShadowFrame::CreateDeoptimizedFrame(num_vregs, nullptr, method, dex_pc);
523   FrameIdToShadowFrame* record = FrameIdToShadowFrame::Create(frame_id,
524                                                               shadow_frame,
525                                                               tlsPtr_.frame_id_to_shadow_frame,
526                                                               num_vregs);
527   for (uint32_t i = 0; i < num_vregs; i++) {
528     // Do this to clear all references for root visitors.
529     shadow_frame->SetVRegReference(i, nullptr);
530     // This flag will be changed to true if the debugger modifies the value.
531     record->GetUpdatedVRegFlags()[i] = false;
532   }
533   tlsPtr_.frame_id_to_shadow_frame = record;
534   return shadow_frame;
535 }
536 
GetCustomTLS(const char * key)537 TLSData* Thread::GetCustomTLS(const char* key) {
538   MutexLock mu(Thread::Current(), *Locks::custom_tls_lock_);
539   auto it = custom_tls_.find(key);
540   return (it != custom_tls_.end()) ? it->second.get() : nullptr;
541 }
542 
SetCustomTLS(const char * key,TLSData * data)543 void Thread::SetCustomTLS(const char* key, TLSData* data) {
544   // We will swap the old data (which might be nullptr) with this and then delete it outside of the
545   // custom_tls_lock_.
546   std::unique_ptr<TLSData> old_data(data);
547   {
548     MutexLock mu(Thread::Current(), *Locks::custom_tls_lock_);
549     custom_tls_.GetOrCreate(key, []() { return std::unique_ptr<TLSData>(); }).swap(old_data);
550   }
551 }
552 
RemoveDebuggerShadowFrameMapping(size_t frame_id)553 void Thread::RemoveDebuggerShadowFrameMapping(size_t frame_id) {
554   FrameIdToShadowFrame* head = tlsPtr_.frame_id_to_shadow_frame;
555   if (head->GetFrameId() == frame_id) {
556     tlsPtr_.frame_id_to_shadow_frame = head->GetNext();
557     FrameIdToShadowFrame::Delete(head);
558     return;
559   }
560   FrameIdToShadowFrame* prev = head;
561   for (FrameIdToShadowFrame* record = head->GetNext();
562        record != nullptr;
563        prev = record, record = record->GetNext()) {
564     if (record->GetFrameId() == frame_id) {
565       prev->SetNext(record->GetNext());
566       FrameIdToShadowFrame::Delete(record);
567       return;
568     }
569   }
570   LOG(FATAL) << "No shadow frame for frame " << frame_id;
571   UNREACHABLE();
572 }
573 
InitTid()574 void Thread::InitTid() {
575   tls32_.tid = ::art::GetTid();
576 }
577 
InitAfterFork()578 void Thread::InitAfterFork() {
579   // One thread (us) survived the fork, but we have a new tid so we need to
580   // update the value stashed in this Thread*.
581   InitTid();
582 }
583 
DeleteJPeer(JNIEnv * env)584 void Thread::DeleteJPeer(JNIEnv* env) {
585   // Make sure nothing can observe both opeer and jpeer set at the same time.
586   jobject old_jpeer = tlsPtr_.jpeer;
587   CHECK(old_jpeer != nullptr);
588   tlsPtr_.jpeer = nullptr;
589   env->DeleteGlobalRef(old_jpeer);
590 }
591 
CreateCallback(void * arg)592 void* Thread::CreateCallback(void* arg) {
593   Thread* self = reinterpret_cast<Thread*>(arg);
594   Runtime* runtime = Runtime::Current();
595   if (runtime == nullptr) {
596     LOG(ERROR) << "Thread attaching to non-existent runtime: " << *self;
597     return nullptr;
598   }
599   {
600     // TODO: pass self to MutexLock - requires self to equal Thread::Current(), which is only true
601     //       after self->Init().
602     MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_);
603     // Check that if we got here we cannot be shutting down (as shutdown should never have started
604     // while threads are being born).
605     CHECK(!runtime->IsShuttingDownLocked());
606     // Note: given that the JNIEnv is created in the parent thread, the only failure point here is
607     //       a mess in InitStackHwm. We do not have a reasonable way to recover from that, so abort
608     //       the runtime in such a case. In case this ever changes, we need to make sure here to
609     //       delete the tmp_jni_env, as we own it at this point.
610     CHECK(self->Init(runtime->GetThreadList(), runtime->GetJavaVM(), self->tlsPtr_.tmp_jni_env));
611     self->tlsPtr_.tmp_jni_env = nullptr;
612     Runtime::Current()->EndThreadBirth();
613   }
614   {
615     ScopedObjectAccess soa(self);
616     self->InitStringEntryPoints();
617 
618     // Copy peer into self, deleting global reference when done.
619     CHECK(self->tlsPtr_.jpeer != nullptr);
620     self->tlsPtr_.opeer = soa.Decode<mirror::Object>(self->tlsPtr_.jpeer).Ptr();
621     // Make sure nothing can observe both opeer and jpeer set at the same time.
622     self->DeleteJPeer(self->GetJniEnv());
623     self->SetThreadName(self->GetThreadName()->ToModifiedUtf8().c_str());
624 
625     ArtField* priorityField = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_priority);
626     self->SetNativePriority(priorityField->GetInt(self->tlsPtr_.opeer));
627 
628     runtime->GetRuntimeCallbacks()->ThreadStart(self);
629 
630     // Unpark ourselves if the java peer was unparked before it started (see
631     // b/28845097#comment49 for more information)
632 
633     ArtField* unparkedField = jni::DecodeArtField(
634         WellKnownClasses::java_lang_Thread_unparkedBeforeStart);
635     bool should_unpark = false;
636     {
637       // Hold the lock here, so that if another thread calls unpark before the thread starts
638       // we don't observe the unparkedBeforeStart field before the unparker writes to it,
639       // which could cause a lost unpark.
640       art::MutexLock mu(soa.Self(), *art::Locks::thread_list_lock_);
641       should_unpark = unparkedField->GetBoolean(self->tlsPtr_.opeer) == JNI_TRUE;
642     }
643     if (should_unpark) {
644       self->Unpark();
645     }
646     // Invoke the 'run' method of our java.lang.Thread.
647     ObjPtr<mirror::Object> receiver = self->tlsPtr_.opeer;
648     jmethodID mid = WellKnownClasses::java_lang_Thread_run;
649     ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(receiver));
650     InvokeVirtualOrInterfaceWithJValues(soa, ref.get(), mid, nullptr);
651   }
652   // Detach and delete self.
653   Runtime::Current()->GetThreadList()->Unregister(self);
654 
655   return nullptr;
656 }
657 
FromManagedThread(const ScopedObjectAccessAlreadyRunnable & soa,ObjPtr<mirror::Object> thread_peer)658 Thread* Thread::FromManagedThread(const ScopedObjectAccessAlreadyRunnable& soa,
659                                   ObjPtr<mirror::Object> thread_peer) {
660   ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_nativePeer);
661   Thread* result = reinterpret_cast64<Thread*>(f->GetLong(thread_peer));
662   // Check that if we have a result it is either suspended or we hold the thread_list_lock_
663   // to stop it from going away.
664   if (kIsDebugBuild) {
665     MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
666     if (result != nullptr && !result->IsSuspended()) {
667       Locks::thread_list_lock_->AssertHeld(soa.Self());
668     }
669   }
670   return result;
671 }
672 
FromManagedThread(const ScopedObjectAccessAlreadyRunnable & soa,jobject java_thread)673 Thread* Thread::FromManagedThread(const ScopedObjectAccessAlreadyRunnable& soa,
674                                   jobject java_thread) {
675   return FromManagedThread(soa, soa.Decode<mirror::Object>(java_thread));
676 }
677 
FixStackSize(size_t stack_size)678 static size_t FixStackSize(size_t stack_size) {
679   // A stack size of zero means "use the default".
680   if (stack_size == 0) {
681     stack_size = Runtime::Current()->GetDefaultStackSize();
682   }
683 
684   // Dalvik used the bionic pthread default stack size for native threads,
685   // so include that here to support apps that expect large native stacks.
686   stack_size += 1 * MB;
687 
688   // Under sanitization, frames of the interpreter may become bigger, both for C code as
689   // well as the ShadowFrame. Ensure a larger minimum size. Otherwise initialization
690   // of all core classes cannot be done in all test circumstances.
691   if (kMemoryToolIsAvailable) {
692     stack_size = std::max(2 * MB, stack_size);
693   }
694 
695   // It's not possible to request a stack smaller than the system-defined PTHREAD_STACK_MIN.
696   if (stack_size < PTHREAD_STACK_MIN) {
697     stack_size = PTHREAD_STACK_MIN;
698   }
699 
700   if (Runtime::Current()->ExplicitStackOverflowChecks()) {
701     // It's likely that callers are trying to ensure they have at least a certain amount of
702     // stack space, so we should add our reserved space on top of what they requested, rather
703     // than implicitly take it away from them.
704     stack_size += GetStackOverflowReservedBytes(kRuntimeISA);
705   } else {
706     // If we are going to use implicit stack checks, allocate space for the protected
707     // region at the bottom of the stack.
708     stack_size += Thread::kStackOverflowImplicitCheckSize +
709         GetStackOverflowReservedBytes(kRuntimeISA);
710   }
711 
712   // Some systems require the stack size to be a multiple of the system page size, so round up.
713   stack_size = RoundUp(stack_size, kPageSize);
714 
715   return stack_size;
716 }
717 
718 // Return the nearest page-aligned address below the current stack top.
719 NO_INLINE
FindStackTop()720 static uint8_t* FindStackTop() {
721   return reinterpret_cast<uint8_t*>(
722       AlignDown(__builtin_frame_address(0), kPageSize));
723 }
724 
725 // Install a protected region in the stack.  This is used to trigger a SIGSEGV if a stack
726 // overflow is detected.  It is located right below the stack_begin_.
727 ATTRIBUTE_NO_SANITIZE_ADDRESS
InstallImplicitProtection()728 void Thread::InstallImplicitProtection() {
729   uint8_t* pregion = tlsPtr_.stack_begin - kStackOverflowProtectedSize;
730   // Page containing current top of stack.
731   uint8_t* stack_top = FindStackTop();
732 
733   // Try to directly protect the stack.
734   VLOG(threads) << "installing stack protected region at " << std::hex <<
735         static_cast<void*>(pregion) << " to " <<
736         static_cast<void*>(pregion + kStackOverflowProtectedSize - 1);
737   if (ProtectStack(/* fatal_on_error= */ false)) {
738     // Tell the kernel that we won't be needing these pages any more.
739     // NB. madvise will probably write zeroes into the memory (on linux it does).
740     uint32_t unwanted_size = stack_top - pregion - kPageSize;
741     madvise(pregion, unwanted_size, MADV_DONTNEED);
742     return;
743   }
744 
745   // There is a little complexity here that deserves a special mention.  On some
746   // architectures, the stack is created using a VM_GROWSDOWN flag
747   // to prevent memory being allocated when it's not needed.  This flag makes the
748   // kernel only allocate memory for the stack by growing down in memory.  Because we
749   // want to put an mprotected region far away from that at the stack top, we need
750   // to make sure the pages for the stack are mapped in before we call mprotect.
751   //
752   // The failed mprotect in UnprotectStack is an indication of a thread with VM_GROWSDOWN
753   // with a non-mapped stack (usually only the main thread).
754   //
755   // We map in the stack by reading every page from the stack bottom (highest address)
756   // to the stack top. (We then madvise this away.) This must be done by reading from the
757   // current stack pointer downwards.
758   //
759   // Accesses too far below the current machine register corresponding to the stack pointer (e.g.,
760   // ESP on x86[-32], SP on ARM) might cause a SIGSEGV (at least on x86 with newer kernels). We
761   // thus have to move the stack pointer. We do this portably by using a recursive function with a
762   // large stack frame size.
763 
764   // (Defensively) first remove the protection on the protected region as we'll want to read
765   // and write it. Ignore errors.
766   UnprotectStack();
767 
768   VLOG(threads) << "Need to map in stack for thread at " << std::hex <<
769       static_cast<void*>(pregion);
770 
771   struct RecurseDownStack {
772     // This function has an intentionally large stack size.
773 #pragma GCC diagnostic push
774 #pragma GCC diagnostic ignored "-Wframe-larger-than="
775     NO_INLINE
776     static void Touch(uintptr_t target) {
777       volatile size_t zero = 0;
778       // Use a large local volatile array to ensure a large frame size. Do not use anything close
779       // to a full page for ASAN. It would be nice to ensure the frame size is at most a page, but
780       // there is no pragma support for this.
781       // Note: for ASAN we need to shrink the array a bit, as there's other overhead.
782       constexpr size_t kAsanMultiplier =
783 #ifdef ADDRESS_SANITIZER
784           2u;
785 #else
786           1u;
787 #endif
788       // Keep space uninitialized as it can overflow the stack otherwise (should Clang actually
789       // auto-initialize this local variable).
790       volatile char space[kPageSize - (kAsanMultiplier * 256)] __attribute__((uninitialized));
791       char sink ATTRIBUTE_UNUSED = space[zero];  // NOLINT
792       // Remove tag from the pointer. Nop in non-hwasan builds.
793       uintptr_t addr = reinterpret_cast<uintptr_t>(__hwasan_tag_pointer(space, 0));
794       if (addr >= target + kPageSize) {
795         Touch(target);
796       }
797       zero *= 2;  // Try to avoid tail recursion.
798     }
799 #pragma GCC diagnostic pop
800   };
801   RecurseDownStack::Touch(reinterpret_cast<uintptr_t>(pregion));
802 
803   VLOG(threads) << "(again) installing stack protected region at " << std::hex <<
804       static_cast<void*>(pregion) << " to " <<
805       static_cast<void*>(pregion + kStackOverflowProtectedSize - 1);
806 
807   // Protect the bottom of the stack to prevent read/write to it.
808   ProtectStack(/* fatal_on_error= */ true);
809 
810   // Tell the kernel that we won't be needing these pages any more.
811   // NB. madvise will probably write zeroes into the memory (on linux it does).
812   uint32_t unwanted_size = stack_top - pregion - kPageSize;
813   madvise(pregion, unwanted_size, MADV_DONTNEED);
814 }
815 
CreateNativeThread(JNIEnv * env,jobject java_peer,size_t stack_size,bool is_daemon)816 void Thread::CreateNativeThread(JNIEnv* env, jobject java_peer, size_t stack_size, bool is_daemon) {
817   CHECK(java_peer != nullptr);
818   Thread* self = static_cast<JNIEnvExt*>(env)->GetSelf();
819 
820   if (VLOG_IS_ON(threads)) {
821     ScopedObjectAccess soa(env);
822 
823     ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_name);
824     ObjPtr<mirror::String> java_name =
825         f->GetObject(soa.Decode<mirror::Object>(java_peer))->AsString();
826     std::string thread_name;
827     if (java_name != nullptr) {
828       thread_name = java_name->ToModifiedUtf8();
829     } else {
830       thread_name = "(Unnamed)";
831     }
832 
833     VLOG(threads) << "Creating native thread for " << thread_name;
834     self->Dump(LOG_STREAM(INFO));
835   }
836 
837   Runtime* runtime = Runtime::Current();
838 
839   // Atomically start the birth of the thread ensuring the runtime isn't shutting down.
840   bool thread_start_during_shutdown = false;
841   {
842     MutexLock mu(self, *Locks::runtime_shutdown_lock_);
843     if (runtime->IsShuttingDownLocked()) {
844       thread_start_during_shutdown = true;
845     } else {
846       runtime->StartThreadBirth();
847     }
848   }
849   if (thread_start_during_shutdown) {
850     ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/InternalError"));
851     env->ThrowNew(error_class.get(), "Thread starting during runtime shutdown");
852     return;
853   }
854 
855   Thread* child_thread = new Thread(is_daemon);
856   // Use global JNI ref to hold peer live while child thread starts.
857   child_thread->tlsPtr_.jpeer = env->NewGlobalRef(java_peer);
858   stack_size = FixStackSize(stack_size);
859 
860   // Thread.start is synchronized, so we know that nativePeer is 0, and know that we're not racing
861   // to assign it.
862   env->SetLongField(java_peer, WellKnownClasses::java_lang_Thread_nativePeer,
863                     reinterpret_cast<jlong>(child_thread));
864 
865   // Try to allocate a JNIEnvExt for the thread. We do this here as we might be out of memory and
866   // do not have a good way to report this on the child's side.
867   std::string error_msg;
868   std::unique_ptr<JNIEnvExt> child_jni_env_ext(
869       JNIEnvExt::Create(child_thread, Runtime::Current()->GetJavaVM(), &error_msg));
870 
871   int pthread_create_result = 0;
872   if (child_jni_env_ext.get() != nullptr) {
873     pthread_t new_pthread;
874     pthread_attr_t attr;
875     child_thread->tlsPtr_.tmp_jni_env = child_jni_env_ext.get();
876     CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
877     CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED),
878                        "PTHREAD_CREATE_DETACHED");
879     CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
880     pthread_create_result = pthread_create(&new_pthread,
881                                            &attr,
882                                            Thread::CreateCallback,
883                                            child_thread);
884     CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
885 
886     if (pthread_create_result == 0) {
887       // pthread_create started the new thread. The child is now responsible for managing the
888       // JNIEnvExt we created.
889       // Note: we can't check for tmp_jni_env == nullptr, as that would require synchronization
890       //       between the threads.
891       child_jni_env_ext.release();  // NOLINT pthreads API.
892       return;
893     }
894   }
895 
896   // Either JNIEnvExt::Create or pthread_create(3) failed, so clean up.
897   {
898     MutexLock mu(self, *Locks::runtime_shutdown_lock_);
899     runtime->EndThreadBirth();
900   }
901   // Manually delete the global reference since Thread::Init will not have been run. Make sure
902   // nothing can observe both opeer and jpeer set at the same time.
903   child_thread->DeleteJPeer(env);
904   delete child_thread;
905   child_thread = nullptr;
906   // TODO: remove from thread group?
907   env->SetLongField(java_peer, WellKnownClasses::java_lang_Thread_nativePeer, 0);
908   {
909     std::string msg(child_jni_env_ext.get() == nullptr ?
910         StringPrintf("Could not allocate JNI Env: %s", error_msg.c_str()) :
911         StringPrintf("pthread_create (%s stack) failed: %s",
912                                  PrettySize(stack_size).c_str(), strerror(pthread_create_result)));
913     ScopedObjectAccess soa(env);
914     soa.Self()->ThrowOutOfMemoryError(msg.c_str());
915   }
916 }
917 
Init(ThreadList * thread_list,JavaVMExt * java_vm,JNIEnvExt * jni_env_ext)918 bool Thread::Init(ThreadList* thread_list, JavaVMExt* java_vm, JNIEnvExt* jni_env_ext) {
919   // This function does all the initialization that must be run by the native thread it applies to.
920   // (When we create a new thread from managed code, we allocate the Thread* in Thread::Create so
921   // we can handshake with the corresponding native thread when it's ready.) Check this native
922   // thread hasn't been through here already...
923   CHECK(Thread::Current() == nullptr);
924 
925   // Set pthread_self_ ahead of pthread_setspecific, that makes Thread::Current function, this
926   // avoids pthread_self_ ever being invalid when discovered from Thread::Current().
927   tlsPtr_.pthread_self = pthread_self();
928   CHECK(is_started_);
929 
930   ScopedTrace trace("Thread::Init");
931 
932   SetUpAlternateSignalStack();
933   if (!InitStackHwm()) {
934     return false;
935   }
936   InitCpu();
937   InitTlsEntryPoints();
938   RemoveSuspendTrigger();
939   InitCardTable();
940   InitTid();
941   {
942     ScopedTrace trace2("InitInterpreterTls");
943     interpreter::InitInterpreterTls(this);
944   }
945 
946 #ifdef __BIONIC__
947   __get_tls()[TLS_SLOT_ART_THREAD_SELF] = this;
948 #else
949   CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach self");
950   Thread::self_tls_ = this;
951 #endif
952   DCHECK_EQ(Thread::Current(), this);
953 
954   tls32_.thin_lock_thread_id = thread_list->AllocThreadId(this);
955 
956   if (jni_env_ext != nullptr) {
957     DCHECK_EQ(jni_env_ext->GetVm(), java_vm);
958     DCHECK_EQ(jni_env_ext->GetSelf(), this);
959     tlsPtr_.jni_env = jni_env_ext;
960   } else {
961     std::string error_msg;
962     tlsPtr_.jni_env = JNIEnvExt::Create(this, java_vm, &error_msg);
963     if (tlsPtr_.jni_env == nullptr) {
964       LOG(ERROR) << "Failed to create JNIEnvExt: " << error_msg;
965       return false;
966     }
967   }
968 
969   ScopedTrace trace3("ThreadList::Register");
970   thread_list->Register(this);
971   return true;
972 }
973 
974 template <typename PeerAction>
Attach(const char * thread_name,bool as_daemon,PeerAction peer_action)975 Thread* Thread::Attach(const char* thread_name, bool as_daemon, PeerAction peer_action) {
976   Runtime* runtime = Runtime::Current();
977   ScopedTrace trace("Thread::Attach");
978   if (runtime == nullptr) {
979     LOG(ERROR) << "Thread attaching to non-existent runtime: " <<
980         ((thread_name != nullptr) ? thread_name : "(Unnamed)");
981     return nullptr;
982   }
983   Thread* self;
984   {
985     ScopedTrace trace2("Thread birth");
986     MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_);
987     if (runtime->IsShuttingDownLocked()) {
988       LOG(WARNING) << "Thread attaching while runtime is shutting down: " <<
989           ((thread_name != nullptr) ? thread_name : "(Unnamed)");
990       return nullptr;
991     } else {
992       Runtime::Current()->StartThreadBirth();
993       self = new Thread(as_daemon);
994       bool init_success = self->Init(runtime->GetThreadList(), runtime->GetJavaVM());
995       Runtime::Current()->EndThreadBirth();
996       if (!init_success) {
997         delete self;
998         return nullptr;
999       }
1000     }
1001   }
1002 
1003   self->InitStringEntryPoints();
1004 
1005   CHECK_NE(self->GetState(), kRunnable);
1006   self->SetState(kNative);
1007 
1008   // Run the action that is acting on the peer.
1009   if (!peer_action(self)) {
1010     runtime->GetThreadList()->Unregister(self);
1011     // Unregister deletes self, no need to do this here.
1012     return nullptr;
1013   }
1014 
1015   if (VLOG_IS_ON(threads)) {
1016     if (thread_name != nullptr) {
1017       VLOG(threads) << "Attaching thread " << thread_name;
1018     } else {
1019       VLOG(threads) << "Attaching unnamed thread.";
1020     }
1021     ScopedObjectAccess soa(self);
1022     self->Dump(LOG_STREAM(INFO));
1023   }
1024 
1025   {
1026     ScopedObjectAccess soa(self);
1027     runtime->GetRuntimeCallbacks()->ThreadStart(self);
1028   }
1029 
1030   return self;
1031 }
1032 
Attach(const char * thread_name,bool as_daemon,jobject thread_group,bool create_peer)1033 Thread* Thread::Attach(const char* thread_name,
1034                        bool as_daemon,
1035                        jobject thread_group,
1036                        bool create_peer) {
1037   auto create_peer_action = [&](Thread* self) {
1038     // If we're the main thread, ClassLinker won't be created until after we're attached,
1039     // so that thread needs a two-stage attach. Regular threads don't need this hack.
1040     // In the compiler, all threads need this hack, because no-one's going to be getting
1041     // a native peer!
1042     if (create_peer) {
1043       self->CreatePeer(thread_name, as_daemon, thread_group);
1044       if (self->IsExceptionPending()) {
1045         // We cannot keep the exception around, as we're deleting self. Try to be helpful and log
1046         // it.
1047         {
1048           ScopedObjectAccess soa(self);
1049           LOG(ERROR) << "Exception creating thread peer:";
1050           LOG(ERROR) << self->GetException()->Dump();
1051           self->ClearException();
1052         }
1053         return false;
1054       }
1055     } else {
1056       // These aren't necessary, but they improve diagnostics for unit tests & command-line tools.
1057       if (thread_name != nullptr) {
1058         self->tlsPtr_.name->assign(thread_name);
1059         ::art::SetThreadName(thread_name);
1060       } else if (self->GetJniEnv()->IsCheckJniEnabled()) {
1061         LOG(WARNING) << *Thread::Current() << " attached without supplying a name";
1062       }
1063     }
1064     return true;
1065   };
1066   return Attach(thread_name, as_daemon, create_peer_action);
1067 }
1068 
Attach(const char * thread_name,bool as_daemon,jobject thread_peer)1069 Thread* Thread::Attach(const char* thread_name, bool as_daemon, jobject thread_peer) {
1070   auto set_peer_action = [&](Thread* self) {
1071     // Install the given peer.
1072     {
1073       DCHECK(self == Thread::Current());
1074       ScopedObjectAccess soa(self);
1075       self->tlsPtr_.opeer = soa.Decode<mirror::Object>(thread_peer).Ptr();
1076     }
1077     self->GetJniEnv()->SetLongField(thread_peer,
1078                                     WellKnownClasses::java_lang_Thread_nativePeer,
1079                                     reinterpret_cast64<jlong>(self));
1080     return true;
1081   };
1082   return Attach(thread_name, as_daemon, set_peer_action);
1083 }
1084 
CreatePeer(const char * name,bool as_daemon,jobject thread_group)1085 void Thread::CreatePeer(const char* name, bool as_daemon, jobject thread_group) {
1086   Runtime* runtime = Runtime::Current();
1087   CHECK(runtime->IsStarted());
1088   JNIEnv* env = tlsPtr_.jni_env;
1089 
1090   if (thread_group == nullptr) {
1091     thread_group = runtime->GetMainThreadGroup();
1092   }
1093   ScopedLocalRef<jobject> thread_name(env, env->NewStringUTF(name));
1094   // Add missing null check in case of OOM b/18297817
1095   if (name != nullptr && thread_name.get() == nullptr) {
1096     CHECK(IsExceptionPending());
1097     return;
1098   }
1099   jint thread_priority = GetNativePriority();
1100   jboolean thread_is_daemon = as_daemon;
1101 
1102   ScopedLocalRef<jobject> peer(env, env->AllocObject(WellKnownClasses::java_lang_Thread));
1103   if (peer.get() == nullptr) {
1104     CHECK(IsExceptionPending());
1105     return;
1106   }
1107   {
1108     ScopedObjectAccess soa(this);
1109     tlsPtr_.opeer = soa.Decode<mirror::Object>(peer.get()).Ptr();
1110   }
1111   env->CallNonvirtualVoidMethod(peer.get(),
1112                                 WellKnownClasses::java_lang_Thread,
1113                                 WellKnownClasses::java_lang_Thread_init,
1114                                 thread_group, thread_name.get(), thread_priority, thread_is_daemon);
1115   if (IsExceptionPending()) {
1116     return;
1117   }
1118 
1119   Thread* self = this;
1120   DCHECK_EQ(self, Thread::Current());
1121   env->SetLongField(peer.get(),
1122                     WellKnownClasses::java_lang_Thread_nativePeer,
1123                     reinterpret_cast64<jlong>(self));
1124 
1125   ScopedObjectAccess soa(self);
1126   StackHandleScope<1> hs(self);
1127   MutableHandle<mirror::String> peer_thread_name(hs.NewHandle(GetThreadName()));
1128   if (peer_thread_name == nullptr) {
1129     // The Thread constructor should have set the Thread.name to a
1130     // non-null value. However, because we can run without code
1131     // available (in the compiler, in tests), we manually assign the
1132     // fields the constructor should have set.
1133     if (runtime->IsActiveTransaction()) {
1134       InitPeer<true>(soa,
1135                      tlsPtr_.opeer,
1136                      thread_is_daemon,
1137                      thread_group,
1138                      thread_name.get(),
1139                      thread_priority);
1140     } else {
1141       InitPeer<false>(soa,
1142                       tlsPtr_.opeer,
1143                       thread_is_daemon,
1144                       thread_group,
1145                       thread_name.get(),
1146                       thread_priority);
1147     }
1148     peer_thread_name.Assign(GetThreadName());
1149   }
1150   // 'thread_name' may have been null, so don't trust 'peer_thread_name' to be non-null.
1151   if (peer_thread_name != nullptr) {
1152     SetThreadName(peer_thread_name->ToModifiedUtf8().c_str());
1153   }
1154 }
1155 
CreateCompileTimePeer(JNIEnv * env,const char * name,bool as_daemon,jobject thread_group)1156 jobject Thread::CreateCompileTimePeer(JNIEnv* env,
1157                                       const char* name,
1158                                       bool as_daemon,
1159                                       jobject thread_group) {
1160   Runtime* runtime = Runtime::Current();
1161   CHECK(!runtime->IsStarted());
1162 
1163   if (thread_group == nullptr) {
1164     thread_group = runtime->GetMainThreadGroup();
1165   }
1166   ScopedLocalRef<jobject> thread_name(env, env->NewStringUTF(name));
1167   // Add missing null check in case of OOM b/18297817
1168   if (name != nullptr && thread_name.get() == nullptr) {
1169     CHECK(Thread::Current()->IsExceptionPending());
1170     return nullptr;
1171   }
1172   jint thread_priority = kNormThreadPriority;  // Always normalize to NORM priority.
1173   jboolean thread_is_daemon = as_daemon;
1174 
1175   ScopedLocalRef<jobject> peer(env, env->AllocObject(WellKnownClasses::java_lang_Thread));
1176   if (peer.get() == nullptr) {
1177     CHECK(Thread::Current()->IsExceptionPending());
1178     return nullptr;
1179   }
1180 
1181   // We cannot call Thread.init, as it will recursively ask for currentThread.
1182 
1183   // The Thread constructor should have set the Thread.name to a
1184   // non-null value. However, because we can run without code
1185   // available (in the compiler, in tests), we manually assign the
1186   // fields the constructor should have set.
1187   ScopedObjectAccessUnchecked soa(Thread::Current());
1188   if (runtime->IsActiveTransaction()) {
1189     InitPeer<true>(soa,
1190                    soa.Decode<mirror::Object>(peer.get()),
1191                    thread_is_daemon,
1192                    thread_group,
1193                    thread_name.get(),
1194                    thread_priority);
1195   } else {
1196     InitPeer<false>(soa,
1197                     soa.Decode<mirror::Object>(peer.get()),
1198                     thread_is_daemon,
1199                     thread_group,
1200                     thread_name.get(),
1201                     thread_priority);
1202   }
1203 
1204   return peer.release();
1205 }
1206 
1207 template<bool kTransactionActive>
InitPeer(ScopedObjectAccessAlreadyRunnable & soa,ObjPtr<mirror::Object> peer,jboolean thread_is_daemon,jobject thread_group,jobject thread_name,jint thread_priority)1208 void Thread::InitPeer(ScopedObjectAccessAlreadyRunnable& soa,
1209                       ObjPtr<mirror::Object> peer,
1210                       jboolean thread_is_daemon,
1211                       jobject thread_group,
1212                       jobject thread_name,
1213                       jint thread_priority) {
1214   jni::DecodeArtField(WellKnownClasses::java_lang_Thread_daemon)->
1215       SetBoolean<kTransactionActive>(peer, thread_is_daemon);
1216   jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group)->
1217       SetObject<kTransactionActive>(peer, soa.Decode<mirror::Object>(thread_group));
1218   jni::DecodeArtField(WellKnownClasses::java_lang_Thread_name)->
1219       SetObject<kTransactionActive>(peer, soa.Decode<mirror::Object>(thread_name));
1220   jni::DecodeArtField(WellKnownClasses::java_lang_Thread_priority)->
1221       SetInt<kTransactionActive>(peer, thread_priority);
1222 }
1223 
SetThreadName(const char * name)1224 void Thread::SetThreadName(const char* name) {
1225   tlsPtr_.name->assign(name);
1226   ::art::SetThreadName(name);
1227   Dbg::DdmSendThreadNotification(this, CHUNK_TYPE("THNM"));
1228 }
1229 
GetThreadStack(pthread_t thread,void ** stack_base,size_t * stack_size,size_t * guard_size)1230 static void GetThreadStack(pthread_t thread,
1231                            void** stack_base,
1232                            size_t* stack_size,
1233                            size_t* guard_size) {
1234 #if defined(__APPLE__)
1235   *stack_size = pthread_get_stacksize_np(thread);
1236   void* stack_addr = pthread_get_stackaddr_np(thread);
1237 
1238   // Check whether stack_addr is the base or end of the stack.
1239   // (On Mac OS 10.7, it's the end.)
1240   int stack_variable;
1241   if (stack_addr > &stack_variable) {
1242     *stack_base = reinterpret_cast<uint8_t*>(stack_addr) - *stack_size;
1243   } else {
1244     *stack_base = stack_addr;
1245   }
1246 
1247   // This is wrong, but there doesn't seem to be a way to get the actual value on the Mac.
1248   pthread_attr_t attributes;
1249   CHECK_PTHREAD_CALL(pthread_attr_init, (&attributes), __FUNCTION__);
1250   CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
1251   CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
1252 #else
1253   pthread_attr_t attributes;
1254   CHECK_PTHREAD_CALL(pthread_getattr_np, (thread, &attributes), __FUNCTION__);
1255   CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, stack_base, stack_size), __FUNCTION__);
1256   CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
1257   CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
1258 
1259 #if defined(__GLIBC__)
1260   // If we're the main thread, check whether we were run with an unlimited stack. In that case,
1261   // glibc will have reported a 2GB stack for our 32-bit process, and our stack overflow detection
1262   // will be broken because we'll die long before we get close to 2GB.
1263   bool is_main_thread = (::art::GetTid() == getpid());
1264   if (is_main_thread) {
1265     rlimit stack_limit;
1266     if (getrlimit(RLIMIT_STACK, &stack_limit) == -1) {
1267       PLOG(FATAL) << "getrlimit(RLIMIT_STACK) failed";
1268     }
1269     if (stack_limit.rlim_cur == RLIM_INFINITY) {
1270       size_t old_stack_size = *stack_size;
1271 
1272       // Use the kernel default limit as our size, and adjust the base to match.
1273       *stack_size = 8 * MB;
1274       *stack_base = reinterpret_cast<uint8_t*>(*stack_base) + (old_stack_size - *stack_size);
1275 
1276       VLOG(threads) << "Limiting unlimited stack (reported as " << PrettySize(old_stack_size) << ")"
1277                     << " to " << PrettySize(*stack_size)
1278                     << " with base " << *stack_base;
1279     }
1280   }
1281 #endif
1282 
1283 #endif
1284 }
1285 
InitStackHwm()1286 bool Thread::InitStackHwm() {
1287   ScopedTrace trace("InitStackHwm");
1288   void* read_stack_base;
1289   size_t read_stack_size;
1290   size_t read_guard_size;
1291   GetThreadStack(tlsPtr_.pthread_self, &read_stack_base, &read_stack_size, &read_guard_size);
1292 
1293   tlsPtr_.stack_begin = reinterpret_cast<uint8_t*>(read_stack_base);
1294   tlsPtr_.stack_size = read_stack_size;
1295 
1296   // The minimum stack size we can cope with is the overflow reserved bytes (typically
1297   // 8K) + the protected region size (4K) + another page (4K).  Typically this will
1298   // be 8+4+4 = 16K.  The thread won't be able to do much with this stack even the GC takes
1299   // between 8K and 12K.
1300   uint32_t min_stack = GetStackOverflowReservedBytes(kRuntimeISA) + kStackOverflowProtectedSize
1301     + 4 * KB;
1302   if (read_stack_size <= min_stack) {
1303     // Note, as we know the stack is small, avoid operations that could use a lot of stack.
1304     LogHelper::LogLineLowStack(__PRETTY_FUNCTION__,
1305                                __LINE__,
1306                                ::android::base::ERROR,
1307                                "Attempt to attach a thread with a too-small stack");
1308     return false;
1309   }
1310 
1311   // This is included in the SIGQUIT output, but it's useful here for thread debugging.
1312   VLOG(threads) << StringPrintf("Native stack is at %p (%s with %s guard)",
1313                                 read_stack_base,
1314                                 PrettySize(read_stack_size).c_str(),
1315                                 PrettySize(read_guard_size).c_str());
1316 
1317   // Set stack_end_ to the bottom of the stack saving space of stack overflows
1318 
1319   Runtime* runtime = Runtime::Current();
1320   bool implicit_stack_check = !runtime->ExplicitStackOverflowChecks() && !runtime->IsAotCompiler();
1321 
1322   ResetDefaultStackEnd();
1323 
1324   // Install the protected region if we are doing implicit overflow checks.
1325   if (implicit_stack_check) {
1326     // The thread might have protected region at the bottom.  We need
1327     // to install our own region so we need to move the limits
1328     // of the stack to make room for it.
1329 
1330     tlsPtr_.stack_begin += read_guard_size + kStackOverflowProtectedSize;
1331     tlsPtr_.stack_end += read_guard_size + kStackOverflowProtectedSize;
1332     tlsPtr_.stack_size -= read_guard_size;
1333 
1334     InstallImplicitProtection();
1335   }
1336 
1337   // Consistency check.
1338   CHECK_GT(FindStackTop(), reinterpret_cast<void*>(tlsPtr_.stack_end));
1339 
1340   return true;
1341 }
1342 
ShortDump(std::ostream & os) const1343 void Thread::ShortDump(std::ostream& os) const {
1344   os << "Thread[";
1345   if (GetThreadId() != 0) {
1346     // If we're in kStarting, we won't have a thin lock id or tid yet.
1347     os << GetThreadId()
1348        << ",tid=" << GetTid() << ',';
1349   }
1350   os << GetState()
1351      << ",Thread*=" << this
1352      << ",peer=" << tlsPtr_.opeer
1353      << ",\"" << (tlsPtr_.name != nullptr ? *tlsPtr_.name : "null") << "\""
1354      << "]";
1355 }
1356 
Dump(std::ostream & os,bool dump_native_stack,BacktraceMap * backtrace_map,bool force_dump_stack) const1357 void Thread::Dump(std::ostream& os, bool dump_native_stack, BacktraceMap* backtrace_map,
1358                   bool force_dump_stack) const {
1359   DumpState(os);
1360   DumpStack(os, dump_native_stack, backtrace_map, force_dump_stack);
1361 }
1362 
GetThreadName() const1363 ObjPtr<mirror::String> Thread::GetThreadName() const {
1364   ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_name);
1365   if (tlsPtr_.opeer == nullptr) {
1366     return nullptr;
1367   }
1368   ObjPtr<mirror::Object> name = f->GetObject(tlsPtr_.opeer);
1369   return name == nullptr ? nullptr : name->AsString();
1370 }
1371 
GetThreadName(std::string & name) const1372 void Thread::GetThreadName(std::string& name) const {
1373   name.assign(*tlsPtr_.name);
1374 }
1375 
GetCpuMicroTime() const1376 uint64_t Thread::GetCpuMicroTime() const {
1377 #if defined(__linux__)
1378   clockid_t cpu_clock_id;
1379   pthread_getcpuclockid(tlsPtr_.pthread_self, &cpu_clock_id);
1380   timespec now;
1381   clock_gettime(cpu_clock_id, &now);
1382   return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_nsec / UINT64_C(1000);
1383 #else  // __APPLE__
1384   UNIMPLEMENTED(WARNING);
1385   return -1;
1386 #endif
1387 }
1388 
1389 // Attempt to rectify locks so that we dump thread list with required locks before exiting.
UnsafeLogFatalForSuspendCount(Thread * self,Thread * thread)1390 static void UnsafeLogFatalForSuspendCount(Thread* self, Thread* thread) NO_THREAD_SAFETY_ANALYSIS {
1391   LOG(ERROR) << *thread << " suspend count already zero.";
1392   Locks::thread_suspend_count_lock_->Unlock(self);
1393   if (!Locks::mutator_lock_->IsSharedHeld(self)) {
1394     Locks::mutator_lock_->SharedTryLock(self);
1395     if (!Locks::mutator_lock_->IsSharedHeld(self)) {
1396       LOG(WARNING) << "Dumping thread list without holding mutator_lock_";
1397     }
1398   }
1399   if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) {
1400     Locks::thread_list_lock_->TryLock(self);
1401     if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) {
1402       LOG(WARNING) << "Dumping thread list without holding thread_list_lock_";
1403     }
1404   }
1405   std::ostringstream ss;
1406   Runtime::Current()->GetThreadList()->Dump(ss);
1407   LOG(FATAL) << ss.str();
1408 }
1409 
ModifySuspendCountInternal(Thread * self,int delta,AtomicInteger * suspend_barrier,SuspendReason reason)1410 bool Thread::ModifySuspendCountInternal(Thread* self,
1411                                         int delta,
1412                                         AtomicInteger* suspend_barrier,
1413                                         SuspendReason reason) {
1414   if (kIsDebugBuild) {
1415     DCHECK(delta == -1 || delta == +1)
1416           << reason << " " << delta << " " << this;
1417     Locks::thread_suspend_count_lock_->AssertHeld(self);
1418     if (this != self && !IsSuspended()) {
1419       Locks::thread_list_lock_->AssertHeld(self);
1420     }
1421   }
1422   // User code suspensions need to be checked more closely since they originate from code outside of
1423   // the runtime's control.
1424   if (UNLIKELY(reason == SuspendReason::kForUserCode)) {
1425     Locks::user_code_suspension_lock_->AssertHeld(self);
1426     if (UNLIKELY(delta + tls32_.user_code_suspend_count < 0)) {
1427       LOG(ERROR) << "attempting to modify suspend count in an illegal way.";
1428       return false;
1429     }
1430   }
1431   if (UNLIKELY(delta < 0 && tls32_.suspend_count <= 0)) {
1432     UnsafeLogFatalForSuspendCount(self, this);
1433     return false;
1434   }
1435 
1436   if (kUseReadBarrier && delta > 0 && this != self && tlsPtr_.flip_function != nullptr) {
1437     // Force retry of a suspend request if it's in the middle of a thread flip to avoid a
1438     // deadlock. b/31683379.
1439     return false;
1440   }
1441 
1442   uint16_t flags = kSuspendRequest;
1443   if (delta > 0 && suspend_barrier != nullptr) {
1444     uint32_t available_barrier = kMaxSuspendBarriers;
1445     for (uint32_t i = 0; i < kMaxSuspendBarriers; ++i) {
1446       if (tlsPtr_.active_suspend_barriers[i] == nullptr) {
1447         available_barrier = i;
1448         break;
1449       }
1450     }
1451     if (available_barrier == kMaxSuspendBarriers) {
1452       // No barrier spaces available, we can't add another.
1453       return false;
1454     }
1455     tlsPtr_.active_suspend_barriers[available_barrier] = suspend_barrier;
1456     flags |= kActiveSuspendBarrier;
1457   }
1458 
1459   tls32_.suspend_count += delta;
1460   switch (reason) {
1461     case SuspendReason::kForUserCode:
1462       tls32_.user_code_suspend_count += delta;
1463       break;
1464     case SuspendReason::kInternal:
1465       break;
1466   }
1467 
1468   if (tls32_.suspend_count == 0) {
1469     AtomicClearFlag(kSuspendRequest);
1470   } else {
1471     // Two bits might be set simultaneously.
1472     tls32_.state_and_flags.as_atomic_int.fetch_or(flags, std::memory_order_seq_cst);
1473     TriggerSuspend();
1474   }
1475   return true;
1476 }
1477 
PassActiveSuspendBarriers(Thread * self)1478 bool Thread::PassActiveSuspendBarriers(Thread* self) {
1479   // Grab the suspend_count lock and copy the current set of
1480   // barriers. Then clear the list and the flag. The ModifySuspendCount
1481   // function requires the lock so we prevent a race between setting
1482   // the kActiveSuspendBarrier flag and clearing it.
1483   AtomicInteger* pass_barriers[kMaxSuspendBarriers];
1484   {
1485     MutexLock mu(self, *Locks::thread_suspend_count_lock_);
1486     if (!ReadFlag(kActiveSuspendBarrier)) {
1487       // quick exit test: the barriers have already been claimed - this is
1488       // possible as there may be a race to claim and it doesn't matter
1489       // who wins.
1490       // All of the callers of this function (except the SuspendAllInternal)
1491       // will first test the kActiveSuspendBarrier flag without lock. Here
1492       // double-check whether the barrier has been passed with the
1493       // suspend_count lock.
1494       return false;
1495     }
1496 
1497     for (uint32_t i = 0; i < kMaxSuspendBarriers; ++i) {
1498       pass_barriers[i] = tlsPtr_.active_suspend_barriers[i];
1499       tlsPtr_.active_suspend_barriers[i] = nullptr;
1500     }
1501     AtomicClearFlag(kActiveSuspendBarrier);
1502   }
1503 
1504   uint32_t barrier_count = 0;
1505   for (uint32_t i = 0; i < kMaxSuspendBarriers; i++) {
1506     AtomicInteger* pending_threads = pass_barriers[i];
1507     if (pending_threads != nullptr) {
1508       bool done = false;
1509       do {
1510         int32_t cur_val = pending_threads->load(std::memory_order_relaxed);
1511         CHECK_GT(cur_val, 0) << "Unexpected value for PassActiveSuspendBarriers(): " << cur_val;
1512         // Reduce value by 1.
1513         done = pending_threads->CompareAndSetWeakRelaxed(cur_val, cur_val - 1);
1514 #if ART_USE_FUTEXES
1515         if (done && (cur_val - 1) == 0) {  // Weak CAS may fail spuriously.
1516           futex(pending_threads->Address(), FUTEX_WAKE_PRIVATE, INT_MAX, nullptr, nullptr, 0);
1517         }
1518 #endif
1519       } while (!done);
1520       ++barrier_count;
1521     }
1522   }
1523   CHECK_GT(barrier_count, 0U);
1524   return true;
1525 }
1526 
ClearSuspendBarrier(AtomicInteger * target)1527 void Thread::ClearSuspendBarrier(AtomicInteger* target) {
1528   CHECK(ReadFlag(kActiveSuspendBarrier));
1529   bool clear_flag = true;
1530   for (uint32_t i = 0; i < kMaxSuspendBarriers; ++i) {
1531     AtomicInteger* ptr = tlsPtr_.active_suspend_barriers[i];
1532     if (ptr == target) {
1533       tlsPtr_.active_suspend_barriers[i] = nullptr;
1534     } else if (ptr != nullptr) {
1535       clear_flag = false;
1536     }
1537   }
1538   if (LIKELY(clear_flag)) {
1539     AtomicClearFlag(kActiveSuspendBarrier);
1540   }
1541 }
1542 
RunCheckpointFunction()1543 void Thread::RunCheckpointFunction() {
1544   // Grab the suspend_count lock, get the next checkpoint and update all the checkpoint fields. If
1545   // there are no more checkpoints we will also clear the kCheckpointRequest flag.
1546   Closure* checkpoint;
1547   {
1548     MutexLock mu(this, *Locks::thread_suspend_count_lock_);
1549     checkpoint = tlsPtr_.checkpoint_function;
1550     if (!checkpoint_overflow_.empty()) {
1551       // Overflow list not empty, copy the first one out and continue.
1552       tlsPtr_.checkpoint_function = checkpoint_overflow_.front();
1553       checkpoint_overflow_.pop_front();
1554     } else {
1555       // No overflow checkpoints. Clear the kCheckpointRequest flag
1556       tlsPtr_.checkpoint_function = nullptr;
1557       AtomicClearFlag(kCheckpointRequest);
1558     }
1559   }
1560   // Outside the lock, run the checkpoint function.
1561   ScopedTrace trace("Run checkpoint function");
1562   CHECK(checkpoint != nullptr) << "Checkpoint flag set without pending checkpoint";
1563   checkpoint->Run(this);
1564 }
1565 
RunEmptyCheckpoint()1566 void Thread::RunEmptyCheckpoint() {
1567   DCHECK_EQ(Thread::Current(), this);
1568   AtomicClearFlag(kEmptyCheckpointRequest);
1569   Runtime::Current()->GetThreadList()->EmptyCheckpointBarrier()->Pass(this);
1570 }
1571 
RequestCheckpoint(Closure * function)1572 bool Thread::RequestCheckpoint(Closure* function) {
1573   union StateAndFlags old_state_and_flags;
1574   old_state_and_flags.as_int = tls32_.state_and_flags.as_int;
1575   if (old_state_and_flags.as_struct.state != kRunnable) {
1576     return false;  // Fail, thread is suspended and so can't run a checkpoint.
1577   }
1578 
1579   // We must be runnable to request a checkpoint.
1580   DCHECK_EQ(old_state_and_flags.as_struct.state, kRunnable);
1581   union StateAndFlags new_state_and_flags;
1582   new_state_and_flags.as_int = old_state_and_flags.as_int;
1583   new_state_and_flags.as_struct.flags |= kCheckpointRequest;
1584   bool success = tls32_.state_and_flags.as_atomic_int.CompareAndSetStrongSequentiallyConsistent(
1585       old_state_and_flags.as_int, new_state_and_flags.as_int);
1586   if (success) {
1587     // Succeeded setting checkpoint flag, now insert the actual checkpoint.
1588     if (tlsPtr_.checkpoint_function == nullptr) {
1589       tlsPtr_.checkpoint_function = function;
1590     } else {
1591       checkpoint_overflow_.push_back(function);
1592     }
1593     CHECK_EQ(ReadFlag(kCheckpointRequest), true);
1594     TriggerSuspend();
1595   }
1596   return success;
1597 }
1598 
RequestEmptyCheckpoint()1599 bool Thread::RequestEmptyCheckpoint() {
1600   union StateAndFlags old_state_and_flags;
1601   old_state_and_flags.as_int = tls32_.state_and_flags.as_int;
1602   if (old_state_and_flags.as_struct.state != kRunnable) {
1603     // If it's not runnable, we don't need to do anything because it won't be in the middle of a
1604     // heap access (eg. the read barrier).
1605     return false;
1606   }
1607 
1608   // We must be runnable to request a checkpoint.
1609   DCHECK_EQ(old_state_and_flags.as_struct.state, kRunnable);
1610   union StateAndFlags new_state_and_flags;
1611   new_state_and_flags.as_int = old_state_and_flags.as_int;
1612   new_state_and_flags.as_struct.flags |= kEmptyCheckpointRequest;
1613   bool success = tls32_.state_and_flags.as_atomic_int.CompareAndSetStrongSequentiallyConsistent(
1614       old_state_and_flags.as_int, new_state_and_flags.as_int);
1615   if (success) {
1616     TriggerSuspend();
1617   }
1618   return success;
1619 }
1620 
1621 class BarrierClosure : public Closure {
1622  public:
BarrierClosure(Closure * wrapped)1623   explicit BarrierClosure(Closure* wrapped) : wrapped_(wrapped), barrier_(0) {}
1624 
Run(Thread * self)1625   void Run(Thread* self) override {
1626     wrapped_->Run(self);
1627     barrier_.Pass(self);
1628   }
1629 
Wait(Thread * self,ThreadState suspend_state)1630   void Wait(Thread* self, ThreadState suspend_state) {
1631     if (suspend_state != ThreadState::kRunnable) {
1632       barrier_.Increment<Barrier::kDisallowHoldingLocks>(self, 1);
1633     } else {
1634       barrier_.Increment<Barrier::kAllowHoldingLocks>(self, 1);
1635     }
1636   }
1637 
1638  private:
1639   Closure* wrapped_;
1640   Barrier barrier_;
1641 };
1642 
1643 // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its execution.
RequestSynchronousCheckpoint(Closure * function,ThreadState suspend_state)1644 bool Thread::RequestSynchronousCheckpoint(Closure* function, ThreadState suspend_state) {
1645   Thread* self = Thread::Current();
1646   if (this == Thread::Current()) {
1647     Locks::thread_list_lock_->AssertExclusiveHeld(self);
1648     // Unlock the tll before running so that the state is the same regardless of thread.
1649     Locks::thread_list_lock_->ExclusiveUnlock(self);
1650     // Asked to run on this thread. Just run.
1651     function->Run(this);
1652     return true;
1653   }
1654 
1655   // The current thread is not this thread.
1656 
1657   if (GetState() == ThreadState::kTerminated) {
1658     Locks::thread_list_lock_->ExclusiveUnlock(self);
1659     return false;
1660   }
1661 
1662   struct ScopedThreadListLockUnlock {
1663     explicit ScopedThreadListLockUnlock(Thread* self_in) RELEASE(*Locks::thread_list_lock_)
1664         : self_thread(self_in) {
1665       Locks::thread_list_lock_->AssertHeld(self_thread);
1666       Locks::thread_list_lock_->Unlock(self_thread);
1667     }
1668 
1669     ~ScopedThreadListLockUnlock() ACQUIRE(*Locks::thread_list_lock_) {
1670       Locks::thread_list_lock_->AssertNotHeld(self_thread);
1671       Locks::thread_list_lock_->Lock(self_thread);
1672     }
1673 
1674     Thread* self_thread;
1675   };
1676 
1677   for (;;) {
1678     Locks::thread_list_lock_->AssertExclusiveHeld(self);
1679     // If this thread is runnable, try to schedule a checkpoint. Do some gymnastics to not hold the
1680     // suspend-count lock for too long.
1681     if (GetState() == ThreadState::kRunnable) {
1682       BarrierClosure barrier_closure(function);
1683       bool installed = false;
1684       {
1685         MutexLock mu(self, *Locks::thread_suspend_count_lock_);
1686         installed = RequestCheckpoint(&barrier_closure);
1687       }
1688       if (installed) {
1689         // Relinquish the thread-list lock. We should not wait holding any locks. We cannot
1690         // reacquire it since we don't know if 'this' hasn't been deleted yet.
1691         Locks::thread_list_lock_->ExclusiveUnlock(self);
1692         ScopedThreadStateChange sts(self, suspend_state);
1693         barrier_closure.Wait(self, suspend_state);
1694         return true;
1695       }
1696       // Fall-through.
1697     }
1698 
1699     // This thread is not runnable, make sure we stay suspended, then run the checkpoint.
1700     // Note: ModifySuspendCountInternal also expects the thread_list_lock to be held in
1701     //       certain situations.
1702     {
1703       MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
1704 
1705       if (!ModifySuspendCount(self, +1, nullptr, SuspendReason::kInternal)) {
1706         // Just retry the loop.
1707         sched_yield();
1708         continue;
1709       }
1710     }
1711 
1712     {
1713       // Release for the wait. The suspension will keep us from being deleted. Reacquire after so
1714       // that we can call ModifySuspendCount without racing against ThreadList::Unregister.
1715       ScopedThreadListLockUnlock stllu(self);
1716       {
1717         ScopedThreadStateChange sts(self, suspend_state);
1718         while (GetState() == ThreadState::kRunnable) {
1719           // We became runnable again. Wait till the suspend triggered in ModifySuspendCount
1720           // moves us to suspended.
1721           sched_yield();
1722         }
1723       }
1724 
1725       function->Run(this);
1726     }
1727 
1728     {
1729       MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
1730 
1731       DCHECK_NE(GetState(), ThreadState::kRunnable);
1732       bool updated = ModifySuspendCount(self, -1, nullptr, SuspendReason::kInternal);
1733       DCHECK(updated);
1734     }
1735 
1736     {
1737       // Imitate ResumeAll, the thread may be waiting on Thread::resume_cond_ since we raised its
1738       // suspend count. Now the suspend_count_ is lowered so we must do the broadcast.
1739       MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
1740       Thread::resume_cond_->Broadcast(self);
1741     }
1742 
1743     // Release the thread_list_lock_ to be consistent with the barrier-closure path.
1744     Locks::thread_list_lock_->ExclusiveUnlock(self);
1745 
1746     return true;  // We're done, break out of the loop.
1747   }
1748 }
1749 
GetFlipFunction()1750 Closure* Thread::GetFlipFunction() {
1751   Atomic<Closure*>* atomic_func = reinterpret_cast<Atomic<Closure*>*>(&tlsPtr_.flip_function);
1752   Closure* func;
1753   do {
1754     func = atomic_func->load(std::memory_order_relaxed);
1755     if (func == nullptr) {
1756       return nullptr;
1757     }
1758   } while (!atomic_func->CompareAndSetWeakSequentiallyConsistent(func, nullptr));
1759   DCHECK(func != nullptr);
1760   return func;
1761 }
1762 
SetFlipFunction(Closure * function)1763 void Thread::SetFlipFunction(Closure* function) {
1764   CHECK(function != nullptr);
1765   Atomic<Closure*>* atomic_func = reinterpret_cast<Atomic<Closure*>*>(&tlsPtr_.flip_function);
1766   atomic_func->store(function, std::memory_order_seq_cst);
1767 }
1768 
FullSuspendCheck()1769 void Thread::FullSuspendCheck() {
1770   ScopedTrace trace(__FUNCTION__);
1771   VLOG(threads) << this << " self-suspending";
1772   // Make thread appear suspended to other threads, release mutator_lock_.
1773   // Transition to suspended and back to runnable, re-acquire share on mutator_lock_.
1774   ScopedThreadSuspension(this, kSuspended);  // NOLINT
1775   VLOG(threads) << this << " self-reviving";
1776 }
1777 
GetSchedulerGroupName(pid_t tid)1778 static std::string GetSchedulerGroupName(pid_t tid) {
1779   // /proc/<pid>/cgroup looks like this:
1780   // 2:devices:/
1781   // 1:cpuacct,cpu:/
1782   // We want the third field from the line whose second field contains the "cpu" token.
1783   std::string cgroup_file;
1784   if (!android::base::ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid),
1785                                        &cgroup_file)) {
1786     return "";
1787   }
1788   std::vector<std::string> cgroup_lines;
1789   Split(cgroup_file, '\n', &cgroup_lines);
1790   for (size_t i = 0; i < cgroup_lines.size(); ++i) {
1791     std::vector<std::string> cgroup_fields;
1792     Split(cgroup_lines[i], ':', &cgroup_fields);
1793     std::vector<std::string> cgroups;
1794     Split(cgroup_fields[1], ',', &cgroups);
1795     for (size_t j = 0; j < cgroups.size(); ++j) {
1796       if (cgroups[j] == "cpu") {
1797         return cgroup_fields[2].substr(1);  // Skip the leading slash.
1798       }
1799     }
1800   }
1801   return "";
1802 }
1803 
1804 
DumpState(std::ostream & os,const Thread * thread,pid_t tid)1805 void Thread::DumpState(std::ostream& os, const Thread* thread, pid_t tid) {
1806   std::string group_name;
1807   int priority;
1808   bool is_daemon = false;
1809   Thread* self = Thread::Current();
1810 
1811   // If flip_function is not null, it means we have run a checkpoint
1812   // before the thread wakes up to execute the flip function and the
1813   // thread roots haven't been forwarded.  So the following access to
1814   // the roots (opeer or methods in the frames) would be bad. Run it
1815   // here. TODO: clean up.
1816   if (thread != nullptr) {
1817     ScopedObjectAccessUnchecked soa(self);
1818     Thread* this_thread = const_cast<Thread*>(thread);
1819     Closure* flip_func = this_thread->GetFlipFunction();
1820     if (flip_func != nullptr) {
1821       flip_func->Run(this_thread);
1822     }
1823   }
1824 
1825   // Don't do this if we are aborting since the GC may have all the threads suspended. This will
1826   // cause ScopedObjectAccessUnchecked to deadlock.
1827   if (gAborting == 0 && self != nullptr && thread != nullptr && thread->tlsPtr_.opeer != nullptr) {
1828     ScopedObjectAccessUnchecked soa(self);
1829     priority = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_priority)
1830         ->GetInt(thread->tlsPtr_.opeer);
1831     is_daemon = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_daemon)
1832         ->GetBoolean(thread->tlsPtr_.opeer);
1833 
1834     ObjPtr<mirror::Object> thread_group =
1835         jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group)
1836             ->GetObject(thread->tlsPtr_.opeer);
1837 
1838     if (thread_group != nullptr) {
1839       ArtField* group_name_field =
1840           jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_name);
1841       ObjPtr<mirror::String> group_name_string =
1842           group_name_field->GetObject(thread_group)->AsString();
1843       group_name = (group_name_string != nullptr) ? group_name_string->ToModifiedUtf8() : "<null>";
1844     }
1845   } else if (thread != nullptr) {
1846     priority = thread->GetNativePriority();
1847   } else {
1848     PaletteStatus status = PaletteSchedGetPriority(tid, &priority);
1849     CHECK(status == PaletteStatus::kOkay || status == PaletteStatus::kCheckErrno);
1850   }
1851 
1852   std::string scheduler_group_name(GetSchedulerGroupName(tid));
1853   if (scheduler_group_name.empty()) {
1854     scheduler_group_name = "default";
1855   }
1856 
1857   if (thread != nullptr) {
1858     os << '"' << *thread->tlsPtr_.name << '"';
1859     if (is_daemon) {
1860       os << " daemon";
1861     }
1862     os << " prio=" << priority
1863        << " tid=" << thread->GetThreadId()
1864        << " " << thread->GetState();
1865     if (thread->IsStillStarting()) {
1866       os << " (still starting up)";
1867     }
1868     os << "\n";
1869   } else {
1870     os << '"' << ::art::GetThreadName(tid) << '"'
1871        << " prio=" << priority
1872        << " (not attached)\n";
1873   }
1874 
1875   if (thread != nullptr) {
1876     auto suspend_log_fn = [&]() REQUIRES(Locks::thread_suspend_count_lock_) {
1877       os << "  | group=\"" << group_name << "\""
1878          << " sCount=" << thread->tls32_.suspend_count
1879          << " ucsCount=" << thread->tls32_.user_code_suspend_count
1880          << " flags=" << thread->tls32_.state_and_flags.as_struct.flags
1881          << " obj=" << reinterpret_cast<void*>(thread->tlsPtr_.opeer)
1882          << " self=" << reinterpret_cast<const void*>(thread) << "\n";
1883     };
1884     if (Locks::thread_suspend_count_lock_->IsExclusiveHeld(self)) {
1885       Locks::thread_suspend_count_lock_->AssertExclusiveHeld(self);  // For annotalysis.
1886       suspend_log_fn();
1887     } else {
1888       MutexLock mu(self, *Locks::thread_suspend_count_lock_);
1889       suspend_log_fn();
1890     }
1891   }
1892 
1893   os << "  | sysTid=" << tid
1894      << " nice=" << getpriority(PRIO_PROCESS, tid)
1895      << " cgrp=" << scheduler_group_name;
1896   if (thread != nullptr) {
1897     int policy;
1898     sched_param sp;
1899 #if !defined(__APPLE__)
1900     // b/36445592 Don't use pthread_getschedparam since pthread may have exited.
1901     policy = sched_getscheduler(tid);
1902     if (policy == -1) {
1903       PLOG(WARNING) << "sched_getscheduler(" << tid << ")";
1904     }
1905     int sched_getparam_result = sched_getparam(tid, &sp);
1906     if (sched_getparam_result == -1) {
1907       PLOG(WARNING) << "sched_getparam(" << tid << ", &sp)";
1908       sp.sched_priority = -1;
1909     }
1910 #else
1911     CHECK_PTHREAD_CALL(pthread_getschedparam, (thread->tlsPtr_.pthread_self, &policy, &sp),
1912                        __FUNCTION__);
1913 #endif
1914     os << " sched=" << policy << "/" << sp.sched_priority
1915        << " handle=" << reinterpret_cast<void*>(thread->tlsPtr_.pthread_self);
1916   }
1917   os << "\n";
1918 
1919   // Grab the scheduler stats for this thread.
1920   std::string scheduler_stats;
1921   if (android::base::ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", tid),
1922                                       &scheduler_stats)
1923       && !scheduler_stats.empty()) {
1924     scheduler_stats = android::base::Trim(scheduler_stats);  // Lose the trailing '\n'.
1925   } else {
1926     scheduler_stats = "0 0 0";
1927   }
1928 
1929   char native_thread_state = '?';
1930   int utime = 0;
1931   int stime = 0;
1932   int task_cpu = 0;
1933   GetTaskStats(tid, &native_thread_state, &utime, &stime, &task_cpu);
1934 
1935   os << "  | state=" << native_thread_state
1936      << " schedstat=( " << scheduler_stats << " )"
1937      << " utm=" << utime
1938      << " stm=" << stime
1939      << " core=" << task_cpu
1940      << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
1941   if (thread != nullptr) {
1942     os << "  | stack=" << reinterpret_cast<void*>(thread->tlsPtr_.stack_begin) << "-"
1943         << reinterpret_cast<void*>(thread->tlsPtr_.stack_end) << " stackSize="
1944         << PrettySize(thread->tlsPtr_.stack_size) << "\n";
1945     // Dump the held mutexes.
1946     os << "  | held mutexes=";
1947     for (size_t i = 0; i < kLockLevelCount; ++i) {
1948       if (i != kMonitorLock) {
1949         BaseMutex* mutex = thread->GetHeldMutex(static_cast<LockLevel>(i));
1950         if (mutex != nullptr) {
1951           os << " \"" << mutex->GetName() << "\"";
1952           if (mutex->IsReaderWriterMutex()) {
1953             ReaderWriterMutex* rw_mutex = down_cast<ReaderWriterMutex*>(mutex);
1954             if (rw_mutex->GetExclusiveOwnerTid() == tid) {
1955               os << "(exclusive held)";
1956             } else {
1957               os << "(shared held)";
1958             }
1959           }
1960         }
1961       }
1962     }
1963     os << "\n";
1964   }
1965 }
1966 
DumpState(std::ostream & os) const1967 void Thread::DumpState(std::ostream& os) const {
1968   Thread::DumpState(os, this, GetTid());
1969 }
1970 
1971 struct StackDumpVisitor : public MonitorObjectsStackVisitor {
StackDumpVisitorart::StackDumpVisitor1972   StackDumpVisitor(std::ostream& os_in,
1973                    Thread* thread_in,
1974                    Context* context,
1975                    bool can_allocate,
1976                    bool check_suspended = true,
1977                    bool dump_locks = true)
1978       REQUIRES_SHARED(Locks::mutator_lock_)
1979       : MonitorObjectsStackVisitor(thread_in,
1980                                    context,
1981                                    check_suspended,
1982                                    can_allocate && dump_locks),
1983         os(os_in),
1984         last_method(nullptr),
1985         last_line_number(0),
1986         repetition_count(0) {}
1987 
~StackDumpVisitorart::StackDumpVisitor1988   virtual ~StackDumpVisitor() {
1989     if (frame_count == 0) {
1990       os << "  (no managed stack frames)\n";
1991     }
1992   }
1993 
1994   static constexpr size_t kMaxRepetition = 3u;
1995 
StartMethodart::StackDumpVisitor1996   VisitMethodResult StartMethod(ArtMethod* m, size_t frame_nr ATTRIBUTE_UNUSED)
1997       override
1998       REQUIRES_SHARED(Locks::mutator_lock_) {
1999     m = m->GetInterfaceMethodIfProxy(kRuntimePointerSize);
2000     ObjPtr<mirror::DexCache> dex_cache = m->GetDexCache();
2001     int line_number = -1;
2002     if (dex_cache != nullptr) {  // be tolerant of bad input
2003       const DexFile* dex_file = dex_cache->GetDexFile();
2004       line_number = annotations::GetLineNumFromPC(dex_file, m, GetDexPc(false));
2005     }
2006     if (line_number == last_line_number && last_method == m) {
2007       ++repetition_count;
2008     } else {
2009       if (repetition_count >= kMaxRepetition) {
2010         os << "  ... repeated " << (repetition_count - kMaxRepetition) << " times\n";
2011       }
2012       repetition_count = 0;
2013       last_line_number = line_number;
2014       last_method = m;
2015     }
2016 
2017     if (repetition_count >= kMaxRepetition) {
2018       // Skip visiting=printing anything.
2019       return VisitMethodResult::kSkipMethod;
2020     }
2021 
2022     os << "  at " << m->PrettyMethod(false);
2023     if (m->IsNative()) {
2024       os << "(Native method)";
2025     } else {
2026       const char* source_file(m->GetDeclaringClassSourceFile());
2027       os << "(" << (source_file != nullptr ? source_file : "unavailable")
2028                        << ":" << line_number << ")";
2029     }
2030     os << "\n";
2031     // Go and visit locks.
2032     return VisitMethodResult::kContinueMethod;
2033   }
2034 
EndMethodart::StackDumpVisitor2035   VisitMethodResult EndMethod(ArtMethod* m ATTRIBUTE_UNUSED) override {
2036     return VisitMethodResult::kContinueMethod;
2037   }
2038 
VisitWaitingObjectart::StackDumpVisitor2039   void VisitWaitingObject(ObjPtr<mirror::Object> obj, ThreadState state ATTRIBUTE_UNUSED)
2040       override
2041       REQUIRES_SHARED(Locks::mutator_lock_) {
2042     PrintObject(obj, "  - waiting on ", ThreadList::kInvalidThreadId);
2043   }
VisitSleepingObjectart::StackDumpVisitor2044   void VisitSleepingObject(ObjPtr<mirror::Object> obj)
2045       override
2046       REQUIRES_SHARED(Locks::mutator_lock_) {
2047     PrintObject(obj, "  - sleeping on ", ThreadList::kInvalidThreadId);
2048   }
VisitBlockedOnObjectart::StackDumpVisitor2049   void VisitBlockedOnObject(ObjPtr<mirror::Object> obj,
2050                             ThreadState state,
2051                             uint32_t owner_tid)
2052       override
2053       REQUIRES_SHARED(Locks::mutator_lock_) {
2054     const char* msg;
2055     switch (state) {
2056       case kBlocked:
2057         msg = "  - waiting to lock ";
2058         break;
2059 
2060       case kWaitingForLockInflation:
2061         msg = "  - waiting for lock inflation of ";
2062         break;
2063 
2064       default:
2065         LOG(FATAL) << "Unreachable";
2066         UNREACHABLE();
2067     }
2068     PrintObject(obj, msg, owner_tid);
2069   }
VisitLockedObjectart::StackDumpVisitor2070   void VisitLockedObject(ObjPtr<mirror::Object> obj)
2071       override
2072       REQUIRES_SHARED(Locks::mutator_lock_) {
2073     PrintObject(obj, "  - locked ", ThreadList::kInvalidThreadId);
2074   }
2075 
PrintObjectart::StackDumpVisitor2076   void PrintObject(ObjPtr<mirror::Object> obj,
2077                    const char* msg,
2078                    uint32_t owner_tid) REQUIRES_SHARED(Locks::mutator_lock_) {
2079     if (obj == nullptr) {
2080       os << msg << "an unknown object";
2081     } else {
2082       if ((obj->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
2083           Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
2084         // Getting the identity hashcode here would result in lock inflation and suspension of the
2085         // current thread, which isn't safe if this is the only runnable thread.
2086         os << msg << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
2087                                   reinterpret_cast<intptr_t>(obj.Ptr()),
2088                                   obj->PrettyTypeOf().c_str());
2089       } else {
2090         // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
2091         // Call PrettyTypeOf before IdentityHashCode since IdentityHashCode can cause thread
2092         // suspension and move pretty_object.
2093         const std::string pretty_type(obj->PrettyTypeOf());
2094         os << msg << StringPrintf("<0x%08x> (a %s)", obj->IdentityHashCode(), pretty_type.c_str());
2095       }
2096     }
2097     if (owner_tid != ThreadList::kInvalidThreadId) {
2098       os << " held by thread " << owner_tid;
2099     }
2100     os << "\n";
2101   }
2102 
2103   std::ostream& os;
2104   ArtMethod* last_method;
2105   int last_line_number;
2106   size_t repetition_count;
2107 };
2108 
ShouldShowNativeStack(const Thread * thread)2109 static bool ShouldShowNativeStack(const Thread* thread)
2110     REQUIRES_SHARED(Locks::mutator_lock_) {
2111   ThreadState state = thread->GetState();
2112 
2113   // In native code somewhere in the VM (one of the kWaitingFor* states)? That's interesting.
2114   if (state > kWaiting && state < kStarting) {
2115     return true;
2116   }
2117 
2118   // In an Object.wait variant or Thread.sleep? That's not interesting.
2119   if (state == kTimedWaiting || state == kSleeping || state == kWaiting) {
2120     return false;
2121   }
2122 
2123   // Threads with no managed stack frames should be shown.
2124   if (!thread->HasManagedStack()) {
2125     return true;
2126   }
2127 
2128   // In some other native method? That's interesting.
2129   // We don't just check kNative because native methods will be in state kSuspended if they're
2130   // calling back into the VM, or kBlocked if they're blocked on a monitor, or one of the
2131   // thread-startup states if it's early enough in their life cycle (http://b/7432159).
2132   ArtMethod* current_method = thread->GetCurrentMethod(nullptr);
2133   return current_method != nullptr && current_method->IsNative();
2134 }
2135 
DumpJavaStack(std::ostream & os,bool check_suspended,bool dump_locks) const2136 void Thread::DumpJavaStack(std::ostream& os, bool check_suspended, bool dump_locks) const {
2137   // If flip_function is not null, it means we have run a checkpoint
2138   // before the thread wakes up to execute the flip function and the
2139   // thread roots haven't been forwarded.  So the following access to
2140   // the roots (locks or methods in the frames) would be bad. Run it
2141   // here. TODO: clean up.
2142   {
2143     Thread* this_thread = const_cast<Thread*>(this);
2144     Closure* flip_func = this_thread->GetFlipFunction();
2145     if (flip_func != nullptr) {
2146       flip_func->Run(this_thread);
2147     }
2148   }
2149 
2150   // Dumping the Java stack involves the verifier for locks. The verifier operates under the
2151   // assumption that there is no exception pending on entry. Thus, stash any pending exception.
2152   // Thread::Current() instead of this in case a thread is dumping the stack of another suspended
2153   // thread.
2154   ScopedExceptionStorage ses(Thread::Current());
2155 
2156   std::unique_ptr<Context> context(Context::Create());
2157   StackDumpVisitor dumper(os, const_cast<Thread*>(this), context.get(),
2158                           !tls32_.throwing_OutOfMemoryError, check_suspended, dump_locks);
2159   dumper.WalkStack();
2160 }
2161 
DumpStack(std::ostream & os,bool dump_native_stack,BacktraceMap * backtrace_map,bool force_dump_stack) const2162 void Thread::DumpStack(std::ostream& os,
2163                        bool dump_native_stack,
2164                        BacktraceMap* backtrace_map,
2165                        bool force_dump_stack) const {
2166   // TODO: we call this code when dying but may not have suspended the thread ourself. The
2167   //       IsSuspended check is therefore racy with the use for dumping (normally we inhibit
2168   //       the race with the thread_suspend_count_lock_).
2169   bool dump_for_abort = (gAborting > 0);
2170   bool safe_to_dump = (this == Thread::Current() || IsSuspended());
2171   if (!kIsDebugBuild) {
2172     // We always want to dump the stack for an abort, however, there is no point dumping another
2173     // thread's stack in debug builds where we'll hit the not suspended check in the stack walk.
2174     safe_to_dump = (safe_to_dump || dump_for_abort);
2175   }
2176   if (safe_to_dump || force_dump_stack) {
2177     // If we're currently in native code, dump that stack before dumping the managed stack.
2178     if (dump_native_stack && (dump_for_abort || force_dump_stack || ShouldShowNativeStack(this))) {
2179       ArtMethod* method =
2180           GetCurrentMethod(nullptr,
2181                            /*check_suspended=*/ !force_dump_stack,
2182                            /*abort_on_error=*/ !(dump_for_abort || force_dump_stack));
2183       DumpNativeStack(os, GetTid(), backtrace_map, "  native: ", method);
2184     }
2185     DumpJavaStack(os,
2186                   /*check_suspended=*/ !force_dump_stack,
2187                   /*dump_locks=*/ !force_dump_stack);
2188   } else {
2189     os << "Not able to dump stack of thread that isn't suspended";
2190   }
2191 }
2192 
ThreadExitCallback(void * arg)2193 void Thread::ThreadExitCallback(void* arg) {
2194   Thread* self = reinterpret_cast<Thread*>(arg);
2195   if (self->tls32_.thread_exit_check_count == 0) {
2196     LOG(WARNING) << "Native thread exiting without having called DetachCurrentThread (maybe it's "
2197         "going to use a pthread_key_create destructor?): " << *self;
2198     CHECK(is_started_);
2199 #ifdef __BIONIC__
2200     __get_tls()[TLS_SLOT_ART_THREAD_SELF] = self;
2201 #else
2202     CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, self), "reattach self");
2203     Thread::self_tls_ = self;
2204 #endif
2205     self->tls32_.thread_exit_check_count = 1;
2206   } else {
2207     LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
2208   }
2209 }
2210 
Startup()2211 void Thread::Startup() {
2212   CHECK(!is_started_);
2213   is_started_ = true;
2214   {
2215     // MutexLock to keep annotalysis happy.
2216     //
2217     // Note we use null for the thread because Thread::Current can
2218     // return garbage since (is_started_ == true) and
2219     // Thread::pthread_key_self_ is not yet initialized.
2220     // This was seen on glibc.
2221     MutexLock mu(nullptr, *Locks::thread_suspend_count_lock_);
2222     resume_cond_ = new ConditionVariable("Thread resumption condition variable",
2223                                          *Locks::thread_suspend_count_lock_);
2224   }
2225 
2226   // Allocate a TLS slot.
2227   CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback),
2228                      "self key");
2229 
2230   // Double-check the TLS slot allocation.
2231   if (pthread_getspecific(pthread_key_self_) != nullptr) {
2232     LOG(FATAL) << "Newly-created pthread TLS slot is not nullptr";
2233   }
2234 #ifndef __BIONIC__
2235   CHECK(Thread::self_tls_ == nullptr);
2236 #endif
2237 }
2238 
FinishStartup()2239 void Thread::FinishStartup() {
2240   Runtime* runtime = Runtime::Current();
2241   CHECK(runtime->IsStarted());
2242 
2243   // Finish attaching the main thread.
2244   ScopedObjectAccess soa(Thread::Current());
2245   soa.Self()->CreatePeer("main", false, runtime->GetMainThreadGroup());
2246   soa.Self()->AssertNoPendingException();
2247 
2248   runtime->RunRootClinits(soa.Self());
2249 
2250   // The thread counts as started from now on. We need to add it to the ThreadGroup. For regular
2251   // threads, this is done in Thread.start() on the Java side.
2252   soa.Self()->NotifyThreadGroup(soa, runtime->GetMainThreadGroup());
2253   soa.Self()->AssertNoPendingException();
2254 }
2255 
Shutdown()2256 void Thread::Shutdown() {
2257   CHECK(is_started_);
2258   is_started_ = false;
2259   CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
2260   MutexLock mu(Thread::Current(), *Locks::thread_suspend_count_lock_);
2261   if (resume_cond_ != nullptr) {
2262     delete resume_cond_;
2263     resume_cond_ = nullptr;
2264   }
2265 }
2266 
NotifyThreadGroup(ScopedObjectAccessAlreadyRunnable & soa,jobject thread_group)2267 void Thread::NotifyThreadGroup(ScopedObjectAccessAlreadyRunnable& soa, jobject thread_group) {
2268   ScopedLocalRef<jobject> thread_jobject(
2269       soa.Env(), soa.Env()->AddLocalReference<jobject>(Thread::Current()->GetPeer()));
2270   ScopedLocalRef<jobject> thread_group_jobject_scoped(
2271       soa.Env(), nullptr);
2272   jobject thread_group_jobject = thread_group;
2273   if (thread_group == nullptr || kIsDebugBuild) {
2274     // There is always a group set. Retrieve it.
2275     thread_group_jobject_scoped.reset(
2276         soa.Env()->GetObjectField(thread_jobject.get(),
2277                                   WellKnownClasses::java_lang_Thread_group));
2278     thread_group_jobject = thread_group_jobject_scoped.get();
2279     if (kIsDebugBuild && thread_group != nullptr) {
2280       CHECK(soa.Env()->IsSameObject(thread_group, thread_group_jobject));
2281     }
2282   }
2283   soa.Env()->CallNonvirtualVoidMethod(thread_group_jobject,
2284                                       WellKnownClasses::java_lang_ThreadGroup,
2285                                       WellKnownClasses::java_lang_ThreadGroup_add,
2286                                       thread_jobject.get());
2287 }
2288 
Thread(bool daemon)2289 Thread::Thread(bool daemon)
2290     : tls32_(daemon),
2291       wait_monitor_(nullptr),
2292       is_runtime_thread_(false) {
2293   wait_mutex_ = new Mutex("a thread wait mutex", LockLevel::kThreadWaitLock);
2294   wait_cond_ = new ConditionVariable("a thread wait condition variable", *wait_mutex_);
2295   tlsPtr_.instrumentation_stack =
2296       new std::map<uintptr_t, instrumentation::InstrumentationStackFrame>;
2297   tlsPtr_.name = new std::string(kThreadNameDuringStartup);
2298 
2299   static_assert((sizeof(Thread) % 4) == 0U,
2300                 "art::Thread has a size which is not a multiple of 4.");
2301   tls32_.state_and_flags.as_struct.flags = 0;
2302   tls32_.state_and_flags.as_struct.state = kNative;
2303   tls32_.interrupted.store(false, std::memory_order_relaxed);
2304   // Initialize with no permit; if the java Thread was unparked before being
2305   // started, it will unpark itself before calling into java code.
2306   tls32_.park_state_.store(kNoPermit, std::memory_order_relaxed);
2307   memset(&tlsPtr_.held_mutexes[0], 0, sizeof(tlsPtr_.held_mutexes));
2308   std::fill(tlsPtr_.rosalloc_runs,
2309             tlsPtr_.rosalloc_runs + kNumRosAllocThreadLocalSizeBracketsInThread,
2310             gc::allocator::RosAlloc::GetDedicatedFullRun());
2311   tlsPtr_.checkpoint_function = nullptr;
2312   for (uint32_t i = 0; i < kMaxSuspendBarriers; ++i) {
2313     tlsPtr_.active_suspend_barriers[i] = nullptr;
2314   }
2315   tlsPtr_.flip_function = nullptr;
2316   tlsPtr_.thread_local_mark_stack = nullptr;
2317   tls32_.is_transitioning_to_runnable = false;
2318   tls32_.use_mterp = false;
2319   ResetTlab();
2320 }
2321 
NotifyInTheadList()2322 void Thread::NotifyInTheadList() {
2323   tls32_.use_mterp = interpreter::CanUseMterp();
2324 }
2325 
CanLoadClasses() const2326 bool Thread::CanLoadClasses() const {
2327   return !IsRuntimeThread() || !Runtime::Current()->IsJavaDebuggable();
2328 }
2329 
IsStillStarting() const2330 bool Thread::IsStillStarting() const {
2331   // You might think you can check whether the state is kStarting, but for much of thread startup,
2332   // the thread is in kNative; it might also be in kVmWait.
2333   // You might think you can check whether the peer is null, but the peer is actually created and
2334   // assigned fairly early on, and needs to be.
2335   // It turns out that the last thing to change is the thread name; that's a good proxy for "has
2336   // this thread _ever_ entered kRunnable".
2337   return (tlsPtr_.jpeer == nullptr && tlsPtr_.opeer == nullptr) ||
2338       (*tlsPtr_.name == kThreadNameDuringStartup);
2339 }
2340 
AssertPendingException() const2341 void Thread::AssertPendingException() const {
2342   CHECK(IsExceptionPending()) << "Pending exception expected.";
2343 }
2344 
AssertPendingOOMException() const2345 void Thread::AssertPendingOOMException() const {
2346   AssertPendingException();
2347   auto* e = GetException();
2348   CHECK_EQ(e->GetClass(), DecodeJObject(WellKnownClasses::java_lang_OutOfMemoryError)->AsClass())
2349       << e->Dump();
2350 }
2351 
AssertNoPendingException() const2352 void Thread::AssertNoPendingException() const {
2353   if (UNLIKELY(IsExceptionPending())) {
2354     ScopedObjectAccess soa(Thread::Current());
2355     LOG(FATAL) << "No pending exception expected: " << GetException()->Dump();
2356   }
2357 }
2358 
AssertNoPendingExceptionForNewException(const char * msg) const2359 void Thread::AssertNoPendingExceptionForNewException(const char* msg) const {
2360   if (UNLIKELY(IsExceptionPending())) {
2361     ScopedObjectAccess soa(Thread::Current());
2362     LOG(FATAL) << "Throwing new exception '" << msg << "' with unexpected pending exception: "
2363         << GetException()->Dump();
2364   }
2365 }
2366 
2367 class MonitorExitVisitor : public SingleRootVisitor {
2368  public:
MonitorExitVisitor(Thread * self)2369   explicit MonitorExitVisitor(Thread* self) : self_(self) { }
2370 
2371   // NO_THREAD_SAFETY_ANALYSIS due to MonitorExit.
VisitRoot(mirror::Object * entered_monitor,const RootInfo & info ATTRIBUTE_UNUSED)2372   void VisitRoot(mirror::Object* entered_monitor, const RootInfo& info ATTRIBUTE_UNUSED)
2373       override NO_THREAD_SAFETY_ANALYSIS {
2374     if (self_->HoldsLock(entered_monitor)) {
2375       LOG(WARNING) << "Calling MonitorExit on object "
2376                    << entered_monitor << " (" << entered_monitor->PrettyTypeOf() << ")"
2377                    << " left locked by native thread "
2378                    << *Thread::Current() << " which is detaching";
2379       entered_monitor->MonitorExit(self_);
2380     }
2381   }
2382 
2383  private:
2384   Thread* const self_;
2385 };
2386 
Destroy()2387 void Thread::Destroy() {
2388   Thread* self = this;
2389   DCHECK_EQ(self, Thread::Current());
2390 
2391   if (tlsPtr_.jni_env != nullptr) {
2392     {
2393       ScopedObjectAccess soa(self);
2394       MonitorExitVisitor visitor(self);
2395       // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
2396       tlsPtr_.jni_env->monitors_.VisitRoots(&visitor, RootInfo(kRootVMInternal));
2397     }
2398     // Release locally held global references which releasing may require the mutator lock.
2399     if (tlsPtr_.jpeer != nullptr) {
2400       // If pthread_create fails we don't have a jni env here.
2401       tlsPtr_.jni_env->DeleteGlobalRef(tlsPtr_.jpeer);
2402       tlsPtr_.jpeer = nullptr;
2403     }
2404     if (tlsPtr_.class_loader_override != nullptr) {
2405       tlsPtr_.jni_env->DeleteGlobalRef(tlsPtr_.class_loader_override);
2406       tlsPtr_.class_loader_override = nullptr;
2407     }
2408   }
2409 
2410   if (tlsPtr_.opeer != nullptr) {
2411     ScopedObjectAccess soa(self);
2412     // We may need to call user-supplied managed code, do this before final clean-up.
2413     HandleUncaughtExceptions(soa);
2414     RemoveFromThreadGroup(soa);
2415     Runtime* runtime = Runtime::Current();
2416     if (runtime != nullptr) {
2417       runtime->GetRuntimeCallbacks()->ThreadDeath(self);
2418     }
2419 
2420     // this.nativePeer = 0;
2421     if (Runtime::Current()->IsActiveTransaction()) {
2422       jni::DecodeArtField(WellKnownClasses::java_lang_Thread_nativePeer)
2423           ->SetLong<true>(tlsPtr_.opeer, 0);
2424     } else {
2425       jni::DecodeArtField(WellKnownClasses::java_lang_Thread_nativePeer)
2426           ->SetLong<false>(tlsPtr_.opeer, 0);
2427     }
2428 
2429     // Thread.join() is implemented as an Object.wait() on the Thread.lock object. Signal anyone
2430     // who is waiting.
2431     ObjPtr<mirror::Object> lock =
2432         jni::DecodeArtField(WellKnownClasses::java_lang_Thread_lock)->GetObject(tlsPtr_.opeer);
2433     // (This conditional is only needed for tests, where Thread.lock won't have been set.)
2434     if (lock != nullptr) {
2435       StackHandleScope<1> hs(self);
2436       Handle<mirror::Object> h_obj(hs.NewHandle(lock));
2437       ObjectLock<mirror::Object> locker(self, h_obj);
2438       locker.NotifyAll();
2439     }
2440     tlsPtr_.opeer = nullptr;
2441   }
2442 
2443   {
2444     ScopedObjectAccess soa(self);
2445     Runtime::Current()->GetHeap()->RevokeThreadLocalBuffers(this);
2446   }
2447   // Mark-stack revocation must be performed at the very end. No
2448   // checkpoint/flip-function or read-barrier should be called after this.
2449   if (kUseReadBarrier) {
2450     Runtime::Current()->GetHeap()->ConcurrentCopyingCollector()->RevokeThreadLocalMarkStack(this);
2451   }
2452 }
2453 
~Thread()2454 Thread::~Thread() {
2455   CHECK(tlsPtr_.class_loader_override == nullptr);
2456   CHECK(tlsPtr_.jpeer == nullptr);
2457   CHECK(tlsPtr_.opeer == nullptr);
2458   bool initialized = (tlsPtr_.jni_env != nullptr);  // Did Thread::Init run?
2459   if (initialized) {
2460     delete tlsPtr_.jni_env;
2461     tlsPtr_.jni_env = nullptr;
2462   }
2463   CHECK_NE(GetState(), kRunnable);
2464   CHECK(!ReadFlag(kCheckpointRequest));
2465   CHECK(!ReadFlag(kEmptyCheckpointRequest));
2466   CHECK(tlsPtr_.checkpoint_function == nullptr);
2467   CHECK_EQ(checkpoint_overflow_.size(), 0u);
2468   CHECK(tlsPtr_.flip_function == nullptr);
2469   CHECK_EQ(tls32_.is_transitioning_to_runnable, false);
2470 
2471   // Make sure we processed all deoptimization requests.
2472   CHECK(tlsPtr_.deoptimization_context_stack == nullptr) << "Missed deoptimization";
2473   CHECK(tlsPtr_.frame_id_to_shadow_frame == nullptr) <<
2474       "Not all deoptimized frames have been consumed by the debugger.";
2475 
2476   // We may be deleting a still born thread.
2477   SetStateUnsafe(kTerminated);
2478 
2479   delete wait_cond_;
2480   delete wait_mutex_;
2481 
2482   if (tlsPtr_.long_jump_context != nullptr) {
2483     delete tlsPtr_.long_jump_context;
2484   }
2485 
2486   if (initialized) {
2487     CleanupCpu();
2488   }
2489 
2490   delete tlsPtr_.instrumentation_stack;
2491   delete tlsPtr_.name;
2492   delete tlsPtr_.deps_or_stack_trace_sample.stack_trace_sample;
2493 
2494   Runtime::Current()->GetHeap()->AssertThreadLocalBuffersAreRevoked(this);
2495 
2496   TearDownAlternateSignalStack();
2497 }
2498 
HandleUncaughtExceptions(ScopedObjectAccessAlreadyRunnable & soa)2499 void Thread::HandleUncaughtExceptions(ScopedObjectAccessAlreadyRunnable& soa) {
2500   if (!IsExceptionPending()) {
2501     return;
2502   }
2503   ScopedLocalRef<jobject> peer(tlsPtr_.jni_env, soa.AddLocalReference<jobject>(tlsPtr_.opeer));
2504   ScopedThreadStateChange tsc(this, kNative);
2505 
2506   // Get and clear the exception.
2507   ScopedLocalRef<jthrowable> exception(tlsPtr_.jni_env, tlsPtr_.jni_env->ExceptionOccurred());
2508   tlsPtr_.jni_env->ExceptionClear();
2509 
2510   // Call the Thread instance's dispatchUncaughtException(Throwable)
2511   tlsPtr_.jni_env->CallVoidMethod(peer.get(),
2512       WellKnownClasses::java_lang_Thread_dispatchUncaughtException,
2513       exception.get());
2514 
2515   // If the dispatchUncaughtException threw, clear that exception too.
2516   tlsPtr_.jni_env->ExceptionClear();
2517 }
2518 
RemoveFromThreadGroup(ScopedObjectAccessAlreadyRunnable & soa)2519 void Thread::RemoveFromThreadGroup(ScopedObjectAccessAlreadyRunnable& soa) {
2520   // this.group.removeThread(this);
2521   // group can be null if we're in the compiler or a test.
2522   ObjPtr<mirror::Object> ogroup = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group)
2523       ->GetObject(tlsPtr_.opeer);
2524   if (ogroup != nullptr) {
2525     ScopedLocalRef<jobject> group(soa.Env(), soa.AddLocalReference<jobject>(ogroup));
2526     ScopedLocalRef<jobject> peer(soa.Env(), soa.AddLocalReference<jobject>(tlsPtr_.opeer));
2527     ScopedThreadStateChange tsc(soa.Self(), kNative);
2528     tlsPtr_.jni_env->CallVoidMethod(group.get(),
2529                                     WellKnownClasses::java_lang_ThreadGroup_removeThread,
2530                                     peer.get());
2531   }
2532 }
2533 
HandleScopeContains(jobject obj) const2534 bool Thread::HandleScopeContains(jobject obj) const {
2535   StackReference<mirror::Object>* hs_entry =
2536       reinterpret_cast<StackReference<mirror::Object>*>(obj);
2537   for (BaseHandleScope* cur = tlsPtr_.top_handle_scope; cur!= nullptr; cur = cur->GetLink()) {
2538     if (cur->Contains(hs_entry)) {
2539       return true;
2540     }
2541   }
2542   // JNI code invoked from portable code uses shadow frames rather than the handle scope.
2543   return tlsPtr_.managed_stack.ShadowFramesContain(hs_entry);
2544 }
2545 
HandleScopeVisitRoots(RootVisitor * visitor,pid_t thread_id)2546 void Thread::HandleScopeVisitRoots(RootVisitor* visitor, pid_t thread_id) {
2547   BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(
2548       visitor, RootInfo(kRootNativeStack, thread_id));
2549   for (BaseHandleScope* cur = tlsPtr_.top_handle_scope; cur; cur = cur->GetLink()) {
2550     cur->VisitRoots(buffered_visitor);
2551   }
2552 }
2553 
DecodeJObject(jobject obj) const2554 ObjPtr<mirror::Object> Thread::DecodeJObject(jobject obj) const {
2555   if (obj == nullptr) {
2556     return nullptr;
2557   }
2558   IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
2559   IndirectRefKind kind = IndirectReferenceTable::GetIndirectRefKind(ref);
2560   ObjPtr<mirror::Object> result;
2561   bool expect_null = false;
2562   // The "kinds" below are sorted by the frequency we expect to encounter them.
2563   if (kind == kLocal) {
2564     IndirectReferenceTable& locals = tlsPtr_.jni_env->locals_;
2565     // Local references do not need a read barrier.
2566     result = locals.Get<kWithoutReadBarrier>(ref);
2567   } else if (kind == kHandleScopeOrInvalid) {
2568     // TODO: make stack indirect reference table lookup more efficient.
2569     // Check if this is a local reference in the handle scope.
2570     if (LIKELY(HandleScopeContains(obj))) {
2571       // Read from handle scope.
2572       result = reinterpret_cast<StackReference<mirror::Object>*>(obj)->AsMirrorPtr();
2573       VerifyObject(result);
2574     } else {
2575       tlsPtr_.jni_env->vm_->JniAbortF(nullptr, "use of invalid jobject %p", obj);
2576       expect_null = true;
2577       result = nullptr;
2578     }
2579   } else if (kind == kGlobal) {
2580     result = tlsPtr_.jni_env->vm_->DecodeGlobal(ref);
2581   } else {
2582     DCHECK_EQ(kind, kWeakGlobal);
2583     result = tlsPtr_.jni_env->vm_->DecodeWeakGlobal(const_cast<Thread*>(this), ref);
2584     if (Runtime::Current()->IsClearedJniWeakGlobal(result)) {
2585       // This is a special case where it's okay to return null.
2586       expect_null = true;
2587       result = nullptr;
2588     }
2589   }
2590 
2591   if (UNLIKELY(!expect_null && result == nullptr)) {
2592     tlsPtr_.jni_env->vm_->JniAbortF(nullptr, "use of deleted %s %p",
2593                                    ToStr<IndirectRefKind>(kind).c_str(), obj);
2594   }
2595   return result;
2596 }
2597 
IsJWeakCleared(jweak obj) const2598 bool Thread::IsJWeakCleared(jweak obj) const {
2599   CHECK(obj != nullptr);
2600   IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
2601   IndirectRefKind kind = IndirectReferenceTable::GetIndirectRefKind(ref);
2602   CHECK_EQ(kind, kWeakGlobal);
2603   return tlsPtr_.jni_env->vm_->IsWeakGlobalCleared(const_cast<Thread*>(this), ref);
2604 }
2605 
2606 // Implements java.lang.Thread.interrupted.
Interrupted()2607 bool Thread::Interrupted() {
2608   DCHECK_EQ(Thread::Current(), this);
2609   // No other thread can concurrently reset the interrupted flag.
2610   bool interrupted = tls32_.interrupted.load(std::memory_order_seq_cst);
2611   if (interrupted) {
2612     tls32_.interrupted.store(false, std::memory_order_seq_cst);
2613   }
2614   return interrupted;
2615 }
2616 
2617 // Implements java.lang.Thread.isInterrupted.
IsInterrupted()2618 bool Thread::IsInterrupted() {
2619   return tls32_.interrupted.load(std::memory_order_seq_cst);
2620 }
2621 
Interrupt(Thread * self)2622 void Thread::Interrupt(Thread* self) {
2623   {
2624     MutexLock mu(self, *wait_mutex_);
2625     if (tls32_.interrupted.load(std::memory_order_seq_cst)) {
2626       return;
2627     }
2628     tls32_.interrupted.store(true, std::memory_order_seq_cst);
2629     NotifyLocked(self);
2630   }
2631   Unpark();
2632 }
2633 
Notify()2634 void Thread::Notify() {
2635   Thread* self = Thread::Current();
2636   MutexLock mu(self, *wait_mutex_);
2637   NotifyLocked(self);
2638 }
2639 
NotifyLocked(Thread * self)2640 void Thread::NotifyLocked(Thread* self) {
2641   if (wait_monitor_ != nullptr) {
2642     wait_cond_->Signal(self);
2643   }
2644 }
2645 
SetClassLoaderOverride(jobject class_loader_override)2646 void Thread::SetClassLoaderOverride(jobject class_loader_override) {
2647   if (tlsPtr_.class_loader_override != nullptr) {
2648     GetJniEnv()->DeleteGlobalRef(tlsPtr_.class_loader_override);
2649   }
2650   tlsPtr_.class_loader_override = GetJniEnv()->NewGlobalRef(class_loader_override);
2651 }
2652 
2653 using ArtMethodDexPcPair = std::pair<ArtMethod*, uint32_t>;
2654 
2655 // Counts the stack trace depth and also fetches the first max_saved_frames frames.
2656 class FetchStackTraceVisitor : public StackVisitor {
2657  public:
FetchStackTraceVisitor(Thread * thread,ArtMethodDexPcPair * saved_frames=nullptr,size_t max_saved_frames=0)2658   explicit FetchStackTraceVisitor(Thread* thread,
2659                                   ArtMethodDexPcPair* saved_frames = nullptr,
2660                                   size_t max_saved_frames = 0)
2661       REQUIRES_SHARED(Locks::mutator_lock_)
2662       : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2663         saved_frames_(saved_frames),
2664         max_saved_frames_(max_saved_frames) {}
2665 
VisitFrame()2666   bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
2667     // We want to skip frames up to and including the exception's constructor.
2668     // Note we also skip the frame if it doesn't have a method (namely the callee
2669     // save frame)
2670     ArtMethod* m = GetMethod();
2671     if (skipping_ && !m->IsRuntimeMethod() &&
2672         !GetClassRoot<mirror::Throwable>()->IsAssignableFrom(m->GetDeclaringClass())) {
2673       skipping_ = false;
2674     }
2675     if (!skipping_) {
2676       if (!m->IsRuntimeMethod()) {  // Ignore runtime frames (in particular callee save).
2677         if (depth_ < max_saved_frames_) {
2678           saved_frames_[depth_].first = m;
2679           saved_frames_[depth_].second = m->IsProxyMethod() ? dex::kDexNoIndex : GetDexPc();
2680         }
2681         ++depth_;
2682       }
2683     } else {
2684       ++skip_depth_;
2685     }
2686     return true;
2687   }
2688 
GetDepth() const2689   uint32_t GetDepth() const {
2690     return depth_;
2691   }
2692 
GetSkipDepth() const2693   uint32_t GetSkipDepth() const {
2694     return skip_depth_;
2695   }
2696 
2697  private:
2698   uint32_t depth_ = 0;
2699   uint32_t skip_depth_ = 0;
2700   bool skipping_ = true;
2701   ArtMethodDexPcPair* saved_frames_;
2702   const size_t max_saved_frames_;
2703 
2704   DISALLOW_COPY_AND_ASSIGN(FetchStackTraceVisitor);
2705 };
2706 
2707 class BuildInternalStackTraceVisitor : public StackVisitor {
2708  public:
BuildInternalStackTraceVisitor(Thread * self,Thread * thread,int skip_depth)2709   BuildInternalStackTraceVisitor(Thread* self, Thread* thread, int skip_depth)
2710       : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2711         self_(self),
2712         skip_depth_(skip_depth),
2713         pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()) {}
2714 
Init(int depth)2715   bool Init(int depth) REQUIRES_SHARED(Locks::mutator_lock_) ACQUIRE(Roles::uninterruptible_) {
2716     // Allocate method trace as an object array where the first element is a pointer array that
2717     // contains the ArtMethod pointers and dex PCs. The rest of the elements are the declaring
2718     // class of the ArtMethod pointers.
2719     ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2720     StackHandleScope<1> hs(self_);
2721     ObjPtr<mirror::Class> array_class =
2722         GetClassRoot<mirror::ObjectArray<mirror::Object>>(class_linker);
2723     // The first element is the methods and dex pc array, the other elements are declaring classes
2724     // for the methods to ensure classes in the stack trace don't get unloaded.
2725     Handle<mirror::ObjectArray<mirror::Object>> trace(
2726         hs.NewHandle(
2727             mirror::ObjectArray<mirror::Object>::Alloc(hs.Self(), array_class, depth + 1)));
2728     if (trace == nullptr) {
2729       // Acquire uninterruptible_ in all paths.
2730       self_->StartAssertNoThreadSuspension("Building internal stack trace");
2731       self_->AssertPendingOOMException();
2732       return false;
2733     }
2734     ObjPtr<mirror::PointerArray> methods_and_pcs =
2735         class_linker->AllocPointerArray(self_, depth * 2);
2736     const char* last_no_suspend_cause =
2737         self_->StartAssertNoThreadSuspension("Building internal stack trace");
2738     if (methods_and_pcs == nullptr) {
2739       self_->AssertPendingOOMException();
2740       return false;
2741     }
2742     trace->Set</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(0, methods_and_pcs);
2743     trace_ = trace.Get();
2744     // If We are called from native, use non-transactional mode.
2745     CHECK(last_no_suspend_cause == nullptr) << last_no_suspend_cause;
2746     return true;
2747   }
2748 
RELEASE(Roles::uninterruptible_)2749   virtual ~BuildInternalStackTraceVisitor() RELEASE(Roles::uninterruptible_) {
2750     self_->EndAssertNoThreadSuspension(nullptr);
2751   }
2752 
VisitFrame()2753   bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
2754     if (trace_ == nullptr) {
2755       return true;  // We're probably trying to fillInStackTrace for an OutOfMemoryError.
2756     }
2757     if (skip_depth_ > 0) {
2758       skip_depth_--;
2759       return true;
2760     }
2761     ArtMethod* m = GetMethod();
2762     if (m->IsRuntimeMethod()) {
2763       return true;  // Ignore runtime frames (in particular callee save).
2764     }
2765     AddFrame(m, m->IsProxyMethod() ? dex::kDexNoIndex : GetDexPc());
2766     return true;
2767   }
2768 
AddFrame(ArtMethod * method,uint32_t dex_pc)2769   void AddFrame(ArtMethod* method, uint32_t dex_pc) REQUIRES_SHARED(Locks::mutator_lock_) {
2770     ObjPtr<mirror::PointerArray> methods_and_pcs = GetTraceMethodsAndPCs();
2771     methods_and_pcs->SetElementPtrSize</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
2772         count_, method, pointer_size_);
2773     methods_and_pcs->SetElementPtrSize</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
2774         methods_and_pcs->GetLength() / 2 + count_, dex_pc, pointer_size_);
2775     // Save the declaring class of the method to ensure that the declaring classes of the methods
2776     // do not get unloaded while the stack trace is live.
2777     trace_->Set</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
2778         count_ + 1, method->GetDeclaringClass());
2779     ++count_;
2780   }
2781 
GetTraceMethodsAndPCs() const2782   ObjPtr<mirror::PointerArray> GetTraceMethodsAndPCs() const REQUIRES_SHARED(Locks::mutator_lock_) {
2783     return ObjPtr<mirror::PointerArray>::DownCast(trace_->Get(0));
2784   }
2785 
GetInternalStackTrace() const2786   mirror::ObjectArray<mirror::Object>* GetInternalStackTrace() const {
2787     return trace_;
2788   }
2789 
2790  private:
2791   Thread* const self_;
2792   // How many more frames to skip.
2793   int32_t skip_depth_;
2794   // Current position down stack trace.
2795   uint32_t count_ = 0;
2796   // An object array where the first element is a pointer array that contains the ArtMethod
2797   // pointers on the stack and dex PCs. The rest of the elements are the declaring class of
2798   // the ArtMethod pointers. trace_[i+1] contains the declaring class of the ArtMethod of the
2799   // i'th frame. We're initializing a newly allocated trace, so we do not need to record that
2800   // under a transaction. If the transaction is aborted, the whole trace shall be unreachable.
2801   mirror::ObjectArray<mirror::Object>* trace_ = nullptr;
2802   // For cross compilation.
2803   const PointerSize pointer_size_;
2804 
2805   DISALLOW_COPY_AND_ASSIGN(BuildInternalStackTraceVisitor);
2806 };
2807 
CreateInternalStackTrace(const ScopedObjectAccessAlreadyRunnable & soa) const2808 jobject Thread::CreateInternalStackTrace(const ScopedObjectAccessAlreadyRunnable& soa) const {
2809   // Compute depth of stack, save frames if possible to avoid needing to recompute many.
2810   constexpr size_t kMaxSavedFrames = 256;
2811   std::unique_ptr<ArtMethodDexPcPair[]> saved_frames(new ArtMethodDexPcPair[kMaxSavedFrames]);
2812   FetchStackTraceVisitor count_visitor(const_cast<Thread*>(this),
2813                                        &saved_frames[0],
2814                                        kMaxSavedFrames);
2815   count_visitor.WalkStack();
2816   const uint32_t depth = count_visitor.GetDepth();
2817   const uint32_t skip_depth = count_visitor.GetSkipDepth();
2818 
2819   // Build internal stack trace.
2820   BuildInternalStackTraceVisitor build_trace_visitor(
2821       soa.Self(), const_cast<Thread*>(this), skip_depth);
2822   if (!build_trace_visitor.Init(depth)) {
2823     return nullptr;  // Allocation failed.
2824   }
2825   // If we saved all of the frames we don't even need to do the actual stack walk. This is faster
2826   // than doing the stack walk twice.
2827   if (depth < kMaxSavedFrames) {
2828     for (size_t i = 0; i < depth; ++i) {
2829       build_trace_visitor.AddFrame(saved_frames[i].first, saved_frames[i].second);
2830     }
2831   } else {
2832     build_trace_visitor.WalkStack();
2833   }
2834 
2835   mirror::ObjectArray<mirror::Object>* trace = build_trace_visitor.GetInternalStackTrace();
2836   if (kIsDebugBuild) {
2837     ObjPtr<mirror::PointerArray> trace_methods = build_trace_visitor.GetTraceMethodsAndPCs();
2838     // Second half of trace_methods is dex PCs.
2839     for (uint32_t i = 0; i < static_cast<uint32_t>(trace_methods->GetLength() / 2); ++i) {
2840       auto* method = trace_methods->GetElementPtrSize<ArtMethod*>(
2841           i, Runtime::Current()->GetClassLinker()->GetImagePointerSize());
2842       CHECK(method != nullptr);
2843     }
2844   }
2845   return soa.AddLocalReference<jobject>(trace);
2846 }
2847 
IsExceptionThrownByCurrentMethod(ObjPtr<mirror::Throwable> exception) const2848 bool Thread::IsExceptionThrownByCurrentMethod(ObjPtr<mirror::Throwable> exception) const {
2849   // Only count the depth since we do not pass a stack frame array as an argument.
2850   FetchStackTraceVisitor count_visitor(const_cast<Thread*>(this));
2851   count_visitor.WalkStack();
2852   return count_visitor.GetDepth() == static_cast<uint32_t>(exception->GetStackDepth());
2853 }
2854 
CreateStackTraceElement(const ScopedObjectAccessAlreadyRunnable & soa,ArtMethod * method,uint32_t dex_pc)2855 static ObjPtr<mirror::StackTraceElement> CreateStackTraceElement(
2856     const ScopedObjectAccessAlreadyRunnable& soa,
2857     ArtMethod* method,
2858     uint32_t dex_pc) REQUIRES_SHARED(Locks::mutator_lock_) {
2859   int32_t line_number;
2860   StackHandleScope<3> hs(soa.Self());
2861   auto class_name_object(hs.NewHandle<mirror::String>(nullptr));
2862   auto source_name_object(hs.NewHandle<mirror::String>(nullptr));
2863   if (method->IsProxyMethod()) {
2864     line_number = -1;
2865     class_name_object.Assign(method->GetDeclaringClass()->GetName());
2866     // source_name_object intentionally left null for proxy methods
2867   } else {
2868     line_number = method->GetLineNumFromDexPC(dex_pc);
2869     // Allocate element, potentially triggering GC
2870     // TODO: reuse class_name_object via Class::name_?
2871     const char* descriptor = method->GetDeclaringClassDescriptor();
2872     CHECK(descriptor != nullptr);
2873     std::string class_name(PrettyDescriptor(descriptor));
2874     class_name_object.Assign(
2875         mirror::String::AllocFromModifiedUtf8(soa.Self(), class_name.c_str()));
2876     if (class_name_object == nullptr) {
2877       soa.Self()->AssertPendingOOMException();
2878       return nullptr;
2879     }
2880     const char* source_file = method->GetDeclaringClassSourceFile();
2881     if (line_number == -1) {
2882       // Make the line_number field of StackTraceElement hold the dex pc.
2883       // source_name_object is intentionally left null if we failed to map the dex pc to
2884       // a line number (most probably because there is no debug info). See b/30183883.
2885       line_number = dex_pc;
2886     } else {
2887       if (source_file != nullptr) {
2888         source_name_object.Assign(mirror::String::AllocFromModifiedUtf8(soa.Self(), source_file));
2889         if (source_name_object == nullptr) {
2890           soa.Self()->AssertPendingOOMException();
2891           return nullptr;
2892         }
2893       }
2894     }
2895   }
2896   const char* method_name = method->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName();
2897   CHECK(method_name != nullptr);
2898   Handle<mirror::String> method_name_object(
2899       hs.NewHandle(mirror::String::AllocFromModifiedUtf8(soa.Self(), method_name)));
2900   if (method_name_object == nullptr) {
2901     return nullptr;
2902   }
2903   return mirror::StackTraceElement::Alloc(soa.Self(),
2904                                           class_name_object,
2905                                           method_name_object,
2906                                           source_name_object,
2907                                           line_number);
2908 }
2909 
InternalStackTraceToStackTraceElementArray(const ScopedObjectAccessAlreadyRunnable & soa,jobject internal,jobjectArray output_array,int * stack_depth)2910 jobjectArray Thread::InternalStackTraceToStackTraceElementArray(
2911     const ScopedObjectAccessAlreadyRunnable& soa,
2912     jobject internal,
2913     jobjectArray output_array,
2914     int* stack_depth) {
2915   // Decode the internal stack trace into the depth, method trace and PC trace.
2916   // Subtract one for the methods and PC trace.
2917   int32_t depth = soa.Decode<mirror::Array>(internal)->GetLength() - 1;
2918   DCHECK_GE(depth, 0);
2919 
2920   ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
2921 
2922   jobjectArray result;
2923 
2924   if (output_array != nullptr) {
2925     // Reuse the array we were given.
2926     result = output_array;
2927     // ...adjusting the number of frames we'll write to not exceed the array length.
2928     const int32_t traces_length =
2929         soa.Decode<mirror::ObjectArray<mirror::StackTraceElement>>(result)->GetLength();
2930     depth = std::min(depth, traces_length);
2931   } else {
2932     // Create java_trace array and place in local reference table
2933     ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> java_traces =
2934         class_linker->AllocStackTraceElementArray(soa.Self(), depth);
2935     if (java_traces == nullptr) {
2936       return nullptr;
2937     }
2938     result = soa.AddLocalReference<jobjectArray>(java_traces);
2939   }
2940 
2941   if (stack_depth != nullptr) {
2942     *stack_depth = depth;
2943   }
2944 
2945   for (int32_t i = 0; i < depth; ++i) {
2946     ObjPtr<mirror::ObjectArray<mirror::Object>> decoded_traces =
2947         soa.Decode<mirror::Object>(internal)->AsObjectArray<mirror::Object>();
2948     // Methods and dex PC trace is element 0.
2949     DCHECK(decoded_traces->Get(0)->IsIntArray() || decoded_traces->Get(0)->IsLongArray());
2950     const ObjPtr<mirror::PointerArray> method_trace =
2951         ObjPtr<mirror::PointerArray>::DownCast(decoded_traces->Get(0));
2952     // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
2953     ArtMethod* method = method_trace->GetElementPtrSize<ArtMethod*>(i, kRuntimePointerSize);
2954     uint32_t dex_pc = method_trace->GetElementPtrSize<uint32_t>(
2955         i + method_trace->GetLength() / 2, kRuntimePointerSize);
2956     const ObjPtr<mirror::StackTraceElement> obj = CreateStackTraceElement(soa, method, dex_pc);
2957     if (obj == nullptr) {
2958       return nullptr;
2959     }
2960     // We are called from native: use non-transactional mode.
2961     soa.Decode<mirror::ObjectArray<mirror::StackTraceElement>>(result)->Set<false>(i, obj);
2962   }
2963   return result;
2964 }
2965 
CreateAnnotatedStackTrace(const ScopedObjectAccessAlreadyRunnable & soa) const2966 jobjectArray Thread::CreateAnnotatedStackTrace(const ScopedObjectAccessAlreadyRunnable& soa) const {
2967   // This code allocates. Do not allow it to operate with a pending exception.
2968   if (IsExceptionPending()) {
2969     return nullptr;
2970   }
2971 
2972   // If flip_function is not null, it means we have run a checkpoint
2973   // before the thread wakes up to execute the flip function and the
2974   // thread roots haven't been forwarded.  So the following access to
2975   // the roots (locks or methods in the frames) would be bad. Run it
2976   // here. TODO: clean up.
2977   // Note: copied from DumpJavaStack.
2978   {
2979     Thread* this_thread = const_cast<Thread*>(this);
2980     Closure* flip_func = this_thread->GetFlipFunction();
2981     if (flip_func != nullptr) {
2982       flip_func->Run(this_thread);
2983     }
2984   }
2985 
2986   class CollectFramesAndLocksStackVisitor : public MonitorObjectsStackVisitor {
2987    public:
2988     CollectFramesAndLocksStackVisitor(const ScopedObjectAccessAlreadyRunnable& soaa_in,
2989                                       Thread* self,
2990                                       Context* context)
2991         : MonitorObjectsStackVisitor(self, context),
2992           wait_jobject_(soaa_in.Env(), nullptr),
2993           block_jobject_(soaa_in.Env(), nullptr),
2994           soaa_(soaa_in) {}
2995 
2996    protected:
2997     VisitMethodResult StartMethod(ArtMethod* m, size_t frame_nr ATTRIBUTE_UNUSED)
2998         override
2999         REQUIRES_SHARED(Locks::mutator_lock_) {
3000       ObjPtr<mirror::StackTraceElement> obj = CreateStackTraceElement(
3001           soaa_, m, GetDexPc(/* abort on error */ false));
3002       if (obj == nullptr) {
3003         return VisitMethodResult::kEndStackWalk;
3004       }
3005       stack_trace_elements_.emplace_back(soaa_.Env(), soaa_.AddLocalReference<jobject>(obj.Ptr()));
3006       return VisitMethodResult::kContinueMethod;
3007     }
3008 
3009     VisitMethodResult EndMethod(ArtMethod* m ATTRIBUTE_UNUSED) override {
3010       lock_objects_.push_back({});
3011       lock_objects_[lock_objects_.size() - 1].swap(frame_lock_objects_);
3012 
3013       DCHECK_EQ(lock_objects_.size(), stack_trace_elements_.size());
3014 
3015       return VisitMethodResult::kContinueMethod;
3016     }
3017 
3018     void VisitWaitingObject(ObjPtr<mirror::Object> obj, ThreadState state ATTRIBUTE_UNUSED)
3019         override
3020         REQUIRES_SHARED(Locks::mutator_lock_) {
3021       wait_jobject_.reset(soaa_.AddLocalReference<jobject>(obj));
3022     }
3023     void VisitSleepingObject(ObjPtr<mirror::Object> obj)
3024         override
3025         REQUIRES_SHARED(Locks::mutator_lock_) {
3026       wait_jobject_.reset(soaa_.AddLocalReference<jobject>(obj));
3027     }
3028     void VisitBlockedOnObject(ObjPtr<mirror::Object> obj,
3029                               ThreadState state ATTRIBUTE_UNUSED,
3030                               uint32_t owner_tid ATTRIBUTE_UNUSED)
3031         override
3032         REQUIRES_SHARED(Locks::mutator_lock_) {
3033       block_jobject_.reset(soaa_.AddLocalReference<jobject>(obj));
3034     }
3035     void VisitLockedObject(ObjPtr<mirror::Object> obj)
3036         override
3037         REQUIRES_SHARED(Locks::mutator_lock_) {
3038       frame_lock_objects_.emplace_back(soaa_.Env(), soaa_.AddLocalReference<jobject>(obj));
3039     }
3040 
3041    public:
3042     std::vector<ScopedLocalRef<jobject>> stack_trace_elements_;
3043     ScopedLocalRef<jobject> wait_jobject_;
3044     ScopedLocalRef<jobject> block_jobject_;
3045     std::vector<std::vector<ScopedLocalRef<jobject>>> lock_objects_;
3046 
3047    private:
3048     const ScopedObjectAccessAlreadyRunnable& soaa_;
3049 
3050     std::vector<ScopedLocalRef<jobject>> frame_lock_objects_;
3051   };
3052 
3053   std::unique_ptr<Context> context(Context::Create());
3054   CollectFramesAndLocksStackVisitor dumper(soa, const_cast<Thread*>(this), context.get());
3055   dumper.WalkStack();
3056 
3057   // There should not be a pending exception. Otherwise, return with it pending.
3058   if (IsExceptionPending()) {
3059     return nullptr;
3060   }
3061 
3062   // Now go and create Java arrays.
3063 
3064   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
3065 
3066   StackHandleScope<6> hs(soa.Self());
3067   Handle<mirror::Class> h_aste_array_class = hs.NewHandle(class_linker->FindSystemClass(
3068       soa.Self(),
3069       "[Ldalvik/system/AnnotatedStackTraceElement;"));
3070   if (h_aste_array_class == nullptr) {
3071     return nullptr;
3072   }
3073   Handle<mirror::Class> h_aste_class = hs.NewHandle(h_aste_array_class->GetComponentType());
3074 
3075   Handle<mirror::Class> h_o_array_class =
3076       hs.NewHandle(GetClassRoot<mirror::ObjectArray<mirror::Object>>(class_linker));
3077   DCHECK(h_o_array_class != nullptr);  // Class roots must be already initialized.
3078 
3079 
3080   // Make sure the AnnotatedStackTraceElement.class is initialized, b/76208924 .
3081   class_linker->EnsureInitialized(soa.Self(),
3082                                   h_aste_class,
3083                                   /* can_init_fields= */ true,
3084                                   /* can_init_parents= */ true);
3085   if (soa.Self()->IsExceptionPending()) {
3086     // This should not fail in a healthy runtime.
3087     return nullptr;
3088   }
3089 
3090   ArtField* stack_trace_element_field = h_aste_class->FindField(
3091       soa.Self(), h_aste_class.Get(), "stackTraceElement", "Ljava/lang/StackTraceElement;");
3092   DCHECK(stack_trace_element_field != nullptr);
3093   ArtField* held_locks_field = h_aste_class->FindField(
3094         soa.Self(), h_aste_class.Get(), "heldLocks", "[Ljava/lang/Object;");
3095   DCHECK(held_locks_field != nullptr);
3096   ArtField* blocked_on_field = h_aste_class->FindField(
3097         soa.Self(), h_aste_class.Get(), "blockedOn", "Ljava/lang/Object;");
3098   DCHECK(blocked_on_field != nullptr);
3099 
3100   size_t length = dumper.stack_trace_elements_.size();
3101   ObjPtr<mirror::ObjectArray<mirror::Object>> array =
3102       mirror::ObjectArray<mirror::Object>::Alloc(soa.Self(), h_aste_array_class.Get(), length);
3103   if (array == nullptr) {
3104     soa.Self()->AssertPendingOOMException();
3105     return nullptr;
3106   }
3107 
3108   ScopedLocalRef<jobjectArray> result(soa.Env(), soa.Env()->AddLocalReference<jobjectArray>(array));
3109 
3110   MutableHandle<mirror::Object> handle(hs.NewHandle<mirror::Object>(nullptr));
3111   MutableHandle<mirror::ObjectArray<mirror::Object>> handle2(
3112       hs.NewHandle<mirror::ObjectArray<mirror::Object>>(nullptr));
3113   for (size_t i = 0; i != length; ++i) {
3114     handle.Assign(h_aste_class->AllocObject(soa.Self()));
3115     if (handle == nullptr) {
3116       soa.Self()->AssertPendingOOMException();
3117       return nullptr;
3118     }
3119 
3120     // Set stack trace element.
3121     stack_trace_element_field->SetObject<false>(
3122         handle.Get(), soa.Decode<mirror::Object>(dumper.stack_trace_elements_[i].get()));
3123 
3124     // Create locked-on array.
3125     if (!dumper.lock_objects_[i].empty()) {
3126       handle2.Assign(mirror::ObjectArray<mirror::Object>::Alloc(soa.Self(),
3127                                                                 h_o_array_class.Get(),
3128                                                                 dumper.lock_objects_[i].size()));
3129       if (handle2 == nullptr) {
3130         soa.Self()->AssertPendingOOMException();
3131         return nullptr;
3132       }
3133       int32_t j = 0;
3134       for (auto& scoped_local : dumper.lock_objects_[i]) {
3135         if (scoped_local == nullptr) {
3136           continue;
3137         }
3138         handle2->Set(j, soa.Decode<mirror::Object>(scoped_local.get()));
3139         DCHECK(!soa.Self()->IsExceptionPending());
3140         j++;
3141       }
3142       held_locks_field->SetObject<false>(handle.Get(), handle2.Get());
3143     }
3144 
3145     // Set blocked-on object.
3146     if (i == 0) {
3147       if (dumper.block_jobject_ != nullptr) {
3148         blocked_on_field->SetObject<false>(
3149             handle.Get(), soa.Decode<mirror::Object>(dumper.block_jobject_.get()));
3150       }
3151     }
3152 
3153     ScopedLocalRef<jobject> elem(soa.Env(), soa.AddLocalReference<jobject>(handle.Get()));
3154     soa.Env()->SetObjectArrayElement(result.get(), i, elem.get());
3155     DCHECK(!soa.Self()->IsExceptionPending());
3156   }
3157 
3158   return result.release();
3159 }
3160 
ThrowNewExceptionF(const char * exception_class_descriptor,const char * fmt,...)3161 void Thread::ThrowNewExceptionF(const char* exception_class_descriptor, const char* fmt, ...) {
3162   va_list args;
3163   va_start(args, fmt);
3164   ThrowNewExceptionV(exception_class_descriptor, fmt, args);
3165   va_end(args);
3166 }
3167 
ThrowNewExceptionV(const char * exception_class_descriptor,const char * fmt,va_list ap)3168 void Thread::ThrowNewExceptionV(const char* exception_class_descriptor,
3169                                 const char* fmt, va_list ap) {
3170   std::string msg;
3171   StringAppendV(&msg, fmt, ap);
3172   ThrowNewException(exception_class_descriptor, msg.c_str());
3173 }
3174 
ThrowNewException(const char * exception_class_descriptor,const char * msg)3175 void Thread::ThrowNewException(const char* exception_class_descriptor,
3176                                const char* msg) {
3177   // Callers should either clear or call ThrowNewWrappedException.
3178   AssertNoPendingExceptionForNewException(msg);
3179   ThrowNewWrappedException(exception_class_descriptor, msg);
3180 }
3181 
GetCurrentClassLoader(Thread * self)3182 static ObjPtr<mirror::ClassLoader> GetCurrentClassLoader(Thread* self)
3183     REQUIRES_SHARED(Locks::mutator_lock_) {
3184   ArtMethod* method = self->GetCurrentMethod(nullptr);
3185   return method != nullptr
3186       ? method->GetDeclaringClass()->GetClassLoader()
3187       : nullptr;
3188 }
3189 
ThrowNewWrappedException(const char * exception_class_descriptor,const char * msg)3190 void Thread::ThrowNewWrappedException(const char* exception_class_descriptor,
3191                                       const char* msg) {
3192   DCHECK_EQ(this, Thread::Current());
3193   ScopedObjectAccessUnchecked soa(this);
3194   StackHandleScope<3> hs(soa.Self());
3195   Handle<mirror::ClassLoader> class_loader(hs.NewHandle(GetCurrentClassLoader(soa.Self())));
3196   ScopedLocalRef<jobject> cause(GetJniEnv(), soa.AddLocalReference<jobject>(GetException()));
3197   ClearException();
3198   Runtime* runtime = Runtime::Current();
3199   auto* cl = runtime->GetClassLinker();
3200   Handle<mirror::Class> exception_class(
3201       hs.NewHandle(cl->FindClass(this, exception_class_descriptor, class_loader)));
3202   if (UNLIKELY(exception_class == nullptr)) {
3203     CHECK(IsExceptionPending());
3204     LOG(ERROR) << "No exception class " << PrettyDescriptor(exception_class_descriptor);
3205     return;
3206   }
3207 
3208   if (UNLIKELY(!runtime->GetClassLinker()->EnsureInitialized(soa.Self(), exception_class, true,
3209                                                              true))) {
3210     DCHECK(IsExceptionPending());
3211     return;
3212   }
3213   DCHECK(!runtime->IsStarted() || exception_class->IsThrowableClass());
3214   Handle<mirror::Throwable> exception(
3215       hs.NewHandle(ObjPtr<mirror::Throwable>::DownCast(exception_class->AllocObject(this))));
3216 
3217   // If we couldn't allocate the exception, throw the pre-allocated out of memory exception.
3218   if (exception == nullptr) {
3219     Dump(LOG_STREAM(WARNING));  // The pre-allocated OOME has no stack, so help out and log one.
3220     SetException(Runtime::Current()->GetPreAllocatedOutOfMemoryErrorWhenThrowingException());
3221     return;
3222   }
3223 
3224   // Choose an appropriate constructor and set up the arguments.
3225   const char* signature;
3226   ScopedLocalRef<jstring> msg_string(GetJniEnv(), nullptr);
3227   if (msg != nullptr) {
3228     // Ensure we remember this and the method over the String allocation.
3229     msg_string.reset(
3230         soa.AddLocalReference<jstring>(mirror::String::AllocFromModifiedUtf8(this, msg)));
3231     if (UNLIKELY(msg_string.get() == nullptr)) {
3232       CHECK(IsExceptionPending());  // OOME.
3233       return;
3234     }
3235     if (cause.get() == nullptr) {
3236       signature = "(Ljava/lang/String;)V";
3237     } else {
3238       signature = "(Ljava/lang/String;Ljava/lang/Throwable;)V";
3239     }
3240   } else {
3241     if (cause.get() == nullptr) {
3242       signature = "()V";
3243     } else {
3244       signature = "(Ljava/lang/Throwable;)V";
3245     }
3246   }
3247   ArtMethod* exception_init_method =
3248       exception_class->FindConstructor(signature, cl->GetImagePointerSize());
3249 
3250   CHECK(exception_init_method != nullptr) << "No <init>" << signature << " in "
3251       << PrettyDescriptor(exception_class_descriptor);
3252 
3253   if (UNLIKELY(!runtime->IsStarted())) {
3254     // Something is trying to throw an exception without a started runtime, which is the common
3255     // case in the compiler. We won't be able to invoke the constructor of the exception, so set
3256     // the exception fields directly.
3257     if (msg != nullptr) {
3258       exception->SetDetailMessage(DecodeJObject(msg_string.get())->AsString());
3259     }
3260     if (cause.get() != nullptr) {
3261       exception->SetCause(DecodeJObject(cause.get())->AsThrowable());
3262     }
3263     ScopedLocalRef<jobject> trace(GetJniEnv(), CreateInternalStackTrace(soa));
3264     if (trace.get() != nullptr) {
3265       exception->SetStackState(DecodeJObject(trace.get()).Ptr());
3266     }
3267     SetException(exception.Get());
3268   } else {
3269     jvalue jv_args[2];
3270     size_t i = 0;
3271 
3272     if (msg != nullptr) {
3273       jv_args[i].l = msg_string.get();
3274       ++i;
3275     }
3276     if (cause.get() != nullptr) {
3277       jv_args[i].l = cause.get();
3278       ++i;
3279     }
3280     ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(exception.Get()));
3281     InvokeWithJValues(soa, ref.get(), exception_init_method, jv_args);
3282     if (LIKELY(!IsExceptionPending())) {
3283       SetException(exception.Get());
3284     }
3285   }
3286 }
3287 
ThrowOutOfMemoryError(const char * msg)3288 void Thread::ThrowOutOfMemoryError(const char* msg) {
3289   LOG(WARNING) << "Throwing OutOfMemoryError "
3290                << '"' << msg << '"'
3291                << " (VmSize " << GetProcessStatus("VmSize")
3292                << (tls32_.throwing_OutOfMemoryError ? ", recursive case)" : ")");
3293   if (!tls32_.throwing_OutOfMemoryError) {
3294     tls32_.throwing_OutOfMemoryError = true;
3295     ThrowNewException("Ljava/lang/OutOfMemoryError;", msg);
3296     tls32_.throwing_OutOfMemoryError = false;
3297   } else {
3298     Dump(LOG_STREAM(WARNING));  // The pre-allocated OOME has no stack, so help out and log one.
3299     SetException(Runtime::Current()->GetPreAllocatedOutOfMemoryErrorWhenThrowingOOME());
3300   }
3301 }
3302 
CurrentFromGdb()3303 Thread* Thread::CurrentFromGdb() {
3304   return Thread::Current();
3305 }
3306 
DumpFromGdb() const3307 void Thread::DumpFromGdb() const {
3308   std::ostringstream ss;
3309   Dump(ss);
3310   std::string str(ss.str());
3311   // log to stderr for debugging command line processes
3312   std::cerr << str;
3313 #ifdef ART_TARGET_ANDROID
3314   // log to logcat for debugging frameworks processes
3315   LOG(INFO) << str;
3316 #endif
3317 }
3318 
3319 // Explicitly instantiate 32 and 64bit thread offset dumping support.
3320 template
3321 void Thread::DumpThreadOffset<PointerSize::k32>(std::ostream& os, uint32_t offset);
3322 template
3323 void Thread::DumpThreadOffset<PointerSize::k64>(std::ostream& os, uint32_t offset);
3324 
3325 template<PointerSize ptr_size>
DumpThreadOffset(std::ostream & os,uint32_t offset)3326 void Thread::DumpThreadOffset(std::ostream& os, uint32_t offset) {
3327 #define DO_THREAD_OFFSET(x, y) \
3328     if (offset == (x).Uint32Value()) { \
3329       os << (y); \
3330       return; \
3331     }
3332   DO_THREAD_OFFSET(ThreadFlagsOffset<ptr_size>(), "state_and_flags")
3333   DO_THREAD_OFFSET(CardTableOffset<ptr_size>(), "card_table")
3334   DO_THREAD_OFFSET(ExceptionOffset<ptr_size>(), "exception")
3335   DO_THREAD_OFFSET(PeerOffset<ptr_size>(), "peer");
3336   DO_THREAD_OFFSET(JniEnvOffset<ptr_size>(), "jni_env")
3337   DO_THREAD_OFFSET(SelfOffset<ptr_size>(), "self")
3338   DO_THREAD_OFFSET(StackEndOffset<ptr_size>(), "stack_end")
3339   DO_THREAD_OFFSET(ThinLockIdOffset<ptr_size>(), "thin_lock_thread_id")
3340   DO_THREAD_OFFSET(IsGcMarkingOffset<ptr_size>(), "is_gc_marking")
3341   DO_THREAD_OFFSET(TopOfManagedStackOffset<ptr_size>(), "top_quick_frame_method")
3342   DO_THREAD_OFFSET(TopShadowFrameOffset<ptr_size>(), "top_shadow_frame")
3343   DO_THREAD_OFFSET(TopHandleScopeOffset<ptr_size>(), "top_handle_scope")
3344   DO_THREAD_OFFSET(ThreadSuspendTriggerOffset<ptr_size>(), "suspend_trigger")
3345 #undef DO_THREAD_OFFSET
3346 
3347 #define JNI_ENTRY_POINT_INFO(x) \
3348     if (JNI_ENTRYPOINT_OFFSET(ptr_size, x).Uint32Value() == offset) { \
3349       os << #x; \
3350       return; \
3351     }
3352   JNI_ENTRY_POINT_INFO(pDlsymLookup)
3353   JNI_ENTRY_POINT_INFO(pDlsymLookupCritical)
3354 #undef JNI_ENTRY_POINT_INFO
3355 
3356 #define QUICK_ENTRY_POINT_INFO(x) \
3357     if (QUICK_ENTRYPOINT_OFFSET(ptr_size, x).Uint32Value() == offset) { \
3358       os << #x; \
3359       return; \
3360     }
3361   QUICK_ENTRY_POINT_INFO(pAllocArrayResolved)
3362   QUICK_ENTRY_POINT_INFO(pAllocArrayResolved8)
3363   QUICK_ENTRY_POINT_INFO(pAllocArrayResolved16)
3364   QUICK_ENTRY_POINT_INFO(pAllocArrayResolved32)
3365   QUICK_ENTRY_POINT_INFO(pAllocArrayResolved64)
3366   QUICK_ENTRY_POINT_INFO(pAllocObjectResolved)
3367   QUICK_ENTRY_POINT_INFO(pAllocObjectInitialized)
3368   QUICK_ENTRY_POINT_INFO(pAllocObjectWithChecks)
3369   QUICK_ENTRY_POINT_INFO(pAllocStringObject)
3370   QUICK_ENTRY_POINT_INFO(pAllocStringFromBytes)
3371   QUICK_ENTRY_POINT_INFO(pAllocStringFromChars)
3372   QUICK_ENTRY_POINT_INFO(pAllocStringFromString)
3373   QUICK_ENTRY_POINT_INFO(pInstanceofNonTrivial)
3374   QUICK_ENTRY_POINT_INFO(pCheckInstanceOf)
3375   QUICK_ENTRY_POINT_INFO(pInitializeStaticStorage)
3376   QUICK_ENTRY_POINT_INFO(pResolveTypeAndVerifyAccess)
3377   QUICK_ENTRY_POINT_INFO(pResolveType)
3378   QUICK_ENTRY_POINT_INFO(pResolveString)
3379   QUICK_ENTRY_POINT_INFO(pSet8Instance)
3380   QUICK_ENTRY_POINT_INFO(pSet8Static)
3381   QUICK_ENTRY_POINT_INFO(pSet16Instance)
3382   QUICK_ENTRY_POINT_INFO(pSet16Static)
3383   QUICK_ENTRY_POINT_INFO(pSet32Instance)
3384   QUICK_ENTRY_POINT_INFO(pSet32Static)
3385   QUICK_ENTRY_POINT_INFO(pSet64Instance)
3386   QUICK_ENTRY_POINT_INFO(pSet64Static)
3387   QUICK_ENTRY_POINT_INFO(pSetObjInstance)
3388   QUICK_ENTRY_POINT_INFO(pSetObjStatic)
3389   QUICK_ENTRY_POINT_INFO(pGetByteInstance)
3390   QUICK_ENTRY_POINT_INFO(pGetBooleanInstance)
3391   QUICK_ENTRY_POINT_INFO(pGetByteStatic)
3392   QUICK_ENTRY_POINT_INFO(pGetBooleanStatic)
3393   QUICK_ENTRY_POINT_INFO(pGetShortInstance)
3394   QUICK_ENTRY_POINT_INFO(pGetCharInstance)
3395   QUICK_ENTRY_POINT_INFO(pGetShortStatic)
3396   QUICK_ENTRY_POINT_INFO(pGetCharStatic)
3397   QUICK_ENTRY_POINT_INFO(pGet32Instance)
3398   QUICK_ENTRY_POINT_INFO(pGet32Static)
3399   QUICK_ENTRY_POINT_INFO(pGet64Instance)
3400   QUICK_ENTRY_POINT_INFO(pGet64Static)
3401   QUICK_ENTRY_POINT_INFO(pGetObjInstance)
3402   QUICK_ENTRY_POINT_INFO(pGetObjStatic)
3403   QUICK_ENTRY_POINT_INFO(pAputObject)
3404   QUICK_ENTRY_POINT_INFO(pJniMethodStart)
3405   QUICK_ENTRY_POINT_INFO(pJniMethodStartSynchronized)
3406   QUICK_ENTRY_POINT_INFO(pJniMethodEnd)
3407   QUICK_ENTRY_POINT_INFO(pJniMethodEndSynchronized)
3408   QUICK_ENTRY_POINT_INFO(pJniMethodEndWithReference)
3409   QUICK_ENTRY_POINT_INFO(pJniMethodEndWithReferenceSynchronized)
3410   QUICK_ENTRY_POINT_INFO(pQuickGenericJniTrampoline)
3411   QUICK_ENTRY_POINT_INFO(pLockObject)
3412   QUICK_ENTRY_POINT_INFO(pUnlockObject)
3413   QUICK_ENTRY_POINT_INFO(pCmpgDouble)
3414   QUICK_ENTRY_POINT_INFO(pCmpgFloat)
3415   QUICK_ENTRY_POINT_INFO(pCmplDouble)
3416   QUICK_ENTRY_POINT_INFO(pCmplFloat)
3417   QUICK_ENTRY_POINT_INFO(pCos)
3418   QUICK_ENTRY_POINT_INFO(pSin)
3419   QUICK_ENTRY_POINT_INFO(pAcos)
3420   QUICK_ENTRY_POINT_INFO(pAsin)
3421   QUICK_ENTRY_POINT_INFO(pAtan)
3422   QUICK_ENTRY_POINT_INFO(pAtan2)
3423   QUICK_ENTRY_POINT_INFO(pCbrt)
3424   QUICK_ENTRY_POINT_INFO(pCosh)
3425   QUICK_ENTRY_POINT_INFO(pExp)
3426   QUICK_ENTRY_POINT_INFO(pExpm1)
3427   QUICK_ENTRY_POINT_INFO(pHypot)
3428   QUICK_ENTRY_POINT_INFO(pLog)
3429   QUICK_ENTRY_POINT_INFO(pLog10)
3430   QUICK_ENTRY_POINT_INFO(pNextAfter)
3431   QUICK_ENTRY_POINT_INFO(pSinh)
3432   QUICK_ENTRY_POINT_INFO(pTan)
3433   QUICK_ENTRY_POINT_INFO(pTanh)
3434   QUICK_ENTRY_POINT_INFO(pFmod)
3435   QUICK_ENTRY_POINT_INFO(pL2d)
3436   QUICK_ENTRY_POINT_INFO(pFmodf)
3437   QUICK_ENTRY_POINT_INFO(pL2f)
3438   QUICK_ENTRY_POINT_INFO(pD2iz)
3439   QUICK_ENTRY_POINT_INFO(pF2iz)
3440   QUICK_ENTRY_POINT_INFO(pIdivmod)
3441   QUICK_ENTRY_POINT_INFO(pD2l)
3442   QUICK_ENTRY_POINT_INFO(pF2l)
3443   QUICK_ENTRY_POINT_INFO(pLdiv)
3444   QUICK_ENTRY_POINT_INFO(pLmod)
3445   QUICK_ENTRY_POINT_INFO(pLmul)
3446   QUICK_ENTRY_POINT_INFO(pShlLong)
3447   QUICK_ENTRY_POINT_INFO(pShrLong)
3448   QUICK_ENTRY_POINT_INFO(pUshrLong)
3449   QUICK_ENTRY_POINT_INFO(pIndexOf)
3450   QUICK_ENTRY_POINT_INFO(pStringCompareTo)
3451   QUICK_ENTRY_POINT_INFO(pMemcpy)
3452   QUICK_ENTRY_POINT_INFO(pQuickImtConflictTrampoline)
3453   QUICK_ENTRY_POINT_INFO(pQuickResolutionTrampoline)
3454   QUICK_ENTRY_POINT_INFO(pQuickToInterpreterBridge)
3455   QUICK_ENTRY_POINT_INFO(pInvokeDirectTrampolineWithAccessCheck)
3456   QUICK_ENTRY_POINT_INFO(pInvokeInterfaceTrampolineWithAccessCheck)
3457   QUICK_ENTRY_POINT_INFO(pInvokeStaticTrampolineWithAccessCheck)
3458   QUICK_ENTRY_POINT_INFO(pInvokeSuperTrampolineWithAccessCheck)
3459   QUICK_ENTRY_POINT_INFO(pInvokeVirtualTrampolineWithAccessCheck)
3460   QUICK_ENTRY_POINT_INFO(pInvokePolymorphic)
3461   QUICK_ENTRY_POINT_INFO(pTestSuspend)
3462   QUICK_ENTRY_POINT_INFO(pDeliverException)
3463   QUICK_ENTRY_POINT_INFO(pThrowArrayBounds)
3464   QUICK_ENTRY_POINT_INFO(pThrowDivZero)
3465   QUICK_ENTRY_POINT_INFO(pThrowNullPointer)
3466   QUICK_ENTRY_POINT_INFO(pThrowStackOverflow)
3467   QUICK_ENTRY_POINT_INFO(pDeoptimize)
3468   QUICK_ENTRY_POINT_INFO(pA64Load)
3469   QUICK_ENTRY_POINT_INFO(pA64Store)
3470   QUICK_ENTRY_POINT_INFO(pNewEmptyString)
3471   QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_B)
3472   QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BI)
3473   QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BII)
3474   QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BIII)
3475   QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BIIString)
3476   QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BString)
3477   QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BIICharset)
3478   QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BCharset)
3479   QUICK_ENTRY_POINT_INFO(pNewStringFromChars_C)
3480   QUICK_ENTRY_POINT_INFO(pNewStringFromChars_CII)
3481   QUICK_ENTRY_POINT_INFO(pNewStringFromChars_IIC)
3482   QUICK_ENTRY_POINT_INFO(pNewStringFromCodePoints)
3483   QUICK_ENTRY_POINT_INFO(pNewStringFromString)
3484   QUICK_ENTRY_POINT_INFO(pNewStringFromStringBuffer)
3485   QUICK_ENTRY_POINT_INFO(pNewStringFromStringBuilder)
3486   QUICK_ENTRY_POINT_INFO(pReadBarrierJni)
3487   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg00)
3488   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg01)
3489   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg02)
3490   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg03)
3491   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg04)
3492   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg05)
3493   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg06)
3494   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg07)
3495   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg08)
3496   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg09)
3497   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg10)
3498   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg11)
3499   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg12)
3500   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg13)
3501   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg14)
3502   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg15)
3503   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg16)
3504   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg17)
3505   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg18)
3506   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg19)
3507   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg20)
3508   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg21)
3509   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg22)
3510   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg23)
3511   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg24)
3512   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg25)
3513   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg26)
3514   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg27)
3515   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg28)
3516   QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg29)
3517   QUICK_ENTRY_POINT_INFO(pReadBarrierSlow)
3518   QUICK_ENTRY_POINT_INFO(pReadBarrierForRootSlow)
3519 
3520   QUICK_ENTRY_POINT_INFO(pJniMethodFastStart)
3521   QUICK_ENTRY_POINT_INFO(pJniMethodFastEnd)
3522 #undef QUICK_ENTRY_POINT_INFO
3523 
3524   os << offset;
3525 }
3526 
QuickDeliverException()3527 void Thread::QuickDeliverException() {
3528   // Get exception from thread.
3529   ObjPtr<mirror::Throwable> exception = GetException();
3530   CHECK(exception != nullptr);
3531   if (exception == GetDeoptimizationException()) {
3532     artDeoptimize(this);
3533     UNREACHABLE();
3534   }
3535 
3536   ReadBarrier::MaybeAssertToSpaceInvariant(exception.Ptr());
3537 
3538   // This is a real exception: let the instrumentation know about it.
3539   instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
3540   if (instrumentation->HasExceptionThrownListeners() &&
3541       IsExceptionThrownByCurrentMethod(exception)) {
3542     // Instrumentation may cause GC so keep the exception object safe.
3543     StackHandleScope<1> hs(this);
3544     HandleWrapperObjPtr<mirror::Throwable> h_exception(hs.NewHandleWrapper(&exception));
3545     instrumentation->ExceptionThrownEvent(this, exception);
3546   }
3547   // Does instrumentation need to deoptimize the stack or otherwise go to interpreter for something?
3548   // Note: we do this *after* reporting the exception to instrumentation in case it now requires
3549   // deoptimization. It may happen if a debugger is attached and requests new events (single-step,
3550   // breakpoint, ...) when the exception is reported.
3551   //
3552   // Note we need to check for both force_frame_pop and force_retry_instruction. The first is
3553   // expected to happen fairly regularly but the second can only happen if we are using
3554   // instrumentation trampolines (for example with DDMS tracing). That forces us to do deopt later
3555   // and see every frame being popped. We don't need to handle it any differently.
3556   ShadowFrame* cf;
3557   bool force_deopt = false;
3558   if (Runtime::Current()->AreNonStandardExitsEnabled() || kIsDebugBuild) {
3559     NthCallerVisitor visitor(this, 0, false);
3560     visitor.WalkStack();
3561     cf = visitor.GetCurrentShadowFrame();
3562     if (cf == nullptr) {
3563       cf = FindDebuggerShadowFrame(visitor.GetFrameId());
3564     }
3565     bool force_frame_pop = cf != nullptr && cf->GetForcePopFrame();
3566     bool force_retry_instr = cf != nullptr && cf->GetForceRetryInstruction();
3567     if (kIsDebugBuild && force_frame_pop) {
3568       DCHECK(Runtime::Current()->AreNonStandardExitsEnabled());
3569       NthCallerVisitor penultimate_visitor(this, 1, false);
3570       penultimate_visitor.WalkStack();
3571       ShadowFrame* penultimate_frame = penultimate_visitor.GetCurrentShadowFrame();
3572       if (penultimate_frame == nullptr) {
3573         penultimate_frame = FindDebuggerShadowFrame(penultimate_visitor.GetFrameId());
3574       }
3575     }
3576     if (force_retry_instr) {
3577       DCHECK(Runtime::Current()->AreNonStandardExitsEnabled());
3578     }
3579     force_deopt = force_frame_pop || force_retry_instr;
3580   }
3581   if (Dbg::IsForcedInterpreterNeededForException(this) || force_deopt || IsForceInterpreter()) {
3582     NthCallerVisitor visitor(this, 0, false);
3583     visitor.WalkStack();
3584     if (Runtime::Current()->IsAsyncDeoptimizeable(visitor.caller_pc)) {
3585       // method_type shouldn't matter due to exception handling.
3586       const DeoptimizationMethodType method_type = DeoptimizationMethodType::kDefault;
3587       // Save the exception into the deoptimization context so it can be restored
3588       // before entering the interpreter.
3589       if (force_deopt) {
3590         VLOG(deopt) << "Deopting " << cf->GetMethod()->PrettyMethod() << " for frame-pop";
3591         DCHECK(Runtime::Current()->AreNonStandardExitsEnabled());
3592         // Get rid of the exception since we are doing a framepop instead.
3593         LOG(WARNING) << "Suppressing pending exception for retry-instruction/frame-pop: "
3594                      << exception->Dump();
3595         ClearException();
3596       }
3597       PushDeoptimizationContext(
3598           JValue(),
3599           /* is_reference= */ false,
3600           (force_deopt ? nullptr : exception),
3601           /* from_code= */ false,
3602           method_type);
3603       artDeoptimize(this);
3604       UNREACHABLE();
3605     } else if (visitor.caller != nullptr) {
3606       LOG(WARNING) << "Got a deoptimization request on un-deoptimizable method "
3607                    << visitor.caller->PrettyMethod();
3608     }
3609   }
3610 
3611   // Don't leave exception visible while we try to find the handler, which may cause class
3612   // resolution.
3613   ClearException();
3614   QuickExceptionHandler exception_handler(this, false);
3615   exception_handler.FindCatch(exception);
3616   if (exception_handler.GetClearException()) {
3617     // Exception was cleared as part of delivery.
3618     DCHECK(!IsExceptionPending());
3619   } else {
3620     // Exception was put back with a throw location.
3621     DCHECK(IsExceptionPending());
3622     // Check the to-space invariant on the re-installed exception (if applicable).
3623     ReadBarrier::MaybeAssertToSpaceInvariant(GetException());
3624   }
3625   exception_handler.DoLongJump();
3626 }
3627 
GetLongJumpContext()3628 Context* Thread::GetLongJumpContext() {
3629   Context* result = tlsPtr_.long_jump_context;
3630   if (result == nullptr) {
3631     result = Context::Create();
3632   } else {
3633     tlsPtr_.long_jump_context = nullptr;  // Avoid context being shared.
3634     result->Reset();
3635   }
3636   return result;
3637 }
3638 
GetCurrentMethod(uint32_t * dex_pc_out,bool check_suspended,bool abort_on_error) const3639 ArtMethod* Thread::GetCurrentMethod(uint32_t* dex_pc_out,
3640                                     bool check_suspended,
3641                                     bool abort_on_error) const {
3642   // Note: this visitor may return with a method set, but dex_pc_ being DexFile:kDexNoIndex. This is
3643   //       so we don't abort in a special situation (thinlocked monitor) when dumping the Java
3644   //       stack.
3645   ArtMethod* method = nullptr;
3646   uint32_t dex_pc = dex::kDexNoIndex;
3647   StackVisitor::WalkStack(
3648       [&](const StackVisitor* visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
3649         ArtMethod* m = visitor->GetMethod();
3650         if (m->IsRuntimeMethod()) {
3651           // Continue if this is a runtime method.
3652           return true;
3653         }
3654         method = m;
3655         dex_pc = visitor->GetDexPc(abort_on_error);
3656         return false;
3657       },
3658       const_cast<Thread*>(this),
3659       /* context= */ nullptr,
3660       StackVisitor::StackWalkKind::kIncludeInlinedFrames,
3661       check_suspended);
3662 
3663   if (dex_pc_out != nullptr) {
3664     *dex_pc_out = dex_pc;
3665   }
3666   return method;
3667 }
3668 
HoldsLock(ObjPtr<mirror::Object> object) const3669 bool Thread::HoldsLock(ObjPtr<mirror::Object> object) const {
3670   return object != nullptr && object->GetLockOwnerThreadId() == GetThreadId();
3671 }
3672 
3673 extern std::vector<StackReference<mirror::Object>*> GetProxyReferenceArguments(ArtMethod** sp)
3674     REQUIRES_SHARED(Locks::mutator_lock_);
3675 
3676 // RootVisitor parameters are: (const Object* obj, size_t vreg, const StackVisitor* visitor).
3677 template <typename RootVisitor, bool kPrecise = false>
3678 class ReferenceMapVisitor : public StackVisitor {
3679  public:
ReferenceMapVisitor(Thread * thread,Context * context,RootVisitor & visitor)3680   ReferenceMapVisitor(Thread* thread, Context* context, RootVisitor& visitor)
3681       REQUIRES_SHARED(Locks::mutator_lock_)
3682         // We are visiting the references in compiled frames, so we do not need
3683         // to know the inlined frames.
3684       : StackVisitor(thread, context, StackVisitor::StackWalkKind::kSkipInlinedFrames),
3685         visitor_(visitor) {}
3686 
VisitFrame()3687   bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
3688     if (false) {
3689       LOG(INFO) << "Visiting stack roots in " << ArtMethod::PrettyMethod(GetMethod())
3690                 << StringPrintf("@ PC:%04x", GetDexPc());
3691     }
3692     ShadowFrame* shadow_frame = GetCurrentShadowFrame();
3693     if (shadow_frame != nullptr) {
3694       VisitShadowFrame(shadow_frame);
3695     } else if (GetCurrentOatQuickMethodHeader()->IsNterpMethodHeader()) {
3696       VisitNterpFrame();
3697     } else {
3698       VisitQuickFrame();
3699     }
3700     return true;
3701   }
3702 
VisitShadowFrame(ShadowFrame * shadow_frame)3703   void VisitShadowFrame(ShadowFrame* shadow_frame) REQUIRES_SHARED(Locks::mutator_lock_) {
3704     ArtMethod* m = shadow_frame->GetMethod();
3705     VisitDeclaringClass(m);
3706     DCHECK(m != nullptr);
3707     size_t num_regs = shadow_frame->NumberOfVRegs();
3708     // handle scope for JNI or References for interpreter.
3709     for (size_t reg = 0; reg < num_regs; ++reg) {
3710       mirror::Object* ref = shadow_frame->GetVRegReference(reg);
3711       if (ref != nullptr) {
3712         mirror::Object* new_ref = ref;
3713         visitor_(&new_ref, reg, this);
3714         if (new_ref != ref) {
3715           shadow_frame->SetVRegReference(reg, new_ref);
3716         }
3717       }
3718     }
3719     // Mark lock count map required for structured locking checks.
3720     shadow_frame->GetLockCountData().VisitMonitors(visitor_, /* vreg= */ -1, this);
3721   }
3722 
3723  private:
3724   // Visiting the declaring class is necessary so that we don't unload the class of a method that
3725   // is executing. We need to ensure that the code stays mapped. NO_THREAD_SAFETY_ANALYSIS since
3726   // the threads do not all hold the heap bitmap lock for parallel GC.
VisitDeclaringClass(ArtMethod * method)3727   void VisitDeclaringClass(ArtMethod* method)
3728       REQUIRES_SHARED(Locks::mutator_lock_)
3729       NO_THREAD_SAFETY_ANALYSIS {
3730     ObjPtr<mirror::Class> klass = method->GetDeclaringClassUnchecked<kWithoutReadBarrier>();
3731     // klass can be null for runtime methods.
3732     if (klass != nullptr) {
3733       if (kVerifyImageObjectsMarked) {
3734         gc::Heap* const heap = Runtime::Current()->GetHeap();
3735         gc::space::ContinuousSpace* space = heap->FindContinuousSpaceFromObject(klass,
3736                                                                                 /*fail_ok=*/true);
3737         if (space != nullptr && space->IsImageSpace()) {
3738           bool failed = false;
3739           if (!space->GetLiveBitmap()->Test(klass.Ptr())) {
3740             failed = true;
3741             LOG(FATAL_WITHOUT_ABORT) << "Unmarked object in image " << *space;
3742           } else if (!heap->GetLiveBitmap()->Test(klass.Ptr())) {
3743             failed = true;
3744             LOG(FATAL_WITHOUT_ABORT) << "Unmarked object in image through live bitmap " << *space;
3745           }
3746           if (failed) {
3747             GetThread()->Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
3748             space->AsImageSpace()->DumpSections(LOG_STREAM(FATAL_WITHOUT_ABORT));
3749             LOG(FATAL_WITHOUT_ABORT) << "Method@" << method->GetDexMethodIndex() << ":" << method
3750                                      << " klass@" << klass.Ptr();
3751             // Pretty info last in case it crashes.
3752             LOG(FATAL) << "Method " << method->PrettyMethod() << " klass "
3753                        << klass->PrettyClass();
3754           }
3755         }
3756       }
3757       mirror::Object* new_ref = klass.Ptr();
3758       visitor_(&new_ref, /* vreg= */ JavaFrameRootInfo::kMethodDeclaringClass, this);
3759       if (new_ref != klass) {
3760         method->CASDeclaringClass(klass.Ptr(), new_ref->AsClass());
3761       }
3762     }
3763   }
3764 
VisitNterpFrame()3765   void VisitNterpFrame() REQUIRES_SHARED(Locks::mutator_lock_) {
3766     ArtMethod** cur_quick_frame = GetCurrentQuickFrame();
3767     StackReference<mirror::Object>* vreg_ref_base =
3768         reinterpret_cast<StackReference<mirror::Object>*>(NterpGetReferenceArray(cur_quick_frame));
3769     StackReference<mirror::Object>* vreg_int_base =
3770         reinterpret_cast<StackReference<mirror::Object>*>(NterpGetRegistersArray(cur_quick_frame));
3771     CodeItemDataAccessor accessor((*cur_quick_frame)->DexInstructionData());
3772     const uint16_t num_regs = accessor.RegistersSize();
3773     // An nterp frame has two arrays: a dex register array and a reference array
3774     // that shadows the dex register array but only containing references
3775     // (non-reference dex registers have nulls). See nterp_helpers.cc.
3776     for (size_t reg = 0; reg < num_regs; ++reg) {
3777       StackReference<mirror::Object>* ref_addr = vreg_ref_base + reg;
3778       mirror::Object* ref = ref_addr->AsMirrorPtr();
3779       if (ref != nullptr) {
3780         mirror::Object* new_ref = ref;
3781         visitor_(&new_ref, reg, this);
3782         if (new_ref != ref) {
3783           ref_addr->Assign(new_ref);
3784           StackReference<mirror::Object>* int_addr = vreg_int_base + reg;
3785           int_addr->Assign(new_ref);
3786         }
3787       }
3788     }
3789   }
3790 
3791   template <typename T>
3792   ALWAYS_INLINE
VisitQuickFrameWithVregCallback()3793   inline void VisitQuickFrameWithVregCallback() REQUIRES_SHARED(Locks::mutator_lock_) {
3794     ArtMethod** cur_quick_frame = GetCurrentQuickFrame();
3795     DCHECK(cur_quick_frame != nullptr);
3796     ArtMethod* m = *cur_quick_frame;
3797     VisitDeclaringClass(m);
3798 
3799     // Process register map (which native and runtime methods don't have)
3800     if (!m->IsNative() && !m->IsRuntimeMethod() && (!m->IsProxyMethod() || m->IsConstructor())) {
3801       const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
3802       DCHECK(method_header->IsOptimized());
3803       StackReference<mirror::Object>* vreg_base =
3804           reinterpret_cast<StackReference<mirror::Object>*>(cur_quick_frame);
3805       uintptr_t native_pc_offset = method_header->NativeQuickPcOffset(GetCurrentQuickFramePc());
3806       CodeInfo code_info = kPrecise
3807           ? CodeInfo(method_header)  // We will need dex register maps.
3808           : CodeInfo::DecodeGcMasksOnly(method_header);
3809       StackMap map = code_info.GetStackMapForNativePcOffset(native_pc_offset);
3810       DCHECK(map.IsValid());
3811 
3812       T vreg_info(m, code_info, map, visitor_);
3813 
3814       // Visit stack entries that hold pointers.
3815       BitMemoryRegion stack_mask = code_info.GetStackMaskOf(map);
3816       for (size_t i = 0; i < stack_mask.size_in_bits(); ++i) {
3817         if (stack_mask.LoadBit(i)) {
3818           StackReference<mirror::Object>* ref_addr = vreg_base + i;
3819           mirror::Object* ref = ref_addr->AsMirrorPtr();
3820           if (ref != nullptr) {
3821             mirror::Object* new_ref = ref;
3822             vreg_info.VisitStack(&new_ref, i, this);
3823             if (ref != new_ref) {
3824               ref_addr->Assign(new_ref);
3825             }
3826           }
3827         }
3828       }
3829       // Visit callee-save registers that hold pointers.
3830       uint32_t register_mask = code_info.GetRegisterMaskOf(map);
3831       for (size_t i = 0; i < BitSizeOf<uint32_t>(); ++i) {
3832         if (register_mask & (1 << i)) {
3833           mirror::Object** ref_addr = reinterpret_cast<mirror::Object**>(GetGPRAddress(i));
3834           if (kIsDebugBuild && ref_addr == nullptr) {
3835             std::string thread_name;
3836             GetThread()->GetThreadName(thread_name);
3837             LOG(FATAL_WITHOUT_ABORT) << "On thread " << thread_name;
3838             DescribeStack(GetThread());
3839             LOG(FATAL) << "Found an unsaved callee-save register " << i << " (null GPRAddress) "
3840                        << "set in register_mask=" << register_mask << " at " << DescribeLocation();
3841           }
3842           if (*ref_addr != nullptr) {
3843             vreg_info.VisitRegister(ref_addr, i, this);
3844           }
3845         }
3846       }
3847     } else if (!m->IsRuntimeMethod() && m->IsProxyMethod()) {
3848       // If this is a proxy method, visit its reference arguments.
3849       DCHECK(!m->IsStatic());
3850       DCHECK(!m->IsNative());
3851       std::vector<StackReference<mirror::Object>*> ref_addrs =
3852           GetProxyReferenceArguments(cur_quick_frame);
3853       for (StackReference<mirror::Object>* ref_addr : ref_addrs) {
3854         mirror::Object* ref = ref_addr->AsMirrorPtr();
3855         if (ref != nullptr) {
3856           mirror::Object* new_ref = ref;
3857           visitor_(&new_ref, /* vreg= */ JavaFrameRootInfo::kProxyReferenceArgument, this);
3858           if (ref != new_ref) {
3859             ref_addr->Assign(new_ref);
3860           }
3861         }
3862       }
3863     }
3864   }
3865 
VisitQuickFrame()3866   void VisitQuickFrame() REQUIRES_SHARED(Locks::mutator_lock_) {
3867     if (kPrecise) {
3868       VisitQuickFramePrecise();
3869     } else {
3870       VisitQuickFrameNonPrecise();
3871     }
3872   }
3873 
VisitQuickFrameNonPrecise()3874   void VisitQuickFrameNonPrecise() REQUIRES_SHARED(Locks::mutator_lock_) {
3875     struct UndefinedVRegInfo {
3876       UndefinedVRegInfo(ArtMethod* method ATTRIBUTE_UNUSED,
3877                         const CodeInfo& code_info ATTRIBUTE_UNUSED,
3878                         const StackMap& map ATTRIBUTE_UNUSED,
3879                         RootVisitor& _visitor)
3880           : visitor(_visitor) {
3881       }
3882 
3883       ALWAYS_INLINE
3884       void VisitStack(mirror::Object** ref,
3885                       size_t stack_index ATTRIBUTE_UNUSED,
3886                       const StackVisitor* stack_visitor)
3887           REQUIRES_SHARED(Locks::mutator_lock_) {
3888         visitor(ref, JavaFrameRootInfo::kImpreciseVreg, stack_visitor);
3889       }
3890 
3891       ALWAYS_INLINE
3892       void VisitRegister(mirror::Object** ref,
3893                          size_t register_index ATTRIBUTE_UNUSED,
3894                          const StackVisitor* stack_visitor)
3895           REQUIRES_SHARED(Locks::mutator_lock_) {
3896         visitor(ref, JavaFrameRootInfo::kImpreciseVreg, stack_visitor);
3897       }
3898 
3899       RootVisitor& visitor;
3900     };
3901     VisitQuickFrameWithVregCallback<UndefinedVRegInfo>();
3902   }
3903 
VisitQuickFramePrecise()3904   void VisitQuickFramePrecise() REQUIRES_SHARED(Locks::mutator_lock_) {
3905     struct StackMapVRegInfo {
3906       StackMapVRegInfo(ArtMethod* method,
3907                        const CodeInfo& _code_info,
3908                        const StackMap& map,
3909                        RootVisitor& _visitor)
3910           : number_of_dex_registers(method->DexInstructionData().RegistersSize()),
3911             code_info(_code_info),
3912             dex_register_map(code_info.GetDexRegisterMapOf(map)),
3913             visitor(_visitor) {
3914         DCHECK_EQ(dex_register_map.size(), number_of_dex_registers);
3915       }
3916 
3917       // TODO: If necessary, we should consider caching a reverse map instead of the linear
3918       //       lookups for each location.
3919       void FindWithType(const size_t index,
3920                         const DexRegisterLocation::Kind kind,
3921                         mirror::Object** ref,
3922                         const StackVisitor* stack_visitor)
3923           REQUIRES_SHARED(Locks::mutator_lock_) {
3924         bool found = false;
3925         for (size_t dex_reg = 0; dex_reg != number_of_dex_registers; ++dex_reg) {
3926           DexRegisterLocation location = dex_register_map[dex_reg];
3927           if (location.GetKind() == kind && static_cast<size_t>(location.GetValue()) == index) {
3928             visitor(ref, dex_reg, stack_visitor);
3929             found = true;
3930           }
3931         }
3932 
3933         if (!found) {
3934           // If nothing found, report with unknown.
3935           visitor(ref, JavaFrameRootInfo::kUnknownVreg, stack_visitor);
3936         }
3937       }
3938 
3939       void VisitStack(mirror::Object** ref, size_t stack_index, const StackVisitor* stack_visitor)
3940           REQUIRES_SHARED(Locks::mutator_lock_) {
3941         const size_t stack_offset = stack_index * kFrameSlotSize;
3942         FindWithType(stack_offset,
3943                      DexRegisterLocation::Kind::kInStack,
3944                      ref,
3945                      stack_visitor);
3946       }
3947 
3948       void VisitRegister(mirror::Object** ref,
3949                          size_t register_index,
3950                          const StackVisitor* stack_visitor)
3951           REQUIRES_SHARED(Locks::mutator_lock_) {
3952         FindWithType(register_index,
3953                      DexRegisterLocation::Kind::kInRegister,
3954                      ref,
3955                      stack_visitor);
3956       }
3957 
3958       size_t number_of_dex_registers;
3959       const CodeInfo& code_info;
3960       DexRegisterMap dex_register_map;
3961       RootVisitor& visitor;
3962     };
3963     VisitQuickFrameWithVregCallback<StackMapVRegInfo>();
3964   }
3965 
3966   // Visitor for when we visit a root.
3967   RootVisitor& visitor_;
3968 };
3969 
3970 class RootCallbackVisitor {
3971  public:
RootCallbackVisitor(RootVisitor * visitor,uint32_t tid)3972   RootCallbackVisitor(RootVisitor* visitor, uint32_t tid) : visitor_(visitor), tid_(tid) {}
3973 
operator ()(mirror::Object ** obj,size_t vreg,const StackVisitor * stack_visitor) const3974   void operator()(mirror::Object** obj, size_t vreg, const StackVisitor* stack_visitor) const
3975       REQUIRES_SHARED(Locks::mutator_lock_) {
3976     visitor_->VisitRoot(obj, JavaFrameRootInfo(tid_, stack_visitor, vreg));
3977   }
3978 
3979  private:
3980   RootVisitor* const visitor_;
3981   const uint32_t tid_;
3982 };
3983 
VisitReflectiveTargets(ReflectiveValueVisitor * visitor)3984 void Thread::VisitReflectiveTargets(ReflectiveValueVisitor* visitor) {
3985   for (BaseReflectiveHandleScope* brhs = GetTopReflectiveHandleScope();
3986        brhs != nullptr;
3987        brhs = brhs->GetLink()) {
3988     brhs->VisitTargets(visitor);
3989   }
3990 }
3991 
3992 template <bool kPrecise>
VisitRoots(RootVisitor * visitor)3993 void Thread::VisitRoots(RootVisitor* visitor) {
3994   const pid_t thread_id = GetThreadId();
3995   visitor->VisitRootIfNonNull(&tlsPtr_.opeer, RootInfo(kRootThreadObject, thread_id));
3996   if (tlsPtr_.exception != nullptr && tlsPtr_.exception != GetDeoptimizationException()) {
3997     visitor->VisitRoot(reinterpret_cast<mirror::Object**>(&tlsPtr_.exception),
3998                        RootInfo(kRootNativeStack, thread_id));
3999   }
4000   if (tlsPtr_.async_exception != nullptr) {
4001     visitor->VisitRoot(reinterpret_cast<mirror::Object**>(&tlsPtr_.async_exception),
4002                        RootInfo(kRootNativeStack, thread_id));
4003   }
4004   visitor->VisitRootIfNonNull(&tlsPtr_.monitor_enter_object, RootInfo(kRootNativeStack, thread_id));
4005   tlsPtr_.jni_env->VisitJniLocalRoots(visitor, RootInfo(kRootJNILocal, thread_id));
4006   tlsPtr_.jni_env->VisitMonitorRoots(visitor, RootInfo(kRootJNIMonitor, thread_id));
4007   HandleScopeVisitRoots(visitor, thread_id);
4008   // Visit roots for deoptimization.
4009   if (tlsPtr_.stacked_shadow_frame_record != nullptr) {
4010     RootCallbackVisitor visitor_to_callback(visitor, thread_id);
4011     ReferenceMapVisitor<RootCallbackVisitor, kPrecise> mapper(this, nullptr, visitor_to_callback);
4012     for (StackedShadowFrameRecord* record = tlsPtr_.stacked_shadow_frame_record;
4013          record != nullptr;
4014          record = record->GetLink()) {
4015       for (ShadowFrame* shadow_frame = record->GetShadowFrame();
4016            shadow_frame != nullptr;
4017            shadow_frame = shadow_frame->GetLink()) {
4018         mapper.VisitShadowFrame(shadow_frame);
4019       }
4020     }
4021   }
4022   for (DeoptimizationContextRecord* record = tlsPtr_.deoptimization_context_stack;
4023        record != nullptr;
4024        record = record->GetLink()) {
4025     if (record->IsReference()) {
4026       visitor->VisitRootIfNonNull(record->GetReturnValueAsGCRoot(),
4027                                   RootInfo(kRootThreadObject, thread_id));
4028     }
4029     visitor->VisitRootIfNonNull(record->GetPendingExceptionAsGCRoot(),
4030                                 RootInfo(kRootThreadObject, thread_id));
4031   }
4032   if (tlsPtr_.frame_id_to_shadow_frame != nullptr) {
4033     RootCallbackVisitor visitor_to_callback(visitor, thread_id);
4034     ReferenceMapVisitor<RootCallbackVisitor, kPrecise> mapper(this, nullptr, visitor_to_callback);
4035     for (FrameIdToShadowFrame* record = tlsPtr_.frame_id_to_shadow_frame;
4036          record != nullptr;
4037          record = record->GetNext()) {
4038       mapper.VisitShadowFrame(record->GetShadowFrame());
4039     }
4040   }
4041   for (auto* verifier = tlsPtr_.method_verifier; verifier != nullptr; verifier = verifier->link_) {
4042     verifier->VisitRoots(visitor, RootInfo(kRootNativeStack, thread_id));
4043   }
4044   // Visit roots on this thread's stack
4045   RuntimeContextType context;
4046   RootCallbackVisitor visitor_to_callback(visitor, thread_id);
4047   ReferenceMapVisitor<RootCallbackVisitor, kPrecise> mapper(this, &context, visitor_to_callback);
4048   mapper.template WalkStack<StackVisitor::CountTransitions::kNo>(false);
4049   for (auto& entry : *GetInstrumentationStack()) {
4050     visitor->VisitRootIfNonNull(&entry.second.this_object_, RootInfo(kRootVMInternal, thread_id));
4051   }
4052 }
4053 
SweepInterpreterCache(IsMarkedVisitor * visitor)4054 void Thread::SweepInterpreterCache(IsMarkedVisitor* visitor) {
4055   for (InterpreterCache::Entry& entry : GetInterpreterCache()->GetArray()) {
4056     const Instruction* inst = reinterpret_cast<const Instruction*>(entry.first);
4057     if (inst != nullptr) {
4058       if (inst->Opcode() == Instruction::NEW_INSTANCE ||
4059           inst->Opcode() == Instruction::CHECK_CAST ||
4060           inst->Opcode() == Instruction::INSTANCE_OF ||
4061           inst->Opcode() == Instruction::NEW_ARRAY ||
4062           inst->Opcode() == Instruction::CONST_CLASS) {
4063         mirror::Class* cls = reinterpret_cast<mirror::Class*>(entry.second);
4064         if (cls == nullptr || cls == Runtime::GetWeakClassSentinel()) {
4065           // Entry got deleted in a previous sweep.
4066           continue;
4067         }
4068         Runtime::ProcessWeakClass(
4069             reinterpret_cast<GcRoot<mirror::Class>*>(&entry.second),
4070             visitor,
4071             Runtime::GetWeakClassSentinel());
4072       } else if (inst->Opcode() == Instruction::CONST_STRING ||
4073                  inst->Opcode() == Instruction::CONST_STRING_JUMBO) {
4074         mirror::Object* object = reinterpret_cast<mirror::Object*>(entry.second);
4075         mirror::Object* new_object = visitor->IsMarked(object);
4076         // We know the string is marked because it's a strongly-interned string that
4077         // is always alive (see b/117621117 for trying to make those strings weak).
4078         // The IsMarked implementation of the CMS collector returns
4079         // null for newly allocated objects, but we know those haven't moved. Therefore,
4080         // only update the entry if we get a different non-null string.
4081         if (new_object != nullptr && new_object != object) {
4082           entry.second = reinterpret_cast<size_t>(new_object);
4083         }
4084       }
4085     }
4086   }
4087 }
4088 
VisitRoots(RootVisitor * visitor,VisitRootFlags flags)4089 void Thread::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
4090   if ((flags & VisitRootFlags::kVisitRootFlagPrecise) != 0) {
4091     VisitRoots</* kPrecise= */ true>(visitor);
4092   } else {
4093     VisitRoots</* kPrecise= */ false>(visitor);
4094   }
4095 }
4096 
4097 class VerifyRootVisitor : public SingleRootVisitor {
4098  public:
VisitRoot(mirror::Object * root,const RootInfo & info ATTRIBUTE_UNUSED)4099   void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
4100       override REQUIRES_SHARED(Locks::mutator_lock_) {
4101     VerifyObject(root);
4102   }
4103 };
4104 
VerifyStackImpl()4105 void Thread::VerifyStackImpl() {
4106   if (Runtime::Current()->GetHeap()->IsObjectValidationEnabled()) {
4107     VerifyRootVisitor visitor;
4108     std::unique_ptr<Context> context(Context::Create());
4109     RootCallbackVisitor visitor_to_callback(&visitor, GetThreadId());
4110     ReferenceMapVisitor<RootCallbackVisitor> mapper(this, context.get(), visitor_to_callback);
4111     mapper.WalkStack();
4112   }
4113 }
4114 
4115 // Set the stack end to that to be used during a stack overflow
SetStackEndForStackOverflow()4116 void Thread::SetStackEndForStackOverflow() {
4117   // During stack overflow we allow use of the full stack.
4118   if (tlsPtr_.stack_end == tlsPtr_.stack_begin) {
4119     // However, we seem to have already extended to use the full stack.
4120     LOG(ERROR) << "Need to increase kStackOverflowReservedBytes (currently "
4121                << GetStackOverflowReservedBytes(kRuntimeISA) << ")?";
4122     DumpStack(LOG_STREAM(ERROR));
4123     LOG(FATAL) << "Recursive stack overflow.";
4124   }
4125 
4126   tlsPtr_.stack_end = tlsPtr_.stack_begin;
4127 
4128   // Remove the stack overflow protection if is it set up.
4129   bool implicit_stack_check = !Runtime::Current()->ExplicitStackOverflowChecks();
4130   if (implicit_stack_check) {
4131     if (!UnprotectStack()) {
4132       LOG(ERROR) << "Unable to remove stack protection for stack overflow";
4133     }
4134   }
4135 }
4136 
SetTlab(uint8_t * start,uint8_t * end,uint8_t * limit)4137 void Thread::SetTlab(uint8_t* start, uint8_t* end, uint8_t* limit) {
4138   DCHECK_LE(start, end);
4139   DCHECK_LE(end, limit);
4140   tlsPtr_.thread_local_start = start;
4141   tlsPtr_.thread_local_pos  = tlsPtr_.thread_local_start;
4142   tlsPtr_.thread_local_end = end;
4143   tlsPtr_.thread_local_limit = limit;
4144   tlsPtr_.thread_local_objects = 0;
4145 }
4146 
ResetTlab()4147 void Thread::ResetTlab() {
4148   SetTlab(nullptr, nullptr, nullptr);
4149 }
4150 
HasTlab() const4151 bool Thread::HasTlab() const {
4152   const bool has_tlab = tlsPtr_.thread_local_pos != nullptr;
4153   if (has_tlab) {
4154     DCHECK(tlsPtr_.thread_local_start != nullptr && tlsPtr_.thread_local_end != nullptr);
4155   } else {
4156     DCHECK(tlsPtr_.thread_local_start == nullptr && tlsPtr_.thread_local_end == nullptr);
4157   }
4158   return has_tlab;
4159 }
4160 
operator <<(std::ostream & os,const Thread & thread)4161 std::ostream& operator<<(std::ostream& os, const Thread& thread) {
4162   thread.ShortDump(os);
4163   return os;
4164 }
4165 
ProtectStack(bool fatal_on_error)4166 bool Thread::ProtectStack(bool fatal_on_error) {
4167   void* pregion = tlsPtr_.stack_begin - kStackOverflowProtectedSize;
4168   VLOG(threads) << "Protecting stack at " << pregion;
4169   if (mprotect(pregion, kStackOverflowProtectedSize, PROT_NONE) == -1) {
4170     if (fatal_on_error) {
4171       LOG(FATAL) << "Unable to create protected region in stack for implicit overflow check. "
4172           "Reason: "
4173           << strerror(errno) << " size:  " << kStackOverflowProtectedSize;
4174     }
4175     return false;
4176   }
4177   return true;
4178 }
4179 
UnprotectStack()4180 bool Thread::UnprotectStack() {
4181   void* pregion = tlsPtr_.stack_begin - kStackOverflowProtectedSize;
4182   VLOG(threads) << "Unprotecting stack at " << pregion;
4183   return mprotect(pregion, kStackOverflowProtectedSize, PROT_READ|PROT_WRITE) == 0;
4184 }
4185 
PushVerifier(verifier::MethodVerifier * verifier)4186 void Thread::PushVerifier(verifier::MethodVerifier* verifier) {
4187   verifier->link_ = tlsPtr_.method_verifier;
4188   tlsPtr_.method_verifier = verifier;
4189 }
4190 
PopVerifier(verifier::MethodVerifier * verifier)4191 void Thread::PopVerifier(verifier::MethodVerifier* verifier) {
4192   CHECK_EQ(tlsPtr_.method_verifier, verifier);
4193   tlsPtr_.method_verifier = verifier->link_;
4194 }
4195 
NumberOfHeldMutexes() const4196 size_t Thread::NumberOfHeldMutexes() const {
4197   size_t count = 0;
4198   for (BaseMutex* mu : tlsPtr_.held_mutexes) {
4199     count += mu != nullptr ? 1 : 0;
4200   }
4201   return count;
4202 }
4203 
DeoptimizeWithDeoptimizationException(JValue * result)4204 void Thread::DeoptimizeWithDeoptimizationException(JValue* result) {
4205   DCHECK_EQ(GetException(), Thread::GetDeoptimizationException());
4206   ClearException();
4207   ShadowFrame* shadow_frame =
4208       PopStackedShadowFrame(StackedShadowFrameType::kDeoptimizationShadowFrame);
4209   ObjPtr<mirror::Throwable> pending_exception;
4210   bool from_code = false;
4211   DeoptimizationMethodType method_type;
4212   PopDeoptimizationContext(result, &pending_exception, &from_code, &method_type);
4213   SetTopOfStack(nullptr);
4214   SetTopOfShadowStack(shadow_frame);
4215 
4216   // Restore the exception that was pending before deoptimization then interpret the
4217   // deoptimized frames.
4218   if (pending_exception != nullptr) {
4219     SetException(pending_exception);
4220   }
4221   interpreter::EnterInterpreterFromDeoptimize(this,
4222                                               shadow_frame,
4223                                               result,
4224                                               from_code,
4225                                               method_type);
4226 }
4227 
SetAsyncException(ObjPtr<mirror::Throwable> new_exception)4228 void Thread::SetAsyncException(ObjPtr<mirror::Throwable> new_exception) {
4229   CHECK(new_exception != nullptr);
4230   Runtime::Current()->SetAsyncExceptionsThrown();
4231   if (kIsDebugBuild) {
4232     // Make sure we are in a checkpoint.
4233     MutexLock mu(Thread::Current(), *Locks::thread_suspend_count_lock_);
4234     CHECK(this == Thread::Current() || GetSuspendCount() >= 1)
4235         << "It doesn't look like this was called in a checkpoint! this: "
4236         << this << " count: " << GetSuspendCount();
4237   }
4238   tlsPtr_.async_exception = new_exception.Ptr();
4239 }
4240 
ObserveAsyncException()4241 bool Thread::ObserveAsyncException() {
4242   DCHECK(this == Thread::Current());
4243   if (tlsPtr_.async_exception != nullptr) {
4244     if (tlsPtr_.exception != nullptr) {
4245       LOG(WARNING) << "Overwriting pending exception with async exception. Pending exception is: "
4246                    << tlsPtr_.exception->Dump();
4247       LOG(WARNING) << "Async exception is " << tlsPtr_.async_exception->Dump();
4248     }
4249     tlsPtr_.exception = tlsPtr_.async_exception;
4250     tlsPtr_.async_exception = nullptr;
4251     return true;
4252   } else {
4253     return IsExceptionPending();
4254   }
4255 }
4256 
SetException(ObjPtr<mirror::Throwable> new_exception)4257 void Thread::SetException(ObjPtr<mirror::Throwable> new_exception) {
4258   CHECK(new_exception != nullptr);
4259   // TODO: DCHECK(!IsExceptionPending());
4260   tlsPtr_.exception = new_exception.Ptr();
4261 }
4262 
IsAotCompiler()4263 bool Thread::IsAotCompiler() {
4264   return Runtime::Current()->IsAotCompiler();
4265 }
4266 
GetPeerFromOtherThread() const4267 mirror::Object* Thread::GetPeerFromOtherThread() const {
4268   DCHECK(tlsPtr_.jpeer == nullptr);
4269   mirror::Object* peer = tlsPtr_.opeer;
4270   if (kUseReadBarrier && Current()->GetIsGcMarking()) {
4271     // We may call Thread::Dump() in the middle of the CC thread flip and this thread's stack
4272     // may have not been flipped yet and peer may be a from-space (stale) ref. So explicitly
4273     // mark/forward it here.
4274     peer = art::ReadBarrier::Mark(peer);
4275   }
4276   return peer;
4277 }
4278 
SetReadBarrierEntrypoints()4279 void Thread::SetReadBarrierEntrypoints() {
4280   // Make sure entrypoints aren't null.
4281   UpdateReadBarrierEntrypoints(&tlsPtr_.quick_entrypoints, /* is_active=*/ true);
4282 }
4283 
ClearAllInterpreterCaches()4284 void Thread::ClearAllInterpreterCaches() {
4285   static struct ClearInterpreterCacheClosure : Closure {
4286     void Run(Thread* thread) override {
4287       thread->GetInterpreterCache()->Clear(thread);
4288     }
4289   } closure;
4290   Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
4291 }
4292 
4293 
ReleaseLongJumpContextInternal()4294 void Thread::ReleaseLongJumpContextInternal() {
4295   // Each QuickExceptionHandler gets a long jump context and uses
4296   // it for doing the long jump, after finding catch blocks/doing deoptimization.
4297   // Both finding catch blocks and deoptimization can trigger another
4298   // exception such as a result of class loading. So there can be nested
4299   // cases of exception handling and multiple contexts being used.
4300   // ReleaseLongJumpContext tries to save the context in tlsPtr_.long_jump_context
4301   // for reuse so there is no need to always allocate a new one each time when
4302   // getting a context. Since we only keep one context for reuse, delete the
4303   // existing one since the passed in context is yet to be used for longjump.
4304   delete tlsPtr_.long_jump_context;
4305 }
4306 
SetNativePriority(int new_priority)4307 void Thread::SetNativePriority(int new_priority) {
4308   PaletteStatus status = PaletteSchedSetPriority(GetTid(), new_priority);
4309   CHECK(status == PaletteStatus::kOkay || status == PaletteStatus::kCheckErrno);
4310 }
4311 
GetNativePriority() const4312 int Thread::GetNativePriority() const {
4313   int priority = 0;
4314   PaletteStatus status = PaletteSchedGetPriority(GetTid(), &priority);
4315   CHECK(status == PaletteStatus::kOkay || status == PaletteStatus::kCheckErrno);
4316   return priority;
4317 }
4318 
IsSystemDaemon() const4319 bool Thread::IsSystemDaemon() const {
4320   if (GetPeer() == nullptr) {
4321     return false;
4322   }
4323   return jni::DecodeArtField(
4324       WellKnownClasses::java_lang_Thread_systemDaemon)->GetBoolean(GetPeer());
4325 }
4326 
ScopedExceptionStorage(art::Thread * self)4327 ScopedExceptionStorage::ScopedExceptionStorage(art::Thread* self)
4328     : self_(self), hs_(self_), excp_(hs_.NewHandle<art::mirror::Throwable>(self_->GetException())) {
4329   self_->ClearException();
4330 }
4331 
SuppressOldException(const char * message)4332 void ScopedExceptionStorage::SuppressOldException(const char* message) {
4333   CHECK(self_->IsExceptionPending()) << *self_;
4334   ObjPtr<mirror::Throwable> old_suppressed(excp_.Get());
4335   excp_.Assign(self_->GetException());
4336   LOG(WARNING) << message << "Suppressing old exception: " << old_suppressed->Dump();
4337   self_->ClearException();
4338 }
4339 
~ScopedExceptionStorage()4340 ScopedExceptionStorage::~ScopedExceptionStorage() {
4341   CHECK(!self_->IsExceptionPending()) << *self_;
4342   if (!excp_.IsNull()) {
4343     self_->SetException(excp_.Get());
4344   }
4345 }
4346 
4347 }  // namespace art
4348