• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef ART_RUNTIME_THREAD_INL_H_
18 #define ART_RUNTIME_THREAD_INL_H_
19 
20 #include "arch/instruction_set.h"
21 #include "base/aborting.h"
22 #include "base/casts.h"
23 #include "base/mutex-inl.h"
24 #include "base/time_utils.h"
25 #include "indirect_reference_table.h"
26 #include "jni/jni_env_ext.h"
27 #include "managed_stack-inl.h"
28 #include "obj_ptr-inl.h"
29 #include "runtime.h"
30 #include "thread-current-inl.h"
31 #include "thread.h"
32 #include "thread_list.h"
33 #include "thread_pool.h"
34 
35 namespace art HIDDEN {
36 
37 // Quickly access the current thread from a JNIEnv.
ForEnv(JNIEnv * env)38 inline Thread* Thread::ForEnv(JNIEnv* env) {
39   JNIEnvExt* full_env(down_cast<JNIEnvExt*>(env));
40   return full_env->GetSelf();
41 }
42 
GetStackOverflowProtectedSize()43 inline size_t Thread::GetStackOverflowProtectedSize() {
44   // The kMemoryToolStackGuardSizeScale is expected to be 1 when ASan is not enabled.
45   // As the function is always inlined, in those cases each function call should turn
46   // into a simple reference to gPageSize.
47   return kMemoryToolStackGuardSizeScale * gPageSize;
48 }
49 
DecodeJObject(jobject obj)50 inline ObjPtr<mirror::Object> Thread::DecodeJObject(jobject obj) const {
51   if (obj == nullptr) {
52     return nullptr;
53   }
54   IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
55   if (LIKELY(IndirectReferenceTable::IsJniTransitionOrLocalReference(ref))) {
56     // For JNI transitions, the `jclass` for a static method points to the
57     // `CompressedReference<>` in the `ArtMethod::declaring_class_` and other `jobject`
58     // arguments point to spilled stack references but a `StackReference<>` is just
59     // a subclass of `CompressedReference<>`. Local references also point to
60     // a `CompressedReference<>` encapsulated in a `GcRoot<>`.
61     if (kIsDebugBuild && IndirectReferenceTable::GetIndirectRefKind(ref) == kJniTransition) {
62       CHECK(IsJniTransitionReference(obj));
63     }
64     auto* cref = IndirectReferenceTable::ClearIndirectRefKind<
65         mirror::CompressedReference<mirror::Object>*>(ref);
66     ObjPtr<mirror::Object> result = cref->AsMirrorPtr();
67     if (kIsDebugBuild && IndirectReferenceTable::GetIndirectRefKind(ref) != kJniTransition) {
68       CHECK_EQ(result, tlsPtr_.jni_env->locals_.Get(ref));
69     }
70     return result;
71   } else {
72     return DecodeGlobalJObject(obj);
73   }
74 }
75 
AllowThreadSuspension()76 inline void Thread::AllowThreadSuspension() {
77   CheckSuspend();
78   // Invalidate the current thread's object pointers (ObjPtr) to catch possible moving GC bugs due
79   // to missing handles.
80   PoisonObjectPointers();
81 }
82 
CheckSuspend(bool implicit)83 inline void Thread::CheckSuspend(bool implicit) {
84   DCHECK_EQ(Thread::Current(), this);
85   while (true) {
86     // Memory_order_relaxed should be OK, since RunCheckpointFunction shares a lock with the
87     // requestor, and FullSuspendCheck() re-checks later. But we currently need memory_order_acquire
88     // for the empty checkpoint path.
89     // TODO (b/382722942): Revisit after we fix RunEmptyCheckpoint().
90     StateAndFlags state_and_flags = GetStateAndFlags(std::memory_order_acquire);
91     if (LIKELY(!state_and_flags.IsAnyOfFlagsSet(SuspendOrCheckpointRequestFlags()))) {
92       break;
93     } else if (state_and_flags.IsFlagSet(ThreadFlag::kCheckpointRequest)) {
94       RunCheckpointFunction();
95     } else if (state_and_flags.IsFlagSet(ThreadFlag::kSuspendRequest) &&
96                !state_and_flags.IsFlagSet(ThreadFlag::kSuspensionImmune)) {
97       FullSuspendCheck(implicit);
98       implicit = false;  // We do not need to `MadviseAwayAlternateSignalStack()` anymore.
99     } else if (state_and_flags.IsFlagSet(ThreadFlag::kEmptyCheckpointRequest)) {
100       RunEmptyCheckpoint();
101     } else {
102       DCHECK(state_and_flags.IsFlagSet(ThreadFlag::kSuspensionImmune));
103       break;
104     }
105   }
106   if (implicit) {
107     // For implicit suspend check we want to `madvise()` away
108     // the alternate signal stack to avoid wasting memory.
109     MadviseAwayAlternateSignalStack();
110   }
111 }
112 
CheckEmptyCheckpointFromWeakRefAccess(BaseMutex * cond_var_mutex)113 inline void Thread::CheckEmptyCheckpointFromWeakRefAccess(BaseMutex* cond_var_mutex) {
114   Thread* self = Thread::Current();
115   DCHECK_EQ(self, this);
116   for (;;) {
117     // TODO (b/382722942): Revisit memory ordering after we fix RunEmptyCheckpoint().
118     if (ReadFlag(ThreadFlag::kEmptyCheckpointRequest, std::memory_order_acquire)) {
119       RunEmptyCheckpoint();
120       // Check we hold only an expected mutex when accessing weak ref.
121       if (kIsDebugBuild) {
122         for (int i = kLockLevelCount - 1; i >= 0; --i) {
123           BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
124           if (held_mutex != nullptr && held_mutex != GetMutatorLock() &&
125               held_mutex != cond_var_mutex &&
126               held_mutex != cp_placeholder_mutex_.load(std::memory_order_relaxed)) {
127             // placeholder_mutex may still be nullptr. That's OK.
128             CHECK(Locks::IsExpectedOnWeakRefAccess(held_mutex))
129                 << "Holding unexpected mutex " << held_mutex->GetName()
130                 << " when accessing weak ref";
131           }
132         }
133       }
134     } else {
135       break;
136     }
137   }
138 }
139 
CheckEmptyCheckpointFromMutex()140 inline void Thread::CheckEmptyCheckpointFromMutex() {
141   DCHECK_EQ(Thread::Current(), this);
142   for (;;) {
143     // TODO (b/382722942): Revisit memory ordering after we fix RunEmptyCheckpoint().
144     if (ReadFlag(ThreadFlag::kEmptyCheckpointRequest, std::memory_order_acquire)) {
145       RunEmptyCheckpoint();
146     } else {
147       break;
148     }
149   }
150 }
151 
SetState(ThreadState new_state)152 inline ThreadState Thread::SetState(ThreadState new_state) {
153   // Should only be used to change between suspended states.
154   // Cannot use this code to change into or from Runnable as changing to Runnable should
155   // fail if the `ThreadFlag::kSuspendRequest` is set and changing from Runnable might
156   // miss passing an active suspend barrier.
157   DCHECK_NE(new_state, ThreadState::kRunnable);
158   if (kIsDebugBuild && this != Thread::Current()) {
159     std::string name;
160     GetThreadName(name);
161     LOG(FATAL) << "Thread \"" << name << "\"(" << this << " != Thread::Current()="
162                << Thread::Current() << ") changing state to " << new_state;
163   }
164 
165   while (true) {
166     StateAndFlags old_state_and_flags = GetStateAndFlags(std::memory_order_relaxed);
167     CHECK_NE(old_state_and_flags.GetState(), ThreadState::kRunnable)
168         << new_state << " " << *this << " " << *Thread::Current();
169     StateAndFlags new_state_and_flags = old_state_and_flags.WithState(new_state);
170     bool done =
171         tls32_.state_and_flags.CompareAndSetWeakRelaxed(old_state_and_flags.GetValue(),
172                                                         new_state_and_flags.GetValue());
173     if (done) {
174       return static_cast<ThreadState>(old_state_and_flags.GetState());
175     }
176   }
177 }
178 
IsThreadSuspensionAllowable()179 inline bool Thread::IsThreadSuspensionAllowable() const {
180   if (tls32_.no_thread_suspension != 0) {
181     return false;
182   }
183   for (int i = kLockLevelCount - 1; i >= 0; --i) {
184     if (i != kMutatorLock &&
185         i != kUserCodeSuspensionLock &&
186         GetHeldMutex(static_cast<LockLevel>(i)) != nullptr) {
187       return false;
188     }
189   }
190   // Thread autoanalysis isn't able to understand that the GetHeldMutex(...) or AssertHeld means we
191   // have the mutex meaning we need to do this hack.
192   auto is_suspending_for_user_code = [this]() NO_THREAD_SAFETY_ANALYSIS {
193     return tls32_.user_code_suspend_count != 0;
194   };
195   if (GetHeldMutex(kUserCodeSuspensionLock) != nullptr && is_suspending_for_user_code()) {
196     return false;
197   }
198   return true;
199 }
200 
AssertThreadSuspensionIsAllowable(bool check_locks)201 inline void Thread::AssertThreadSuspensionIsAllowable(bool check_locks) const {
202   if (kIsDebugBuild) {
203     if (gAborting == 0) {
204       CHECK_EQ(0u, tls32_.no_thread_suspension) << tlsPtr_.last_no_thread_suspension_cause;
205     }
206     if (check_locks) {
207       bool bad_mutexes_held = false;
208       for (int i = kLockLevelCount - 1; i >= 0; --i) {
209         // We expect no locks except the mutator lock. User code suspension lock is OK as long as
210         // we aren't going to be held suspended due to SuspendReason::kForUserCode.
211         if (i != kMutatorLock && i != kUserCodeSuspensionLock) {
212           BaseMutex* held_mutex = GetHeldMutex(static_cast<LockLevel>(i));
213           if (held_mutex != nullptr) {
214             LOG(ERROR) << "holding \"" << held_mutex->GetName()
215                       << "\" at point where thread suspension is expected";
216             bad_mutexes_held = true;
217           }
218         }
219       }
220       // Make sure that if we hold the user_code_suspension_lock_ we aren't suspending due to
221       // user_code_suspend_count which would prevent the thread from ever waking up.  Thread
222       // autoanalysis isn't able to understand that the GetHeldMutex(...) or AssertHeld means we
223       // have the mutex meaning we need to do this hack.
224       auto is_suspending_for_user_code = [this]() NO_THREAD_SAFETY_ANALYSIS {
225         return tls32_.user_code_suspend_count != 0;
226       };
227       if (GetHeldMutex(kUserCodeSuspensionLock) != nullptr && is_suspending_for_user_code()) {
228         LOG(ERROR) << "suspending due to user-code while holding \""
229                    << Locks::user_code_suspension_lock_->GetName() << "\"! Thread would never "
230                    << "wake up.";
231         bad_mutexes_held = true;
232       }
233       if (gAborting == 0) {
234         CHECK(!bad_mutexes_held);
235       }
236     }
237   }
238 }
239 
TransitionToSuspendedAndRunCheckpoints(ThreadState new_state)240 inline void Thread::TransitionToSuspendedAndRunCheckpoints(ThreadState new_state) {
241   DCHECK_NE(new_state, ThreadState::kRunnable);
242   while (true) {
243     // memory_order_relaxed is OK for ordinary checkpoints, which enforce ordering via
244     // thread_suspend_count_lock_ . It is not currently OK for empty checkpoints.
245     // TODO (b/382722942): Consider changing back to memory_order_relaxed after fixing empty
246     // checkpoints.
247     StateAndFlags old_state_and_flags = GetStateAndFlags(std::memory_order_acquire);
248     DCHECK_EQ(old_state_and_flags.GetState(), ThreadState::kRunnable);
249     if (UNLIKELY(old_state_and_flags.IsFlagSet(ThreadFlag::kCheckpointRequest))) {
250       IncrementStatsCounter(&checkpoint_count_);
251       RunCheckpointFunction();
252       continue;
253     }
254     if (UNLIKELY(old_state_and_flags.IsFlagSet(ThreadFlag::kEmptyCheckpointRequest))) {
255       RunEmptyCheckpoint();
256       continue;
257     }
258     // Change the state but keep the current flags (kCheckpointRequest is clear).
259     DCHECK(!old_state_and_flags.IsFlagSet(ThreadFlag::kCheckpointRequest));
260     DCHECK(!old_state_and_flags.IsFlagSet(ThreadFlag::kEmptyCheckpointRequest));
261     StateAndFlags new_state_and_flags = old_state_and_flags.WithState(new_state);
262 
263     // CAS the value, ensuring that prior memory operations are visible to any thread
264     // that observes that we are suspended.
265     bool done =
266         tls32_.state_and_flags.CompareAndSetWeakRelease(old_state_and_flags.GetValue(),
267                                                         new_state_and_flags.GetValue());
268     if (LIKELY(done)) {
269       IncrementStatsCounter(&suspended_count_);
270       break;
271     }
272   }
273 }
274 
CheckActiveSuspendBarriers()275 inline void Thread::CheckActiveSuspendBarriers() {
276   DCHECK_NE(GetState(), ThreadState::kRunnable);
277   while (true) {
278     // memory_order_relaxed is OK here, since PassActiveSuspendBarriers() rechecks with
279     // thread_suspend_count_lock_ .
280     StateAndFlags state_and_flags = GetStateAndFlags(std::memory_order_relaxed);
281     if (LIKELY(!state_and_flags.IsFlagSet(ThreadFlag::kCheckpointRequest) &&
282                !state_and_flags.IsFlagSet(ThreadFlag::kEmptyCheckpointRequest) &&
283                !state_and_flags.IsFlagSet(ThreadFlag::kActiveSuspendBarrier))) {
284       break;
285     } else if (state_and_flags.IsFlagSet(ThreadFlag::kActiveSuspendBarrier)) {
286       PassActiveSuspendBarriers();
287     } else {
288       // Impossible
289       LOG(FATAL) << "Fatal, thread transitioned into suspended without running the checkpoint";
290     }
291   }
292 }
293 
CheckBarrierInactive(WrappedSuspend1Barrier * suspend1_barrier)294 inline void Thread::CheckBarrierInactive(WrappedSuspend1Barrier* suspend1_barrier) {
295   for (WrappedSuspend1Barrier* w = tlsPtr_.active_suspend1_barriers; w != nullptr; w = w->next_) {
296     CHECK_EQ(w->magic_, WrappedSuspend1Barrier::kMagic)
297         << "first = " << tlsPtr_.active_suspend1_barriers << " current = " << w
298         << " next = " << w->next_;
299     CHECK_NE(w, suspend1_barrier);
300   }
301 }
302 
AddSuspend1Barrier(WrappedSuspend1Barrier * suspend1_barrier)303 inline void Thread::AddSuspend1Barrier(WrappedSuspend1Barrier* suspend1_barrier) {
304   if (tlsPtr_.active_suspend1_barriers != nullptr) {
305     CHECK_EQ(tlsPtr_.active_suspend1_barriers->magic_, WrappedSuspend1Barrier::kMagic)
306         << "first = " << tlsPtr_.active_suspend1_barriers;
307   }
308   CHECK_EQ(suspend1_barrier->magic_, WrappedSuspend1Barrier::kMagic);
309   suspend1_barrier->next_ = tlsPtr_.active_suspend1_barriers;
310   tlsPtr_.active_suspend1_barriers = suspend1_barrier;
311 }
312 
RemoveFirstSuspend1Barrier(WrappedSuspend1Barrier * suspend1_barrier)313 inline void Thread::RemoveFirstSuspend1Barrier(WrappedSuspend1Barrier* suspend1_barrier) {
314   DCHECK_EQ(tlsPtr_.active_suspend1_barriers, suspend1_barrier);
315   tlsPtr_.active_suspend1_barriers = tlsPtr_.active_suspend1_barriers->next_;
316 }
317 
RemoveSuspend1Barrier(WrappedSuspend1Barrier * barrier)318 inline void Thread::RemoveSuspend1Barrier(WrappedSuspend1Barrier* barrier) {
319   // 'barrier' should be in the list. If not, we will get a SIGSEGV with fault address of 4 or 8.
320   WrappedSuspend1Barrier** last = &tlsPtr_.active_suspend1_barriers;
321   while (*last != barrier) {
322     last = &((*last)->next_);
323   }
324   *last = (*last)->next_;
325 }
326 
HasActiveSuspendBarrier()327 inline bool Thread::HasActiveSuspendBarrier() {
328   return tlsPtr_.active_suspend1_barriers != nullptr ||
329          tlsPtr_.active_suspendall_barrier != nullptr;
330 }
331 
TransitionFromRunnableToSuspended(ThreadState new_state)332 inline void Thread::TransitionFromRunnableToSuspended(ThreadState new_state) {
333   // Note: JNI stubs inline a fast path of this method that transitions to suspended if
334   // there are no flags set and then clears the `held_mutexes[kMutatorLock]` (this comes
335   // from a specialized `BaseMutex::RegisterAsLockedImpl(., kMutatorLock)` inlined from
336   // the `GetMutatorLock()->TransitionFromRunnableToSuspended(this)` below).
337   // Therefore any code added here (other than debug build assertions) should be gated
338   // on some flag being set, so that the JNI stub can take the slow path to get here.
339   AssertThreadSuspensionIsAllowable();
340   PoisonObjectPointersIfDebug();
341   DCHECK_EQ(this, Thread::Current());
342   // Change to non-runnable state, thereby appearing suspended to the system.
343   TransitionToSuspendedAndRunCheckpoints(new_state);
344   // Mark the release of the share of the mutator lock.
345   GetMutatorLock()->TransitionFromRunnableToSuspended(this);
346   // Once suspended - check the active suspend barrier flag
347   CheckActiveSuspendBarriers();
348 }
349 
TransitionFromSuspendedToRunnable(bool fail_on_suspend_req)350 inline ThreadState Thread::TransitionFromSuspendedToRunnable(bool fail_on_suspend_req) {
351   // Note: JNI stubs inline a fast path of this method that transitions to Runnable if
352   // there are no flags set and then stores the mutator lock to `held_mutexes[kMutatorLock]`
353   // (this comes from a specialized `BaseMutex::RegisterAsUnlockedImpl(., kMutatorLock)`
354   // inlined from the `GetMutatorLock()->TransitionFromSuspendedToRunnable(this)` below).
355   // Therefore any code added here (other than debug build assertions) should be gated
356   // on some flag being set, so that the JNI stub can take the slow path to get here.
357   DCHECK(this == Current());
358   StateAndFlags old_state_and_flags = GetStateAndFlags(std::memory_order_relaxed);
359   ThreadState old_state = old_state_and_flags.GetState();
360   DCHECK_NE(old_state, ThreadState::kRunnable);
361   while (true) {
362     DCHECK(!old_state_and_flags.IsFlagSet(ThreadFlag::kSuspensionImmune));
363     GetMutatorLock()->AssertNotHeld(this);  // Otherwise we starve GC.
364     // Optimize for the return from native code case - this is the fast path.
365     // Atomically change from suspended to runnable if no suspend request pending.
366     constexpr uint32_t kCheckedFlags =
367         SuspendOrCheckpointRequestFlags() |
368         enum_cast<uint32_t>(ThreadFlag::kActiveSuspendBarrier) |
369         FlipFunctionFlags();
370     if (LIKELY(!old_state_and_flags.IsAnyOfFlagsSet(kCheckedFlags))) {
371       // CAS the value with a memory barrier.
372       StateAndFlags new_state_and_flags = old_state_and_flags.WithState(ThreadState::kRunnable);
373       if (LIKELY(tls32_.state_and_flags.CompareAndSetWeakAcquire(old_state_and_flags.GetValue(),
374                                                                  new_state_and_flags.GetValue()))) {
375         // Mark the acquisition of a share of the mutator lock.
376         GetMutatorLock()->TransitionFromSuspendedToRunnable(this);
377         break;
378       }
379     } else if (old_state_and_flags.IsFlagSet(ThreadFlag::kActiveSuspendBarrier)) {
380       PassActiveSuspendBarriers();
381     } else if (UNLIKELY(old_state_and_flags.IsFlagSet(ThreadFlag::kCheckpointRequest) ||
382                         old_state_and_flags.IsFlagSet(ThreadFlag::kEmptyCheckpointRequest))) {
383       // Checkpoint flags should not be set while in suspended state.
384       static_assert(static_cast<std::underlying_type_t<ThreadState>>(ThreadState::kRunnable) == 0u);
385       LOG(FATAL) << "Transitioning to Runnable with checkpoint flag,"
386                  // Note: Keeping unused flags. If they are set, it points to memory corruption.
387                  << " flags=" << old_state_and_flags.WithState(ThreadState::kRunnable).GetValue()
388                  << " state=" << old_state_and_flags.GetState();
389     } else if (old_state_and_flags.IsFlagSet(ThreadFlag::kSuspendRequest)) {
390       auto fake_mutator_locker = []() SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
391                                      NO_THREAD_SAFETY_ANALYSIS {};
392       if (fail_on_suspend_req) {
393         // Should get here EXTREMELY rarely.
394         fake_mutator_locker();  // We lie to make thread-safety analysis mostly work. See thread.h.
395         return ThreadState::kInvalidState;
396       }
397       // Wait while our suspend count is non-zero.
398 
399       // We pass null to the MutexLock as we may be in a situation where the
400       // runtime is shutting down. Guarding ourselves from that situation
401       // requires to take the shutdown lock, which is undesirable here.
402       Thread* thread_to_pass = nullptr;
403       if (kIsDebugBuild && !IsDaemon()) {
404         // We know we can make our debug locking checks on non-daemon threads,
405         // so re-enable them on debug builds.
406         thread_to_pass = this;
407       }
408       MutexLock mu(thread_to_pass, *Locks::thread_suspend_count_lock_);
409       // Reload state and flags after locking the mutex.
410       old_state_and_flags = GetStateAndFlags(std::memory_order_relaxed);
411       DCHECK_EQ(old_state, old_state_and_flags.GetState());
412       while (old_state_and_flags.IsFlagSet(ThreadFlag::kSuspendRequest)) {
413         // Re-check when Thread::resume_cond_ is notified.
414         Thread::resume_cond_->Wait(thread_to_pass);
415         // Reload state and flags after waiting.
416         old_state_and_flags = GetStateAndFlags(std::memory_order_relaxed);
417         DCHECK_EQ(old_state, old_state_and_flags.GetState());
418       }
419       DCHECK_EQ(GetSuspendCount(), 0);
420     } else if (UNLIKELY(old_state_and_flags.IsFlagSet(ThreadFlag::kRunningFlipFunction))) {
421       DCHECK(!old_state_and_flags.IsFlagSet(ThreadFlag::kPendingFlipFunction));
422       // Do this before transitioning to runnable, both because we shouldn't wait in a runnable
423       // state, and so that the thread running the flip function can DCHECK we're not runnable.
424       WaitForFlipFunction(this);
425     } else if (old_state_and_flags.IsFlagSet(ThreadFlag::kPendingFlipFunction)) {
426       // Logically acquire mutator lock in shared mode.
427       DCHECK(!old_state_and_flags.IsFlagSet(ThreadFlag::kRunningFlipFunction));
428       if (EnsureFlipFunctionStarted(this, this, old_state_and_flags)) {
429         break;
430       }
431     }
432     // Reload state and flags.
433     old_state_and_flags = GetStateAndFlags(std::memory_order_relaxed);
434     DCHECK_EQ(old_state, old_state_and_flags.GetState());
435   }
436   DCHECK_EQ(this->GetState(), ThreadState::kRunnable);
437   return static_cast<ThreadState>(old_state);
438 }
439 
AllocTlab(size_t bytes)440 inline mirror::Object* Thread::AllocTlab(size_t bytes) {
441   DCHECK_GE(TlabSize(), bytes);
442   ++tlsPtr_.thread_local_objects;
443   mirror::Object* ret = reinterpret_cast<mirror::Object*>(tlsPtr_.thread_local_pos);
444   tlsPtr_.thread_local_pos += bytes;
445   return ret;
446 }
447 
PushOnThreadLocalAllocationStack(mirror::Object * obj)448 inline bool Thread::PushOnThreadLocalAllocationStack(mirror::Object* obj) {
449   DCHECK_LE(tlsPtr_.thread_local_alloc_stack_top, tlsPtr_.thread_local_alloc_stack_end);
450   if (tlsPtr_.thread_local_alloc_stack_top < tlsPtr_.thread_local_alloc_stack_end) {
451     // There's room.
452     DCHECK_LE(reinterpret_cast<uint8_t*>(tlsPtr_.thread_local_alloc_stack_top) +
453               sizeof(StackReference<mirror::Object>),
454               reinterpret_cast<uint8_t*>(tlsPtr_.thread_local_alloc_stack_end));
455     DCHECK(tlsPtr_.thread_local_alloc_stack_top->AsMirrorPtr() == nullptr);
456     tlsPtr_.thread_local_alloc_stack_top->Assign(obj);
457     ++tlsPtr_.thread_local_alloc_stack_top;
458     return true;
459   }
460   return false;
461 }
462 
GetWeakRefAccessEnabled()463 inline bool Thread::GetWeakRefAccessEnabled() const {
464   DCHECK(gUseReadBarrier);
465   DCHECK(this == Thread::Current());
466   WeakRefAccessState s = tls32_.weak_ref_access_enabled.load(std::memory_order_relaxed);
467   if (LIKELY(s == WeakRefAccessState::kVisiblyEnabled)) {
468     return true;
469   }
470   s = tls32_.weak_ref_access_enabled.load(std::memory_order_acquire);
471   if (s == WeakRefAccessState::kVisiblyEnabled) {
472     return true;
473   } else if (s == WeakRefAccessState::kDisabled) {
474     return false;
475   }
476   DCHECK(s == WeakRefAccessState::kEnabled)
477       << "state = " << static_cast<std::underlying_type_t<WeakRefAccessState>>(s);
478   // The state is only changed back to DISABLED during a checkpoint. Thus no other thread can
479   // change the value concurrently here. No other thread reads the value we store here, so there
480   // is no need for a release store.
481   tls32_.weak_ref_access_enabled.store(WeakRefAccessState::kVisiblyEnabled,
482                                        std::memory_order_relaxed);
483   return true;
484 }
485 
SetThreadLocalAllocationStack(StackReference<mirror::Object> * start,StackReference<mirror::Object> * end)486 inline void Thread::SetThreadLocalAllocationStack(StackReference<mirror::Object>* start,
487                                                   StackReference<mirror::Object>* end) {
488   DCHECK(Thread::Current() == this) << "Should be called by self";
489   DCHECK(start != nullptr);
490   DCHECK(end != nullptr);
491   DCHECK_ALIGNED(start, sizeof(StackReference<mirror::Object>));
492   DCHECK_ALIGNED(end, sizeof(StackReference<mirror::Object>));
493   DCHECK_LT(start, end);
494   tlsPtr_.thread_local_alloc_stack_end = end;
495   tlsPtr_.thread_local_alloc_stack_top = start;
496 }
497 
RevokeThreadLocalAllocationStack()498 inline void Thread::RevokeThreadLocalAllocationStack() {
499   if (kIsDebugBuild) {
500     // Note: self is not necessarily equal to this thread since thread may be suspended.
501     Thread* self = Thread::Current();
502     DCHECK(this == self || GetState() != ThreadState::kRunnable)
503         << GetState() << " thread " << this << " self " << self;
504   }
505   tlsPtr_.thread_local_alloc_stack_end = nullptr;
506   tlsPtr_.thread_local_alloc_stack_top = nullptr;
507 }
508 
PoisonObjectPointersIfDebug()509 inline void Thread::PoisonObjectPointersIfDebug() {
510   if (kObjPtrPoisoning) {
511     Thread::Current()->PoisonObjectPointers();
512   }
513 }
514 
IncrementSuspendCount(Thread * self,AtomicInteger * suspendall_barrier,WrappedSuspend1Barrier * suspend1_barrier,SuspendReason reason)515 inline void Thread::IncrementSuspendCount(Thread* self,
516                                           AtomicInteger* suspendall_barrier,
517                                           WrappedSuspend1Barrier* suspend1_barrier,
518                                           SuspendReason reason) {
519   if (kIsDebugBuild) {
520     Locks::thread_suspend_count_lock_->AssertHeld(self);
521     if (this != self) {
522       Locks::thread_list_lock_->AssertHeld(self);
523     }
524   }
525   if (UNLIKELY(reason == SuspendReason::kForUserCode)) {
526     Locks::user_code_suspension_lock_->AssertHeld(self);
527   }
528 
529   uint32_t flags = enum_cast<uint32_t>(ThreadFlag::kSuspendRequest);
530   if (suspendall_barrier != nullptr) {
531     DCHECK(suspend1_barrier == nullptr);
532     DCHECK(tlsPtr_.active_suspendall_barrier == nullptr);
533     tlsPtr_.active_suspendall_barrier = suspendall_barrier;
534     flags |= enum_cast<uint32_t>(ThreadFlag::kActiveSuspendBarrier);
535   } else if (suspend1_barrier != nullptr) {
536     AddSuspend1Barrier(suspend1_barrier);
537     flags |= enum_cast<uint32_t>(ThreadFlag::kActiveSuspendBarrier);
538   }
539 
540   ++tls32_.suspend_count;
541   if (reason == SuspendReason::kForUserCode) {
542     ++tls32_.user_code_suspend_count;
543   }
544 
545   // Two bits might be set simultaneously.
546   tls32_.state_and_flags.fetch_or(flags, std::memory_order_release);
547   TriggerSuspend();
548 }
549 
IncrementSuspendCount(Thread * self)550 inline void Thread::IncrementSuspendCount(Thread* self) {
551   IncrementSuspendCount(self, nullptr, nullptr, SuspendReason::kInternal);
552 }
553 
DecrementSuspendCount(Thread * self,bool for_user_code)554 inline void Thread::DecrementSuspendCount(Thread* self, bool for_user_code) {
555   DCHECK(ReadFlag(ThreadFlag::kSuspendRequest, std::memory_order_relaxed));
556   Locks::thread_suspend_count_lock_->AssertHeld(self);
557   if (UNLIKELY(tls32_.suspend_count <= 0)) {
558     UnsafeLogFatalForSuspendCount(self, this);
559     UNREACHABLE();
560   }
561   if (for_user_code) {
562     Locks::user_code_suspension_lock_->AssertHeld(self);
563     if (UNLIKELY(tls32_.user_code_suspend_count <= 0)) {
564       LOG(ERROR) << "user_code_suspend_count incorrect";
565       UnsafeLogFatalForSuspendCount(self, this);
566       UNREACHABLE();
567     }
568     --tls32_.user_code_suspend_count;
569   }
570 
571   --tls32_.suspend_count;
572 
573   if (tls32_.suspend_count == 0) {
574     AtomicClearFlag(ThreadFlag::kSuspendRequest, std::memory_order_release);
575   }
576 }
577 
PushShadowFrame(ShadowFrame * new_top_frame)578 inline ShadowFrame* Thread::PushShadowFrame(ShadowFrame* new_top_frame) {
579   new_top_frame->CheckConsistentVRegs();
580   return tlsPtr_.managed_stack.PushShadowFrame(new_top_frame);
581 }
582 
PopShadowFrame()583 inline ShadowFrame* Thread::PopShadowFrame() {
584   return tlsPtr_.managed_stack.PopShadowFrame();
585 }
586 
587 template <>
588 inline uint8_t* Thread::GetStackEnd<StackType::kHardware>() const {
589   return tlsPtr_.stack_end;
590 }
591 template <>
592 inline void Thread::SetStackEnd<StackType::kHardware>(uint8_t* new_stack_end) {
593   tlsPtr_.stack_end = new_stack_end;
594 }
595 template <>
596 inline uint8_t* Thread::GetStackBegin<StackType::kHardware>() const {
597   return tlsPtr_.stack_begin;
598 }
599 template <>
600 inline void Thread::SetStackBegin<StackType::kHardware>(uint8_t* new_stack_begin) {
601   tlsPtr_.stack_begin = new_stack_begin;
602 }
603 template <>
604 inline size_t Thread::GetStackSize<StackType::kHardware>() const {
605   return tlsPtr_.stack_size;
606 }
607 template <>
608 inline void Thread::SetStackSize<StackType::kHardware>(size_t new_stack_size) {
609   tlsPtr_.stack_size = new_stack_size;
610 }
611 
GetStackEndForInterpreter(bool implicit_overflow_check)612 inline uint8_t* Thread::GetStackEndForInterpreter(bool implicit_overflow_check) const {
613   uint8_t* end = GetStackEnd<kNativeStackType>() + (implicit_overflow_check
614       ? GetStackOverflowReservedBytes(kRuntimeQuickCodeISA)
615           : 0);
616   if (kIsDebugBuild) {
617     // In a debuggable build, but especially under ASAN, the access-checks interpreter has a
618     // potentially humongous stack size. We don't want to take too much of the stack regularly,
619     // so do not increase the regular reserved size (for compiled code etc) and only report the
620     // virtually smaller stack to the interpreter here.
621     end += GetStackOverflowReservedBytes(kRuntimeQuickCodeISA);
622   }
623   return end;
624 }
625 
626 template <StackType stack_type>
ResetDefaultStackEnd()627 inline void Thread::ResetDefaultStackEnd() {
628   // Our stacks grow down, so we want stack_end_ to be near there, but reserving enough room
629   // to throw a StackOverflowError.
630   SetStackEnd<stack_type>(
631       GetStackBegin<stack_type>() + GetStackOverflowReservedBytes(kRuntimeQuickCodeISA));
632 }
633 
634 template <StackType stack_type>
SetStackEndForStackOverflow()635 inline void Thread::SetStackEndForStackOverflow()
636     REQUIRES_SHARED(Locks::mutator_lock_) {
637   // During stack overflow we allow use of the full stack.
638   if (GetStackEnd<stack_type>() == GetStackBegin<stack_type>()) {
639     // However, we seem to have already extended to use the full stack.
640     LOG(ERROR) << "Need to increase kStackOverflowReservedBytes (currently "
641                << GetStackOverflowReservedBytes(kRuntimeQuickCodeISA) << ")?";
642     DumpStack(LOG_STREAM(ERROR));
643     LOG(FATAL) << "Recursive stack overflow.";
644   }
645 
646   SetStackEnd<stack_type>(GetStackBegin<stack_type>());
647 }
648 
NotifyOnThreadExit(ThreadExitFlag * tef)649 inline void Thread::NotifyOnThreadExit(ThreadExitFlag* tef) {
650   DCHECK_EQ(tef->exited_, false);
651   DCHECK(tlsPtr_.thread_exit_flags == nullptr || !tlsPtr_.thread_exit_flags->exited_);
652   tef->next_ = tlsPtr_.thread_exit_flags;
653   tlsPtr_.thread_exit_flags = tef;
654   if (tef->next_ != nullptr) {
655     DCHECK(!tef->next_->HasExited());
656     tef->next_->prev_ = tef;
657   }
658   tef->prev_ = nullptr;
659 }
660 
UnregisterThreadExitFlag(ThreadExitFlag * tef)661 inline void Thread::UnregisterThreadExitFlag(ThreadExitFlag* tef) {
662   if (tef->HasExited()) {
663     // List is no longer used; each client will deallocate its own ThreadExitFlag.
664     return;
665   }
666   DCHECK(IsRegistered(tef));
667   // Remove tef from the list.
668   if (tef->next_ != nullptr) {
669     tef->next_->prev_ = tef->prev_;
670   }
671   if (tef->prev_ == nullptr) {
672     DCHECK_EQ(tlsPtr_.thread_exit_flags, tef);
673     tlsPtr_.thread_exit_flags = tef->next_;
674   } else {
675     DCHECK_NE(tlsPtr_.thread_exit_flags, tef);
676     tef->prev_->next_ = tef->next_;
677   }
678   DCHECK(tlsPtr_.thread_exit_flags == nullptr || tlsPtr_.thread_exit_flags->prev_ == nullptr);
679 }
680 
DCheckUnregisteredEverywhere(ThreadExitFlag * first,ThreadExitFlag * last)681 inline void Thread::DCheckUnregisteredEverywhere(ThreadExitFlag* first, ThreadExitFlag* last) {
682   if (!kIsDebugBuild) {
683     return;
684   }
685   Thread* self = Thread::Current();
686   MutexLock mu(self, *Locks::thread_list_lock_);
687   Runtime::Current()->GetThreadList()->ForEach([&](Thread* t) REQUIRES(Locks::thread_list_lock_) {
688     for (ThreadExitFlag* tef = t->tlsPtr_.thread_exit_flags; tef != nullptr; tef = tef->next_) {
689       CHECK(tef < first || tef > last)
690           << "tef = " << std::hex << tef << " first = " << first << std::dec;
691     }
692     // Also perform a minimal consistency check on each list.
693     ThreadExitFlag* flags = t->tlsPtr_.thread_exit_flags;
694     CHECK(flags == nullptr || flags->prev_ == nullptr);
695   });
696 }
697 
IsRegistered(ThreadExitFlag * query_tef)698 inline bool Thread::IsRegistered(ThreadExitFlag* query_tef) {
699   for (ThreadExitFlag* tef = tlsPtr_.thread_exit_flags; tef != nullptr; tef = tef->next_) {
700     if (tef == query_tef) {
701       return true;
702     }
703   }
704   return false;
705 }
706 
DisallowPreMonitorMutexes()707 inline void Thread::DisallowPreMonitorMutexes() {
708   if (kIsDebugBuild) {
709     CHECK(this == Thread::Current());
710     CHECK(GetHeldMutex(kMonitorLock) == nullptr);
711     // Pretend we hold a kMonitorLock level mutex to detect disallowed mutex
712     // acquisitions by checkpoint Run() methods.  We don't normally register or thus check
713     // kMonitorLock level mutexes, but this is an exception.
714     Mutex* ph = cp_placeholder_mutex_.load(std::memory_order_acquire);
715     if (UNLIKELY(ph == nullptr)) {
716       Mutex* new_ph = new Mutex("checkpoint placeholder mutex", kMonitorLock);
717       if (LIKELY(cp_placeholder_mutex_.compare_exchange_strong(ph, new_ph))) {
718         ph = new_ph;
719       } else {
720         // ph now has the value set by another thread.
721         delete new_ph;
722       }
723     }
724     SetHeldMutex(kMonitorLock, ph);
725   }
726 }
727 
728 // Undo the effect of the previous call. Again only invoked by the thread itself.
AllowPreMonitorMutexes()729 inline void Thread::AllowPreMonitorMutexes() {
730   if (kIsDebugBuild) {
731     CHECK_EQ(GetHeldMutex(kMonitorLock), cp_placeholder_mutex_.load(std::memory_order_relaxed));
732     SetHeldMutex(kMonitorLock, nullptr);
733   }
734 }
735 
736 }  // namespace art
737 
738 #endif  // ART_RUNTIME_THREAD_INL_H_
739