#include "base/threading/thread_local_storage.h"
#include <array>
#include "base/memory/raw_ptr.h"
#include "base/no_destructor.h"
#include "base/threading/simple_thread.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
#if BUILDFLAG(IS_WIN)
#include <windows.h>
#include <process.h>
#pragma warning(disable : 4311 4312)
#endif
namespace base {
#if BUILDFLAG(IS_POSIX)
namespace internal {
class ThreadLocalStorageTestInternal {
public:
static bool HasBeenDestroyed() {
return ThreadLocalStorage::HasBeenDestroyed();
}
};
}
#endif
namespace {
const int kInitialTlsValue = 0x5555;
const int kFinalTlsValue = 0x7777;
const int kNumberDestructorCallRepetitions = 3;
void ThreadLocalStorageCleanup(void* value);
ThreadLocalStorage::Slot& TLSSlot() {
static NoDestructor<ThreadLocalStorage::Slot> slot(
&ThreadLocalStorageCleanup);
return *slot;
}
class ThreadLocalStorageRunner : public DelegateSimpleThread::Delegate {
public:
explicit ThreadLocalStorageRunner(int* tls_value_ptr)
: tls_value_ptr_(tls_value_ptr) {}
ThreadLocalStorageRunner(const ThreadLocalStorageRunner&) = delete;
ThreadLocalStorageRunner& operator=(const ThreadLocalStorageRunner&) = delete;
~ThreadLocalStorageRunner() override = default;
void Run() override {
*tls_value_ptr_ = kInitialTlsValue;
TLSSlot().Set(tls_value_ptr_);
int* ptr = static_cast<int*>(TLSSlot().Get());
EXPECT_EQ(ptr, tls_value_ptr_);
EXPECT_EQ(*ptr, kInitialTlsValue);
*tls_value_ptr_ = 0;
ptr = static_cast<int*>(TLSSlot().Get());
EXPECT_EQ(ptr, tls_value_ptr_);
EXPECT_EQ(*ptr, 0);
*ptr = kFinalTlsValue + kNumberDestructorCallRepetitions;
}
private:
raw_ptr<int> tls_value_ptr_;
};
void ThreadLocalStorageCleanup(void* value) {
int* ptr = static_cast<int*>(value);
ASSERT_NE(nullptr, ptr);
if (*ptr == kFinalTlsValue) {
return;
}
ASSERT_LT(kFinalTlsValue, *ptr);
ASSERT_GE(kFinalTlsValue + kNumberDestructorCallRepetitions, *ptr);
--*ptr;
TLSSlot().Set(value);
}
#if BUILDFLAG(IS_POSIX)
constexpr intptr_t kDummyValue = 0xABCD;
constexpr size_t kKeyCount = 20;
class UseTLSDuringDestructionRunner {
public:
UseTLSDuringDestructionRunner() = default;
UseTLSDuringDestructionRunner(const UseTLSDuringDestructionRunner&) = delete;
UseTLSDuringDestructionRunner& operator=(
const UseTLSDuringDestructionRunner&) = delete;
void Run() {
ASSERT_FALSE(internal::ThreadLocalStorageTestInternal::HasBeenDestroyed());
size_t slot_index = 0;
for (; slot_index < 10; ++slot_index) {
CreateTlsKeyWithDestructor(slot_index);
}
slot_.Set(reinterpret_cast<void*>(kDummyValue));
for (; slot_index < kKeyCount; ++slot_index) {
CreateTlsKeyWithDestructor(slot_index);
}
}
bool teardown_works_correctly() { return teardown_works_correctly_; }
private:
struct TLSState {
pthread_key_t key;
raw_ptr<bool> teardown_works_correctly;
};
static void ThreadLocalDestructor(void* value) {
TLSState* state = static_cast<TLSState*>(value);
int result = pthread_setspecific(state->key, nullptr);
ASSERT_EQ(result, 0);
if (internal::ThreadLocalStorageTestInternal::HasBeenDestroyed()) {
*(state->teardown_works_correctly) = true;
return;
}
ASSERT_EQ(reinterpret_cast<intptr_t>(slot_.Get()), kDummyValue);
}
void CreateTlsKeyWithDestructor(size_t index) {
ASSERT_LT(index, kKeyCount);
tls_states_[index].teardown_works_correctly = &teardown_works_correctly_;
int result = pthread_key_create(
&(tls_states_[index].key),
UseTLSDuringDestructionRunner::ThreadLocalDestructor);
ASSERT_EQ(result, 0);
result = pthread_setspecific(tls_states_[index].key, &tls_states_[index]);
ASSERT_EQ(result, 0);
}
static base::ThreadLocalStorage::Slot slot_;
bool teardown_works_correctly_ = false;
std::array<TLSState, kKeyCount> tls_states_;
};
base::ThreadLocalStorage::Slot UseTLSDuringDestructionRunner::slot_;
void* UseTLSTestThreadRun(void* input) {
UseTLSDuringDestructionRunner* runner =
static_cast<UseTLSDuringDestructionRunner*>(input);
runner->Run();
return nullptr;
}
#endif
class TlsDestructionOrderRunner : public DelegateSimpleThread::Delegate {
public:
TlsDestructionOrderRunner(int n_slots, int spacing)
: n_slots_(n_slots), spacing_(spacing) {}
void Run() override {
destructor_calls.clear();
for (int slot = 1; slot < n_slots_ + 1; ++slot) {
for (int i = 0; i < spacing_; ++i) {
ThreadLocalStorage::Slot empty_slot(nullptr);
}
NewStaticTLSSlot(slot);
}
}
static std::vector<int> destructor_calls;
private:
ThreadLocalStorage::Slot& NewStaticTLSSlot(int n) {
NoDestructor<ThreadLocalStorage::Slot> slot(
&TlsDestructionOrderRunner::Destructor);
slot->Set(reinterpret_cast<void*>(n));
return *slot;
}
static void Destructor(void* value) {
int n = reinterpret_cast<intptr_t>(value);
destructor_calls.push_back(n);
}
int n_slots_;
int spacing_;
};
std::vector<int> TlsDestructionOrderRunner::destructor_calls;
class CreateDuringDestructionRunner : public DelegateSimpleThread::Delegate {
public:
void Run() override {
second_destructor_called = false;
NoDestructor<ThreadLocalStorage::Slot> slot(
&CreateDuringDestructionRunner::FirstDestructor);
slot->Set(reinterpret_cast<void*>(123));
}
static bool second_destructor_called;
private:
static void FirstDestructor(void*) {
NoDestructor<ThreadLocalStorage::Slot> slot(
&CreateDuringDestructionRunner::SecondDestructor);
slot->Set(reinterpret_cast<void*>(234));
}
static void SecondDestructor(void*) { second_destructor_called = true; }
};
bool CreateDuringDestructionRunner::second_destructor_called = false;
}
TEST(ThreadLocalStorageTest, Basics) {
ThreadLocalStorage::Slot slot;
slot.Set(reinterpret_cast<void*>(123));
int value = reinterpret_cast<intptr_t>(slot.Get());
EXPECT_EQ(value, 123);
}
#if defined(THREAD_SANITIZER)
#define MAYBE_TLSDestructors DISABLED_TLSDestructors
#else
#define MAYBE_TLSDestructors TLSDestructors
#endif
TEST(ThreadLocalStorageTest, MAYBE_TLSDestructors) {
const int kNumThreads = 5;
std::array<int, kNumThreads> values;
std::array<ThreadLocalStorageRunner*, kNumThreads> thread_delegates;
std::array<DelegateSimpleThread*, kNumThreads> threads;
for (int index = 0; index < kNumThreads; index++) {
values[index] = kInitialTlsValue;
thread_delegates[index] = new ThreadLocalStorageRunner(&values[index]);
threads[index] =
new DelegateSimpleThread(thread_delegates[index], "tls thread");
threads[index]->Start();
}
for (int index = 0; index < kNumThreads; index++) {
threads[index]->Join();
delete threads[index];
delete thread_delegates[index];
EXPECT_EQ(values[index], kFinalTlsValue);
}
}
TEST(ThreadLocalStorageTest, TLSReclaim) {
for (int i = 0; i < 1000; ++i) {
ThreadLocalStorage::Slot slot(nullptr);
EXPECT_EQ(nullptr, slot.Get());
slot.Set(reinterpret_cast<void*>(0xBAADF00D));
EXPECT_EQ(reinterpret_cast<void*>(0xBAADF00D), slot.Get());
}
}
#if BUILDFLAG(IS_POSIX)
TEST(ThreadLocalStorageTest, UseTLSDuringDestruction) {
UseTLSDuringDestructionRunner runner;
pthread_t thread;
int result = pthread_create(&thread, nullptr, UseTLSTestThreadRun, &runner);
ASSERT_EQ(result, 0);
result = pthread_join(thread, nullptr);
ASSERT_EQ(result, 0);
EXPECT_TRUE(runner.teardown_works_correctly());
}
#endif
TEST(ThreadLocalStorageTest, DestructionOrder) {
const size_t kNSlots = 5;
const size_t kSpacing = 100;
TlsDestructionOrderRunner runner(kNSlots, kSpacing);
DelegateSimpleThread thread(&runner, "tls thread");
thread.Start();
thread.Join();
ASSERT_EQ(kNSlots, TlsDestructionOrderRunner::destructor_calls.size());
for (int call = 0, slot = kNSlots; slot > 0; --slot, ++call) {
EXPECT_EQ(slot, TlsDestructionOrderRunner::destructor_calls[call]);
}
}
TEST(ThreadLocalStorageTest, CreateDuringDestruction) {
CreateDuringDestructionRunner runner;
DelegateSimpleThread thread(&runner, "tls thread");
thread.Start();
thread.Join();
ASSERT_TRUE(CreateDuringDestructionRunner::second_destructor_called);
}
}