#include "base/threading/thread_checker_impl.h"
#include "base/check.h"
#include "base/debug/stack_trace.h"
#include "base/sequence_token.h"
#include "base/task/single_thread_task_runner.h"
#include "base/threading/platform_thread.h"
#include "base/threading/thread_checker.h"
#include "base/threading/thread_local.h"
namespace {
bool g_log_stack = false;
}
namespace base {
void ThreadCheckerImpl::EnableStackLogging() {
g_log_stack = true;
}
ThreadCheckerImpl::ThreadCheckerImpl() {
AutoLock auto_lock(lock_);
EnsureAssigned();
}
ThreadCheckerImpl::~ThreadCheckerImpl() = default;
ThreadCheckerImpl::ThreadCheckerImpl(ThreadCheckerImpl&& other) {
CHECK(other.CalledOnValidThread());
bound_at_ = std::move(other.bound_at_);
thread_ref_ = other.thread_ref_;
task_token_ = other.task_token_;
sequence_token_ = other.sequence_token_;
other.thread_ref_ = PlatformThreadRef();
other.task_token_ = internal::TaskToken();
other.sequence_token_ = internal::SequenceToken();
}
ThreadCheckerImpl& ThreadCheckerImpl::operator=(ThreadCheckerImpl&& other) {
CHECK(CalledOnValidThread());
CHECK(other.CalledOnValidThread());
TS_UNCHECKED_READ(thread_ref_) = TS_UNCHECKED_READ(other.thread_ref_);
TS_UNCHECKED_READ(task_token_) = TS_UNCHECKED_READ(other.task_token_);
TS_UNCHECKED_READ(sequence_token_) = TS_UNCHECKED_READ(other.sequence_token_);
TS_UNCHECKED_READ(other.thread_ref_) = PlatformThreadRef();
TS_UNCHECKED_READ(other.task_token_) = internal::TaskToken();
TS_UNCHECKED_READ(other.sequence_token_) = internal::SequenceToken();
return *this;
}
bool ThreadCheckerImpl::CalledOnValidThread(
std::unique_ptr<debug::StackTrace>* out_bound_at) const {
AutoLock auto_lock(lock_);
EnsureAssigned();
DCHECK(sequence_token_.IsValid());
if (thread_ref_ == PlatformThread::CurrentRef()) {
if (!task_token_.IsValid()) {
return true;
}
if (task_token_ == internal::TaskToken::GetForCurrentThread()) {
return true;
}
if (ThreadLocalStorage::HasBeenDestroyed()) {
return true;
}
if (sequence_token_ == internal::SequenceToken::GetForCurrentThread() &&
internal::CurrentTaskIsThreadBound()) {
return true;
}
}
if (out_bound_at && bound_at_) {
*out_bound_at = std::make_unique<debug::StackTrace>(*bound_at_);
}
return false;
}
void ThreadCheckerImpl::DetachFromThread() {
AutoLock auto_lock(lock_);
bound_at_ = nullptr;
thread_ref_ = PlatformThreadRef();
task_token_ = internal::TaskToken();
sequence_token_ = internal::SequenceToken();
}
void ThreadCheckerImpl::EnsureAssigned() const {
if (!thread_ref_.is_null()) {
return;
}
if (g_log_stack) {
bound_at_ = std::make_unique<debug::StackTrace>(size_t{10});
}
thread_ref_ = PlatformThread::CurrentRef();
task_token_ = internal::TaskToken::GetForCurrentThread();
sequence_token_ = internal::SequenceToken::GetForCurrentThread();
}
}