aboutsummaryrefslogtreecommitdiff
path: root/lib/asan/tests
diff options
context:
space:
mode:
Diffstat (limited to 'lib/asan/tests')
-rw-r--r--lib/asan/tests/asan_benchmarks_test.cc86
-rw-r--r--lib/asan/tests/asan_break_optimization.cc18
-rw-r--r--lib/asan/tests/asan_exceptions_test.cc27
-rw-r--r--lib/asan/tests/asan_globals_test.cc24
-rw-r--r--lib/asan/tests/asan_interface_test.cc334
-rw-r--r--lib/asan/tests/asan_mac_test.h16
-rw-r--r--lib/asan/tests/asan_mac_test.mm203
-rw-r--r--lib/asan/tests/asan_noinst_test.cc329
-rw-r--r--lib/asan/tests/asan_test.cc2022
-rw-r--r--lib/asan/tests/asan_test.ignore2
-rw-r--r--lib/asan/tests/asan_test_config.h44
-rw-r--r--lib/asan/tests/asan_test_utils.h30
-rw-r--r--lib/asan/tests/dlclose-test-so.cc33
-rw-r--r--lib/asan/tests/dlclose-test.cc73
-rw-r--r--lib/asan/tests/dlclose-test.tmpl1
-rw-r--r--lib/asan/tests/global-overflow.cc12
-rw-r--r--lib/asan/tests/global-overflow.tmpl3
-rw-r--r--lib/asan/tests/heap-overflow.cc9
-rw-r--r--lib/asan/tests/heap-overflow.tmpl6
-rw-r--r--lib/asan/tests/heap-overflow.tmpl.Darwin8
-rw-r--r--lib/asan/tests/large_func_test.cc33
-rw-r--r--lib/asan/tests/large_func_test.tmpl8
-rwxr-xr-xlib/asan/tests/match_output.py35
-rw-r--r--lib/asan/tests/null_deref.cc7
-rw-r--r--lib/asan/tests/null_deref.tmpl4
-rw-r--r--lib/asan/tests/shared-lib-test-so.cc21
-rw-r--r--lib/asan/tests/shared-lib-test.cc37
-rw-r--r--lib/asan/tests/shared-lib-test.tmpl7
-rw-r--r--lib/asan/tests/stack-overflow.cc7
-rw-r--r--lib/asan/tests/stack-overflow.tmpl3
-rw-r--r--lib/asan/tests/stack-use-after-return.cc24
-rw-r--r--lib/asan/tests/stack-use-after-return.disabled3
-rw-r--r--lib/asan/tests/strncpy-overflow.cc9
-rw-r--r--lib/asan/tests/strncpy-overflow.tmpl7
-rwxr-xr-xlib/asan/tests/test_output.sh47
-rw-r--r--lib/asan/tests/use-after-free.c6
-rw-r--r--lib/asan/tests/use-after-free.cc6
-rw-r--r--lib/asan/tests/use-after-free.tmpl10
38 files changed, 3554 insertions, 0 deletions
diff --git a/lib/asan/tests/asan_benchmarks_test.cc b/lib/asan/tests/asan_benchmarks_test.cc
new file mode 100644
index 000000000000..b72cc3fbe14b
--- /dev/null
+++ b/lib/asan/tests/asan_benchmarks_test.cc
@@ -0,0 +1,86 @@
+//===-- asan_benchmarks_test.cc ------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file is a part of AddressSanitizer, an address sanity checker.
+//
+// Some benchmarks for the instrumented code.
+//===----------------------------------------------------------------------===//
+
+#include "asan_test_config.h"
+#include "asan_test_utils.h"
+
+template<class T>
+__attribute__((noinline))
+static void ManyAccessFunc(T *x, size_t n_elements, size_t n_iter) {
+ for (size_t iter = 0; iter < n_iter; iter++) {
+ break_optimization(0);
+ // hand unroll the loop to stress the reg alloc.
+ for (size_t i = 0; i <= n_elements - 16; i += 16) {
+ x[i + 0] = i;
+ x[i + 1] = i;
+ x[i + 2] = i;
+ x[i + 3] = i;
+ x[i + 4] = i;
+ x[i + 5] = i;
+ x[i + 6] = i;
+ x[i + 7] = i;
+ x[i + 8] = i;
+ x[i + 9] = i;
+ x[i + 10] = i;
+ x[i + 11] = i;
+ x[i + 12] = i;
+ x[i + 13] = i;
+ x[i + 14] = i;
+ x[i + 15] = i;
+ }
+ }
+}
+
+TEST(AddressSanitizer, ManyAccessBenchmark) {
+ size_t kLen = 1024;
+ int *int_array = new int[kLen];
+ ManyAccessFunc(int_array, kLen, 1 << 24);
+ delete [] int_array;
+}
+
+// access 7 char elements in a 7 byte array (i.e. on the border).
+__attribute__((noinline))
+static void BorderAccessFunc(char *x, size_t n_iter) {
+ for (size_t iter = 0; iter < n_iter; iter++) {
+ break_optimization(x);
+ x[0] = 0;
+ x[1] = 0;
+ x[2] = 0;
+ x[3] = 0;
+ x[4] = 0;
+ x[5] = 0;
+ x[6] = 0;
+ }
+}
+
+TEST(AddressSanitizer, BorderAccessBenchmark) {
+ char *char_7_array = new char[7];
+ BorderAccessFunc(char_7_array, 1 << 30);
+ delete [] char_7_array;
+}
+
+static void FunctionWithLargeStack() {
+ int stack[1000];
+ Ident(stack);
+}
+
+TEST(AddressSanitizer, FakeStackBenchmark) {
+ for (int i = 0; i < 10000000; i++)
+ Ident(&FunctionWithLargeStack)();
+}
+
+int main(int argc, char **argv) {
+ testing::InitGoogleTest(&argc, argv);
+ return RUN_ALL_TESTS();
+}
diff --git a/lib/asan/tests/asan_break_optimization.cc b/lib/asan/tests/asan_break_optimization.cc
new file mode 100644
index 000000000000..acd042701e1e
--- /dev/null
+++ b/lib/asan/tests/asan_break_optimization.cc
@@ -0,0 +1,18 @@
+//===-- asan_break_optimization.cc ------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file is a part of AddressSanitizer, an address sanity checker.
+//
+//===----------------------------------------------------------------------===//
+
+#include "asan_test_utils.h"
+// Have this function in a separate file to avoid inlining.
+// (Yes, we know about cross-file inlining, but let's assume we don't use it).
+extern "C" void break_optimization(void *x) {
+}
diff --git a/lib/asan/tests/asan_exceptions_test.cc b/lib/asan/tests/asan_exceptions_test.cc
new file mode 100644
index 000000000000..ecd406de7561
--- /dev/null
+++ b/lib/asan/tests/asan_exceptions_test.cc
@@ -0,0 +1,27 @@
+// See http://llvm.org/bugs/show_bug.cgi?id=11468
+#include <stdio.h>
+#include <string>
+
+class Action {
+ public:
+ Action() {}
+ void PrintString(const std::string& msg) const {
+ fprintf(stderr, "%s\n", msg.c_str());
+ }
+ void Throw(const char& arg) const {
+ PrintString("PrintString called!"); // this line is important
+ throw arg;
+ }
+};
+
+int main() {
+ const Action a;
+ fprintf(stderr, "&a before = %p\n", &a);
+ try {
+ a.Throw('c');
+ } catch(const char&) {
+ fprintf(stderr, "&a in catch = %p\n", &a);
+ }
+ fprintf(stderr, "&a final = %p\n", &a);
+ return 0;
+}
diff --git a/lib/asan/tests/asan_globals_test.cc b/lib/asan/tests/asan_globals_test.cc
new file mode 100644
index 000000000000..2303f8bdc43b
--- /dev/null
+++ b/lib/asan/tests/asan_globals_test.cc
@@ -0,0 +1,24 @@
+//===-- asan_globals_test.cc ------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file is a part of AddressSanitizer, an address sanity checker.
+//
+// Some globals in a separate file.
+//===----------------------------------------------------------------------===//
+
+extern char glob5[5];
+static char static10[10];
+
+int GlobalsTest(int zero) {
+ static char func_static15[15];
+ glob5[zero] = 0;
+ static10[zero] = 0;
+ func_static15[zero] = 0;
+ return glob5[1] + func_static15[2];
+}
diff --git a/lib/asan/tests/asan_interface_test.cc b/lib/asan/tests/asan_interface_test.cc
new file mode 100644
index 000000000000..c26ed92468b3
--- /dev/null
+++ b/lib/asan/tests/asan_interface_test.cc
@@ -0,0 +1,334 @@
+//===-- asan_interface_test.cc ------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file is a part of AddressSanitizer, an address sanity checker.
+//
+//===----------------------------------------------------------------------===//
+#include <pthread.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "asan_test_config.h"
+#include "asan_test_utils.h"
+#include "asan_interface.h"
+
+TEST(AddressSanitizerInterface, GetEstimatedAllocatedSize) {
+ EXPECT_EQ(1, __asan_get_estimated_allocated_size(0));
+ const size_t sizes[] = { 1, 30, 1<<30 };
+ for (size_t i = 0; i < 3; i++) {
+ EXPECT_EQ(sizes[i], __asan_get_estimated_allocated_size(sizes[i]));
+ }
+}
+
+static const char* kGetAllocatedSizeErrorMsg =
+ "__asan_get_allocated_size failed";
+
+TEST(AddressSanitizerInterface, GetAllocatedSizeAndOwnershipTest) {
+ const size_t kArraySize = 100;
+ char *array = Ident((char*)malloc(kArraySize));
+ int *int_ptr = Ident(new int);
+
+ // Allocated memory is owned by allocator. Allocated size should be
+ // equal to requested size.
+ EXPECT_EQ(true, __asan_get_ownership(array));
+ EXPECT_EQ(kArraySize, __asan_get_allocated_size(array));
+ EXPECT_EQ(true, __asan_get_ownership(int_ptr));
+ EXPECT_EQ(sizeof(int), __asan_get_allocated_size(int_ptr));
+
+ // We cannot call GetAllocatedSize from the memory we didn't map,
+ // and from the interior pointers (not returned by previous malloc).
+ void *wild_addr = (void*)0x1;
+ EXPECT_EQ(false, __asan_get_ownership(wild_addr));
+ EXPECT_DEATH(__asan_get_allocated_size(wild_addr), kGetAllocatedSizeErrorMsg);
+ EXPECT_EQ(false, __asan_get_ownership(array + kArraySize / 2));
+ EXPECT_DEATH(__asan_get_allocated_size(array + kArraySize / 2),
+ kGetAllocatedSizeErrorMsg);
+
+ // NULL is a valid argument and is owned.
+ EXPECT_EQ(true, __asan_get_ownership(NULL));
+ EXPECT_EQ(0, __asan_get_allocated_size(NULL));
+
+ // When memory is freed, it's not owned, and call to GetAllocatedSize
+ // is forbidden.
+ free(array);
+ EXPECT_EQ(false, __asan_get_ownership(array));
+ EXPECT_DEATH(__asan_get_allocated_size(array), kGetAllocatedSizeErrorMsg);
+
+ delete int_ptr;
+}
+
+TEST(AddressSanitizerInterface, GetCurrentAllocatedBytesTest) {
+ size_t before_malloc, after_malloc, after_free;
+ char *array;
+ const size_t kMallocSize = 100;
+ before_malloc = __asan_get_current_allocated_bytes();
+
+ array = Ident((char*)malloc(kMallocSize));
+ after_malloc = __asan_get_current_allocated_bytes();
+ EXPECT_EQ(before_malloc + kMallocSize, after_malloc);
+
+ free(array);
+ after_free = __asan_get_current_allocated_bytes();
+ EXPECT_EQ(before_malloc, after_free);
+}
+
+static void DoDoubleFree() {
+ int *x = Ident(new int);
+ delete Ident(x);
+ delete Ident(x);
+}
+
+// This test is run in a separate process, so that large malloced
+// chunk won't remain in the free lists after the test.
+// Note: use ASSERT_* instead of EXPECT_* here.
+static void RunGetHeapSizeTestAndDie() {
+ size_t old_heap_size, new_heap_size, heap_growth;
+ // We unlikely have have chunk of this size in free list.
+ static const size_t kLargeMallocSize = 1 << 29; // 512M
+ old_heap_size = __asan_get_heap_size();
+ fprintf(stderr, "allocating %zu bytes:\n", kLargeMallocSize);
+ free(Ident(malloc(kLargeMallocSize)));
+ new_heap_size = __asan_get_heap_size();
+ heap_growth = new_heap_size - old_heap_size;
+ fprintf(stderr, "heap growth after first malloc: %zu\n", heap_growth);
+ ASSERT_GE(heap_growth, kLargeMallocSize);
+ ASSERT_LE(heap_growth, 2 * kLargeMallocSize);
+
+ // Now large chunk should fall into free list, and can be
+ // allocated without increasing heap size.
+ old_heap_size = new_heap_size;
+ free(Ident(malloc(kLargeMallocSize)));
+ heap_growth = __asan_get_heap_size() - old_heap_size;
+ fprintf(stderr, "heap growth after second malloc: %zu\n", heap_growth);
+ ASSERT_LT(heap_growth, kLargeMallocSize);
+
+ // Test passed. Now die with expected double-free.
+ DoDoubleFree();
+}
+
+TEST(AddressSanitizerInterface, GetHeapSizeTest) {
+ EXPECT_DEATH(RunGetHeapSizeTestAndDie(), "double-free");
+}
+
+// Note: use ASSERT_* instead of EXPECT_* here.
+static void DoLargeMallocForGetFreeBytesTestAndDie() {
+ size_t old_free_bytes, new_free_bytes;
+ static const size_t kLargeMallocSize = 1 << 29; // 512M
+ // If we malloc and free a large memory chunk, it will not fall
+ // into quarantine and will be available for future requests.
+ old_free_bytes = __asan_get_free_bytes();
+ fprintf(stderr, "allocating %zu bytes:\n", kLargeMallocSize);
+ fprintf(stderr, "free bytes before malloc: %zu\n", old_free_bytes);
+ free(Ident(malloc(kLargeMallocSize)));
+ new_free_bytes = __asan_get_free_bytes();
+ fprintf(stderr, "free bytes after malloc and free: %zu\n", new_free_bytes);
+ ASSERT_GE(new_free_bytes, old_free_bytes + kLargeMallocSize);
+ // Test passed.
+ DoDoubleFree();
+}
+
+TEST(AddressSanitizerInterface, GetFreeBytesTest) {
+ static const size_t kNumOfChunks = 100;
+ static const size_t kChunkSize = 100;
+ char *chunks[kNumOfChunks];
+ size_t i;
+ size_t old_free_bytes, new_free_bytes;
+ // Allocate a small chunk. Now allocator probably has a lot of these
+ // chunks to fulfill future requests. So, future requests will decrease
+ // the number of free bytes.
+ chunks[0] = Ident((char*)malloc(kChunkSize));
+ old_free_bytes = __asan_get_free_bytes();
+ for (i = 1; i < kNumOfChunks; i++) {
+ chunks[i] = Ident((char*)malloc(kChunkSize));
+ new_free_bytes = __asan_get_free_bytes();
+ EXPECT_LT(new_free_bytes, old_free_bytes);
+ old_free_bytes = new_free_bytes;
+ }
+ // Deleting these chunks will move them to quarantine, number of free
+ // bytes won't increase.
+ for (i = 0; i < kNumOfChunks; i++) {
+ free(chunks[i]);
+ EXPECT_EQ(old_free_bytes, __asan_get_free_bytes());
+ }
+ EXPECT_DEATH(DoLargeMallocForGetFreeBytesTestAndDie(), "double-free");
+}
+
+static const size_t kManyThreadsMallocSizes[] = {5, 1UL<<10, 1UL<<20, 357};
+static const size_t kManyThreadsIterations = 250;
+static const size_t kManyThreadsNumThreads = 200;
+
+void *ManyThreadsWithStatsWorker(void *arg) {
+ for (size_t iter = 0; iter < kManyThreadsIterations; iter++) {
+ for (size_t size_index = 0; size_index < 4; size_index++) {
+ free(Ident(malloc(kManyThreadsMallocSizes[size_index])));
+ }
+ }
+ return 0;
+}
+
+TEST(AddressSanitizerInterface, ManyThreadsWithStatsStressTest) {
+ size_t before_test, after_test, i;
+ pthread_t threads[kManyThreadsNumThreads];
+ before_test = __asan_get_current_allocated_bytes();
+ for (i = 0; i < kManyThreadsNumThreads; i++) {
+ pthread_create(&threads[i], 0,
+ (void* (*)(void *x))ManyThreadsWithStatsWorker, (void*)i);
+ }
+ for (i = 0; i < kManyThreadsNumThreads; i++) {
+ pthread_join(threads[i], 0);
+ }
+ after_test = __asan_get_current_allocated_bytes();
+ // ASan stats also reflect memory usage of internal ASan RTL structs,
+ // so we can't check for equality here.
+ EXPECT_LT(after_test, before_test + (1UL<<20));
+}
+
+TEST(AddressSanitizerInterface, ExitCode) {
+ int original_exit_code = __asan_set_error_exit_code(7);
+ EXPECT_EXIT(DoDoubleFree(), ::testing::ExitedWithCode(7), "");
+ EXPECT_EQ(7, __asan_set_error_exit_code(8));
+ EXPECT_EXIT(DoDoubleFree(), ::testing::ExitedWithCode(8), "");
+ EXPECT_EQ(8, __asan_set_error_exit_code(original_exit_code));
+ EXPECT_EXIT(DoDoubleFree(),
+ ::testing::ExitedWithCode(original_exit_code), "");
+}
+
+static const char* kUseAfterPoisonErrorMessage = "use-after-poison";
+
+#define ACCESS(ptr, offset) Ident(*(ptr + offset))
+
+#define DIE_ON_ACCESS(ptr, offset) \
+ EXPECT_DEATH(Ident(*(ptr + offset)), kUseAfterPoisonErrorMessage)
+
+TEST(AddressSanitizerInterface, SimplePoisonMemoryRegionTest) {
+ char *array = Ident((char*)malloc(120));
+ // poison array[40..80)
+ ASAN_POISON_MEMORY_REGION(array + 40, 40);
+ ACCESS(array, 39);
+ ACCESS(array, 80);
+ DIE_ON_ACCESS(array, 40);
+ DIE_ON_ACCESS(array, 60);
+ DIE_ON_ACCESS(array, 79);
+ ASAN_UNPOISON_MEMORY_REGION(array + 40, 40);
+ // access previously poisoned memory.
+ ACCESS(array, 40);
+ ACCESS(array, 79);
+ free(array);
+}
+
+TEST(AddressSanitizerInterface, OverlappingPoisonMemoryRegionTest) {
+ char *array = Ident((char*)malloc(120));
+ // Poison [0..40) and [80..120)
+ ASAN_POISON_MEMORY_REGION(array, 40);
+ ASAN_POISON_MEMORY_REGION(array + 80, 40);
+ DIE_ON_ACCESS(array, 20);
+ ACCESS(array, 60);
+ DIE_ON_ACCESS(array, 100);
+ // Poison whole array - [0..120)
+ ASAN_POISON_MEMORY_REGION(array, 120);
+ DIE_ON_ACCESS(array, 60);
+ // Unpoison [24..96)
+ ASAN_UNPOISON_MEMORY_REGION(array + 24, 72);
+ DIE_ON_ACCESS(array, 23);
+ ACCESS(array, 24);
+ ACCESS(array, 60);
+ ACCESS(array, 95);
+ DIE_ON_ACCESS(array, 96);
+ free(array);
+}
+
+TEST(AddressSanitizerInterface, PushAndPopWithPoisoningTest) {
+ // Vector of capacity 20
+ char *vec = Ident((char*)malloc(20));
+ ASAN_POISON_MEMORY_REGION(vec, 20);
+ for (size_t i = 0; i < 7; i++) {
+ // Simulate push_back.
+ ASAN_UNPOISON_MEMORY_REGION(vec + i, 1);
+ ACCESS(vec, i);
+ DIE_ON_ACCESS(vec, i + 1);
+ }
+ for (size_t i = 7; i > 0; i--) {
+ // Simulate pop_back.
+ ASAN_POISON_MEMORY_REGION(vec + i - 1, 1);
+ DIE_ON_ACCESS(vec, i - 1);
+ if (i > 1) ACCESS(vec, i - 2);
+ }
+ free(vec);
+}
+
+// Make sure that each aligned block of size "2^granularity" doesn't have
+// "true" value before "false" value.
+static void MakeShadowValid(bool *shadow, int length, int granularity) {
+ bool can_be_poisoned = true;
+ for (int i = length - 1; i >= 0; i--) {
+ can_be_poisoned &= shadow[i];
+ shadow[i] &= can_be_poisoned;
+ if (i % (1 << granularity) == 0) {
+ can_be_poisoned = true;
+ }
+ }
+}
+
+TEST(AddressSanitizerInterface, PoisoningStressTest) {
+ const size_t kSize = 24;
+ bool expected[kSize];
+ char *arr = Ident((char*)malloc(kSize));
+ for (size_t l1 = 0; l1 < kSize; l1++) {
+ for (size_t s1 = 1; l1 + s1 <= kSize; s1++) {
+ for (size_t l2 = 0; l2 < kSize; l2++) {
+ for (size_t s2 = 1; l2 + s2 <= kSize; s2++) {
+ // Poison [l1, l1+s1), [l2, l2+s2) and check result.
+ ASAN_UNPOISON_MEMORY_REGION(arr, kSize);
+ ASAN_POISON_MEMORY_REGION(arr + l1, s1);
+ ASAN_POISON_MEMORY_REGION(arr + l2, s2);
+ memset(expected, false, kSize);
+ memset(expected + l1, true, s1);
+ MakeShadowValid(expected, 24, /*granularity*/ 3);
+ memset(expected + l2, true, s2);
+ MakeShadowValid(expected, 24, /*granularity*/ 3);
+ for (size_t i = 0; i < kSize; i++) {
+ ASSERT_EQ(expected[i], __asan_address_is_poisoned(arr + i));
+ }
+ // Unpoison [l1, l1+s1) and [l2, l2+s2) and check result.
+ ASAN_POISON_MEMORY_REGION(arr, kSize);
+ ASAN_UNPOISON_MEMORY_REGION(arr + l1, s1);
+ ASAN_UNPOISON_MEMORY_REGION(arr + l2, s2);
+ memset(expected, true, kSize);
+ memset(expected + l1, false, s1);
+ MakeShadowValid(expected, 24, /*granularity*/ 3);
+ memset(expected + l2, false, s2);
+ MakeShadowValid(expected, 24, /*granularity*/ 3);
+ for (size_t i = 0; i < kSize; i++) {
+ ASSERT_EQ(expected[i], __asan_address_is_poisoned(arr + i));
+ }
+ }
+ }
+ }
+ }
+}
+
+static const char *kInvalidPoisonMessage = "invalid-poison-memory-range";
+static const char *kInvalidUnpoisonMessage = "invalid-unpoison-memory-range";
+
+TEST(AddressSanitizerInterface, DISABLED_InvalidPoisonAndUnpoisonCallsTest) {
+ char *array = Ident((char*)malloc(120));
+ ASAN_UNPOISON_MEMORY_REGION(array, 120);
+ // Try to unpoison not owned memory
+ EXPECT_DEATH(ASAN_UNPOISON_MEMORY_REGION(array, 121),
+ kInvalidUnpoisonMessage);
+ EXPECT_DEATH(ASAN_UNPOISON_MEMORY_REGION(array - 1, 120),
+ kInvalidUnpoisonMessage);
+
+ ASAN_POISON_MEMORY_REGION(array, 120);
+ // Try to poison not owned memory.
+ EXPECT_DEATH(ASAN_POISON_MEMORY_REGION(array, 121), kInvalidPoisonMessage);
+ EXPECT_DEATH(ASAN_POISON_MEMORY_REGION(array - 1, 120),
+ kInvalidPoisonMessage);
+ free(array);
+}
diff --git a/lib/asan/tests/asan_mac_test.h b/lib/asan/tests/asan_mac_test.h
new file mode 100644
index 000000000000..e3ad8273ae14
--- /dev/null
+++ b/lib/asan/tests/asan_mac_test.h
@@ -0,0 +1,16 @@
+extern "C" {
+ void CFAllocatorDefaultDoubleFree();
+ void CFAllocatorSystemDefaultDoubleFree();
+ void CFAllocatorMallocDoubleFree();
+ void CFAllocatorMallocZoneDoubleFree();
+ void CallFreeOnWorkqueue(void *mem);
+ void TestGCDDispatchAsync();
+ void TestGCDDispatchSync();
+ void TestGCDReuseWqthreadsAsync();
+ void TestGCDReuseWqthreadsSync();
+ void TestGCDDispatchAfter();
+ void TestGCDInTSDDestructor();
+ void TestGCDSourceEvent();
+ void TestGCDSourceCancel();
+ void TestGCDGroupAsync();
+}
diff --git a/lib/asan/tests/asan_mac_test.mm b/lib/asan/tests/asan_mac_test.mm
new file mode 100644
index 000000000000..b5dbbde4f315
--- /dev/null
+++ b/lib/asan/tests/asan_mac_test.mm
@@ -0,0 +1,203 @@
+// Mac OS X 10.6 or higher only.
+#include <dispatch/dispatch.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#import <CoreFoundation/CFBase.h>
+#import <Foundation/NSObject.h>
+
+void CFAllocatorDefaultDoubleFree() {
+ void *mem = CFAllocatorAllocate(kCFAllocatorDefault, 5, 0);
+ CFAllocatorDeallocate(kCFAllocatorDefault, mem);
+ CFAllocatorDeallocate(kCFAllocatorDefault, mem);
+}
+
+void CFAllocatorSystemDefaultDoubleFree() {
+ void *mem = CFAllocatorAllocate(kCFAllocatorSystemDefault, 5, 0);
+ CFAllocatorDeallocate(kCFAllocatorSystemDefault, mem);
+ CFAllocatorDeallocate(kCFAllocatorSystemDefault, mem);
+}
+
+void CFAllocatorMallocDoubleFree() {
+ void *mem = CFAllocatorAllocate(kCFAllocatorMalloc, 5, 0);
+ CFAllocatorDeallocate(kCFAllocatorMalloc, mem);
+ CFAllocatorDeallocate(kCFAllocatorMalloc, mem);
+}
+
+void CFAllocatorMallocZoneDoubleFree() {
+ void *mem = CFAllocatorAllocate(kCFAllocatorMallocZone, 5, 0);
+ CFAllocatorDeallocate(kCFAllocatorMallocZone, mem);
+ CFAllocatorDeallocate(kCFAllocatorMallocZone, mem);
+}
+
+
+// Test the +load instrumentation.
+// Because the +load methods are invoked before anything else is initialized,
+// it makes little sense to wrap the code below into a gTest test case.
+// If AddressSanitizer doesn't instrument the +load method below correctly,
+// everything will just crash.
+
+char kStartupStr[] =
+ "If your test didn't crash, AddressSanitizer is instrumenting "
+ "the +load methods correctly.";
+
+@interface LoadSomething : NSObject {
+}
+@end
+
+@implementation LoadSomething
+
++(void) load {
+ for (int i = 0; i < strlen(kStartupStr); i++) {
+ volatile char ch = kStartupStr[i]; // make sure no optimizations occur.
+ }
+ // Don't print anything here not to interfere with the death tests.
+}
+
+@end
+
+void worker_do_alloc(int size) {
+ char * volatile mem = malloc(size);
+ mem[0] = 0; // Ok
+ free(mem);
+}
+
+void worker_do_crash(int size) {
+ char * volatile mem = malloc(size);
+ mem[size] = 0; // BOOM
+ free(mem);
+}
+
+// Tests for the Grand Central Dispatch. See
+// http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
+// for the reference.
+
+void TestGCDDispatchAsync() {
+ dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
+ dispatch_block_t block = ^{ worker_do_crash(1024); };
+ // dispatch_async() runs the task on a worker thread that does not go through
+ // pthread_create(). We need to verify that AddressSanitizer notices that the
+ // thread has started.
+ dispatch_async(queue, block);
+ // TODO(glider): this is hacky. Need to wait for the worker instead.
+ sleep(1);
+}
+
+void TestGCDDispatchSync() {
+ dispatch_queue_t queue = dispatch_get_global_queue(2, 0);
+ dispatch_block_t block = ^{ worker_do_crash(1024); };
+ // dispatch_sync() runs the task on a worker thread that does not go through
+ // pthread_create(). We need to verify that AddressSanitizer notices that the
+ // thread has started.
+ dispatch_sync(queue, block);
+ // TODO(glider): this is hacky. Need to wait for the worker instead.
+ sleep(1);
+}
+
+// libdispatch spawns a rather small number of threads and reuses them. We need
+// to make sure AddressSanitizer handles the reusing correctly.
+void TestGCDReuseWqthreadsAsync() {
+ dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
+ dispatch_block_t block_alloc = ^{ worker_do_alloc(1024); };
+ dispatch_block_t block_crash = ^{ worker_do_crash(1024); };
+ for (int i = 0; i < 100; i++) {
+ dispatch_async(queue, block_alloc);
+ }
+ dispatch_async(queue, block_crash);
+ // TODO(glider): this is hacky. Need to wait for the workers instead.
+ sleep(1);
+}
+
+// Try to trigger abnormal behaviour of dispatch_sync() being unhandled by us.
+void TestGCDReuseWqthreadsSync() {
+ dispatch_queue_t queue[4];
+ queue[0] = dispatch_get_global_queue(2, 0);
+ queue[1] = dispatch_get_global_queue(0, 0);
+ queue[2] = dispatch_get_global_queue(-2, 0);
+ queue[3] = dispatch_queue_create("my_queue", NULL);
+ dispatch_block_t block_alloc = ^{ worker_do_alloc(1024); };
+ dispatch_block_t block_crash = ^{ worker_do_crash(1024); };
+ for (int i = 0; i < 1000; i++) {
+ dispatch_sync(queue[i % 4], block_alloc);
+ }
+ dispatch_sync(queue[3], block_crash);
+ // TODO(glider): this is hacky. Need to wait for the workers instead.
+ sleep(1);
+}
+
+void TestGCDDispatchAfter() {
+ dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
+ dispatch_block_t block_crash = ^{ worker_do_crash(1024); };
+ // Schedule the event one second from the current time.
+ dispatch_time_t milestone =
+ dispatch_time(DISPATCH_TIME_NOW, 1LL * NSEC_PER_SEC);
+ dispatch_after(milestone, queue, block_crash);
+ // Let's wait for a bit longer now.
+ // TODO(glider): this is still hacky.
+ sleep(2);
+}
+
+void worker_do_deallocate(void *ptr) {
+ free(ptr);
+}
+
+void CallFreeOnWorkqueue(void *tsd) {
+ dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
+ dispatch_block_t block_dealloc = ^{ worker_do_deallocate(tsd); };
+ dispatch_async(queue, block_dealloc);
+ // Do not wait for the worker to free the memory -- nobody is going to touch
+ // it.
+}
+
+void TestGCDSourceEvent() {
+ dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
+ dispatch_source_t timer =
+ dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
+ // Schedule the timer one second from the current time.
+ dispatch_time_t milestone =
+ dispatch_time(DISPATCH_TIME_NOW, 1LL * NSEC_PER_SEC);
+
+ dispatch_source_set_timer(timer, milestone, DISPATCH_TIME_FOREVER, 0);
+ char * volatile mem = malloc(10);
+ dispatch_source_set_event_handler(timer, ^{
+ mem[10] = 1;
+ });
+ dispatch_resume(timer);
+ sleep(2);
+}
+
+void TestGCDSourceCancel() {
+ dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
+ dispatch_source_t timer =
+ dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
+ // Schedule the timer one second from the current time.
+ dispatch_time_t milestone =
+ dispatch_time(DISPATCH_TIME_NOW, 1LL * NSEC_PER_SEC);
+
+ dispatch_source_set_timer(timer, milestone, DISPATCH_TIME_FOREVER, 0);
+ char * volatile mem = malloc(10);
+ // Both dispatch_source_set_cancel_handler() and
+ // dispatch_source_set_event_handler() use dispatch_barrier_async_f().
+ // It's tricky to test dispatch_source_set_cancel_handler() separately,
+ // so we test both here.
+ dispatch_source_set_event_handler(timer, ^{
+ dispatch_source_cancel(timer);
+ });
+ dispatch_source_set_cancel_handler(timer, ^{
+ mem[10] = 1;
+ });
+ dispatch_resume(timer);
+ sleep(2);
+}
+
+void TestGCDGroupAsync() {
+ dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
+ dispatch_group_t group = dispatch_group_create();
+ char * volatile mem = malloc(10);
+ dispatch_group_async(group, queue, ^{
+ mem[10] = 1;
+ });
+ dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
+}
diff --git a/lib/asan/tests/asan_noinst_test.cc b/lib/asan/tests/asan_noinst_test.cc
new file mode 100644
index 000000000000..204c0dacc342
--- /dev/null
+++ b/lib/asan/tests/asan_noinst_test.cc
@@ -0,0 +1,329 @@
+//===-- asan_noinst_test.cc ------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file is a part of AddressSanitizer, an address sanity checker.
+//
+// This test file should be compiled w/o asan instrumentation.
+//===----------------------------------------------------------------------===//
+#include "asan_allocator.h"
+#include "asan_interface.h"
+#include "asan_internal.h"
+#include "asan_mapping.h"
+#include "asan_stack.h"
+#include "asan_test_utils.h"
+
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <vector>
+#include <algorithm>
+#include "gtest/gtest.h"
+
+// Simple stand-alone pseudorandom number generator.
+// Current algorithm is ANSI C linear congruential PRNG.
+static inline uint32_t my_rand(uint32_t* state) {
+ return (*state = *state * 1103515245 + 12345) >> 16;
+}
+
+static uint32_t global_seed = 0;
+
+
+TEST(AddressSanitizer, InternalSimpleDeathTest) {
+ EXPECT_DEATH(exit(1), "");
+}
+
+static void MallocStress(size_t n) {
+ uint32_t seed = my_rand(&global_seed);
+ __asan::AsanStackTrace stack1;
+ stack1.trace[0] = 0xa123;
+ stack1.trace[1] = 0xa456;
+ stack1.size = 2;
+
+ __asan::AsanStackTrace stack2;
+ stack2.trace[0] = 0xb123;
+ stack2.trace[1] = 0xb456;
+ stack2.size = 2;
+
+ __asan::AsanStackTrace stack3;
+ stack3.trace[0] = 0xc123;
+ stack3.trace[1] = 0xc456;
+ stack3.size = 2;
+
+ std::vector<void *> vec;
+ for (size_t i = 0; i < n; i++) {
+ if ((i % 3) == 0) {
+ if (vec.empty()) continue;
+ size_t idx = my_rand(&seed) % vec.size();
+ void *ptr = vec[idx];
+ vec[idx] = vec.back();
+ vec.pop_back();
+ __asan::asan_free(ptr, &stack1);
+ } else {
+ size_t size = my_rand(&seed) % 1000 + 1;
+ switch ((my_rand(&seed) % 128)) {
+ case 0: size += 1024; break;
+ case 1: size += 2048; break;
+ case 2: size += 4096; break;
+ }
+ size_t alignment = 1 << (my_rand(&seed) % 10 + 1);
+ char *ptr = (char*)__asan::asan_memalign(alignment, size, &stack2);
+ vec.push_back(ptr);
+ ptr[0] = 0;
+ ptr[size-1] = 0;
+ ptr[size/2] = 0;
+ }
+ }
+ for (size_t i = 0; i < vec.size(); i++)
+ __asan::asan_free(vec[i], &stack3);
+}
+
+
+TEST(AddressSanitizer, NoInstMallocTest) {
+#ifdef __arm__
+ MallocStress(300000);
+#else
+ MallocStress(1000000);
+#endif
+}
+
+static void PrintShadow(const char *tag, uintptr_t ptr, size_t size) {
+ fprintf(stderr, "%s shadow: %lx size % 3ld: ", tag, (long)ptr, (long)size);
+ uintptr_t prev_shadow = 0;
+ for (intptr_t i = -32; i < (intptr_t)size + 32; i++) {
+ uintptr_t shadow = __asan::MemToShadow(ptr + i);
+ if (i == 0 || i == (intptr_t)size)
+ fprintf(stderr, ".");
+ if (shadow != prev_shadow) {
+ prev_shadow = shadow;
+ fprintf(stderr, "%02x", (int)*(uint8_t*)shadow);
+ }
+ }
+ fprintf(stderr, "\n");
+}
+
+TEST(AddressSanitizer, DISABLED_InternalPrintShadow) {
+ for (size_t size = 1; size <= 513; size++) {
+ char *ptr = new char[size];
+ PrintShadow("m", (uintptr_t)ptr, size);
+ delete [] ptr;
+ PrintShadow("f", (uintptr_t)ptr, size);
+ }
+}
+
+static uintptr_t pc_array[] = {
+#if __WORDSIZE == 64
+ 0x7effbf756068ULL,
+ 0x7effbf75e5abULL,
+ 0x7effc0625b7cULL,
+ 0x7effc05b8997ULL,
+ 0x7effbf990577ULL,
+ 0x7effbf990c56ULL,
+ 0x7effbf992f3cULL,
+ 0x7effbf950c22ULL,
+ 0x7effc036dba0ULL,
+ 0x7effc03638a3ULL,
+ 0x7effc035be4aULL,
+ 0x7effc0539c45ULL,
+ 0x7effc0539a65ULL,
+ 0x7effc03db9b3ULL,
+ 0x7effc03db100ULL,
+ 0x7effc037c7b8ULL,
+ 0x7effc037bfffULL,
+ 0x7effc038b777ULL,
+ 0x7effc038021cULL,
+ 0x7effc037c7d1ULL,
+ 0x7effc037bfffULL,
+ 0x7effc038b777ULL,
+ 0x7effc038021cULL,
+ 0x7effc037c7d1ULL,
+ 0x7effc037bfffULL,
+ 0x7effc038b777ULL,
+ 0x7effc038021cULL,
+ 0x7effc037c7d1ULL,
+ 0x7effc037bfffULL,
+ 0x7effc0520d26ULL,
+ 0x7effc009ddffULL,
+ 0x7effbf90bb50ULL,
+ 0x7effbdddfa69ULL,
+ 0x7effbdde1fe2ULL,
+ 0x7effbdde2424ULL,
+ 0x7effbdde27b3ULL,
+ 0x7effbddee53bULL,
+ 0x7effbdde1988ULL,
+ 0x7effbdde0904ULL,
+ 0x7effc106ce0dULL,
+ 0x7effbcc3fa04ULL,
+ 0x7effbcc3f6a4ULL,
+ 0x7effbcc3e726ULL,
+ 0x7effbcc40852ULL,
+ 0x7effb681ec4dULL,
+#endif // __WORDSIZE
+ 0xB0B5E768,
+ 0x7B682EC1,
+ 0x367F9918,
+ 0xAE34E13,
+ 0xBA0C6C6,
+ 0x13250F46,
+ 0xA0D6A8AB,
+ 0x2B07C1A8,
+ 0x6C844F4A,
+ 0x2321B53,
+ 0x1F3D4F8F,
+ 0x3FE2924B,
+ 0xB7A2F568,
+ 0xBD23950A,
+ 0x61020930,
+ 0x33E7970C,
+ 0x405998A1,
+ 0x59F3551D,
+ 0x350E3028,
+ 0xBC55A28D,
+ 0x361F3AED,
+ 0xBEAD0F73,
+ 0xAEF28479,
+ 0x757E971F,
+ 0xAEBA450,
+ 0x43AD22F5,
+ 0x8C2C50C4,
+ 0x7AD8A2E1,
+ 0x69EE4EE8,
+ 0xC08DFF,
+ 0x4BA6538,
+ 0x3708AB2,
+ 0xC24B6475,
+ 0x7C8890D7,
+ 0x6662495F,
+ 0x9B641689,
+ 0xD3596B,
+ 0xA1049569,
+ 0x44CBC16,
+ 0x4D39C39F
+};
+
+void CompressStackTraceTest(size_t n_iter) {
+ uint32_t seed = my_rand(&global_seed);
+ const size_t kNumPcs = ASAN_ARRAY_SIZE(pc_array);
+ uint32_t compressed[2 * kNumPcs];
+
+ for (size_t iter = 0; iter < n_iter; iter++) {
+ std::random_shuffle(pc_array, pc_array + kNumPcs);
+ __asan::AsanStackTrace stack0, stack1;
+ stack0.CopyFrom(pc_array, kNumPcs);
+ stack0.size = std::max((size_t)1, (size_t)my_rand(&seed) % stack0.size);
+ size_t compress_size =
+ std::max((size_t)2, (size_t)my_rand(&seed) % (2 * kNumPcs));
+ size_t n_frames =
+ __asan::AsanStackTrace::CompressStack(&stack0, compressed, compress_size);
+ assert(n_frames <= stack0.size);
+ __asan::AsanStackTrace::UncompressStack(&stack1, compressed, compress_size);
+ assert(stack1.size == n_frames);
+ for (size_t i = 0; i < stack1.size; i++) {
+ assert(stack0.trace[i] == stack1.trace[i]);
+ }
+ }
+}
+
+TEST(AddressSanitizer, CompressStackTraceTest) {
+ CompressStackTraceTest(10000);
+}
+
+void CompressStackTraceBenchmark(size_t n_iter) {
+ const size_t kNumPcs = ASAN_ARRAY_SIZE(pc_array);
+ uint32_t compressed[2 * kNumPcs];
+ std::random_shuffle(pc_array, pc_array + kNumPcs);
+
+ __asan::AsanStackTrace stack0;
+ stack0.CopyFrom(pc_array, kNumPcs);
+ stack0.size = kNumPcs;
+ for (size_t iter = 0; iter < n_iter; iter++) {
+ size_t compress_size = kNumPcs;
+ size_t n_frames =
+ __asan::AsanStackTrace::CompressStack(&stack0, compressed, compress_size);
+ Ident(n_frames);
+ }
+}
+
+TEST(AddressSanitizer, CompressStackTraceBenchmark) {
+ CompressStackTraceBenchmark(1 << 24);
+}
+
+TEST(AddressSanitizer, QuarantineTest) {
+ __asan::AsanStackTrace stack;
+ stack.trace[0] = 0x890;
+ stack.size = 1;
+
+ const int size = 32;
+ void *p = __asan::asan_malloc(size, &stack);
+ __asan::asan_free(p, &stack);
+ size_t i;
+ size_t max_i = 1 << 30;
+ for (i = 0; i < max_i; i++) {
+ void *p1 = __asan::asan_malloc(size, &stack);
+ __asan::asan_free(p1, &stack);
+ if (p1 == p) break;
+ }
+ // fprintf(stderr, "i=%ld\n", i);
+ EXPECT_GE(i, 100000U);
+ EXPECT_LT(i, max_i);
+}
+
+void *ThreadedQuarantineTestWorker(void *unused) {
+ uint32_t seed = my_rand(&global_seed);
+ __asan::AsanStackTrace stack;
+ stack.trace[0] = 0x890;
+ stack.size = 1;
+
+ for (size_t i = 0; i < 1000; i++) {
+ void *p = __asan::asan_malloc(1 + (my_rand(&seed) % 4000), &stack);
+ __asan::asan_free(p, &stack);
+ }
+ return NULL;
+}
+
+// Check that the thread local allocators are flushed when threads are
+// destroyed.
+TEST(AddressSanitizer, ThreadedQuarantineTest) {
+ const int n_threads = 3000;
+ size_t mmaped1 = __asan_get_heap_size();
+ for (int i = 0; i < n_threads; i++) {
+ pthread_t t;
+ pthread_create(&t, NULL, ThreadedQuarantineTestWorker, 0);
+ pthread_join(t, 0);
+ size_t mmaped2 = __asan_get_heap_size();
+ EXPECT_LT(mmaped2 - mmaped1, 320U * (1 << 20));
+ }
+}
+
+void *ThreadedOneSizeMallocStress(void *unused) {
+ __asan::AsanStackTrace stack;
+ stack.trace[0] = 0x890;
+ stack.size = 1;
+ const size_t kNumMallocs = 1000;
+ for (int iter = 0; iter < 1000; iter++) {
+ void *p[kNumMallocs];
+ for (size_t i = 0; i < kNumMallocs; i++) {
+ p[i] = __asan::asan_malloc(32, &stack);
+ }
+ for (size_t i = 0; i < kNumMallocs; i++) {
+ __asan::asan_free(p[i], &stack);
+ }
+ }
+ return NULL;
+}
+
+TEST(AddressSanitizer, ThreadedOneSizeMallocStressTest) {
+ const int kNumThreads = 4;
+ pthread_t t[kNumThreads];
+ for (int i = 0; i < kNumThreads; i++) {
+ pthread_create(&t[i], 0, ThreadedOneSizeMallocStress, 0);
+ }
+ for (int i = 0; i < kNumThreads; i++) {
+ pthread_join(t[i], 0);
+ }
+}
diff --git a/lib/asan/tests/asan_test.cc b/lib/asan/tests/asan_test.cc
new file mode 100644
index 000000000000..0ff72d3cf6d8
--- /dev/null
+++ b/lib/asan/tests/asan_test.cc
@@ -0,0 +1,2022 @@
+//===-- asan_test.cc ------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file is a part of AddressSanitizer, an address sanity checker.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+#include <pthread.h>
+#include <stdint.h>
+#include <setjmp.h>
+#include <assert.h>
+
+#if defined(__i386__) or defined(__x86_64__)
+#include <emmintrin.h>
+#endif
+
+#include "asan_test_config.h"
+#include "asan_test_utils.h"
+
+#ifndef __APPLE__
+#include <malloc.h>
+#endif // __APPLE__
+
+#ifdef __APPLE__
+static bool APPLE = true;
+#else
+static bool APPLE = false;
+#endif
+
+#if ASAN_HAS_EXCEPTIONS
+# define ASAN_THROW(x) throw (x)
+#else
+# define ASAN_THROW(x)
+#endif
+
+#include <sys/mman.h>
+
+typedef uint8_t U1;
+typedef uint16_t U2;
+typedef uint32_t U4;
+typedef uint64_t U8;
+
+static const char *progname;
+static const int kPageSize = 4096;
+
+// Simple stand-alone pseudorandom number generator.
+// Current algorithm is ANSI C linear congruential PRNG.
+static inline uint32_t my_rand(uint32_t* state) {
+ return (*state = *state * 1103515245 + 12345) >> 16;
+}
+
+static uint32_t global_seed = 0;
+
+class ObjdumpOfMyself {
+ public:
+ explicit ObjdumpOfMyself(const string &binary) {
+ is_correct = true;
+ string objdump_name = APPLE ? "gobjdump" : "objdump";
+ string prog = objdump_name + " -d " + binary;
+ // TODO(glider): popen() succeeds even if the file does not exist.
+ FILE *pipe = popen(prog.c_str(), "r");
+ string objdump;
+ if (pipe) {
+ const int kBuffSize = 4096;
+ char buff[kBuffSize+1];
+ int read_bytes;
+ while ((read_bytes = fread(buff, 1, kBuffSize, pipe)) > 0) {
+ buff[read_bytes] = 0;
+ objdump.append(buff);
+ }
+ pclose(pipe);
+ } else {
+ is_correct = false;
+ }
+ // cut the objdump into functions
+ string fn, next_fn;
+ size_t next_start;
+ for (size_t start = fn_start(objdump, 0, &fn);
+ start != string::npos;
+ start = next_start, fn = next_fn) {
+ next_start = fn_start(objdump, start, &next_fn);
+ // fprintf(stderr, "start: %d next_start = %d fn: %s\n",
+ // (int)start, (int)next_start, fn.c_str());
+ // Mac OS adds the "_" prefix to function names.
+ if (fn.find(APPLE ? "_Disasm" : "Disasm") == string::npos) {
+ continue;
+ }
+ string fn_body = objdump.substr(start, next_start - start);
+ // fprintf(stderr, "%s:\n%s", fn.c_str(), fn_body.c_str());
+ functions_[fn] = fn_body;
+ }
+ }
+
+ string &GetFuncDisasm(const string &fn) {
+ return functions_[fn];
+ }
+
+ int CountInsnInFunc(const string &fn, const vector<string> &insns) {
+ // Mac OS adds the "_" prefix to function names.
+ string fn_ref = APPLE ? "_" + fn : fn;
+ const string &disasm = GetFuncDisasm(fn_ref);
+ if (disasm.empty()) return -1;
+ size_t counter = 0;
+ for (size_t i = 0; i < insns.size(); i++) {
+ size_t pos = 0;
+ while ((pos = disasm.find(insns[i], pos)) != string::npos) {
+ counter++;
+ pos++;
+ }
+ }
+ return counter;
+ }
+
+ bool IsCorrect() { return is_correct; }
+
+ private:
+ size_t fn_start(const string &objdump, size_t start_pos, string *fn) {
+ size_t pos = objdump.find(">:\n", start_pos);
+ if (pos == string::npos)
+ return string::npos;
+ size_t beg = pos;
+ while (beg > 0 && objdump[beg - 1] != '<')
+ beg--;
+ *fn = objdump.substr(beg, pos - beg);
+ return pos + 3;
+ }
+
+ map<string, string> functions_;
+ bool is_correct;
+};
+
+static ObjdumpOfMyself *objdump_of_myself() {
+ static ObjdumpOfMyself *o = new ObjdumpOfMyself(progname);
+ return o;
+}
+
+const size_t kLargeMalloc = 1 << 24;
+
+template<class T>
+__attribute__((noinline))
+void asan_write(T *a) {
+ *a = 0;
+}
+
+__attribute__((noinline))
+void asan_write_sized_aligned(uint8_t *p, size_t size) {
+ EXPECT_EQ(0, ((uintptr_t)p % size));
+ if (size == 1) asan_write((uint8_t*)p);
+ else if (size == 2) asan_write((uint16_t*)p);
+ else if (size == 4) asan_write((uint32_t*)p);
+ else if (size == 8) asan_write((uint64_t*)p);
+}
+
+__attribute__((noinline)) void *malloc_fff(size_t size) {
+ void *res = malloc/**/(size); break_optimization(0); return res;}
+__attribute__((noinline)) void *malloc_eee(size_t size) {
+ void *res = malloc_fff(size); break_optimization(0); return res;}
+__attribute__((noinline)) void *malloc_ddd(size_t size) {
+ void *res = malloc_eee(size); break_optimization(0); return res;}
+__attribute__((noinline)) void *malloc_ccc(size_t size) {
+ void *res = malloc_ddd(size); break_optimization(0); return res;}
+__attribute__((noinline)) void *malloc_bbb(size_t size) {
+ void *res = malloc_ccc(size); break_optimization(0); return res;}
+__attribute__((noinline)) void *malloc_aaa(size_t size) {
+ void *res = malloc_bbb(size); break_optimization(0); return res;}
+
+#ifndef __APPLE__
+__attribute__((noinline)) void *memalign_fff(size_t alignment, size_t size) {
+ void *res = memalign/**/(alignment, size); break_optimization(0); return res;}
+__attribute__((noinline)) void *memalign_eee(size_t alignment, size_t size) {
+ void *res = memalign_fff(alignment, size); break_optimization(0); return res;}
+__attribute__((noinline)) void *memalign_ddd(size_t alignment, size_t size) {
+ void *res = memalign_eee(alignment, size); break_optimization(0); return res;}
+__attribute__((noinline)) void *memalign_ccc(size_t alignment, size_t size) {
+ void *res = memalign_ddd(alignment, size); break_optimization(0); return res;}
+__attribute__((noinline)) void *memalign_bbb(size_t alignment, size_t size) {
+ void *res = memalign_ccc(alignment, size); break_optimization(0); return res;}
+__attribute__((noinline)) void *memalign_aaa(size_t alignment, size_t size) {
+ void *res = memalign_bbb(alignment, size); break_optimization(0); return res;}
+#endif // __APPLE__
+
+
+__attribute__((noinline))
+ void free_ccc(void *p) { free(p); break_optimization(0);}
+__attribute__((noinline))
+ void free_bbb(void *p) { free_ccc(p); break_optimization(0);}
+__attribute__((noinline))
+ void free_aaa(void *p) { free_bbb(p); break_optimization(0);}
+
+template<class T>
+__attribute__((noinline))
+void oob_test(int size, int off) {
+ char *p = (char*)malloc_aaa(size);
+ // fprintf(stderr, "writing %d byte(s) into [%p,%p) with offset %d\n",
+ // sizeof(T), p, p + size, off);
+ asan_write((T*)(p + off));
+ free_aaa(p);
+}
+
+
+template<class T>
+__attribute__((noinline))
+void uaf_test(int size, int off) {
+ char *p = (char *)malloc_aaa(size);
+ free_aaa(p);
+ for (int i = 1; i < 100; i++)
+ free_aaa(malloc_aaa(i));
+ fprintf(stderr, "writing %ld byte(s) at %p with offset %d\n",
+ (long)sizeof(T), p, off);
+ asan_write((T*)(p + off));
+}
+
+TEST(AddressSanitizer, HasFeatureAddressSanitizerTest) {
+#if defined(__has_feature) && __has_feature(address_sanitizer)
+ bool asan = 1;
+#else
+ bool asan = 0;
+#endif
+ EXPECT_EQ(true, asan);
+}
+
+TEST(AddressSanitizer, SimpleDeathTest) {
+ EXPECT_DEATH(exit(1), "");
+}
+
+TEST(AddressSanitizer, VariousMallocsTest) {
+ // fprintf(stderr, "malloc:\n");
+ int *a = (int*)malloc(100 * sizeof(int));
+ a[50] = 0;
+ free(a);
+
+ // fprintf(stderr, "realloc:\n");
+ int *r = (int*)malloc(10);
+ r = (int*)realloc(r, 2000 * sizeof(int));
+ r[1000] = 0;
+ free(r);
+
+ // fprintf(stderr, "operator new []\n");
+ int *b = new int[100];
+ b[50] = 0;
+ delete [] b;
+
+ // fprintf(stderr, "operator new\n");
+ int *c = new int;
+ *c = 0;
+ delete c;
+
+#ifndef __APPLE__
+ // fprintf(stderr, "posix_memalign\n");
+ int *pm;
+ int pm_res = posix_memalign((void**)&pm, kPageSize, kPageSize);
+ EXPECT_EQ(0, pm_res);
+ free(pm);
+
+ int *ma = (int*)memalign(kPageSize, kPageSize);
+ EXPECT_EQ(0, (uintptr_t)ma % kPageSize);
+ ma[123] = 0;
+ free(ma);
+#endif // __APPLE__
+}
+
+TEST(AddressSanitizer, CallocTest) {
+ int *a = (int*)calloc(100, sizeof(int));
+ EXPECT_EQ(0, a[10]);
+ free(a);
+}
+
+TEST(AddressSanitizer, VallocTest) {
+ void *a = valloc(100);
+ EXPECT_EQ(0, (uintptr_t)a % kPageSize);
+ free(a);
+}
+
+#ifndef __APPLE__
+TEST(AddressSanitizer, PvallocTest) {
+ char *a = (char*)pvalloc(kPageSize + 100);
+ EXPECT_EQ(0, (uintptr_t)a % kPageSize);
+ a[kPageSize + 101] = 1; // we should not report an error here.
+ free(a);
+
+ a = (char*)pvalloc(0); // pvalloc(0) should allocate at least one page.
+ EXPECT_EQ(0, (uintptr_t)a % kPageSize);
+ a[101] = 1; // we should not report an error here.
+ free(a);
+}
+#endif // __APPLE__
+
+void NoOpSignalHandler(int unused) {
+ fprintf(stderr, "NoOpSignalHandler (should not happen). Aborting\n");
+ abort();
+}
+
+void NoOpSigaction(int, siginfo_t *siginfo, void *context) {
+ fprintf(stderr, "NoOpSigaction (should not happen). Aborting\n");
+ abort();
+}
+
+TEST(AddressSanitizer, SignalTest) {
+ signal(SIGSEGV, NoOpSignalHandler);
+ signal(SIGILL, NoOpSignalHandler);
+ // If asan did not intercept sigaction NoOpSigaction will fire.
+ char *x = Ident((char*)malloc(5));
+ EXPECT_DEATH(x[6]++, "is located 1 bytes to the right");
+ free(Ident(x));
+}
+
+TEST(AddressSanitizer, SigactionTest) {
+ {
+ struct sigaction sigact;
+ memset(&sigact, 0, sizeof(sigact));
+ sigact.sa_sigaction = NoOpSigaction;;
+ sigact.sa_flags = SA_SIGINFO;
+ sigaction(SIGSEGV, &sigact, 0);
+ }
+
+ {
+ struct sigaction sigact;
+ memset(&sigact, 0, sizeof(sigact));
+ sigact.sa_sigaction = NoOpSigaction;;
+ sigact.sa_flags = SA_SIGINFO;
+ sigaction(SIGILL, &sigact, 0);
+ }
+
+ // If asan did not intercept sigaction NoOpSigaction will fire.
+ char *x = Ident((char*)malloc(5));
+ EXPECT_DEATH(x[6]++, "is located 1 bytes to the right");
+ free(Ident(x));
+}
+
+void *TSDWorker(void *test_key) {
+ if (test_key) {
+ pthread_setspecific(*(pthread_key_t*)test_key, (void*)0xfeedface);
+ }
+ return NULL;
+}
+
+void TSDDestructor(void *tsd) {
+ // Spawning a thread will check that the current thread id is not -1.
+ pthread_t th;
+ pthread_create(&th, NULL, TSDWorker, NULL);
+ pthread_join(th, NULL);
+}
+
+// This tests triggers the thread-specific data destruction fiasco which occurs
+// if we don't manage the TSD destructors ourselves. We create a new pthread
+// key with a non-NULL destructor which is likely to be put after the destructor
+// of AsanThread in the list of destructors.
+// In this case the TSD for AsanThread will be destroyed before TSDDestructor
+// is called for the child thread, and a CHECK will fail when we call
+// pthread_create() to spawn the grandchild.
+TEST(AddressSanitizer, DISABLED_TSDTest) {
+ pthread_t th;
+ pthread_key_t test_key;
+ pthread_key_create(&test_key, TSDDestructor);
+ pthread_create(&th, NULL, TSDWorker, &test_key);
+ pthread_join(th, NULL);
+ pthread_key_delete(test_key);
+}
+
+template<class T>
+void OOBTest() {
+ char expected_str[100];
+ for (int size = sizeof(T); size < 20; size += 5) {
+ for (int i = -5; i < 0; i++) {
+ const char *str =
+ "is located.*%d byte.*to the left";
+ sprintf(expected_str, str, abs(i));
+ EXPECT_DEATH(oob_test<T>(size, i), expected_str);
+ }
+
+ for (int i = 0; i < size - sizeof(T) + 1; i++)
+ oob_test<T>(size, i);
+
+ for (int i = size - sizeof(T) + 1; i <= size + 3 * sizeof(T); i++) {
+ const char *str =
+ "is located.*%d byte.*to the right";
+ int off = i >= size ? (i - size) : 0;
+ // we don't catch unaligned partially OOB accesses.
+ if (i % sizeof(T)) continue;
+ sprintf(expected_str, str, off);
+ EXPECT_DEATH(oob_test<T>(size, i), expected_str);
+ }
+ }
+
+ EXPECT_DEATH(oob_test<T>(kLargeMalloc, -1),
+ "is located.*1 byte.*to the left");
+ EXPECT_DEATH(oob_test<T>(kLargeMalloc, kLargeMalloc),
+ "is located.*0 byte.*to the right");
+}
+
+// TODO(glider): the following tests are EXTREMELY slow on Darwin:
+// AddressSanitizer.OOB_char (125503 ms)
+// AddressSanitizer.OOB_int (126890 ms)
+// AddressSanitizer.OOBRightTest (315605 ms)
+// AddressSanitizer.SimpleStackTest (366559 ms)
+
+TEST(AddressSanitizer, OOB_char) {
+ OOBTest<U1>();
+}
+
+TEST(AddressSanitizer, OOB_int) {
+ OOBTest<U4>();
+}
+
+TEST(AddressSanitizer, OOBRightTest) {
+ for (size_t access_size = 1; access_size <= 8; access_size *= 2) {
+ for (size_t alloc_size = 1; alloc_size <= 8; alloc_size++) {
+ for (size_t offset = 0; offset <= 8; offset += access_size) {
+ void *p = malloc(alloc_size);
+ // allocated: [p, p + alloc_size)
+ // accessed: [p + offset, p + offset + access_size)
+ uint8_t *addr = (uint8_t*)p + offset;
+ if (offset + access_size <= alloc_size) {
+ asan_write_sized_aligned(addr, access_size);
+ } else {
+ int outside_bytes = offset > alloc_size ? (offset - alloc_size) : 0;
+ const char *str =
+ "is located.%d *byte.*to the right";
+ char expected_str[100];
+ sprintf(expected_str, str, outside_bytes);
+ EXPECT_DEATH(asan_write_sized_aligned(addr, access_size),
+ expected_str);
+ }
+ free(p);
+ }
+ }
+ }
+}
+
+TEST(AddressSanitizer, UAF_char) {
+ const char *uaf_string = "AddressSanitizer.*heap-use-after-free";
+ EXPECT_DEATH(uaf_test<U1>(1, 0), uaf_string);
+ EXPECT_DEATH(uaf_test<U1>(10, 0), uaf_string);
+ EXPECT_DEATH(uaf_test<U1>(10, 10), uaf_string);
+ EXPECT_DEATH(uaf_test<U1>(kLargeMalloc, 0), uaf_string);
+ EXPECT_DEATH(uaf_test<U1>(kLargeMalloc, kLargeMalloc / 2), uaf_string);
+}
+
+#if ASAN_HAS_BLACKLIST
+TEST(AddressSanitizer, IgnoreTest) {
+ int *x = Ident(new int);
+ delete Ident(x);
+ *x = 0;
+}
+#endif // ASAN_HAS_BLACKLIST
+
+struct StructWithBitField {
+ int bf1:1;
+ int bf2:1;
+ int bf3:1;
+ int bf4:29;
+};
+
+TEST(AddressSanitizer, BitFieldPositiveTest) {
+ StructWithBitField *x = new StructWithBitField;
+ delete Ident(x);
+ EXPECT_DEATH(x->bf1 = 0, "use-after-free");
+ EXPECT_DEATH(x->bf2 = 0, "use-after-free");
+ EXPECT_DEATH(x->bf3 = 0, "use-after-free");
+ EXPECT_DEATH(x->bf4 = 0, "use-after-free");
+};
+
+struct StructWithBitFields_8_24 {
+ int a:8;
+ int b:24;
+};
+
+TEST(AddressSanitizer, BitFieldNegativeTest) {
+ StructWithBitFields_8_24 *x = Ident(new StructWithBitFields_8_24);
+ x->a = 0;
+ x->b = 0;
+ delete Ident(x);
+}
+
+TEST(AddressSanitizer, OutOfMemoryTest) {
+ size_t size = __WORDSIZE == 64 ? (size_t)(1ULL << 48) : (0xf0000000);
+ EXPECT_EQ(0, realloc(0, size));
+ EXPECT_EQ(0, realloc(0, ~Ident(0)));
+ EXPECT_EQ(0, malloc(size));
+ EXPECT_EQ(0, malloc(~Ident(0)));
+ EXPECT_EQ(0, calloc(1, size));
+ EXPECT_EQ(0, calloc(1, ~Ident(0)));
+}
+
+#if ASAN_NEEDS_SEGV
+TEST(AddressSanitizer, WildAddressTest) {
+ char *c = (char*)0x123;
+ EXPECT_DEATH(*c = 0, "AddressSanitizer crashed on unknown address");
+}
+#endif
+
+static void MallocStress(size_t n) {
+ uint32_t seed = my_rand(&global_seed);
+ for (size_t iter = 0; iter < 10; iter++) {
+ vector<void *> vec;
+ for (size_t i = 0; i < n; i++) {
+ if ((i % 3) == 0) {
+ if (vec.empty()) continue;
+ size_t idx = my_rand(&seed) % vec.size();
+ void *ptr = vec[idx];
+ vec[idx] = vec.back();
+ vec.pop_back();
+ free_aaa(ptr);
+ } else {
+ size_t size = my_rand(&seed) % 1000 + 1;
+#ifndef __APPLE__
+ size_t alignment = 1 << (my_rand(&seed) % 7 + 3);
+ char *ptr = (char*)memalign_aaa(alignment, size);
+#else
+ char *ptr = (char*) malloc_aaa(size);
+#endif
+ vec.push_back(ptr);
+ ptr[0] = 0;
+ ptr[size-1] = 0;
+ ptr[size/2] = 0;
+ }
+ }
+ for (size_t i = 0; i < vec.size(); i++)
+ free_aaa(vec[i]);
+ }
+}
+
+TEST(AddressSanitizer, MallocStressTest) {
+ MallocStress(200000);
+}
+
+static void TestLargeMalloc(size_t size) {
+ char buff[1024];
+ sprintf(buff, "is located 1 bytes to the left of %lu-byte", (long)size);
+ EXPECT_DEATH(Ident((char*)malloc(size))[-1] = 0, buff);
+}
+
+TEST(AddressSanitizer, LargeMallocTest) {
+ for (int i = 113; i < (1 << 28); i = i * 2 + 13) {
+ TestLargeMalloc(i);
+ }
+}
+
+TEST(AddressSanitizer, HugeMallocTest) {
+#ifdef __APPLE__
+ // It was empirically found out that 1215 megabytes is the maximum amount of
+ // memory available to the process under AddressSanitizer on Darwin.
+ // (the libSystem malloc() allows allocating up to 2300 megabytes without
+ // ASan).
+ size_t n_megs = __WORDSIZE == 32 ? 1200 : 4100;
+#else
+ size_t n_megs = __WORDSIZE == 32 ? 2600 : 4100;
+#endif
+ TestLargeMalloc(n_megs << 20);
+}
+
+TEST(AddressSanitizer, ThreadedMallocStressTest) {
+ const int kNumThreads = 4;
+ pthread_t t[kNumThreads];
+ for (int i = 0; i < kNumThreads; i++) {
+ pthread_create(&t[i], 0, (void* (*)(void *x))MallocStress, (void*)100000);
+ }
+ for (int i = 0; i < kNumThreads; i++) {
+ pthread_join(t[i], 0);
+ }
+}
+
+void *ManyThreadsWorker(void *a) {
+ for (int iter = 0; iter < 100; iter++) {
+ for (size_t size = 100; size < 2000; size *= 2) {
+ free(Ident(malloc(size)));
+ }
+ }
+ return 0;
+}
+
+TEST(AddressSanitizer, ManyThreadsTest) {
+ const size_t kNumThreads = __WORDSIZE == 32 ? 30 : 1000;
+ pthread_t t[kNumThreads];
+ for (size_t i = 0; i < kNumThreads; i++) {
+ pthread_create(&t[i], 0, (void* (*)(void *x))ManyThreadsWorker, (void*)i);
+ }
+ for (size_t i = 0; i < kNumThreads; i++) {
+ pthread_join(t[i], 0);
+ }
+}
+
+TEST(AddressSanitizer, ReallocTest) {
+ const int kMinElem = 5;
+ int *ptr = (int*)malloc(sizeof(int) * kMinElem);
+ ptr[3] = 3;
+ for (int i = 0; i < 10000; i++) {
+ ptr = (int*)realloc(ptr,
+ (my_rand(&global_seed) % 1000 + kMinElem) * sizeof(int));
+ EXPECT_EQ(3, ptr[3]);
+ }
+}
+
+void WrongFree() {
+ int *x = (int*)malloc(100 * sizeof(int));
+ // Use the allocated memory, otherwise Clang will optimize it out.
+ Ident(x);
+ free(x + 1);
+}
+
+TEST(AddressSanitizer, WrongFreeTest) {
+ EXPECT_DEATH(WrongFree(),
+ "ERROR: AddressSanitizer attempting free.*not malloc");
+}
+
+void DoubleFree() {
+ int *x = (int*)malloc(100 * sizeof(int));
+ fprintf(stderr, "DoubleFree: x=%p\n", x);
+ free(x);
+ free(x);
+ fprintf(stderr, "should have failed in the second free(%p)\n", x);
+ abort();
+}
+
+TEST(AddressSanitizer, DoubleFreeTest) {
+ EXPECT_DEATH(DoubleFree(), "ERROR: AddressSanitizer attempting double-free");
+}
+
+template<int kSize>
+__attribute__((noinline))
+void SizedStackTest() {
+ char a[kSize];
+ char *A = Ident((char*)&a);
+ for (size_t i = 0; i < kSize; i++)
+ A[i] = i;
+ EXPECT_DEATH(A[-1] = 0, "");
+ EXPECT_DEATH(A[-20] = 0, "");
+ EXPECT_DEATH(A[-31] = 0, "");
+ EXPECT_DEATH(A[kSize] = 0, "");
+ EXPECT_DEATH(A[kSize + 1] = 0, "");
+ EXPECT_DEATH(A[kSize + 10] = 0, "");
+ EXPECT_DEATH(A[kSize + 31] = 0, "");
+}
+
+TEST(AddressSanitizer, SimpleStackTest) {
+ SizedStackTest<1>();
+ SizedStackTest<2>();
+ SizedStackTest<3>();
+ SizedStackTest<4>();
+ SizedStackTest<5>();
+ SizedStackTest<6>();
+ SizedStackTest<7>();
+ SizedStackTest<16>();
+ SizedStackTest<25>();
+ SizedStackTest<34>();
+ SizedStackTest<43>();
+ SizedStackTest<51>();
+ SizedStackTest<62>();
+ SizedStackTest<64>();
+ SizedStackTest<128>();
+}
+
+TEST(AddressSanitizer, ManyStackObjectsTest) {
+ char XXX[10];
+ char YYY[20];
+ char ZZZ[30];
+ Ident(XXX);
+ Ident(YYY);
+ EXPECT_DEATH(Ident(ZZZ)[-1] = 0, ASAN_PCRE_DOTALL "XXX.*YYY.*ZZZ");
+}
+
+__attribute__((noinline))
+static void Frame0(int frame, char *a, char *b, char *c) {
+ char d[4] = {0};
+ char *D = Ident(d);
+ switch (frame) {
+ case 3: a[5]++; break;
+ case 2: b[5]++; break;
+ case 1: c[5]++; break;
+ case 0: D[5]++; break;
+ }
+}
+__attribute__((noinline)) static void Frame1(int frame, char *a, char *b) {
+ char c[4] = {0}; Frame0(frame, a, b, c);
+ break_optimization(0);
+}
+__attribute__((noinline)) static void Frame2(int frame, char *a) {
+ char b[4] = {0}; Frame1(frame, a, b);
+ break_optimization(0);
+}
+__attribute__((noinline)) static void Frame3(int frame) {
+ char a[4] = {0}; Frame2(frame, a);
+ break_optimization(0);
+}
+
+TEST(AddressSanitizer, GuiltyStackFrame0Test) {
+ EXPECT_DEATH(Frame3(0), "located .*in frame <.*Frame0");
+}
+TEST(AddressSanitizer, GuiltyStackFrame1Test) {
+ EXPECT_DEATH(Frame3(1), "located .*in frame <.*Frame1");
+}
+TEST(AddressSanitizer, GuiltyStackFrame2Test) {
+ EXPECT_DEATH(Frame3(2), "located .*in frame <.*Frame2");
+}
+TEST(AddressSanitizer, GuiltyStackFrame3Test) {
+ EXPECT_DEATH(Frame3(3), "located .*in frame <.*Frame3");
+}
+
+__attribute__((noinline))
+void LongJmpFunc1(jmp_buf buf) {
+ // create three red zones for these two stack objects.
+ int a;
+ int b;
+
+ int *A = Ident(&a);
+ int *B = Ident(&b);
+ *A = *B;
+ longjmp(buf, 1);
+}
+
+__attribute__((noinline))
+void UnderscopeLongJmpFunc1(jmp_buf buf) {
+ // create three red zones for these two stack objects.
+ int a;
+ int b;
+
+ int *A = Ident(&a);
+ int *B = Ident(&b);
+ *A = *B;
+ _longjmp(buf, 1);
+}
+
+__attribute__((noinline))
+void SigLongJmpFunc1(sigjmp_buf buf) {
+ // create three red zones for these two stack objects.
+ int a;
+ int b;
+
+ int *A = Ident(&a);
+ int *B = Ident(&b);
+ *A = *B;
+ siglongjmp(buf, 1);
+}
+
+
+__attribute__((noinline))
+void TouchStackFunc() {
+ int a[100]; // long array will intersect with redzones from LongJmpFunc1.
+ int *A = Ident(a);
+ for (int i = 0; i < 100; i++)
+ A[i] = i*i;
+}
+
+// Test that we handle longjmp and do not report fals positives on stack.
+TEST(AddressSanitizer, LongJmpTest) {
+ static jmp_buf buf;
+ if (!setjmp(buf)) {
+ LongJmpFunc1(buf);
+ } else {
+ TouchStackFunc();
+ }
+}
+
+TEST(AddressSanitizer, UnderscopeLongJmpTest) {
+ static jmp_buf buf;
+ if (!_setjmp(buf)) {
+ UnderscopeLongJmpFunc1(buf);
+ } else {
+ TouchStackFunc();
+ }
+}
+
+TEST(AddressSanitizer, SigLongJmpTest) {
+ static sigjmp_buf buf;
+ if (!sigsetjmp(buf, 1)) {
+ SigLongJmpFunc1(buf);
+ } else {
+ TouchStackFunc();
+ }
+}
+
+#ifdef __EXCEPTIONS
+__attribute__((noinline))
+void ThrowFunc() {
+ // create three red zones for these two stack objects.
+ int a;
+ int b;
+
+ int *A = Ident(&a);
+ int *B = Ident(&b);
+ *A = *B;
+ ASAN_THROW(1);
+}
+
+TEST(AddressSanitizer, CxxExceptionTest) {
+ if (ASAN_UAR) return;
+ // TODO(kcc): this test crashes on 32-bit for some reason...
+ if (__WORDSIZE == 32) return;
+ try {
+ ThrowFunc();
+ } catch(...) {}
+ TouchStackFunc();
+}
+#endif
+
+void *ThreadStackReuseFunc1(void *unused) {
+ // create three red zones for these two stack objects.
+ int a;
+ int b;
+
+ int *A = Ident(&a);
+ int *B = Ident(&b);
+ *A = *B;
+ pthread_exit(0);
+ return 0;
+}
+
+void *ThreadStackReuseFunc2(void *unused) {
+ TouchStackFunc();
+ return 0;
+}
+
+TEST(AddressSanitizer, ThreadStackReuseTest) {
+ pthread_t t;
+ pthread_create(&t, 0, ThreadStackReuseFunc1, 0);
+ pthread_join(t, 0);
+ pthread_create(&t, 0, ThreadStackReuseFunc2, 0);
+ pthread_join(t, 0);
+}
+
+#if defined(__i386__) or defined(__x86_64__)
+TEST(AddressSanitizer, Store128Test) {
+ char *a = Ident((char*)malloc(Ident(12)));
+ char *p = a;
+ if (((uintptr_t)a % 16) != 0)
+ p = a + 8;
+ assert(((uintptr_t)p % 16) == 0);
+ __m128i value_wide = _mm_set1_epi16(0x1234);
+ EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
+ "AddressSanitizer heap-buffer-overflow");
+ EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
+ "WRITE of size 16");
+ EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
+ "located 0 bytes to the right of 12-byte");
+ free(a);
+}
+#endif
+
+static string RightOOBErrorMessage(int oob_distance) {
+ assert(oob_distance >= 0);
+ char expected_str[100];
+ sprintf(expected_str, "located %d bytes to the right", oob_distance);
+ return string(expected_str);
+}
+
+static string LeftOOBErrorMessage(int oob_distance) {
+ assert(oob_distance > 0);
+ char expected_str[100];
+ sprintf(expected_str, "located %d bytes to the left", oob_distance);
+ return string(expected_str);
+}
+
+template<class T>
+void MemSetOOBTestTemplate(size_t length) {
+ if (length == 0) return;
+ size_t size = Ident(sizeof(T) * length);
+ T *array = Ident((T*)malloc(size));
+ int element = Ident(42);
+ int zero = Ident(0);
+ // memset interval inside array
+ memset(array, element, size);
+ memset(array, element, size - 1);
+ memset(array + length - 1, element, sizeof(T));
+ memset(array, element, 1);
+
+ // memset 0 bytes
+ memset(array - 10, element, zero);
+ memset(array - 1, element, zero);
+ memset(array, element, zero);
+ memset(array + length, 0, zero);
+ memset(array + length + 1, 0, zero);
+
+ // try to memset bytes to the right of array
+ EXPECT_DEATH(memset(array, 0, size + 1),
+ RightOOBErrorMessage(0));
+ EXPECT_DEATH(memset((char*)(array + length) - 1, element, 6),
+ RightOOBErrorMessage(4));
+ EXPECT_DEATH(memset(array + 1, element, size + sizeof(T)),
+ RightOOBErrorMessage(2 * sizeof(T) - 1));
+ // whole interval is to the right
+ EXPECT_DEATH(memset(array + length + 1, 0, 10),
+ RightOOBErrorMessage(sizeof(T)));
+
+ // try to memset bytes to the left of array
+ EXPECT_DEATH(memset((char*)array - 1, element, size),
+ LeftOOBErrorMessage(1));
+ EXPECT_DEATH(memset((char*)array - 5, 0, 6),
+ LeftOOBErrorMessage(5));
+ EXPECT_DEATH(memset(array - 5, element, size + 5 * sizeof(T)),
+ LeftOOBErrorMessage(5 * sizeof(T)));
+ // whole interval is to the left
+ EXPECT_DEATH(memset(array - 2, 0, sizeof(T)),
+ LeftOOBErrorMessage(2 * sizeof(T)));
+
+ // try to memset bytes both to the left & to the right
+ EXPECT_DEATH(memset((char*)array - 2, element, size + 4),
+ LeftOOBErrorMessage(2));
+
+ free(array);
+}
+
+TEST(AddressSanitizer, MemSetOOBTest) {
+ MemSetOOBTestTemplate<char>(100);
+ MemSetOOBTestTemplate<int>(5);
+ MemSetOOBTestTemplate<double>(256);
+ // We can test arrays of structres/classes here, but what for?
+}
+
+// Same test for memcpy and memmove functions
+template <class T, class M>
+void MemTransferOOBTestTemplate(size_t length) {
+ if (length == 0) return;
+ size_t size = Ident(sizeof(T) * length);
+ T *src = Ident((T*)malloc(size));
+ T *dest = Ident((T*)malloc(size));
+ int zero = Ident(0);
+
+ // valid transfer of bytes between arrays
+ M::transfer(dest, src, size);
+ M::transfer(dest + 1, src, size - sizeof(T));
+ M::transfer(dest, src + length - 1, sizeof(T));
+ M::transfer(dest, src, 1);
+
+ // transfer zero bytes
+ M::transfer(dest - 1, src, 0);
+ M::transfer(dest + length, src, zero);
+ M::transfer(dest, src - 1, zero);
+ M::transfer(dest, src, zero);
+
+ // try to change mem to the right of dest
+ EXPECT_DEATH(M::transfer(dest + 1, src, size),
+ RightOOBErrorMessage(sizeof(T) - 1));
+ EXPECT_DEATH(M::transfer((char*)(dest + length) - 1, src, 5),
+ RightOOBErrorMessage(3));
+
+ // try to change mem to the left of dest
+ EXPECT_DEATH(M::transfer(dest - 2, src, size),
+ LeftOOBErrorMessage(2 * sizeof(T)));
+ EXPECT_DEATH(M::transfer((char*)dest - 3, src, 4),
+ LeftOOBErrorMessage(3));
+
+ // try to access mem to the right of src
+ EXPECT_DEATH(M::transfer(dest, src + 2, size),
+ RightOOBErrorMessage(2 * sizeof(T) - 1));
+ EXPECT_DEATH(M::transfer(dest, (char*)(src + length) - 3, 6),
+ RightOOBErrorMessage(2));
+
+ // try to access mem to the left of src
+ EXPECT_DEATH(M::transfer(dest, src - 1, size),
+ LeftOOBErrorMessage(sizeof(T)));
+ EXPECT_DEATH(M::transfer(dest, (char*)src - 6, 7),
+ LeftOOBErrorMessage(6));
+
+ // Generally we don't need to test cases where both accessing src and writing
+ // to dest address to poisoned memory.
+
+ T *big_src = Ident((T*)malloc(size * 2));
+ T *big_dest = Ident((T*)malloc(size * 2));
+ // try to change mem to both sides of dest
+ EXPECT_DEATH(M::transfer(dest - 1, big_src, size * 2),
+ LeftOOBErrorMessage(sizeof(T)));
+ // try to access mem to both sides of src
+ EXPECT_DEATH(M::transfer(big_dest, src - 2, size * 2),
+ LeftOOBErrorMessage(2 * sizeof(T)));
+
+ free(src);
+ free(dest);
+ free(big_src);
+ free(big_dest);
+}
+
+class MemCpyWrapper {
+ public:
+ static void* transfer(void *to, const void *from, size_t size) {
+ return memcpy(to, from, size);
+ }
+};
+TEST(AddressSanitizer, MemCpyOOBTest) {
+ MemTransferOOBTestTemplate<char, MemCpyWrapper>(100);
+ MemTransferOOBTestTemplate<int, MemCpyWrapper>(1024);
+}
+
+class MemMoveWrapper {
+ public:
+ static void* transfer(void *to, const void *from, size_t size) {
+ return memmove(to, from, size);
+ }
+};
+TEST(AddressSanitizer, MemMoveOOBTest) {
+ MemTransferOOBTestTemplate<char, MemMoveWrapper>(100);
+ MemTransferOOBTestTemplate<int, MemMoveWrapper>(1024);
+}
+
+// Tests for string functions
+
+// Used for string functions tests
+static char global_string[] = "global";
+static size_t global_string_length = 6;
+
+// Input to a test is a zero-terminated string str with given length
+// Accesses to the bytes to the left and to the right of str
+// are presumed to produce OOB errors
+void StrLenOOBTestTemplate(char *str, size_t length, bool is_global) {
+ // Normal strlen calls
+ EXPECT_EQ(strlen(str), length);
+ if (length > 0) {
+ EXPECT_EQ(strlen(str + 1), length - 1);
+ EXPECT_EQ(strlen(str + length), 0);
+ }
+ // Arg of strlen is not malloced, OOB access
+ if (!is_global) {
+ // We don't insert RedZones to the left of global variables
+ EXPECT_DEATH(Ident(strlen(str - 1)), LeftOOBErrorMessage(1));
+ EXPECT_DEATH(Ident(strlen(str - 5)), LeftOOBErrorMessage(5));
+ }
+ EXPECT_DEATH(Ident(strlen(str + length + 1)), RightOOBErrorMessage(0));
+ // Overwrite terminator
+ str[length] = 'a';
+ // String is not zero-terminated, strlen will lead to OOB access
+ EXPECT_DEATH(Ident(strlen(str)), RightOOBErrorMessage(0));
+ EXPECT_DEATH(Ident(strlen(str + length)), RightOOBErrorMessage(0));
+ // Restore terminator
+ str[length] = 0;
+}
+TEST(AddressSanitizer, StrLenOOBTest) {
+ // Check heap-allocated string
+ size_t length = Ident(10);
+ char *heap_string = Ident((char*)malloc(length + 1));
+ char stack_string[10 + 1];
+ for (int i = 0; i < length; i++) {
+ heap_string[i] = 'a';
+ stack_string[i] = 'b';
+ }
+ heap_string[length] = 0;
+ stack_string[length] = 0;
+ StrLenOOBTestTemplate(heap_string, length, false);
+ // TODO(samsonov): Fix expected messages in StrLenOOBTestTemplate to
+ // make test for stack_string work. Or move it to output tests.
+ // StrLenOOBTestTemplate(stack_string, length, false);
+ StrLenOOBTestTemplate(global_string, global_string_length, true);
+ free(heap_string);
+}
+
+static inline char* MallocAndMemsetString(size_t size) {
+ char *s = Ident((char*)malloc(size));
+ memset(s, 'z', size);
+ return s;
+}
+
+#ifndef __APPLE__
+TEST(AddressSanitizer, StrNLenOOBTest) {
+ size_t size = Ident(123);
+ char *str = MallocAndMemsetString(size);
+ // Normal strnlen calls.
+ Ident(strnlen(str - 1, 0));
+ Ident(strnlen(str, size));
+ Ident(strnlen(str + size - 1, 1));
+ str[size - 1] = '\0';
+ Ident(strnlen(str, 2 * size));
+ // Argument points to not allocated memory.
+ EXPECT_DEATH(Ident(strnlen(str - 1, 1)), LeftOOBErrorMessage(1));
+ EXPECT_DEATH(Ident(strnlen(str + size, 1)), RightOOBErrorMessage(0));
+ // Overwrite the terminating '\0' and hit unallocated memory.
+ str[size - 1] = 'z';
+ EXPECT_DEATH(Ident(strnlen(str, size + 1)), RightOOBErrorMessage(0));
+ free(str);
+}
+#endif
+
+TEST(AddressSanitizer, StrDupOOBTest) {
+ size_t size = Ident(42);
+ char *str = MallocAndMemsetString(size);
+ char *new_str;
+ // Normal strdup calls.
+ str[size - 1] = '\0';
+ new_str = strdup(str);
+ free(new_str);
+ new_str = strdup(str + size - 1);
+ free(new_str);
+ // Argument points to not allocated memory.
+ EXPECT_DEATH(Ident(strdup(str - 1)), LeftOOBErrorMessage(1));
+ EXPECT_DEATH(Ident(strdup(str + size)), RightOOBErrorMessage(0));
+ // Overwrite the terminating '\0' and hit unallocated memory.
+ str[size - 1] = 'z';
+ EXPECT_DEATH(Ident(strdup(str)), RightOOBErrorMessage(0));
+ free(str);
+}
+
+TEST(AddressSanitizer, StrCpyOOBTest) {
+ size_t to_size = Ident(30);
+ size_t from_size = Ident(6); // less than to_size
+ char *to = Ident((char*)malloc(to_size));
+ char *from = Ident((char*)malloc(from_size));
+ // Normal strcpy calls.
+ strcpy(from, "hello");
+ strcpy(to, from);
+ strcpy(to + to_size - from_size, from);
+ // Length of "from" is too small.
+ EXPECT_DEATH(Ident(strcpy(from, "hello2")), RightOOBErrorMessage(0));
+ // "to" or "from" points to not allocated memory.
+ EXPECT_DEATH(Ident(strcpy(to - 1, from)), LeftOOBErrorMessage(1));
+ EXPECT_DEATH(Ident(strcpy(to, from - 1)), LeftOOBErrorMessage(1));
+ EXPECT_DEATH(Ident(strcpy(to, from + from_size)), RightOOBErrorMessage(0));
+ EXPECT_DEATH(Ident(strcpy(to + to_size, from)), RightOOBErrorMessage(0));
+ // Overwrite the terminating '\0' character and hit unallocated memory.
+ from[from_size - 1] = '!';
+ EXPECT_DEATH(Ident(strcpy(to, from)), RightOOBErrorMessage(0));
+ free(to);
+ free(from);
+}
+
+TEST(AddressSanitizer, StrNCpyOOBTest) {
+ size_t to_size = Ident(20);
+ size_t from_size = Ident(6); // less than to_size
+ char *to = Ident((char*)malloc(to_size));
+ // From is a zero-terminated string "hello\0" of length 6
+ char *from = Ident((char*)malloc(from_size));
+ strcpy(from, "hello");
+ // copy 0 bytes
+ strncpy(to, from, 0);
+ strncpy(to - 1, from - 1, 0);
+ // normal strncpy calls
+ strncpy(to, from, from_size);
+ strncpy(to, from, to_size);
+ strncpy(to, from + from_size - 1, to_size);
+ strncpy(to + to_size - 1, from, 1);
+ // One of {to, from} points to not allocated memory
+ EXPECT_DEATH(Ident(strncpy(to, from - 1, from_size)),
+ LeftOOBErrorMessage(1));
+ EXPECT_DEATH(Ident(strncpy(to - 1, from, from_size)),
+ LeftOOBErrorMessage(1));
+ EXPECT_DEATH(Ident(strncpy(to, from + from_size, 1)),
+ RightOOBErrorMessage(0));
+ EXPECT_DEATH(Ident(strncpy(to + to_size, from, 1)),
+ RightOOBErrorMessage(0));
+ // Length of "to" is too small
+ EXPECT_DEATH(Ident(strncpy(to + to_size - from_size + 1, from, from_size)),
+ RightOOBErrorMessage(0));
+ EXPECT_DEATH(Ident(strncpy(to + 1, from, to_size)),
+ RightOOBErrorMessage(0));
+ // Overwrite terminator in from
+ from[from_size - 1] = '!';
+ // normal strncpy call
+ strncpy(to, from, from_size);
+ // Length of "from" is too small
+ EXPECT_DEATH(Ident(strncpy(to, from, to_size)),
+ RightOOBErrorMessage(0));
+ free(to);
+ free(from);
+}
+
+typedef char*(*PointerToStrChr)(const char*, int);
+void RunStrChrTest(PointerToStrChr StrChr) {
+ size_t size = Ident(100);
+ char *str = MallocAndMemsetString(size);
+ str[10] = 'q';
+ str[11] = '\0';
+ EXPECT_EQ(str, StrChr(str, 'z'));
+ EXPECT_EQ(str + 10, StrChr(str, 'q'));
+ EXPECT_EQ(NULL, StrChr(str, 'a'));
+ // StrChr argument points to not allocated memory.
+ EXPECT_DEATH(Ident(StrChr(str - 1, 'z')), LeftOOBErrorMessage(1));
+ EXPECT_DEATH(Ident(StrChr(str + size, 'z')), RightOOBErrorMessage(0));
+ // Overwrite the terminator and hit not allocated memory.
+ str[11] = 'z';
+ EXPECT_DEATH(Ident(StrChr(str, 'a')), RightOOBErrorMessage(0));
+ free(str);
+}
+TEST(AddressSanitizer, StrChrAndIndexOOBTest) {
+ RunStrChrTest(&strchr);
+ RunStrChrTest(&index);
+}
+
+TEST(AddressSanitizer, StrCmpAndFriendsLogicTest) {
+ // strcmp
+ EXPECT_EQ(0, strcmp("", ""));
+ EXPECT_EQ(0, strcmp("abcd", "abcd"));
+ EXPECT_GT(0, strcmp("ab", "ac"));
+ EXPECT_GT(0, strcmp("abc", "abcd"));
+ EXPECT_LT(0, strcmp("acc", "abc"));
+ EXPECT_LT(0, strcmp("abcd", "abc"));
+
+ // strncmp
+ EXPECT_EQ(0, strncmp("a", "b", 0));
+ EXPECT_EQ(0, strncmp("abcd", "abcd", 10));
+ EXPECT_EQ(0, strncmp("abcd", "abcef", 3));
+ EXPECT_GT(0, strncmp("abcde", "abcfa", 4));
+ EXPECT_GT(0, strncmp("a", "b", 5));
+ EXPECT_GT(0, strncmp("bc", "bcde", 4));
+ EXPECT_LT(0, strncmp("xyz", "xyy", 10));
+ EXPECT_LT(0, strncmp("baa", "aaa", 1));
+ EXPECT_LT(0, strncmp("zyx", "", 2));
+
+ // strcasecmp
+ EXPECT_EQ(0, strcasecmp("", ""));
+ EXPECT_EQ(0, strcasecmp("zzz", "zzz"));
+ EXPECT_EQ(0, strcasecmp("abCD", "ABcd"));
+ EXPECT_GT(0, strcasecmp("aB", "Ac"));
+ EXPECT_GT(0, strcasecmp("ABC", "ABCd"));
+ EXPECT_LT(0, strcasecmp("acc", "abc"));
+ EXPECT_LT(0, strcasecmp("ABCd", "abc"));
+
+ // strncasecmp
+ EXPECT_EQ(0, strncasecmp("a", "b", 0));
+ EXPECT_EQ(0, strncasecmp("abCD", "ABcd", 10));
+ EXPECT_EQ(0, strncasecmp("abCd", "ABcef", 3));
+ EXPECT_GT(0, strncasecmp("abcde", "ABCfa", 4));
+ EXPECT_GT(0, strncasecmp("a", "B", 5));
+ EXPECT_GT(0, strncasecmp("bc", "BCde", 4));
+ EXPECT_LT(0, strncasecmp("xyz", "xyy", 10));
+ EXPECT_LT(0, strncasecmp("Baa", "aaa", 1));
+ EXPECT_LT(0, strncasecmp("zyx", "", 2));
+
+ // memcmp
+ EXPECT_EQ(0, memcmp("a", "b", 0));
+ EXPECT_EQ(0, memcmp("ab\0c", "ab\0c", 4));
+ EXPECT_GT(0, memcmp("\0ab", "\0ac", 3));
+ EXPECT_GT(0, memcmp("abb\0", "abba", 4));
+ EXPECT_LT(0, memcmp("ab\0cd", "ab\0c\0", 5));
+ EXPECT_LT(0, memcmp("zza", "zyx", 3));
+}
+
+typedef int(*PointerToStrCmp)(const char*, const char*);
+void RunStrCmpTest(PointerToStrCmp StrCmp) {
+ size_t size = Ident(100);
+ char *s1 = MallocAndMemsetString(size);
+ char *s2 = MallocAndMemsetString(size);
+ s1[size - 1] = '\0';
+ s2[size - 1] = '\0';
+ // Normal StrCmp calls
+ Ident(StrCmp(s1, s2));
+ Ident(StrCmp(s1, s2 + size - 1));
+ Ident(StrCmp(s1 + size - 1, s2 + size - 1));
+ s1[size - 1] = 'z';
+ s2[size - 1] = 'x';
+ Ident(StrCmp(s1, s2));
+ // One of arguments points to not allocated memory.
+ EXPECT_DEATH(Ident(StrCmp)(s1 - 1, s2), LeftOOBErrorMessage(1));
+ EXPECT_DEATH(Ident(StrCmp)(s1, s2 - 1), LeftOOBErrorMessage(1));
+ EXPECT_DEATH(Ident(StrCmp)(s1 + size, s2), RightOOBErrorMessage(0));
+ EXPECT_DEATH(Ident(StrCmp)(s1, s2 + size), RightOOBErrorMessage(0));
+ // Hit unallocated memory and die.
+ s2[size - 1] = 'z';
+ EXPECT_DEATH(Ident(StrCmp)(s1, s1), RightOOBErrorMessage(0));
+ EXPECT_DEATH(Ident(StrCmp)(s1 + size - 1, s2), RightOOBErrorMessage(0));
+ free(s1);
+ free(s2);
+}
+
+TEST(AddressSanitizer, StrCmpOOBTest) {
+ RunStrCmpTest(&strcmp);
+}
+
+TEST(AddressSanitizer, StrCaseCmpOOBTest) {
+ RunStrCmpTest(&strcasecmp);
+}
+
+typedef int(*PointerToStrNCmp)(const char*, const char*, size_t);
+void RunStrNCmpTest(PointerToStrNCmp StrNCmp) {
+ size_t size = Ident(100);
+ char *s1 = MallocAndMemsetString(size);
+ char *s2 = MallocAndMemsetString(size);
+ s1[size - 1] = '\0';
+ s2[size - 1] = '\0';
+ // Normal StrNCmp calls
+ Ident(StrNCmp(s1, s2, size + 2));
+ s1[size - 1] = 'z';
+ s2[size - 1] = 'x';
+ Ident(StrNCmp(s1 + size - 2, s2 + size - 2, size));
+ s2[size - 1] = 'z';
+ Ident(StrNCmp(s1 - 1, s2 - 1, 0));
+ Ident(StrNCmp(s1 + size - 1, s2 + size - 1, 1));
+ // One of arguments points to not allocated memory.
+ EXPECT_DEATH(Ident(StrNCmp)(s1 - 1, s2, 1), LeftOOBErrorMessage(1));
+ EXPECT_DEATH(Ident(StrNCmp)(s1, s2 - 1, 1), LeftOOBErrorMessage(1));
+ EXPECT_DEATH(Ident(StrNCmp)(s1 + size, s2, 1), RightOOBErrorMessage(0));
+ EXPECT_DEATH(Ident(StrNCmp)(s1, s2 + size, 1), RightOOBErrorMessage(0));
+ // Hit unallocated memory and die.
+ EXPECT_DEATH(Ident(StrNCmp)(s1 + 1, s2 + 1, size), RightOOBErrorMessage(0));
+ EXPECT_DEATH(Ident(StrNCmp)(s1 + size - 1, s2, 2), RightOOBErrorMessage(0));
+ free(s1);
+ free(s2);
+}
+
+TEST(AddressSanitizer, StrNCmpOOBTest) {
+ RunStrNCmpTest(&strncmp);
+}
+
+TEST(AddressSanitizer, StrNCaseCmpOOBTest) {
+ RunStrNCmpTest(&strncasecmp);
+}
+
+TEST(AddressSanitizer, MemCmpOOBTest) {
+ size_t size = Ident(100);
+ char *s1 = MallocAndMemsetString(size);
+ char *s2 = MallocAndMemsetString(size);
+ // Normal memcmp calls.
+ Ident(memcmp(s1, s2, size));
+ Ident(memcmp(s1 + size - 1, s2 + size - 1, 1));
+ Ident(memcmp(s1 - 1, s2 - 1, 0));
+ // One of arguments points to not allocated memory.
+ EXPECT_DEATH(Ident(memcmp)(s1 - 1, s2, 1), LeftOOBErrorMessage(1));
+ EXPECT_DEATH(Ident(memcmp)(s1, s2 - 1, 1), LeftOOBErrorMessage(1));
+ EXPECT_DEATH(Ident(memcmp)(s1 + size, s2, 1), RightOOBErrorMessage(0));
+ EXPECT_DEATH(Ident(memcmp)(s1, s2 + size, 1), RightOOBErrorMessage(0));
+ // Hit unallocated memory and die.
+ EXPECT_DEATH(Ident(memcmp)(s1 + 1, s2 + 1, size), RightOOBErrorMessage(0));
+ EXPECT_DEATH(Ident(memcmp)(s1 + size - 1, s2, 2), RightOOBErrorMessage(0));
+ // Zero bytes are not terminators and don't prevent from OOB.
+ s1[size - 1] = '\0';
+ s2[size - 1] = '\0';
+ EXPECT_DEATH(Ident(memcmp)(s1, s2, size + 1), RightOOBErrorMessage(0));
+ free(s1);
+ free(s2);
+}
+
+TEST(AddressSanitizer, StrCatOOBTest) {
+ size_t to_size = Ident(100);
+ char *to = MallocAndMemsetString(to_size);
+ to[0] = '\0';
+ size_t from_size = Ident(20);
+ char *from = MallocAndMemsetString(from_size);
+ from[from_size - 1] = '\0';
+ // Normal strcat calls.
+ strcat(to, from);
+ strcat(to, from);
+ strcat(to + from_size, from + from_size - 2);
+ // Catenate empty string is not always an error.
+ strcat(to - 1, from + from_size - 1);
+ // One of arguments points to not allocated memory.
+ EXPECT_DEATH(strcat(to - 1, from), LeftOOBErrorMessage(1));
+ EXPECT_DEATH(strcat(to, from - 1), LeftOOBErrorMessage(1));
+ EXPECT_DEATH(strcat(to + to_size, from), RightOOBErrorMessage(0));
+ EXPECT_DEATH(strcat(to, from + from_size), RightOOBErrorMessage(0));
+
+ // "from" is not zero-terminated.
+ from[from_size - 1] = 'z';
+ EXPECT_DEATH(strcat(to, from), RightOOBErrorMessage(0));
+ from[from_size - 1] = '\0';
+ // "to" is not zero-terminated.
+ memset(to, 'z', to_size);
+ EXPECT_DEATH(strcat(to, from), RightOOBErrorMessage(0));
+ // "to" is too short to fit "from".
+ to[to_size - from_size + 1] = '\0';
+ EXPECT_DEATH(strcat(to, from), RightOOBErrorMessage(0));
+ // length of "to" is just enough.
+ strcat(to, from + 1);
+}
+
+static string OverlapErrorMessage(const string &func) {
+ return func + "-param-overlap";
+}
+
+TEST(AddressSanitizer, StrArgsOverlapTest) {
+ size_t size = Ident(100);
+ char *str = Ident((char*)malloc(size));
+
+ // Check "memcpy". Use Ident() to avoid inlining.
+ memset(str, 'z', size);
+ Ident(memcpy)(str + 1, str + 11, 10);
+ Ident(memcpy)(str, str, 0);
+ EXPECT_DEATH(Ident(memcpy)(str, str + 14, 15), OverlapErrorMessage("memcpy"));
+ EXPECT_DEATH(Ident(memcpy)(str + 14, str, 15), OverlapErrorMessage("memcpy"));
+ EXPECT_DEATH(Ident(memcpy)(str + 20, str + 20, 1),
+ OverlapErrorMessage("memcpy"));
+
+ // Check "strcpy".
+ memset(str, 'z', size);
+ str[9] = '\0';
+ strcpy(str + 10, str);
+ EXPECT_DEATH(strcpy(str + 9, str), OverlapErrorMessage("strcpy"));
+ EXPECT_DEATH(strcpy(str, str + 4), OverlapErrorMessage("strcpy"));
+ strcpy(str, str + 5);
+
+ // Check "strncpy".
+ memset(str, 'z', size);
+ strncpy(str, str + 10, 10);
+ EXPECT_DEATH(strncpy(str, str + 9, 10), OverlapErrorMessage("strncpy"));
+ EXPECT_DEATH(strncpy(str + 9, str, 10), OverlapErrorMessage("strncpy"));
+ str[10] = '\0';
+ strncpy(str + 11, str, 20);
+ EXPECT_DEATH(strncpy(str + 10, str, 20), OverlapErrorMessage("strncpy"));
+
+ // Check "strcat".
+ memset(str, 'z', size);
+ str[10] = '\0';
+ str[20] = '\0';
+ strcat(str, str + 10);
+ strcat(str, str + 11);
+ str[10] = '\0';
+ strcat(str + 11, str);
+ EXPECT_DEATH(strcat(str, str + 9), OverlapErrorMessage("strcat"));
+ EXPECT_DEATH(strcat(str + 9, str), OverlapErrorMessage("strcat"));
+ EXPECT_DEATH(strcat(str + 10, str), OverlapErrorMessage("strcat"));
+
+ free(str);
+}
+
+// At the moment we instrument memcpy/memove/memset calls at compile time so we
+// can't handle OOB error if these functions are called by pointer, see disabled
+// MemIntrinsicCallByPointerTest below
+typedef void*(*PointerToMemTransfer)(void*, const void*, size_t);
+typedef void*(*PointerToMemSet)(void*, int, size_t);
+
+void CallMemSetByPointer(PointerToMemSet MemSet) {
+ size_t size = Ident(100);
+ char *array = Ident((char*)malloc(size));
+ EXPECT_DEATH(MemSet(array, 0, 101), RightOOBErrorMessage(0));
+ free(array);
+}
+
+void CallMemTransferByPointer(PointerToMemTransfer MemTransfer) {
+ size_t size = Ident(100);
+ char *src = Ident((char*)malloc(size));
+ char *dst = Ident((char*)malloc(size));
+ EXPECT_DEATH(MemTransfer(dst, src, 101), RightOOBErrorMessage(0));
+ free(src);
+ free(dst);
+}
+
+TEST(AddressSanitizer, DISABLED_MemIntrinsicCallByPointerTest) {
+ CallMemSetByPointer(&memset);
+ CallMemTransferByPointer(&memcpy);
+ CallMemTransferByPointer(&memmove);
+}
+
+// This test case fails
+// Clang optimizes memcpy/memset calls which lead to unaligned access
+TEST(AddressSanitizer, DISABLED_MemIntrinsicUnalignedAccessTest) {
+ int size = Ident(4096);
+ char *s = Ident((char*)malloc(size));
+ EXPECT_DEATH(memset(s + size - 1, 0, 2), RightOOBErrorMessage(0));
+ free(s);
+}
+
+// TODO(samsonov): Add a test with malloc(0)
+// TODO(samsonov): Add tests for str* and mem* functions.
+
+__attribute__((noinline))
+static int LargeFunction(bool do_bad_access) {
+ int *x = new int[100];
+ x[0]++;
+ x[1]++;
+ x[2]++;
+ x[3]++;
+ x[4]++;
+ x[5]++;
+ x[6]++;
+ x[7]++;
+ x[8]++;
+ x[9]++;
+
+ x[do_bad_access ? 100 : 0]++; int res = __LINE__;
+
+ x[10]++;
+ x[11]++;
+ x[12]++;
+ x[13]++;
+ x[14]++;
+ x[15]++;
+ x[16]++;
+ x[17]++;
+ x[18]++;
+ x[19]++;
+
+ delete x;
+ return res;
+}
+
+// Test the we have correct debug info for the failing instruction.
+// This test requires the in-process symbolizer to be enabled by default.
+TEST(AddressSanitizer, DISABLED_LargeFunctionSymbolizeTest) {
+ int failing_line = LargeFunction(false);
+ char expected_warning[128];
+ sprintf(expected_warning, "LargeFunction.*asan_test.cc:%d", failing_line);
+ EXPECT_DEATH(LargeFunction(true), expected_warning);
+}
+
+// Check that we unwind and symbolize correctly.
+TEST(AddressSanitizer, DISABLED_MallocFreeUnwindAndSymbolizeTest) {
+ int *a = (int*)malloc_aaa(sizeof(int));
+ *a = 1;
+ free_aaa(a);
+ EXPECT_DEATH(*a = 1, "free_ccc.*free_bbb.*free_aaa.*"
+ "malloc_fff.*malloc_eee.*malloc_ddd");
+}
+
+void *ThreadedTestAlloc(void *a) {
+ int **p = (int**)a;
+ *p = new int;
+ return 0;
+}
+
+void *ThreadedTestFree(void *a) {
+ int **p = (int**)a;
+ delete *p;
+ return 0;
+}
+
+void *ThreadedTestUse(void *a) {
+ int **p = (int**)a;
+ **p = 1;
+ return 0;
+}
+
+void ThreadedTestSpawn() {
+ pthread_t t;
+ int *x;
+ pthread_create(&t, 0, ThreadedTestAlloc, &x);
+ pthread_join(t, 0);
+ pthread_create(&t, 0, ThreadedTestFree, &x);
+ pthread_join(t, 0);
+ pthread_create(&t, 0, ThreadedTestUse, &x);
+ pthread_join(t, 0);
+}
+
+TEST(AddressSanitizer, ThreadedTest) {
+ EXPECT_DEATH(ThreadedTestSpawn(),
+ ASAN_PCRE_DOTALL
+ "Thread T.*created"
+ ".*Thread T.*created"
+ ".*Thread T.*created");
+}
+
+#if ASAN_NEEDS_SEGV
+TEST(AddressSanitizer, ShadowGapTest) {
+#if __WORDSIZE == 32
+ char *addr = (char*)0x22000000;
+#else
+ char *addr = (char*)0x0000100000080000;
+#endif
+ EXPECT_DEATH(*addr = 1, "AddressSanitizer crashed on unknown");
+}
+#endif // ASAN_NEEDS_SEGV
+
+extern "C" {
+__attribute__((noinline))
+static void UseThenFreeThenUse() {
+ char *x = Ident((char*)malloc(8));
+ *x = 1;
+ free_aaa(x);
+ *x = 2;
+}
+}
+
+TEST(AddressSanitizer, UseThenFreeThenUseTest) {
+ EXPECT_DEATH(UseThenFreeThenUse(), "freed by thread");
+}
+
+TEST(AddressSanitizer, StrDupTest) {
+ free(strdup(Ident("123")));
+}
+
+TEST(AddressSanitizer, ObjdumpTest) {
+ ObjdumpOfMyself *o = objdump_of_myself();
+ EXPECT_TRUE(o->IsCorrect());
+}
+
+extern "C" {
+__attribute__((noinline))
+static void DisasmSimple() {
+ Ident(0);
+}
+
+__attribute__((noinline))
+static void DisasmParamWrite(int *a) {
+ *a = 1;
+}
+
+__attribute__((noinline))
+static void DisasmParamInc(int *a) {
+ (*a)++;
+}
+
+__attribute__((noinline))
+static void DisasmParamReadIfWrite(int *a) {
+ if (*a)
+ *a = 1;
+}
+
+__attribute__((noinline))
+static int DisasmParamIfReadWrite(int *a, int cond) {
+ int res = 0;
+ if (cond)
+ res = *a;
+ *a = 0;
+ return res;
+}
+
+static int GLOBAL;
+
+__attribute__((noinline))
+static void DisasmWriteGlob() {
+ GLOBAL = 1;
+}
+} // extern "C"
+
+TEST(AddressSanitizer, DisasmTest) {
+ int a;
+ DisasmSimple();
+ DisasmParamWrite(&a);
+ DisasmParamInc(&a);
+ Ident(DisasmWriteGlob)();
+ DisasmParamReadIfWrite(&a);
+
+ a = 7;
+ EXPECT_EQ(7, DisasmParamIfReadWrite(&a, Ident(1)));
+ EXPECT_EQ(0, a);
+
+ ObjdumpOfMyself *o = objdump_of_myself();
+ vector<string> insns;
+ insns.push_back("ud2");
+ insns.push_back("__asan_report_");
+ EXPECT_EQ(0, o->CountInsnInFunc("DisasmSimple", insns));
+ EXPECT_EQ(1, o->CountInsnInFunc("DisasmParamWrite", insns));
+ EXPECT_EQ(1, o->CountInsnInFunc("DisasmParamInc", insns));
+ EXPECT_EQ(0, o->CountInsnInFunc("DisasmWriteGlob", insns));
+
+ // TODO(kcc): implement these (needs just one __asan_report).
+ EXPECT_EQ(2, o->CountInsnInFunc("DisasmParamReadIfWrite", insns));
+ EXPECT_EQ(2, o->CountInsnInFunc("DisasmParamIfReadWrite", insns));
+}
+
+// Currently we create and poison redzone at right of global variables.
+char glob5[5];
+static char static110[110];
+const char ConstGlob[7] = {1, 2, 3, 4, 5, 6, 7};
+static const char StaticConstGlob[3] = {9, 8, 7};
+extern int GlobalsTest(int x);
+
+TEST(AddressSanitizer, GlobalTest) {
+ static char func_static15[15];
+
+ static char fs1[10];
+ static char fs2[10];
+ static char fs3[10];
+
+ glob5[Ident(0)] = 0;
+ glob5[Ident(1)] = 0;
+ glob5[Ident(2)] = 0;
+ glob5[Ident(3)] = 0;
+ glob5[Ident(4)] = 0;
+
+ EXPECT_DEATH(glob5[Ident(5)] = 0,
+ "0 bytes to the right of global variable.*glob5.* size 5");
+ EXPECT_DEATH(glob5[Ident(5+6)] = 0,
+ "6 bytes to the right of global variable.*glob5.* size 5");
+ Ident(static110); // avoid optimizations
+ static110[Ident(0)] = 0;
+ static110[Ident(109)] = 0;
+ EXPECT_DEATH(static110[Ident(110)] = 0,
+ "0 bytes to the right of global variable");
+ EXPECT_DEATH(static110[Ident(110+7)] = 0,
+ "7 bytes to the right of global variable");
+
+ Ident(func_static15); // avoid optimizations
+ func_static15[Ident(0)] = 0;
+ EXPECT_DEATH(func_static15[Ident(15)] = 0,
+ "0 bytes to the right of global variable");
+ EXPECT_DEATH(func_static15[Ident(15 + 9)] = 0,
+ "9 bytes to the right of global variable");
+
+ Ident(fs1);
+ Ident(fs2);
+ Ident(fs3);
+
+ // We don't create left redzones, so this is not 100% guaranteed to fail.
+ // But most likely will.
+ EXPECT_DEATH(fs2[Ident(-1)] = 0, "is located.*of global variable");
+
+ EXPECT_DEATH(Ident(Ident(ConstGlob)[8]),
+ "is located 1 bytes to the right of .*ConstGlob");
+ EXPECT_DEATH(Ident(Ident(StaticConstGlob)[5]),
+ "is located 2 bytes to the right of .*StaticConstGlob");
+
+ // call stuff from another file.
+ GlobalsTest(0);
+}
+
+TEST(AddressSanitizer, GlobalStringConstTest) {
+ static const char *zoo = "FOOBAR123";
+ const char *p = Ident(zoo);
+ EXPECT_DEATH(Ident(p[15]), "is ascii string 'FOOBAR123'");
+}
+
+TEST(AddressSanitizer, FileNameInGlobalReportTest) {
+ static char zoo[10];
+ const char *p = Ident(zoo);
+ // The file name should be present in the report.
+ EXPECT_DEATH(Ident(p[15]), "zoo.*asan_test.cc");
+}
+
+int *ReturnsPointerToALocalObject() {
+ int a = 0;
+ return Ident(&a);
+}
+
+#if ASAN_UAR == 1
+TEST(AddressSanitizer, LocalReferenceReturnTest) {
+ int *(*f)() = Ident(ReturnsPointerToALocalObject);
+ int *p = f();
+ // Call 'f' a few more times, 'p' should still be poisoned.
+ for (int i = 0; i < 32; i++)
+ f();
+ EXPECT_DEATH(*p = 1, "AddressSanitizer stack-use-after-return");
+ EXPECT_DEATH(*p = 1, "is located.*in frame .*ReturnsPointerToALocal");
+}
+#endif
+
+template <int kSize>
+__attribute__((noinline))
+static void FuncWithStack() {
+ char x[kSize];
+ Ident(x)[0] = 0;
+ Ident(x)[kSize-1] = 0;
+}
+
+static void LotsOfStackReuse() {
+ int LargeStack[10000];
+ Ident(LargeStack)[0] = 0;
+ for (int i = 0; i < 10000; i++) {
+ FuncWithStack<128 * 1>();
+ FuncWithStack<128 * 2>();
+ FuncWithStack<128 * 4>();
+ FuncWithStack<128 * 8>();
+ FuncWithStack<128 * 16>();
+ FuncWithStack<128 * 32>();
+ FuncWithStack<128 * 64>();
+ FuncWithStack<128 * 128>();
+ FuncWithStack<128 * 256>();
+ FuncWithStack<128 * 512>();
+ Ident(LargeStack)[0] = 0;
+ }
+}
+
+TEST(AddressSanitizer, StressStackReuseTest) {
+ LotsOfStackReuse();
+}
+
+TEST(AddressSanitizer, ThreadedStressStackReuseTest) {
+ const int kNumThreads = 20;
+ pthread_t t[kNumThreads];
+ for (int i = 0; i < kNumThreads; i++) {
+ pthread_create(&t[i], 0, (void* (*)(void *x))LotsOfStackReuse, 0);
+ }
+ for (int i = 0; i < kNumThreads; i++) {
+ pthread_join(t[i], 0);
+ }
+}
+
+#ifdef __EXCEPTIONS
+__attribute__((noinline))
+static void StackReuseAndException() {
+ int large_stack[1000];
+ Ident(large_stack);
+ ASAN_THROW(1);
+}
+
+// TODO(kcc): support exceptions with use-after-return.
+TEST(AddressSanitizer, DISABLED_StressStackReuseAndExceptionsTest) {
+ for (int i = 0; i < 10000; i++) {
+ try {
+ StackReuseAndException();
+ } catch(...) {
+ }
+ }
+}
+#endif
+
+TEST(AddressSanitizer, MlockTest) {
+ EXPECT_EQ(0, mlockall(MCL_CURRENT));
+ EXPECT_EQ(0, mlock((void*)0x12345, 0x5678));
+ EXPECT_EQ(0, munlockall());
+ EXPECT_EQ(0, munlock((void*)0x987, 0x654));
+}
+
+// ------------------ demo tests; run each one-by-one -------------
+// e.g. --gtest_filter=*DemoOOBLeftHigh --gtest_also_run_disabled_tests
+TEST(AddressSanitizer, DISABLED_DemoThreadedTest) {
+ ThreadedTestSpawn();
+}
+
+void *SimpleBugOnSTack(void *x = 0) {
+ char a[20];
+ Ident(a)[20] = 0;
+ return 0;
+}
+
+TEST(AddressSanitizer, DISABLED_DemoStackTest) {
+ SimpleBugOnSTack();
+}
+
+TEST(AddressSanitizer, DISABLED_DemoThreadStackTest) {
+ pthread_t t;
+ pthread_create(&t, 0, SimpleBugOnSTack, 0);
+ pthread_join(t, 0);
+}
+
+TEST(AddressSanitizer, DISABLED_DemoUAFLowIn) {
+ uaf_test<U1>(10, 0);
+}
+TEST(AddressSanitizer, DISABLED_DemoUAFLowLeft) {
+ uaf_test<U1>(10, -2);
+}
+TEST(AddressSanitizer, DISABLED_DemoUAFLowRight) {
+ uaf_test<U1>(10, 10);
+}
+
+TEST(AddressSanitizer, DISABLED_DemoUAFHigh) {
+ uaf_test<U1>(kLargeMalloc, 0);
+}
+
+TEST(AddressSanitizer, DISABLED_DemoOOBLeftLow) {
+ oob_test<U1>(10, -1);
+}
+
+TEST(AddressSanitizer, DISABLED_DemoOOBLeftHigh) {
+ oob_test<U1>(kLargeMalloc, -1);
+}
+
+TEST(AddressSanitizer, DISABLED_DemoOOBRightLow) {
+ oob_test<U1>(10, 10);
+}
+
+TEST(AddressSanitizer, DISABLED_DemoOOBRightHigh) {
+ oob_test<U1>(kLargeMalloc, kLargeMalloc);
+}
+
+TEST(AddressSanitizer, DISABLED_DemoOOM) {
+ size_t size = __WORDSIZE == 64 ? (size_t)(1ULL << 40) : (0xf0000000);
+ printf("%p\n", malloc(size));
+}
+
+TEST(AddressSanitizer, DISABLED_DemoDoubleFreeTest) {
+ DoubleFree();
+}
+
+TEST(AddressSanitizer, DISABLED_DemoNullDerefTest) {
+ int *a = 0;
+ Ident(a)[10] = 0;
+}
+
+TEST(AddressSanitizer, DISABLED_DemoFunctionStaticTest) {
+ static char a[100];
+ static char b[100];
+ static char c[100];
+ Ident(a);
+ Ident(b);
+ Ident(c);
+ Ident(a)[5] = 0;
+ Ident(b)[105] = 0;
+ Ident(a)[5] = 0;
+}
+
+TEST(AddressSanitizer, DISABLED_DemoTooMuchMemoryTest) {
+ const size_t kAllocSize = (1 << 28) - 1024;
+ size_t total_size = 0;
+ while (true) {
+ char *x = (char*)malloc(kAllocSize);
+ memset(x, 0, kAllocSize);
+ total_size += kAllocSize;
+ fprintf(stderr, "total: %ldM\n", (long)total_size >> 20);
+ }
+}
+
+#ifdef __APPLE__
+#include "asan_mac_test.h"
+// TODO(glider): figure out whether we still need these tests. Is it correct
+// to intercept CFAllocator?
+TEST(AddressSanitizerMac, DISABLED_CFAllocatorDefaultDoubleFree) {
+ EXPECT_DEATH(
+ CFAllocatorDefaultDoubleFree(),
+ "attempting double-free");
+}
+
+TEST(AddressSanitizerMac, DISABLED_CFAllocatorSystemDefaultDoubleFree) {
+ EXPECT_DEATH(
+ CFAllocatorSystemDefaultDoubleFree(),
+ "attempting double-free");
+}
+
+TEST(AddressSanitizerMac, DISABLED_CFAllocatorMallocDoubleFree) {
+ EXPECT_DEATH(CFAllocatorMallocDoubleFree(), "attempting double-free");
+}
+
+TEST(AddressSanitizerMac, DISABLED_CFAllocatorMallocZoneDoubleFree) {
+ EXPECT_DEATH(CFAllocatorMallocZoneDoubleFree(), "attempting double-free");
+}
+
+TEST(AddressSanitizerMac, GCDDispatchAsync) {
+ // Make sure the whole ASan report is printed, i.e. that we don't die
+ // on a CHECK.
+ EXPECT_DEATH(TestGCDDispatchAsync(), "Shadow byte and word");
+}
+
+TEST(AddressSanitizerMac, GCDDispatchSync) {
+ // Make sure the whole ASan report is printed, i.e. that we don't die
+ // on a CHECK.
+ EXPECT_DEATH(TestGCDDispatchSync(), "Shadow byte and word");
+}
+
+
+TEST(AddressSanitizerMac, GCDReuseWqthreadsAsync) {
+ // Make sure the whole ASan report is printed, i.e. that we don't die
+ // on a CHECK.
+ EXPECT_DEATH(TestGCDReuseWqthreadsAsync(), "Shadow byte and word");
+}
+
+TEST(AddressSanitizerMac, GCDReuseWqthreadsSync) {
+ // Make sure the whole ASan report is printed, i.e. that we don't die
+ // on a CHECK.
+ EXPECT_DEATH(TestGCDReuseWqthreadsSync(), "Shadow byte and word");
+}
+
+TEST(AddressSanitizerMac, GCDDispatchAfter) {
+ // Make sure the whole ASan report is printed, i.e. that we don't die
+ // on a CHECK.
+ EXPECT_DEATH(TestGCDDispatchAfter(), "Shadow byte and word");
+}
+
+TEST(AddressSanitizerMac, GCDSourceEvent) {
+ // Make sure the whole ASan report is printed, i.e. that we don't die
+ // on a CHECK.
+ EXPECT_DEATH(TestGCDSourceEvent(), "Shadow byte and word");
+}
+
+TEST(AddressSanitizerMac, GCDSourceCancel) {
+ // Make sure the whole ASan report is printed, i.e. that we don't die
+ // on a CHECK.
+ EXPECT_DEATH(TestGCDSourceCancel(), "Shadow byte and word");
+}
+
+TEST(AddressSanitizerMac, GCDGroupAsync) {
+ // Make sure the whole ASan report is printed, i.e. that we don't die
+ // on a CHECK.
+ EXPECT_DEATH(TestGCDGroupAsync(), "Shadow byte and word");
+}
+
+void *MallocIntrospectionLockWorker(void *_) {
+ const int kNumPointers = 100;
+ int i;
+ void *pointers[kNumPointers];
+ for (i = 0; i < kNumPointers; i++) {
+ pointers[i] = malloc(i + 1);
+ }
+ for (i = 0; i < kNumPointers; i++) {
+ free(pointers[i]);
+ }
+
+ return NULL;
+}
+
+void *MallocIntrospectionLockForker(void *_) {
+ pid_t result = fork();
+ if (result == -1) {
+ perror("fork");
+ }
+ assert(result != -1);
+ if (result == 0) {
+ // Call malloc in the child process to make sure we won't deadlock.
+ void *ptr = malloc(42);
+ free(ptr);
+ exit(0);
+ } else {
+ // Return in the parent process.
+ return NULL;
+ }
+}
+
+TEST(AddressSanitizerMac, MallocIntrospectionLock) {
+ // Incorrect implementation of force_lock and force_unlock in our malloc zone
+ // will cause forked processes to deadlock.
+ // TODO(glider): need to detect that none of the child processes deadlocked.
+ const int kNumWorkers = 5, kNumIterations = 100;
+ int i, iter;
+ for (iter = 0; iter < kNumIterations; iter++) {
+ pthread_t workers[kNumWorkers], forker;
+ for (i = 0; i < kNumWorkers; i++) {
+ pthread_create(&workers[i], 0, MallocIntrospectionLockWorker, 0);
+ }
+ pthread_create(&forker, 0, MallocIntrospectionLockForker, 0);
+ for (i = 0; i < kNumWorkers; i++) {
+ pthread_join(workers[i], 0);
+ }
+ pthread_join(forker, 0);
+ }
+}
+
+void *TSDAllocWorker(void *test_key) {
+ if (test_key) {
+ void *mem = malloc(10);
+ pthread_setspecific(*(pthread_key_t*)test_key, mem);
+ }
+ return NULL;
+}
+
+TEST(AddressSanitizerMac, DISABLED_TSDWorkqueueTest) {
+ pthread_t th;
+ pthread_key_t test_key;
+ pthread_key_create(&test_key, CallFreeOnWorkqueue);
+ pthread_create(&th, NULL, TSDAllocWorker, &test_key);
+ pthread_join(th, NULL);
+ pthread_key_delete(test_key);
+}
+#endif // __APPLE__
+
+int main(int argc, char **argv) {
+ progname = argv[0];
+ testing::GTEST_FLAG(death_test_style) = "threadsafe";
+ testing::InitGoogleTest(&argc, argv);
+ return RUN_ALL_TESTS();
+}
diff --git a/lib/asan/tests/asan_test.ignore b/lib/asan/tests/asan_test.ignore
new file mode 100644
index 000000000000..7bafa83bf62e
--- /dev/null
+++ b/lib/asan/tests/asan_test.ignore
@@ -0,0 +1,2 @@
+fun:*IgnoreTest*
+fun:*SomeOtherFunc*
diff --git a/lib/asan/tests/asan_test_config.h b/lib/asan/tests/asan_test_config.h
new file mode 100644
index 000000000000..de4ae95bd244
--- /dev/null
+++ b/lib/asan/tests/asan_test_config.h
@@ -0,0 +1,44 @@
+//===-- asan_test_config.h ------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file is a part of AddressSanitizer, an address sanity checker.
+//
+//===----------------------------------------------------------------------===//
+#ifndef ASAN_TEST_CONFIG_H
+#define ASAN_TEST_CONFIG_H
+
+#include <vector>
+#include <string>
+#include <map>
+
+#include "gtest/gtest.h"
+
+using std::string;
+using std::vector;
+using std::map;
+
+#ifndef ASAN_UAR
+# error "please define ASAN_UAR"
+#endif
+
+#ifndef ASAN_HAS_EXCEPTIONS
+# error "please define ASAN_HAS_EXCEPTIONS"
+#endif
+
+#ifndef ASAN_HAS_BLACKLIST
+# error "please define ASAN_HAS_BLACKLIST"
+#endif
+
+#ifndef ASAN_NEEDS_SEGV
+# error "please define ASAN_NEEDS_SEGV"
+#endif
+
+#define ASAN_PCRE_DOTALL ""
+
+#endif // ASAN_TEST_CONFIG_H
diff --git a/lib/asan/tests/asan_test_utils.h b/lib/asan/tests/asan_test_utils.h
new file mode 100644
index 000000000000..a4809812dcf0
--- /dev/null
+++ b/lib/asan/tests/asan_test_utils.h
@@ -0,0 +1,30 @@
+//===-- asan_test_utils.h ------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file is a part of AddressSanitizer, an address sanity checker.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef ASAN_TEST_UTILS_H
+#define ASAN_TEST_UTILS_H
+
+// Make the compiler think that something is going on there.
+extern "C" void break_optimization(void *);
+
+// This function returns its parameter but in such a way that compiler
+// can not prove it.
+template<class T>
+__attribute__((noinline))
+static T Ident(T t) {
+ T ret = t;
+ break_optimization(&ret);
+ return ret;
+}
+
+#endif // ASAN_TEST_UTILS_H
diff --git a/lib/asan/tests/dlclose-test-so.cc b/lib/asan/tests/dlclose-test-so.cc
new file mode 100644
index 000000000000..fae2f813abb7
--- /dev/null
+++ b/lib/asan/tests/dlclose-test-so.cc
@@ -0,0 +1,33 @@
+//===-- asan_rtl.cc ------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file is a part of AddressSanitizer, an address sanity checker.
+//
+// Regression test for
+// http://code.google.com/p/address-sanitizer/issues/detail?id=19
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+static int pad1;
+static int static_var;
+static int pad2;
+
+extern "C"
+int *get_address_of_static_var() {
+ return &static_var;
+}
+
+__attribute__((constructor))
+void at_dlopen() {
+ printf("%s: I am being dlopened\n", __FILE__);
+}
+__attribute__((destructor))
+void at_dlclose() {
+ printf("%s: I am being dlclosed\n", __FILE__);
+}
diff --git a/lib/asan/tests/dlclose-test.cc b/lib/asan/tests/dlclose-test.cc
new file mode 100644
index 000000000000..307886667b15
--- /dev/null
+++ b/lib/asan/tests/dlclose-test.cc
@@ -0,0 +1,73 @@
+//===-- asan_rtl.cc ------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file is a part of AddressSanitizer, an address sanity checker.
+//
+// Regression test for
+// http://code.google.com/p/address-sanitizer/issues/detail?id=19
+// Bug description:
+// 1. application dlopens foo.so
+// 2. asan registers all globals from foo.so
+// 3. application dlcloses foo.so
+// 4. application mmaps some memory to the location where foo.so was before
+// 5. application starts using this mmaped memory, but asan still thinks there
+// are globals.
+// 6. BOOM
+//===----------------------------------------------------------------------===//
+#include <assert.h>
+#include <dlfcn.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/mman.h>
+
+#include <string>
+
+using std::string;
+
+static const int kPageSize = 4096;
+
+typedef int *(fun_t)();
+
+int main(int argc, char *argv[]) {
+ string path = string(argv[0]) + "-so.so";
+ printf("opening %s ... \n", path.c_str());
+ void *lib = dlopen(path.c_str(), RTLD_NOW);
+ if (!lib) {
+ printf("error in dlopen(): %s\n", dlerror());
+ return 1;
+ }
+ fun_t *get = (fun_t*)dlsym(lib, "get_address_of_static_var");
+ if (!get) {
+ printf("failed dlsym\n");
+ return 1;
+ }
+ int *addr = get();
+ assert(((size_t)addr % 32) == 0); // should be 32-byte aligned.
+ printf("addr: %p\n", addr);
+ addr[0] = 1; // make sure we can write there.
+
+ // Now dlclose the shared library.
+ printf("attempting to dlclose\n");
+ if (dlclose(lib)) {
+ printf("failed to dlclose\n");
+ return 1;
+ }
+ // Now, the page where 'addr' is unmapped. Map it.
+ size_t page_beg = ((size_t)addr) & ~(kPageSize - 1);
+ void *res = mmap((void*)(page_beg), kPageSize,
+ PROT_READ | PROT_WRITE,
+ MAP_PRIVATE | MAP_ANON | MAP_FIXED | MAP_NORESERVE, 0, 0);
+ if (res == (char*)-1L) {
+ printf("failed to mmap\n");
+ return 1;
+ }
+ addr[1] = 2; // BOOM (if the bug is not fixed).
+ printf("PASS\n");
+ return 0;
+}
diff --git a/lib/asan/tests/dlclose-test.tmpl b/lib/asan/tests/dlclose-test.tmpl
new file mode 100644
index 000000000000..7ef22e9a431a
--- /dev/null
+++ b/lib/asan/tests/dlclose-test.tmpl
@@ -0,0 +1 @@
+PASS
diff --git a/lib/asan/tests/global-overflow.cc b/lib/asan/tests/global-overflow.cc
new file mode 100644
index 000000000000..b85c4d2a18bf
--- /dev/null
+++ b/lib/asan/tests/global-overflow.cc
@@ -0,0 +1,12 @@
+#include <string.h>
+int main(int argc, char **argv) {
+ static char XXX[10];
+ static char YYY[10];
+ static char ZZZ[10];
+ memset(XXX, 0, 10);
+ memset(YYY, 0, 10);
+ memset(ZZZ, 0, 10);
+ int res = YYY[argc * 10]; // BOOOM
+ res += XXX[argc] + ZZZ[argc];
+ return res;
+}
diff --git a/lib/asan/tests/global-overflow.tmpl b/lib/asan/tests/global-overflow.tmpl
new file mode 100644
index 000000000000..c5d54428143b
--- /dev/null
+++ b/lib/asan/tests/global-overflow.tmpl
@@ -0,0 +1,3 @@
+READ of size 1 at 0x.* thread T0
+ #0 0x.* in main .*global-overflow.cc:9
+0x.* is located 0 bytes to the right of global variable .*YYY.* of size 10
diff --git a/lib/asan/tests/heap-overflow.cc b/lib/asan/tests/heap-overflow.cc
new file mode 100644
index 000000000000..475d1637385a
--- /dev/null
+++ b/lib/asan/tests/heap-overflow.cc
@@ -0,0 +1,9 @@
+#include <stdlib.h>
+#include <string.h>
+int main(int argc, char **argv) {
+ char *x = (char*)malloc(10 * sizeof(char));
+ memset(x, 0, 10);
+ int res = x[argc * 10]; // BOOOM
+ free(x);
+ return res;
+}
diff --git a/lib/asan/tests/heap-overflow.tmpl b/lib/asan/tests/heap-overflow.tmpl
new file mode 100644
index 000000000000..e2ab65f17d82
--- /dev/null
+++ b/lib/asan/tests/heap-overflow.tmpl
@@ -0,0 +1,6 @@
+READ of size 1 at 0x.* thread T0
+ #0 0x.* in main .*heap-overflow.cc:6
+0x.* is located 0 bytes to the right of 10-byte region
+allocated by thread T0 here:
+ #0 0x.* in malloc
+ #1 0x.* in main .*heap-overflow.cc:[45]
diff --git a/lib/asan/tests/heap-overflow.tmpl.Darwin b/lib/asan/tests/heap-overflow.tmpl.Darwin
new file mode 100644
index 000000000000..e4611d067abe
--- /dev/null
+++ b/lib/asan/tests/heap-overflow.tmpl.Darwin
@@ -0,0 +1,8 @@
+READ of size 1 at 0x.* thread T0
+ #0 0x.* in main .*heap-overflow.cc:6
+0x.* is located 0 bytes to the right of 10-byte region
+allocated by thread T0 here:
+ #0 0x.* in .*mz_malloc.* _asan_rtl_
+ #1 0x.* in malloc_zone_malloc.*
+ #2 0x.* in malloc.*
+ #3 0x.* in main heap-overflow.cc:4
diff --git a/lib/asan/tests/large_func_test.cc b/lib/asan/tests/large_func_test.cc
new file mode 100644
index 000000000000..70bc36f40b87
--- /dev/null
+++ b/lib/asan/tests/large_func_test.cc
@@ -0,0 +1,33 @@
+#include <stdlib.h>
+__attribute__((noinline))
+static void LargeFunction(int *x, int zero) {
+ x[0]++;
+ x[1]++;
+ x[2]++;
+ x[3]++;
+ x[4]++;
+ x[5]++;
+ x[6]++;
+ x[7]++;
+ x[8]++;
+ x[9]++;
+
+ x[zero + 111]++; // we should report this exact line
+
+ x[10]++;
+ x[11]++;
+ x[12]++;
+ x[13]++;
+ x[14]++;
+ x[15]++;
+ x[16]++;
+ x[17]++;
+ x[18]++;
+ x[19]++;
+}
+
+int main(int argc, char **argv) {
+ int *x = new int[100];
+ LargeFunction(x, argc - 1);
+ delete x;
+}
diff --git a/lib/asan/tests/large_func_test.tmpl b/lib/asan/tests/large_func_test.tmpl
new file mode 100644
index 000000000000..45a13d0bc5bd
--- /dev/null
+++ b/lib/asan/tests/large_func_test.tmpl
@@ -0,0 +1,8 @@
+.*ERROR: AddressSanitizer heap-buffer-overflow on address 0x.* at pc 0x.* bp 0x.* sp 0x.*
+READ of size 4 at 0x.* thread T0
+ #0 0x.* in LargeFunction .*large_func_test.cc:15
+ #1 0x.* in main .*large_func_test.cc:3[012]
+0x.* is located 44 bytes to the right of 400-byte region
+allocated by thread T0 here:
+ #0 0x.* in operator new.*
+ #1 0x.* in main .*large_func_test.cc:30
diff --git a/lib/asan/tests/match_output.py b/lib/asan/tests/match_output.py
new file mode 100755
index 000000000000..31095f3f62f2
--- /dev/null
+++ b/lib/asan/tests/match_output.py
@@ -0,0 +1,35 @@
+#!/usr/bin/python
+
+import re
+import sys
+
+def matchFile(f, f_re):
+ for line_re in f_re:
+ line_re = line_re.rstrip()
+ if not line_re:
+ continue
+ if line_re[0] == '#':
+ continue
+ match = False
+ for line in f:
+ line = line.rstrip()
+ # print line
+ if re.search(line_re, line):
+ match = True
+ #print 'match: %s =~ %s' % (line, line_re)
+ break
+ if not match:
+ print 'no match for: %s' % (line_re)
+ return False
+ return True
+
+if len(sys.argv) != 2:
+ print >>sys.stderr, 'Usage: %s <template file>'
+ sys.exit(1)
+
+f = sys.stdin
+f_re = open(sys.argv[1])
+
+if not matchFile(f, f_re):
+ print >>sys.stderr, 'File does not match the template'
+ sys.exit(1)
diff --git a/lib/asan/tests/null_deref.cc b/lib/asan/tests/null_deref.cc
new file mode 100644
index 000000000000..f7ba4dd5f63f
--- /dev/null
+++ b/lib/asan/tests/null_deref.cc
@@ -0,0 +1,7 @@
+__attribute__((noinline))
+static void NullDeref(int *ptr) {
+ ptr[10]++;
+}
+int main() {
+ NullDeref((int*)0);
+}
diff --git a/lib/asan/tests/null_deref.tmpl b/lib/asan/tests/null_deref.tmpl
new file mode 100644
index 000000000000..d27cccc06bc8
--- /dev/null
+++ b/lib/asan/tests/null_deref.tmpl
@@ -0,0 +1,4 @@
+.*ERROR: AddressSanitizer crashed on unknown address 0x0*00028 .*pc 0x.*
+AddressSanitizer can not provide additional info. ABORTING
+ #0 0x.* in NullDeref.*null_deref.cc:3
+ #1 0x.* in main.*null_deref.cc:[67]
diff --git a/lib/asan/tests/shared-lib-test-so.cc b/lib/asan/tests/shared-lib-test-so.cc
new file mode 100644
index 000000000000..c3b3bc22aed2
--- /dev/null
+++ b/lib/asan/tests/shared-lib-test-so.cc
@@ -0,0 +1,21 @@
+//===-- asan_rtl.cc ------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file is a part of AddressSanitizer, an address sanity checker.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+int pad[10];
+int GLOB[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
+
+extern "C"
+void inc(int index) {
+ GLOB[index]++;
+}
diff --git a/lib/asan/tests/shared-lib-test.cc b/lib/asan/tests/shared-lib-test.cc
new file mode 100644
index 000000000000..e492572c7280
--- /dev/null
+++ b/lib/asan/tests/shared-lib-test.cc
@@ -0,0 +1,37 @@
+//===-- asan_rtl.cc ------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file is a part of AddressSanitizer, an address sanity checker.
+//
+//===----------------------------------------------------------------------===//
+#include <dlfcn.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <string>
+
+using std::string;
+
+typedef void (fun_t)(int x);
+
+int main(int argc, char *argv[]) {
+ string path = string(argv[0]) + "-so.so";
+ printf("opening %s ... \n", path.c_str());
+ void *lib = dlopen(path.c_str(), RTLD_NOW);
+ if (!lib) {
+ printf("error in dlopen(): %s\n", dlerror());
+ return 1;
+ }
+ fun_t *inc = (fun_t*)dlsym(lib, "inc");
+ if (!inc) return 1;
+ printf("ok\n");
+ inc(1);
+ inc(-1);
+ return 0;
+}
diff --git a/lib/asan/tests/shared-lib-test.tmpl b/lib/asan/tests/shared-lib-test.tmpl
new file mode 100644
index 000000000000..564e3eb5cb8c
--- /dev/null
+++ b/lib/asan/tests/shared-lib-test.tmpl
@@ -0,0 +1,7 @@
+#.*ERROR: AddressSanitizer global-buffer-overflow on address 0x.* at pc 0x.* bp 0x.* sp 0x.*
+#READ of size 4 at 0x.* thread T0
+# #0 0x.* in inc .*shared-lib-test-so.cc:11
+# #1 0x.* in main .*shared-lib-test.cc:33
+# #2 0x.* in __libc_start_main.*
+#0x.* is located 4 bytes to the left of global variable 'GLOB' (.*) of size 40
+#0x.* is located 52 bytes to the right of global variable 'pad' (.*) of size 40
diff --git a/lib/asan/tests/stack-overflow.cc b/lib/asan/tests/stack-overflow.cc
new file mode 100644
index 000000000000..dd86aa32514a
--- /dev/null
+++ b/lib/asan/tests/stack-overflow.cc
@@ -0,0 +1,7 @@
+#include <string.h>
+int main(int argc, char **argv) {
+ char x[10];
+ memset(x, 0, 10);
+ int res = x[argc * 10]; // BOOOM
+ return res;
+}
diff --git a/lib/asan/tests/stack-overflow.tmpl b/lib/asan/tests/stack-overflow.tmpl
new file mode 100644
index 000000000000..6aa717a82b28
--- /dev/null
+++ b/lib/asan/tests/stack-overflow.tmpl
@@ -0,0 +1,3 @@
+READ of size 1 at 0x.* thread T0
+ #0 0x.* in main .*stack-overflow.cc:5
+Address 0x.* is .* frame <main>
diff --git a/lib/asan/tests/stack-use-after-return.cc b/lib/asan/tests/stack-use-after-return.cc
new file mode 100644
index 000000000000..9098edf0adb8
--- /dev/null
+++ b/lib/asan/tests/stack-use-after-return.cc
@@ -0,0 +1,24 @@
+#include <stdio.h>
+
+__attribute__((noinline))
+char *Ident(char *x) {
+ fprintf(stderr, "1: %p\n", x);
+ return x;
+}
+
+__attribute__((noinline))
+char *Func1() {
+ char local;
+ return Ident(&local);
+}
+
+__attribute__((noinline))
+void Func2(char *x) {
+ fprintf(stderr, "2: %p\n", x);
+ *x = 1;
+}
+
+int main(int argc, char **argv) {
+ Func2(Func1());
+ return 0;
+}
diff --git a/lib/asan/tests/stack-use-after-return.disabled b/lib/asan/tests/stack-use-after-return.disabled
new file mode 100644
index 000000000000..02729bc43a74
--- /dev/null
+++ b/lib/asan/tests/stack-use-after-return.disabled
@@ -0,0 +1,3 @@
+WRITE of size 1 .* thread T0
+#0.*Func2.*stack-use-after-return.cc:18
+is located in frame <.*Func1.*> of T0's stack
diff --git a/lib/asan/tests/strncpy-overflow.cc b/lib/asan/tests/strncpy-overflow.cc
new file mode 100644
index 000000000000..044f6494bfa1
--- /dev/null
+++ b/lib/asan/tests/strncpy-overflow.cc
@@ -0,0 +1,9 @@
+#include <string.h>
+#include <stdlib.h>
+int main(int argc, char **argv) {
+ char *hello = (char*)malloc(6);
+ strcpy(hello, "hello");
+ char *short_buffer = (char*)malloc(9);
+ strncpy(short_buffer, hello, 10); // BOOM
+ return short_buffer[8];
+}
diff --git a/lib/asan/tests/strncpy-overflow.tmpl b/lib/asan/tests/strncpy-overflow.tmpl
new file mode 100644
index 000000000000..3780aa81921f
--- /dev/null
+++ b/lib/asan/tests/strncpy-overflow.tmpl
@@ -0,0 +1,7 @@
+WRITE of size 1 at 0x.* thread T0
+ #0 0x.* in strncpy
+ #1 0x.* in main .*strncpy-overflow.cc:[78]
+0x.* is located 0 bytes to the right of 9-byte region
+allocated by thread T0 here:
+ #0 0x.* in malloc
+ #1 0x.* in main .*strncpy-overflow.cc:6
diff --git a/lib/asan/tests/test_output.sh b/lib/asan/tests/test_output.sh
new file mode 100755
index 000000000000..c54b2364b2c3
--- /dev/null
+++ b/lib/asan/tests/test_output.sh
@@ -0,0 +1,47 @@
+#!/bin/bash
+
+set -e # fail on any error
+
+OS=`uname`
+CXX=$1
+CC=$2
+CXXFLAGS="-mno-omit-leaf-frame-pointer -fno-omit-frame-pointer"
+SYMBOLIZER=../scripts/asan_symbolize.py
+
+C_TEST=use-after-free
+echo "Sanity checking a test in pure C"
+$CC -g -faddress-sanitizer -O2 $C_TEST.c
+./a.out 2>&1 | grep "heap-use-after-free" > /dev/null
+rm ./a.out
+
+echo "Sanity checking a test in pure C with -pie"
+$CC -g -faddress-sanitizer -O2 $C_TEST.c -pie
+./a.out 2>&1 | grep "heap-use-after-free" > /dev/null
+rm ./a.out
+
+for t in *.tmpl; do
+ for b in 32 64; do
+ for O in 0 1 2 3; do
+ c=`basename $t .tmpl`
+ c_so=$c-so
+ exe=$c.$b.O$O
+ so=$c.$b.O$O-so.so
+ echo testing $exe
+ $CXX $CXXFLAGS -g -m$b -faddress-sanitizer -O$O $c.cc -o $exe
+ [ -e "$c_so.cc" ] && $CXX $CXXFLAGS -g -m$b -faddress-sanitizer -O$O $c_so.cc -fPIC -shared -o $so
+ # If there's an OS-specific template, use it.
+ # Please minimize the use of OS-specific templates.
+ if [ -e "$t.$OS" ]
+ then
+ actual_t="$t.$OS"
+ else
+ actual_t="$t"
+ fi
+ ./$exe 2>&1 | $SYMBOLIZER 2> /dev/null | c++filt | ./match_output.py $actual_t
+ rm ./$exe
+ [ -e "$so" ] && rm ./$so
+ done
+ done
+done
+
+exit 0
diff --git a/lib/asan/tests/use-after-free.c b/lib/asan/tests/use-after-free.c
new file mode 100644
index 000000000000..60626bff778a
--- /dev/null
+++ b/lib/asan/tests/use-after-free.c
@@ -0,0 +1,6 @@
+#include <stdlib.h>
+int main() {
+ char *x = (char*)malloc(10 * sizeof(char));
+ free(x);
+ return x[5];
+}
diff --git a/lib/asan/tests/use-after-free.cc b/lib/asan/tests/use-after-free.cc
new file mode 100644
index 000000000000..60626bff778a
--- /dev/null
+++ b/lib/asan/tests/use-after-free.cc
@@ -0,0 +1,6 @@
+#include <stdlib.h>
+int main() {
+ char *x = (char*)malloc(10 * sizeof(char));
+ free(x);
+ return x[5];
+}
diff --git a/lib/asan/tests/use-after-free.tmpl b/lib/asan/tests/use-after-free.tmpl
new file mode 100644
index 000000000000..c4b5c74d9887
--- /dev/null
+++ b/lib/asan/tests/use-after-free.tmpl
@@ -0,0 +1,10 @@
+.*ERROR: AddressSanitizer heap-use-after-free on address 0x.* at pc 0x.* bp 0x.* sp 0x.*
+READ of size 1 at 0x.* thread T0
+ #0 0x.* in main .*use-after-free.cc:5
+0x.* is located 5 bytes inside of 10-byte region .0x.*,0x.*
+freed by thread T0 here:
+ #0 0x.* in free
+ #1 0x.* in main .*use-after-free.cc:[45]
+previously allocated by thread T0 here:
+ #0 0x.* in malloc
+ #1 0x.* in main .*use-after-free.cc:3