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