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