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