// Quickly access the current thread from a JNIEnv. inline Thread* Thread::ForEnv(JNIEnv* env) {
JNIEnvExt* full_env(down_cast<JNIEnvExt*>(env)); return full_env->GetSelf();
}
inline size_t Thread::GetStackOverflowProtectedSize() { // The kMemoryToolStackGuardSizeScale is expected to be 1 when ASan is not enabled. // As the function is always inlined, in those cases each function call should turn // into a simple reference to gPageSize. return kMemoryToolStackGuardSizeScale * gPageSize;
}
inline ObjPtr<mirror::Object> Thread::DecodeJObject(jobject obj) const { if (obj == nullptr) { return nullptr;
}
IndirectRef ref = reinterpret_cast<IndirectRef>(obj); if (LIKELY(IndirectReferenceTable::IsJniTransitionOrLocalReference(ref))) { // For JNI transitions, the `jclass` for a static method points to the // `CompressedReference<>` in the `ArtMethod::declaring_class_` and other `jobject` // arguments point to spilled stack references but a `StackReference<>` is just // a subclass of `CompressedReference<>`. Local references also point to // a `CompressedReference<>` encapsulated in a `GcRoot<>`. if (kIsDebugBuild && IndirectReferenceTable::GetIndirectRefKind(ref) == kJniTransition) {
CHECK(IsJniTransitionReference(obj));
} auto* cref = IndirectReferenceTable::ClearIndirectRefKind<
mirror::CompressedReference<mirror::Object>*>(ref);
ObjPtr<mirror::Object> result = cref->AsMirrorPtr(); if (kIsDebugBuild && IndirectReferenceTable::GetIndirectRefKind(ref) != kJniTransition) {
CHECK_EQ(result, tlsPtr_.jni_env->locals_.Get(ref));
} return result;
} else { return DecodeGlobalJObject(obj);
}
}
inlinevoid Thread::AllowThreadSuspension() {
CheckSuspend(); // Invalidate the current thread's object pointers (ObjPtr) to catch possible moving GC bugs due // to missing handles.
PoisonObjectPointers();
}
inlinevoid Thread::CheckSuspend(bool implicit) {
DCHECK_EQ(Thread::Current(), this); while (true) { // Memory_order_relaxed should be OK, since RunCheckpointFunction shares a lock with the // requestor, and FullSuspendCheck() re-checks later. But we currently need memory_order_acquire // for the empty checkpoint path. // TODO (b/382722942): Revisit after we fix RunEmptyCheckpoint().
StateAndFlags state_and_flags = GetStateAndFlags(std::memory_order_acquire); if (LIKELY(!state_and_flags.IsAnyOfFlagsSet(SuspendOrCheckpointRequestFlags()))) { break;
} elseif (state_and_flags.IsFlagSet(ThreadFlag::kCheckpointRequest)) {
RunCheckpointFunction();
} elseif (state_and_flags.IsFlagSet(ThreadFlag::kSuspendRequest) &&
!state_and_flags.IsFlagSet(ThreadFlag::kSuspensionImmune)) {
FullSuspendCheck(implicit);
implicit = false; // We do not need to `MadviseAwayAlternateSignalStack()` anymore.
} elseif (state_and_flags.IsFlagSet(ThreadFlag::kEmptyCheckpointRequest)) {
RunEmptyCheckpoint();
} else {
DCHECK(state_and_flags.IsFlagSet(ThreadFlag::kSuspensionImmune)); break;
}
} if (implicit) { // For implicit suspend check we want to `madvise()` away // the alternate signal stack to avoid wasting memory.
MadviseAwayAlternateSignalStack();
}
}
inlinevoid Thread::CheckEmptyCheckpointFromWeakRefAccess(BaseMutex* cond_var_mutex) {
Thread* self = Thread::Current();
DCHECK_EQ(self, this); for (;;) { // TODO (b/382722942): Revisit memory ordering after we fix RunEmptyCheckpoint(). if (ReadFlag(ThreadFlag::kEmptyCheckpointRequest, std::memory_order_acquire)) {
RunEmptyCheckpoint(); // Check we hold only an expected mutex when accessing weak ref. if (kIsDebugBuild) { for (int i = kLockLevelCount - 1; i >= 0; --i) {
BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i)); if (held_mutex != nullptr && held_mutex != GetMutatorLock() &&
held_mutex != cond_var_mutex &&
held_mutex != cp_placeholder_mutex_.load(std::memory_order_relaxed)) { // placeholder_mutex may still be nullptr. That's OK.
CHECK(Locks::IsExpectedOnWeakRefAccess(held_mutex))
<< "Holding unexpected mutex " << held_mutex->GetName()
<< " when accessing weak ref";
}
}
}
} else { break;
}
}
}
inlinevoid Thread::CheckEmptyCheckpointFromMutex() {
DCHECK_EQ(Thread::Current(), this); for (;;) { // TODO (b/382722942): Revisit memory ordering after we fix RunEmptyCheckpoint(). if (ReadFlag(ThreadFlag::kEmptyCheckpointRequest, std::memory_order_acquire)) {
RunEmptyCheckpoint();
} else { break;
}
}
}
inline ThreadState Thread::SetState(ThreadState new_state) { // Should only be used to change between suspended states. // Cannot use this code to change into or from Runnable as changing to Runnable should // fail if the `ThreadFlag::kSuspendRequest` is set and changing from Runnable might // miss passing an active suspend barrier.
DCHECK_NE(new_state, ThreadState::kRunnable); if (kIsDebugBuild && this != Thread::Current()) {
std::string name;
GetThreadName(name);
LOG(FATAL) << "Thread \"" << name << "\"(" << this << " != Thread::Current()="
<< Thread::Current() << ") changing state to " << new_state;
}
inlinebool Thread::IsThreadSuspensionAllowable() const { if (tls32_.no_thread_suspension != 0) { returnfalse;
} for (int i = kLockLevelCount - 1; i >= 0; --i) { if (i != kMutatorLock &&
i != kUserCodeSuspensionLock &&
GetHeldMutex(static_cast<LockLevel>(i)) != nullptr) { returnfalse;
}
} // Thread autoanalysis isn't able to understand that the GetHeldMutex(...) or AssertHeld means we // have the mutex meaning we need to do this hack. auto is_suspending_for_user_code = [this]() NO_THREAD_SAFETY_ANALYSIS { return tls32_.user_code_suspend_count != 0;
}; if (GetHeldMutex(kUserCodeSuspensionLock) != nullptr && is_suspending_for_user_code()) { returnfalse;
} returntrue;
}
inlinevoid Thread::AssertThreadSuspensionIsAllowable(bool check_locks) const { if (kIsDebugBuild) { if (gAborting == 0) {
CHECK_EQ(0u, tls32_.no_thread_suspension) << tlsPtr_.last_no_thread_suspension_cause;
} if (check_locks) { bool bad_mutexes_held = false; for (int i = kLockLevelCount - 1; i >= 0; --i) { // We expect no locks except the mutator lock. User code suspension lock is OK as long as // we aren't going to be held suspended due to SuspendReason::kForUserCode. if (i != kMutatorLock && i != kUserCodeSuspensionLock) {
BaseMutex* held_mutex = GetHeldMutex(static_cast<LockLevel>(i)); if (held_mutex != nullptr) {
LOG(ERROR) << "holding \"" << held_mutex->GetName()
<< "\" at point where thread suspension is expected";
bad_mutexes_held = true;
}
}
} // Make sure that if we hold the user_code_suspension_lock_ we aren't suspending due to // user_code_suspend_count which would prevent the thread from ever waking up. Thread // autoanalysis isn't able to understand that the GetHeldMutex(...) or AssertHeld means we // have the mutex meaning we need to do this hack. auto is_suspending_for_user_code = [this]() NO_THREAD_SAFETY_ANALYSIS { return tls32_.user_code_suspend_count != 0;
}; if (GetHeldMutex(kUserCodeSuspensionLock) != nullptr && is_suspending_for_user_code()) {
LOG(ERROR) << "suspending due to user-code while holding \""
<< Locks::user_code_suspension_lock_->GetName() << "\"! Thread would never "
<< "wake up.";
bad_mutexes_held = true;
} if (gAborting == 0) {
CHECK(!bad_mutexes_held);
}
}
}
}
inlinevoid Thread::TransitionToSuspendedAndRunCheckpoints(ThreadState new_state) {
DCHECK_NE(new_state, ThreadState::kRunnable); while (true) { // memory_order_relaxed is OK for ordinary checkpoints, which enforce ordering via // thread_suspend_count_lock_ . It is not currently OK for empty checkpoints. // TODO (b/382722942): Consider changing back to memory_order_relaxed after fixing empty // checkpoints.
StateAndFlags old_state_and_flags = GetStateAndFlags(std::memory_order_acquire);
DCHECK_EQ(old_state_and_flags.GetState(), ThreadState::kRunnable); if (UNLIKELY(old_state_and_flags.IsFlagSet(ThreadFlag::kCheckpointRequest))) {
IncrementStatsCounter(&checkpoint_count_);
RunCheckpointFunction(); continue;
} if (UNLIKELY(old_state_and_flags.IsFlagSet(ThreadFlag::kEmptyCheckpointRequest))) {
RunEmptyCheckpoint(); continue;
} // Change the state but keep the current flags (kCheckpointRequest is clear).
DCHECK(!old_state_and_flags.IsFlagSet(ThreadFlag::kCheckpointRequest));
DCHECK(!old_state_and_flags.IsFlagSet(ThreadFlag::kEmptyCheckpointRequest));
StateAndFlags new_state_and_flags = old_state_and_flags.WithState(new_state);
// CAS the value, ensuring that prior memory operations are visible to any thread // that observes that we are suspended. bool done =
tls32_.state_and_flags.CompareAndSetWeakRelease(old_state_and_flags.GetValue(),
new_state_and_flags.GetValue()); if (LIKELY(done)) {
IncrementStatsCounter(&suspended_count_); break;
}
}
}
inlinevoid Thread::CheckActiveSuspendBarriers() {
DCHECK_NE(GetState(), ThreadState::kRunnable); while (true) { // memory_order_relaxed is OK here, since PassActiveSuspendBarriers() rechecks with // thread_suspend_count_lock_ .
StateAndFlags state_and_flags = GetStateAndFlags(std::memory_order_relaxed); if (LIKELY(!state_and_flags.IsFlagSet(ThreadFlag::kCheckpointRequest) &&
!state_and_flags.IsFlagSet(ThreadFlag::kEmptyCheckpointRequest) &&
!state_and_flags.IsFlagSet(ThreadFlag::kActiveSuspendBarrier))) { break;
} elseif (state_and_flags.IsFlagSet(ThreadFlag::kActiveSuspendBarrier)) {
PassActiveSuspendBarriers();
} else { // Impossible
LOG(FATAL) << "Fatal, thread transitioned into suspended without running the checkpoint";
}
}
}
inlinevoid Thread::CheckBarrierInactive(WrappedSuspend1Barrier* suspend1_barrier) { for (WrappedSuspend1Barrier* w = tlsPtr_.active_suspend1_barriers; w != nullptr; w = w->next_) {
CHECK_EQ(w->magic_, WrappedSuspend1Barrier::kMagic)
<< "first = " << tlsPtr_.active_suspend1_barriers << " current = " << w
<< " next = " << w->next_;
CHECK_NE(w, suspend1_barrier);
}
}
inlinevoid Thread::RemoveSuspend1Barrier(WrappedSuspend1Barrier* barrier) { // 'barrier' should be in the list. If not, we will get a SIGSEGV with fault address of 4 or 8.
WrappedSuspend1Barrier** last = &tlsPtr_.active_suspend1_barriers; while (*last != barrier) {
last = &((*last)->next_);
}
*last = (*last)->next_;
}
inlinevoid Thread::TransitionFromRunnableToSuspended(ThreadState new_state) { // Note: JNI stubs inline a fast path of this method that transitions to suspended if // there are no flags set and then clears the `held_mutexes[kMutatorLock]` (this comes // from a specialized `BaseMutex::RegisterAsLockedImpl(., kMutatorLock)` inlined from // the `GetMutatorLock()->TransitionFromRunnableToSuspended(this)` below). // Therefore any code added here (other than debug build assertions) should be gated // on some flag being set, so that the JNI stub can take the slow path to get here.
AssertThreadSuspensionIsAllowable();
PoisonObjectPointersOnCurrentThread();
DCHECK_EQ(this, Thread::Current()); // Change to non-runnable state, thereby appearing suspended to the system.
TransitionToSuspendedAndRunCheckpoints(new_state); // Mark the release of the share of the mutator lock.
GetMutatorLock()->TransitionFromRunnableToSuspended(this); // Once suspended - check the active suspend barrier flag
CheckActiveSuspendBarriers();
}
inline ThreadState Thread::TransitionFromSuspendedToRunnable(bool fail_on_suspend_req) { // Note: JNI stubs inline a fast path of this method that transitions to Runnable if // there are no flags set and then stores the mutator lock to `held_mutexes[kMutatorLock]` // (this comes from a specialized `BaseMutex::RegisterAsUnlockedImpl(., kMutatorLock)` // inlined from the `GetMutatorLock()->TransitionFromSuspendedToRunnable(this)` below). // Therefore any code added here (other than debug build assertions) should be gated // on some flag being set, so that the JNI stub can take the slow path to get here.
DCHECK(this == Current());
StateAndFlags old_state_and_flags = GetStateAndFlags(std::memory_order_relaxed);
ThreadState old_state = old_state_and_flags.GetState();
DCHECK_NE(old_state, ThreadState::kRunnable); while (true) {
DCHECK(!old_state_and_flags.IsFlagSet(ThreadFlag::kSuspensionImmune));
GetMutatorLock()->AssertNotHeld(this); // Otherwise we starve GC. // Optimize for the return from native code case - this is the fast path. // Atomically change from suspended to runnable if no suspend request pending.
constexpr uint32_t kCheckedFlags =
SuspendOrCheckpointRequestFlags() |
enum_cast<uint32_t>(ThreadFlag::kActiveSuspendBarrier) |
FlipFunctionFlags(); if (LIKELY(!old_state_and_flags.IsAnyOfFlagsSet(kCheckedFlags))) { // CAS the value with a memory barrier.
StateAndFlags new_state_and_flags = old_state_and_flags.WithState(ThreadState::kRunnable); if (LIKELY(tls32_.state_and_flags.CompareAndSetWeakAcquire(old_state_and_flags.GetValue(),
new_state_and_flags.GetValue()))) { // Mark the acquisition of a share of the mutator lock.
GetMutatorLock()->TransitionFromSuspendedToRunnable(this); break;
}
} elseif (old_state_and_flags.IsFlagSet(ThreadFlag::kActiveSuspendBarrier)) {
PassActiveSuspendBarriers();
} elseif (UNLIKELY(old_state_and_flags.IsFlagSet(ThreadFlag::kCheckpointRequest) ||
old_state_and_flags.IsFlagSet(ThreadFlag::kEmptyCheckpointRequest))) { // Checkpoint flags should not be set while in suspended state.
static_assert(static_cast<std::underlying_type_t<ThreadState>>(ThreadState::kRunnable) == 0u);
LOG(FATAL) << "Transitioning to Runnable with checkpoint flag," // Note: Keeping unused flags. If they are set, it points to memory corruption.
<< " flags=" << old_state_and_flags.WithState(ThreadState::kRunnable).GetValue()
<< " state=" << old_state_and_flags.GetState();
} elseif (old_state_and_flags.IsFlagSet(ThreadFlag::kSuspendRequest)) { auto fake_mutator_locker = []() SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
NO_THREAD_SAFETY_ANALYSIS {}; if (fail_on_suspend_req) { // Should get here EXTREMELY rarely.
fake_mutator_locker(); // We lie to make thread-safety analysis mostly work. See thread.h. return ThreadState::kInvalidState;
} // Wait while our suspend count is non-zero.
// We pass null to the MutexLock as we may be in a situation where the // runtime is shutting down. Guarding ourselves from that situation // requires to take the shutdown lock, which is undesirable here.
Thread* thread_to_pass = nullptr; if (kIsDebugBuild && !IsDaemon()) { // We know we can make our debug locking checks on non-daemon threads, // so re-enable them on debug builds.
thread_to_pass = this;
}
MutexLock mu(thread_to_pass, *Locks::thread_suspend_count_lock_); // Reload state and flags after locking the mutex.
old_state_and_flags = GetStateAndFlags(std::memory_order_relaxed);
DCHECK_EQ(old_state, old_state_and_flags.GetState()); while (old_state_and_flags.IsFlagSet(ThreadFlag::kSuspendRequest)) { // Re-check when Thread::resume_cond_ is notified.
Thread::resume_cond_->Wait(thread_to_pass); // Reload state and flags after waiting.
old_state_and_flags = GetStateAndFlags(std::memory_order_relaxed);
DCHECK_EQ(old_state, old_state_and_flags.GetState());
}
DCHECK_EQ(GetSuspendCount(), 0);
} elseif (UNLIKELY(old_state_and_flags.IsFlagSet(ThreadFlag::kRunningFlipFunction))) {
DCHECK(!old_state_and_flags.IsFlagSet(ThreadFlag::kPendingFlipFunction)); // Do this before transitioning to runnable, both because we shouldn't wait in a runnable // state, and so that the thread running the flip function can DCHECK we're not runnable.
WaitForFlipFunction(this);
} elseif (old_state_and_flags.IsFlagSet(ThreadFlag::kPendingFlipFunction)) { // Logically acquire mutator lock in shared mode.
DCHECK(!old_state_and_flags.IsFlagSet(ThreadFlag::kRunningFlipFunction)); if (EnsureFlipFunctionStarted(this, this, old_state_and_flags)) { break;
}
} // Reload state and flags.
old_state_and_flags = GetStateAndFlags(std::memory_order_relaxed);
DCHECK_EQ(old_state, old_state_and_flags.GetState());
}
DCHECK_EQ(this->GetState(), ThreadState::kRunnable); returnstatic_cast<ThreadState>(old_state);
}
inlinebool Thread::GetWeakRefAccessEnabled() const {
DCHECK(gUseReadBarrier);
DCHECK(this == Thread::Current());
WeakRefAccessState s = tls32_.weak_ref_access_enabled.load(std::memory_order_relaxed); if (LIKELY(s == WeakRefAccessState::kVisiblyEnabled)) { returntrue;
}
s = tls32_.weak_ref_access_enabled.load(std::memory_order_acquire); if (s == WeakRefAccessState::kVisiblyEnabled) { returntrue;
} elseif (s == WeakRefAccessState::kDisabled) { returnfalse;
}
DCHECK(s == WeakRefAccessState::kEnabled)
<< "state = " << static_cast<std::underlying_type_t<WeakRefAccessState>>(s); // The state is only changed back to DISABLED during a checkpoint. Thus no other thread can // change the value concurrently here. No other thread reads the value we store here, so there // is no need for a release store.
tls32_.weak_ref_access_enabled.store(WeakRefAccessState::kVisiblyEnabled,
std::memory_order_relaxed); returntrue;
}
inline uint8_t* Thread::GetStackEndForInterpreter(bool implicit_overflow_check) const {
uint8_t* end = GetStackEnd<kNativeStackType>() + (implicit_overflow_check
? GetStackOverflowReservedBytes(kRuntimeQuickCodeISA)
: 0); if (kIsDebugBuild) { // In a debuggable build, but especially under ASAN, the access-checks interpreter has a // potentially humongous stack size. We don't want to take too much of the stack regularly, // so do not increase the regular reserved size (for compiled code etc) and only report the // virtually smaller stack to the interpreter here.
end += GetStackOverflowReservedBytes(kRuntimeQuickCodeISA);
} return end;
}
template <StackType stack_type> inlinevoid Thread::ResetDefaultStackEnd() { // Our stacks grow down, so we want stack_end_ to be near there, but reserving enough room // to throw a StackOverflowError.
SetStackEnd<stack_type>(
GetStackBegin<stack_type>() + GetStackOverflowReservedBytes(kRuntimeQuickCodeISA));
}
template <StackType stack_type> inlinevoid Thread::SetStackEndForStackOverflow()
REQUIRES_SHARED(Locks::mutator_lock_) { // During stack overflow we allow use of the full stack. if (GetStackEnd<stack_type>() == GetStackBegin<stack_type>()) { // However, we seem to have already extended to use the full stack.
LOG(ERROR) << "Need to increase kStackOverflowReservedBytes (currently "
<< GetStackOverflowReservedBytes(kRuntimeQuickCodeISA) << ")?";
DumpStack(LOG_STREAM(ERROR));
LOG(FATAL) << "Recursive stack overflow.";
}
inlinevoid Thread::DisallowPreMonitorMutexes() { if (kIsDebugBuild) {
CHECK(this == Thread::Current());
CHECK(GetHeldMutex(kMonitorLock) == nullptr); // Pretend we hold a kMonitorLock level mutex to detect disallowed mutex // acquisitions by checkpoint Run() methods. We don't normally register or thus check // kMonitorLock level mutexes, but this is an exception.
Mutex* ph = cp_placeholder_mutex_.load(std::memory_order_acquire); if (UNLIKELY(ph == nullptr)) {
Mutex* new_ph = new Mutex("checkpoint placeholder mutex", kMonitorLock); if (LIKELY(cp_placeholder_mutex_.compare_exchange_strong(ph, new_ph))) {
ph = new_ph;
} else { // ph now has the value set by another thread. delete new_ph;
}
}
SetHeldMutex(kMonitorLock, ph);
}
}
// Undo the effect of the previous call. Again only invoked by the thread itself. inlinevoid Thread::AllowPreMonitorMutexes() { if (kIsDebugBuild) {
CHECK_EQ(GetHeldMutex(kMonitorLock), cp_placeholder_mutex_.load(std::memory_order_relaxed));
SetHeldMutex(kMonitorLock, nullptr);
}
}
} // namespace art
#endif// ART_RUNTIME_THREAD_INL_H_
Messung V0.5 in Prozent
¤ Dauer der Verarbeitung: 0.3 Sekunden
(vorverarbeitet am 2026-06-29)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.