#include <stddef.h>
#include "base/atomicops.h"
#include "base/cfi_buildflags.h"
#include "base/debug/asan_invalid_access.h"
#include "base/debug/profiler.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/sanitizer_buildflags.h"
#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
#include "base/threading/thread.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
#if BUILDFLAG(IS_WIN)
#include <windows.h>
#else
#include <dlfcn.h>
#endif
namespace base {
namespace {
const base::subtle::Atomic32 kMagicValue = 42;
#if defined(ADDRESS_SANITIZER)
#define HARMFUL_ACCESS(action, error_regexp) \
EXPECT_DEATH_IF_SUPPORTED(action, error_regexp)
#elif BUILDFLAG(IS_HWASAN)
#define HARMFUL_ACCESS(action, error_regexp) \
EXPECT_DEATH(action, "tag-mismatch")
#else
#define HARMFUL_ACCESS(action, error_regexp)
#define HARMFUL_ACCESS_IS_NOOP
#endif
void DoReadUninitializedValue(volatile char *ptr) {
if (*ptr == 64) {
VLOG(1) << "Uninit condition is true";
} else {
VLOG(1) << "Uninit condition is false";
}
}
void ReadUninitializedValue(volatile char *ptr) {
#if defined(MEMORY_SANITIZER)
EXPECT_DEATH(DoReadUninitializedValue(ptr),
"use-of-uninitialized-value");
#else
DoReadUninitializedValue(ptr);
#endif
}
#ifndef HARMFUL_ACCESS_IS_NOOP
void ReadValueOutOfArrayBoundsLeft(char *ptr) {
char c = ptr[-2];
VLOG(1) << "Reading a byte out of bounds: " << c;
}
void ReadValueOutOfArrayBoundsRight(char *ptr, size_t size) {
char c = ptr[size + 1];
VLOG(1) << "Reading a byte out of bounds: " << c;
}
void WriteValueOutOfArrayBoundsLeft(char *ptr) {
ptr[-1] = kMagicValue;
}
void WriteValueOutOfArrayBoundsRight(char *ptr, size_t size) {
ptr[size] = kMagicValue;
}
#endif
void MakeSomeErrors(char *ptr, size_t size) {
ReadUninitializedValue(ptr);
HARMFUL_ACCESS(ReadValueOutOfArrayBoundsLeft(ptr), "2 bytes before");
HARMFUL_ACCESS(ReadValueOutOfArrayBoundsRight(ptr, size), "1 bytes after");
HARMFUL_ACCESS(WriteValueOutOfArrayBoundsLeft(ptr), "1 bytes before");
HARMFUL_ACCESS(WriteValueOutOfArrayBoundsRight(ptr, size), "0 bytes after");
}
}
#if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \
defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
defined(UNDEFINED_SANITIZER)
#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_WIN)
#define MAYBE_LinksSanitizerOptions DISABLED_LinksSanitizerOptions
#else
#define MAYBE_LinksSanitizerOptions LinksSanitizerOptions
#endif
TEST(ToolsSanityTest, MAYBE_LinksSanitizerOptions) {
constexpr char kSym[] = "_sanitizer_options_link_helper";
#if BUILDFLAG(IS_WIN)
auto sym = GetProcAddress(GetModuleHandle(nullptr), kSym);
#else
void* sym = dlsym(RTLD_DEFAULT, kSym);
#endif
EXPECT_TRUE(sym != nullptr);
}
#endif
TEST(ToolsSanityTest, MemoryLeak) {
int* volatile leak = new int[256];
leak[4] = 1;
}
TEST(ToolsSanityTest, AccessesToNewMemory) {
char* foo = new char[16];
MakeSomeErrors(foo, 16);
delete [] foo;
HARMFUL_ACCESS(foo[5] = 0, "heap-use-after-free");
}
TEST(ToolsSanityTest, AccessesToMallocMemory) {
char* foo = reinterpret_cast<char*>(malloc(16));
MakeSomeErrors(foo, 16);
free(foo);
HARMFUL_ACCESS(foo[5] = 0, "heap-use-after-free");
}
TEST(ToolsSanityTest, AccessesToStack) {
char foo[16];
ReadUninitializedValue(foo);
HARMFUL_ACCESS(ReadValueOutOfArrayBoundsLeft(foo),
"underflows this variable");
HARMFUL_ACCESS(ReadValueOutOfArrayBoundsRight(foo, 16),
"overflows this variable");
HARMFUL_ACCESS(WriteValueOutOfArrayBoundsLeft(foo),
"underflows this variable");
HARMFUL_ACCESS(WriteValueOutOfArrayBoundsRight(foo, 16),
"overflows this variable");
}
#if defined(ADDRESS_SANITIZER)
#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) || \
BUILDFLAG(IS_FUCHSIA)
#define MAYBE_SingleElementDeletedWithBraces \
DISABLED_SingleElementDeletedWithBraces
#define MAYBE_ArrayDeletedWithoutBraces DISABLED_ArrayDeletedWithoutBraces
#else
#define MAYBE_ArrayDeletedWithoutBraces ArrayDeletedWithoutBraces
#define MAYBE_SingleElementDeletedWithBraces SingleElementDeletedWithBraces
#endif
static int* allocateArray() {
return new int[10];
}
TEST(ToolsSanityTest, MAYBE_ArrayDeletedWithoutBraces) {
int* volatile foo = allocateArray();
HARMFUL_ACCESS(delete foo, "alloc-dealloc-mismatch");
delete [] foo;
}
static int* allocateScalar() {
return new int;
}
TEST(ToolsSanityTest, MAYBE_SingleElementDeletedWithBraces) {
int* volatile foo = allocateScalar();
(void) foo;
HARMFUL_ACCESS(delete [] foo, "alloc-dealloc-mismatch");
delete foo;
}
#endif
TEST(ToolsSanityTest, DISABLED_AddressSanitizerNullDerefCrashTest) {
int* volatile zero = NULL;
*zero = 0;
}
TEST(ToolsSanityTest, DISABLED_AddressSanitizerLocalOOBCrashTest) {
int array[5];
int* volatile access = &array[5];
*access = 43;
}
namespace {
int g_asan_test_global_array[10];
}
TEST(ToolsSanityTest, DISABLED_AddressSanitizerGlobalOOBCrashTest) {
int* volatile access = g_asan_test_global_array - 1;
*access = 43;
}
#ifndef HARMFUL_ACCESS_IS_NOOP
TEST(ToolsSanityTest, AsanHeapOverflow) {
HARMFUL_ACCESS(debug::AsanHeapOverflow(), "after");
}
TEST(ToolsSanityTest, AsanHeapUnderflow) {
HARMFUL_ACCESS(debug::AsanHeapUnderflow(), "before");
}
TEST(ToolsSanityTest, AsanHeapUseAfterFree) {
HARMFUL_ACCESS(debug::AsanHeapUseAfterFree(), "heap-use-after-free");
}
#if BUILDFLAG(IS_WIN)
TEST(ToolsSanityTest, DISABLED_AsanCorruptHeapBlock) {
HARMFUL_ACCESS(debug::AsanCorruptHeapBlock(), "");
}
TEST(ToolsSanityTest, DISABLED_AsanCorruptHeap) {
EXPECT_DEATH(debug::AsanCorruptHeap(), "");
}
#endif
#endif
namespace {
class TOOLS_SANITY_TEST_CONCURRENT_THREAD : public PlatformThread::Delegate {
public:
explicit TOOLS_SANITY_TEST_CONCURRENT_THREAD(bool *value) : value_(value) {}
~TOOLS_SANITY_TEST_CONCURRENT_THREAD() override = default;
void ThreadMain() override {
*value_ = true;
PlatformThread::Sleep(Milliseconds(100));
}
private:
raw_ptr<bool> value_;
};
class ReleaseStoreThread : public PlatformThread::Delegate {
public:
explicit ReleaseStoreThread(base::subtle::Atomic32 *value) : value_(value) {}
~ReleaseStoreThread() override = default;
void ThreadMain() override {
base::subtle::Release_Store(value_, kMagicValue);
PlatformThread::Sleep(Milliseconds(100));
}
private:
raw_ptr<base::subtle::Atomic32> value_;
};
class AcquireLoadThread : public PlatformThread::Delegate {
public:
explicit AcquireLoadThread(base::subtle::Atomic32 *value) : value_(value) {}
~AcquireLoadThread() override = default;
void ThreadMain() override {
PlatformThread::Sleep(Milliseconds(100));
base::subtle::Acquire_Load(value_);
}
private:
raw_ptr<base::subtle::Atomic32> value_;
};
void RunInParallel(PlatformThread::Delegate *d1, PlatformThread::Delegate *d2) {
PlatformThreadHandle a;
PlatformThreadHandle b;
PlatformThread::Create(0, d1, &a);
PlatformThread::Create(0, d2, &b);
PlatformThread::Join(a);
PlatformThread::Join(b);
}
#if defined(THREAD_SANITIZER)
void DataRace() {
bool *shared = new bool(false);
TOOLS_SANITY_TEST_CONCURRENT_THREAD thread1(shared), thread2(shared);
RunInParallel(&thread1, &thread2);
EXPECT_TRUE(*shared);
delete shared;
CHECK(0);
}
#endif
}
#if defined(THREAD_SANITIZER)
TEST(ToolsSanityTest, DataRace) {
EXPECT_DEATH(DataRace(), "1 race:base/tools_sanity_unittest.cc");
}
#endif
TEST(ToolsSanityTest, AnnotateBenignRace) {
bool shared = false;
ANNOTATE_BENIGN_RACE(&shared, "Intentional race - make sure doesn't show up");
TOOLS_SANITY_TEST_CONCURRENT_THREAD thread1(&shared), thread2(&shared);
RunInParallel(&thread1, &thread2);
EXPECT_TRUE(shared);
}
TEST(ToolsSanityTest, AtomicsAreIgnored) {
base::subtle::Atomic32 shared = 0;
ReleaseStoreThread thread1(&shared);
AcquireLoadThread thread2(&shared);
RunInParallel(&thread1, &thread2);
EXPECT_EQ(kMagicValue, shared);
}
#if BUILDFLAG(CFI_ENFORCEMENT_TRAP)
#if BUILDFLAG(IS_WIN)
#define CFI_ERROR_MSG "EXCEPTION_ILLEGAL_INSTRUCTION"
#elif BUILDFLAG(IS_ANDROID)
#define CFI_ERROR_MSG "^$"
#else
#define CFI_ERROR_MSG "ILL_ILLOPN"
#endif
#elif BUILDFLAG(CFI_ENFORCEMENT_DIAGNOSTIC)
#define CFI_ERROR_MSG "runtime error: control flow integrity check"
#endif
#if defined(CFI_ERROR_MSG)
class A {
public:
A(): n_(0) {}
virtual void f() { n_++; }
protected:
int n_;
};
class B: public A {
public:
void f() override { n_--; }
};
class C: public B {
public:
void f() override { n_ += 2; }
};
NOINLINE void KillVptrAndCall(A *obj) {
*reinterpret_cast<void **>(obj) = 0;
obj->f();
}
TEST(ToolsSanityTest, BadVirtualCallNull) {
A a;
B b;
EXPECT_DEATH({ KillVptrAndCall(&a); KillVptrAndCall(&b); }, CFI_ERROR_MSG);
}
NOINLINE void OverwriteVptrAndCall(B *obj, A *vptr) {
*reinterpret_cast<void **>(obj) = *reinterpret_cast<void **>(vptr);
obj->f();
}
TEST(ToolsSanityTest, BadVirtualCallWrongType) {
A a;
B b;
C c;
EXPECT_DEATH({ OverwriteVptrAndCall(&b, &a); OverwriteVptrAndCall(&b, &c); },
CFI_ERROR_MSG);
}
#if BUILDFLAG(CFI_CAST_CHECK)
TEST(ToolsSanityTest, BadDerivedCast) {
A a;
EXPECT_DEATH((void)(B*)&a, CFI_ERROR_MSG);
}
TEST(ToolsSanityTest, BadUnrelatedCast) {
class A {
virtual void f() {}
};
class B {
virtual void f() {}
};
A a;
EXPECT_DEATH((void)(B*)&a, CFI_ERROR_MSG);
}
#endif
#endif
#undef CFI_ERROR_MSG
#undef HARMFUL_ACCESS
#undef HARMFUL_ACCESS_IS_NOOP
}