1 //===-- asan_test.cc ------------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is a part of AddressSanitizer, an address sanity checker.
12 //===----------------------------------------------------------------------===//
13 #include "asan_test_utils.h"
15 NOINLINE void *malloc_fff(size_t size) {
16 void *res = malloc/**/(size); break_optimization(0); return res;}
17 NOINLINE void *malloc_eee(size_t size) {
18 void *res = malloc_fff(size); break_optimization(0); return res;}
19 NOINLINE void *malloc_ddd(size_t size) {
20 void *res = malloc_eee(size); break_optimization(0); return res;}
21 NOINLINE void *malloc_ccc(size_t size) {
22 void *res = malloc_ddd(size); break_optimization(0); return res;}
23 NOINLINE void *malloc_bbb(size_t size) {
24 void *res = malloc_ccc(size); break_optimization(0); return res;}
25 NOINLINE void *malloc_aaa(size_t size) {
26 void *res = malloc_bbb(size); break_optimization(0); return res;}
28 NOINLINE void free_ccc(void *p) { free(p); break_optimization(0);}
29 NOINLINE void free_bbb(void *p) { free_ccc(p); break_optimization(0);}
30 NOINLINE void free_aaa(void *p) { free_bbb(p); break_optimization(0);}
33 NOINLINE void uaf_test(int size, int off) {
34 void *p = malloc_aaa(size);
36 for (int i = 1; i < 100; i++)
37 free_aaa(malloc_aaa(i));
38 fprintf(stderr, "writing %ld byte(s) at %p with offset %d\n",
39 (long)sizeof(T), p, off);
40 asan_write((T *)((char *)p + off));
43 TEST(AddressSanitizer, HasFeatureAddressSanitizerTest) {
44 #if defined(__has_feature) && __has_feature(address_sanitizer)
46 #elif defined(__SANITIZE_ADDRESS__)
51 EXPECT_EQ(true, asan);
54 TEST(AddressSanitizer, SimpleDeathTest) {
55 EXPECT_DEATH(exit(1), "");
58 TEST(AddressSanitizer, VariousMallocsTest) {
59 int *a = (int*)malloc(100 * sizeof(int));
63 int *r = (int*)malloc(10);
64 r = (int*)realloc(r, 2000 * sizeof(int));
68 int *b = new int[100];
76 #if SANITIZER_TEST_HAS_POSIX_MEMALIGN
78 int pm_res = posix_memalign((void**)&pm, kPageSize, kPageSize);
81 #endif // SANITIZER_TEST_HAS_POSIX_MEMALIGN
83 #if SANITIZER_TEST_HAS_MEMALIGN
84 int *ma = (int*)memalign(kPageSize, kPageSize);
85 EXPECT_EQ(0U, (uintptr_t)ma % kPageSize);
88 #endif // SANITIZER_TEST_HAS_MEMALIGN
91 TEST(AddressSanitizer, CallocTest) {
92 int *a = (int*)calloc(100, sizeof(int));
97 TEST(AddressSanitizer, CallocReturnsZeroMem) {
98 size_t sizes[] = {16, 1000, 10000, 100000, 2100000};
99 for (size_t s = 0; s < sizeof(sizes)/sizeof(sizes[0]); s++) {
100 size_t size = sizes[s];
101 for (size_t iter = 0; iter < 5; iter++) {
102 char *x = Ident((char*)calloc(1, size));
104 EXPECT_EQ(x[size - 1], 0);
105 EXPECT_EQ(x[size / 2], 0);
106 EXPECT_EQ(x[size / 3], 0);
107 EXPECT_EQ(x[size / 4], 0);
108 memset(x, 0x42, size);
111 // FIXME: OOM on Windows. We should just make this a lit test
112 // with quarantine size set to 1.
113 free(Ident(malloc(Ident(1 << 27)))); // Try to drain the quarantine.
119 // No valloc on Windows or Android.
120 #if !defined(_WIN32) && !defined(__ANDROID__)
121 TEST(AddressSanitizer, VallocTest) {
122 void *a = valloc(100);
123 EXPECT_EQ(0U, (uintptr_t)a % kPageSize);
128 #if SANITIZER_TEST_HAS_PVALLOC
129 TEST(AddressSanitizer, PvallocTest) {
130 char *a = (char*)pvalloc(kPageSize + 100);
131 EXPECT_EQ(0U, (uintptr_t)a % kPageSize);
132 a[kPageSize + 101] = 1; // we should not report an error here.
135 a = (char*)pvalloc(0); // pvalloc(0) should allocate at least one page.
136 EXPECT_EQ(0U, (uintptr_t)a % kPageSize);
137 a[101] = 1; // we should not report an error here.
140 #endif // SANITIZER_TEST_HAS_PVALLOC
143 // FIXME: Use an equivalent of pthread_setspecific on Windows.
144 void *TSDWorker(void *test_key) {
146 pthread_setspecific(*(pthread_key_t*)test_key, (void*)0xfeedface);
151 void TSDDestructor(void *tsd) {
152 // Spawning a thread will check that the current thread id is not -1.
154 PTHREAD_CREATE(&th, NULL, TSDWorker, NULL);
155 PTHREAD_JOIN(th, NULL);
158 // This tests triggers the thread-specific data destruction fiasco which occurs
159 // if we don't manage the TSD destructors ourselves. We create a new pthread
160 // key with a non-NULL destructor which is likely to be put after the destructor
161 // of AsanThread in the list of destructors.
162 // In this case the TSD for AsanThread will be destroyed before TSDDestructor
163 // is called for the child thread, and a CHECK will fail when we call
164 // pthread_create() to spawn the grandchild.
165 TEST(AddressSanitizer, DISABLED_TSDTest) {
167 pthread_key_t test_key;
168 pthread_key_create(&test_key, TSDDestructor);
169 PTHREAD_CREATE(&th, NULL, TSDWorker, &test_key);
170 PTHREAD_JOIN(th, NULL);
171 pthread_key_delete(test_key);
175 TEST(AddressSanitizer, UAF_char) {
176 const char *uaf_string = "AddressSanitizer:.*heap-use-after-free";
177 EXPECT_DEATH(uaf_test<U1>(1, 0), uaf_string);
178 EXPECT_DEATH(uaf_test<U1>(10, 0), uaf_string);
179 EXPECT_DEATH(uaf_test<U1>(10, 10), uaf_string);
180 EXPECT_DEATH(uaf_test<U1>(kLargeMalloc, 0), uaf_string);
181 EXPECT_DEATH(uaf_test<U1>(kLargeMalloc, kLargeMalloc / 2), uaf_string);
184 TEST(AddressSanitizer, UAF_long_double) {
185 if (sizeof(long double) == sizeof(double)) return;
186 long double *p = Ident(new long double[10]);
187 EXPECT_DEATH(Ident(p)[12] = 0, "WRITE of size 1[026]");
188 EXPECT_DEATH(Ident(p)[0] = Ident(p)[12], "READ of size 1[026]");
196 } __attribute__((packed));
198 # pragma pack(push, 1)
206 TEST(AddressSanitizer, UAF_Packed5) {
207 static_assert(sizeof(Packed5) == 5, "Please check the keywords used");
208 Packed5 *p = Ident(new Packed5[2]);
209 EXPECT_DEATH(p[0] = p[3], "READ of size 5");
210 EXPECT_DEATH(p[3] = p[0], "WRITE of size 5");
214 #if ASAN_HAS_BLACKLIST
215 TEST(AddressSanitizer, IgnoreTest) {
216 int *x = Ident(new int);
220 #endif // ASAN_HAS_BLACKLIST
222 struct StructWithBitField {
229 TEST(AddressSanitizer, BitFieldPositiveTest) {
230 StructWithBitField *x = new StructWithBitField;
232 EXPECT_DEATH(x->bf1 = 0, "use-after-free");
233 EXPECT_DEATH(x->bf2 = 0, "use-after-free");
234 EXPECT_DEATH(x->bf3 = 0, "use-after-free");
235 EXPECT_DEATH(x->bf4 = 0, "use-after-free");
238 struct StructWithBitFields_8_24 {
243 TEST(AddressSanitizer, BitFieldNegativeTest) {
244 StructWithBitFields_8_24 *x = Ident(new StructWithBitFields_8_24);
253 const char kUnknownCrash[] = "AddressSanitizer: SEGV on unknown address";
254 const char kOverriddenHandler[] = "ASan signal handler has been overridden\n";
256 TEST(AddressSanitizer, WildAddressTest) {
257 char *c = (char*)0x123;
258 EXPECT_DEATH(*c = 0, kUnknownCrash);
261 void my_sigaction_sighandler(int, siginfo_t*, void*) {
262 fprintf(stderr, kOverriddenHandler);
266 void my_signal_sighandler(int signum) {
267 fprintf(stderr, kOverriddenHandler);
271 TEST(AddressSanitizer, SignalTest) {
272 struct sigaction sigact;
273 memset(&sigact, 0, sizeof(sigact));
274 sigact.sa_sigaction = my_sigaction_sighandler;
275 sigact.sa_flags = SA_SIGINFO;
276 // ASan should silently ignore sigaction()...
277 EXPECT_EQ(0, sigaction(SIGSEGV, &sigact, 0));
279 EXPECT_EQ(0, sigaction(SIGBUS, &sigact, 0));
281 char *c = (char*)0x123;
282 EXPECT_DEATH(*c = 0, kUnknownCrash);
284 EXPECT_EQ(0, signal(SIGSEGV, my_signal_sighandler));
285 EXPECT_DEATH(*c = 0, kUnknownCrash);
290 static void TestLargeMalloc(size_t size) {
292 sprintf(buff, "is located 1 bytes to the left of %lu-byte", (long)size);
293 EXPECT_DEATH(Ident((char*)malloc(size))[-1] = 0, buff);
296 TEST(AddressSanitizer, LargeMallocTest) {
297 const int max_size = (SANITIZER_WORDSIZE == 32) ? 1 << 26 : 1 << 28;
298 for (int i = 113; i < max_size; i = i * 2 + 13) {
303 TEST(AddressSanitizer, HugeMallocTest) {
304 if (SANITIZER_WORDSIZE != 64 || ASAN_AVOID_EXPENSIVE_TESTS) return;
305 size_t n_megs = 4100;
306 EXPECT_DEATH(Ident((char*)malloc(n_megs << 20))[-1] = 0,
307 "is located 1 bytes to the left|"
308 "AddressSanitizer failed to allocate");
311 #if SANITIZER_TEST_HAS_MEMALIGN
312 void MemalignRun(size_t align, size_t size, int idx) {
313 char *p = (char *)memalign(align, size);
318 TEST(AddressSanitizer, memalign) {
319 for (int align = 16; align <= (1 << 23); align *= 2) {
320 size_t size = align * 5;
321 EXPECT_DEATH(MemalignRun(align, size, -1),
322 "is located 1 bytes to the left");
323 EXPECT_DEATH(MemalignRun(align, size, size + 1),
324 "is located 1 bytes to the right");
327 #endif // SANITIZER_TEST_HAS_MEMALIGN
329 void *ManyThreadsWorker(void *a) {
330 for (int iter = 0; iter < 100; iter++) {
331 for (size_t size = 100; size < 2000; size *= 2) {
332 free(Ident(malloc(size)));
338 TEST(AddressSanitizer, ManyThreadsTest) {
339 const size_t kNumThreads =
340 (SANITIZER_WORDSIZE == 32 || ASAN_AVOID_EXPENSIVE_TESTS) ? 30 : 1000;
341 pthread_t t[kNumThreads];
342 for (size_t i = 0; i < kNumThreads; i++) {
343 PTHREAD_CREATE(&t[i], 0, ManyThreadsWorker, (void*)i);
345 for (size_t i = 0; i < kNumThreads; i++) {
346 PTHREAD_JOIN(t[i], 0);
350 TEST(AddressSanitizer, ReallocTest) {
351 const int kMinElem = 5;
352 int *ptr = (int*)malloc(sizeof(int) * kMinElem);
354 for (int i = 0; i < 10000; i++) {
355 ptr = (int*)realloc(ptr,
356 (my_rand() % 1000 + kMinElem) * sizeof(int));
357 EXPECT_EQ(3, ptr[3]);
360 // Realloc pointer returned by malloc(0).
361 int *ptr2 = Ident((int*)malloc(0));
362 ptr2 = Ident((int*)realloc(ptr2, sizeof(*ptr2)));
364 EXPECT_EQ(42, *ptr2);
368 TEST(AddressSanitizer, ReallocFreedPointerTest) {
369 void *ptr = Ident(malloc(42));
370 ASSERT_TRUE(NULL != ptr);
372 EXPECT_DEATH(ptr = realloc(ptr, 77), "attempting double-free");
375 TEST(AddressSanitizer, ReallocInvalidPointerTest) {
376 void *ptr = Ident(malloc(42));
377 EXPECT_DEATH(ptr = realloc((int*)ptr + 1, 77), "attempting free.*not malloc");
381 TEST(AddressSanitizer, ZeroSizeMallocTest) {
382 // Test that malloc(0) and similar functions don't return NULL.
383 void *ptr = Ident(malloc(0));
384 EXPECT_TRUE(NULL != ptr);
386 #if SANITIZER_TEST_HAS_POSIX_MEMALIGN
387 int pm_res = posix_memalign(&ptr, 1<<20, 0);
388 EXPECT_EQ(0, pm_res);
389 EXPECT_TRUE(NULL != ptr);
391 #endif // SANITIZER_TEST_HAS_POSIX_MEMALIGN
392 int *int_ptr = new int[0];
393 int *int_ptr2 = new int[0];
394 EXPECT_TRUE(NULL != int_ptr);
395 EXPECT_TRUE(NULL != int_ptr2);
396 EXPECT_NE(int_ptr, int_ptr2);
401 #if SANITIZER_TEST_HAS_MALLOC_USABLE_SIZE
402 static const char *kMallocUsableSizeErrorMsg =
403 "AddressSanitizer: attempting to call malloc_usable_size()";
405 TEST(AddressSanitizer, MallocUsableSizeTest) {
406 const size_t kArraySize = 100;
407 char *array = Ident((char*)malloc(kArraySize));
408 int *int_ptr = Ident(new int);
409 EXPECT_EQ(0U, malloc_usable_size(NULL));
410 EXPECT_EQ(kArraySize, malloc_usable_size(array));
411 EXPECT_EQ(sizeof(int), malloc_usable_size(int_ptr));
412 EXPECT_DEATH(malloc_usable_size((void*)0x123), kMallocUsableSizeErrorMsg);
413 EXPECT_DEATH(malloc_usable_size(array + kArraySize / 2),
414 kMallocUsableSizeErrorMsg);
416 EXPECT_DEATH(malloc_usable_size(array), kMallocUsableSizeErrorMsg);
419 #endif // SANITIZER_TEST_HAS_MALLOC_USABLE_SIZE
422 int *x = (int*)malloc(100 * sizeof(int));
423 // Use the allocated memory, otherwise Clang will optimize it out.
428 #if !defined(_WIN32) // FIXME: This should be a lit test.
429 TEST(AddressSanitizer, WrongFreeTest) {
430 EXPECT_DEATH(WrongFree(), ASAN_PCRE_DOTALL
431 "ERROR: AddressSanitizer: attempting free.*not malloc"
432 ".*is located 4 bytes inside of 400-byte region"
433 ".*allocated by thread");
438 int *x = (int*)malloc(100 * sizeof(int));
439 fprintf(stderr, "DoubleFree: x=%p\n", (void *)x);
442 fprintf(stderr, "should have failed in the second free(%p)\n", (void *)x);
446 #if !defined(_WIN32) // FIXME: This should be a lit test.
447 TEST(AddressSanitizer, DoubleFreeTest) {
448 EXPECT_DEATH(DoubleFree(), ASAN_PCRE_DOTALL
449 "ERROR: AddressSanitizer: attempting double-free"
450 ".*is located 0 bytes inside of 400-byte region"
451 ".*freed by thread T0 here"
452 ".*previously allocated by thread T0 here");
457 NOINLINE void SizedStackTest() {
459 char *A = Ident((char*)&a);
460 const char *expected_death = "AddressSanitizer: stack-buffer-";
461 for (size_t i = 0; i < kSize; i++)
463 EXPECT_DEATH(A[-1] = 0, expected_death);
464 EXPECT_DEATH(A[-5] = 0, expected_death);
465 EXPECT_DEATH(A[kSize] = 0, expected_death);
466 EXPECT_DEATH(A[kSize + 1] = 0, expected_death);
467 EXPECT_DEATH(A[kSize + 5] = 0, expected_death);
469 EXPECT_DEATH(A[kSize + 31] = 0, expected_death);
472 TEST(AddressSanitizer, SimpleStackTest) {
480 SizedStackTest<16>();
481 SizedStackTest<25>();
482 SizedStackTest<34>();
483 SizedStackTest<43>();
484 SizedStackTest<51>();
485 SizedStackTest<62>();
486 SizedStackTest<64>();
487 SizedStackTest<128>();
491 // FIXME: It's a bit hard to write multi-line death test expectations
492 // in a portable way. Anyways, this should just be turned into a lit test.
493 TEST(AddressSanitizer, ManyStackObjectsTest) {
499 EXPECT_DEATH(Ident(ZZZ)[-1] = 0, ASAN_PCRE_DOTALL "XXX.*YYY.*ZZZ");
503 #if 0 // This test requires online symbolizer.
504 // Moved to lit_tests/stack-oob-frames.cc.
505 // Reenable here once we have online symbolizer by default.
506 NOINLINE static void Frame0(int frame, char *a, char *b, char *c) {
510 case 3: a[5]++; break;
511 case 2: b[5]++; break;
512 case 1: c[5]++; break;
513 case 0: D[5]++; break;
516 NOINLINE static void Frame1(int frame, char *a, char *b) {
517 char c[4] = {0}; Frame0(frame, a, b, c);
518 break_optimization(0);
520 NOINLINE static void Frame2(int frame, char *a) {
521 char b[4] = {0}; Frame1(frame, a, b);
522 break_optimization(0);
524 NOINLINE static void Frame3(int frame) {
525 char a[4] = {0}; Frame2(frame, a);
526 break_optimization(0);
529 TEST(AddressSanitizer, GuiltyStackFrame0Test) {
530 EXPECT_DEATH(Frame3(0), "located .*in frame <.*Frame0");
532 TEST(AddressSanitizer, GuiltyStackFrame1Test) {
533 EXPECT_DEATH(Frame3(1), "located .*in frame <.*Frame1");
535 TEST(AddressSanitizer, GuiltyStackFrame2Test) {
536 EXPECT_DEATH(Frame3(2), "located .*in frame <.*Frame2");
538 TEST(AddressSanitizer, GuiltyStackFrame3Test) {
539 EXPECT_DEATH(Frame3(3), "located .*in frame <.*Frame3");
543 NOINLINE void LongJmpFunc1(jmp_buf buf) {
544 // create three red zones for these two stack objects.
554 NOINLINE void TouchStackFunc() {
555 int a[100]; // long array will intersect with redzones from LongJmpFunc1.
557 for (int i = 0; i < 100; i++)
561 // Test that we handle longjmp and do not report false positives on stack.
562 TEST(AddressSanitizer, LongJmpTest) {
571 #if !defined(_WIN32) // Only basic longjmp is available on Windows.
572 NOINLINE void UnderscopeLongJmpFunc1(jmp_buf buf) {
573 // create three red zones for these two stack objects.
583 NOINLINE void SigLongJmpFunc1(sigjmp_buf buf) {
584 // create three red zones for these two stack objects.
594 #if !defined(__ANDROID__) && !defined(__arm__) && \
595 !defined(__powerpc64__) && !defined(__powerpc__) && \
596 !defined(__aarch64__) && !defined(__mips__) && \
598 NOINLINE void BuiltinLongJmpFunc1(jmp_buf buf) {
599 // create three red zones for these two stack objects.
606 __builtin_longjmp((void**)buf, 1);
609 // Does not work on Power and ARM:
610 // https://code.google.com/p/address-sanitizer/issues/detail?id=185
611 TEST(AddressSanitizer, BuiltinLongJmpTest) {
613 if (!__builtin_setjmp((void**)buf)) {
614 BuiltinLongJmpFunc1(buf);
619 #endif // !defined(__ANDROID__) && !defined(__powerpc64__) &&
620 // !defined(__powerpc__) && !defined(__arm__) &&
621 // !defined(__mips__) && !defined(__mips64)
623 TEST(AddressSanitizer, UnderscopeLongJmpTest) {
626 UnderscopeLongJmpFunc1(buf);
632 TEST(AddressSanitizer, SigLongJmpTest) {
633 static sigjmp_buf buf;
634 if (!sigsetjmp(buf, 1)) {
635 SigLongJmpFunc1(buf);
642 // FIXME: Why does clang-cl define __EXCEPTIONS?
643 #if defined(__EXCEPTIONS) && !defined(_WIN32)
644 NOINLINE void ThrowFunc() {
645 // create three red zones for these two stack objects.
655 TEST(AddressSanitizer, CxxExceptionTest) {
656 if (ASAN_UAR) return;
657 // TODO(kcc): this test crashes on 32-bit for some reason...
658 if (SANITIZER_WORDSIZE == 32) return;
666 void *ThreadStackReuseFunc1(void *unused) {
667 // create three red zones for these two stack objects.
678 void *ThreadStackReuseFunc2(void *unused) {
683 TEST(AddressSanitizer, ThreadStackReuseTest) {
685 PTHREAD_CREATE(&t, 0, ThreadStackReuseFunc1, 0);
687 PTHREAD_CREATE(&t, 0, ThreadStackReuseFunc2, 0);
691 #if defined(__i686__) || defined(__x86_64__)
692 #include <emmintrin.h>
693 TEST(AddressSanitizer, Store128Test) {
694 char *a = Ident((char*)malloc(Ident(12)));
696 if (((uintptr_t)a % 16) != 0)
698 assert(((uintptr_t)p % 16) == 0);
699 __m128i value_wide = _mm_set1_epi16(0x1234);
700 EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
701 "AddressSanitizer: heap-buffer-overflow");
702 EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
704 EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
705 "located 0 bytes to the right of 12-byte");
710 // FIXME: All tests that use this function should be turned into lit tests.
711 string RightOOBErrorMessage(int oob_distance, bool is_write) {
712 assert(oob_distance >= 0);
713 char expected_str[100];
714 sprintf(expected_str, ASAN_PCRE_DOTALL
715 #if !GTEST_USES_SIMPLE_RE
716 "buffer-overflow.*%s.*"
718 "located %d bytes to the right",
719 #if !GTEST_USES_SIMPLE_RE
720 is_write ? "WRITE" : "READ",
723 return string(expected_str);
726 string RightOOBWriteMessage(int oob_distance) {
727 return RightOOBErrorMessage(oob_distance, /*is_write*/true);
730 string RightOOBReadMessage(int oob_distance) {
731 return RightOOBErrorMessage(oob_distance, /*is_write*/false);
734 // FIXME: All tests that use this function should be turned into lit tests.
735 string LeftOOBErrorMessage(int oob_distance, bool is_write) {
736 assert(oob_distance > 0);
737 char expected_str[100];
738 sprintf(expected_str,
739 #if !GTEST_USES_SIMPLE_RE
740 ASAN_PCRE_DOTALL "%s.*"
742 "located %d bytes to the left",
743 #if !GTEST_USES_SIMPLE_RE
744 is_write ? "WRITE" : "READ",
747 return string(expected_str);
750 string LeftOOBWriteMessage(int oob_distance) {
751 return LeftOOBErrorMessage(oob_distance, /*is_write*/true);
754 string LeftOOBReadMessage(int oob_distance) {
755 return LeftOOBErrorMessage(oob_distance, /*is_write*/false);
758 string LeftOOBAccessMessage(int oob_distance) {
759 assert(oob_distance > 0);
760 char expected_str[100];
761 sprintf(expected_str, "located %d bytes to the left", oob_distance);
762 return string(expected_str);
765 char* MallocAndMemsetString(size_t size, char ch) {
766 char *s = Ident((char*)malloc(size));
771 char* MallocAndMemsetString(size_t size) {
772 return MallocAndMemsetString(size, 'z');
775 #if defined(__linux__) && !defined(__ANDROID__)
776 #define READ_TEST(READ_N_BYTES) \
777 char *x = new char[10]; \
778 int fd = open("/proc/self/stat", O_RDONLY); \
780 EXPECT_DEATH(READ_N_BYTES, \
782 "AddressSanitizer: heap-buffer-overflow" \
783 ".* is located 0 bytes to the right of 10-byte region"); \
787 TEST(AddressSanitizer, pread) {
788 READ_TEST(pread(fd, x, 15, 0));
791 TEST(AddressSanitizer, pread64) {
792 READ_TEST(pread64(fd, x, 15, 0));
795 TEST(AddressSanitizer, read) {
796 READ_TEST(read(fd, x, 15));
798 #endif // defined(__linux__) && !defined(__ANDROID__)
800 // This test case fails
801 // Clang optimizes memcpy/memset calls which lead to unaligned access
802 TEST(AddressSanitizer, DISABLED_MemIntrinsicUnalignedAccessTest) {
803 int size = Ident(4096);
804 char *s = Ident((char*)malloc(size));
805 EXPECT_DEATH(memset(s + size - 1, 0, 2), RightOOBWriteMessage(0));
809 // TODO(samsonov): Add a test with malloc(0)
810 // TODO(samsonov): Add tests for str* and mem* functions.
812 NOINLINE static int LargeFunction(bool do_bad_access) {
813 int *x = new int[100];
825 x[do_bad_access ? 100 : 0]++; int res = __LINE__;
842 // Test the we have correct debug info for the failing instruction.
843 // This test requires the in-process symbolizer to be enabled by default.
844 TEST(AddressSanitizer, DISABLED_LargeFunctionSymbolizeTest) {
845 int failing_line = LargeFunction(false);
846 char expected_warning[128];
847 sprintf(expected_warning, "LargeFunction.*asan_test.*:%d", failing_line);
848 EXPECT_DEATH(LargeFunction(true), expected_warning);
851 // Check that we unwind and symbolize correctly.
852 TEST(AddressSanitizer, DISABLED_MallocFreeUnwindAndSymbolizeTest) {
853 int *a = (int*)malloc_aaa(sizeof(int));
856 EXPECT_DEATH(*a = 1, "free_ccc.*free_bbb.*free_aaa.*"
857 "malloc_fff.*malloc_eee.*malloc_ddd");
860 static bool TryToSetThreadName(const char *name) {
861 #if defined(__linux__) && defined(PR_SET_NAME)
862 return 0 == prctl(PR_SET_NAME, (unsigned long)name, 0, 0, 0);
868 void *ThreadedTestAlloc(void *a) {
869 EXPECT_EQ(true, TryToSetThreadName("AllocThr"));
875 void *ThreadedTestFree(void *a) {
876 EXPECT_EQ(true, TryToSetThreadName("FreeThr"));
882 void *ThreadedTestUse(void *a) {
883 EXPECT_EQ(true, TryToSetThreadName("UseThr"));
889 void ThreadedTestSpawn() {
892 PTHREAD_CREATE(&t, 0, ThreadedTestAlloc, &x);
894 PTHREAD_CREATE(&t, 0, ThreadedTestFree, &x);
896 PTHREAD_CREATE(&t, 0, ThreadedTestUse, &x);
900 #if !defined(_WIN32) // FIXME: This should be a lit test.
901 TEST(AddressSanitizer, ThreadedTest) {
902 EXPECT_DEATH(ThreadedTestSpawn(),
905 ".*Thread T.*created"
906 ".*Thread T.*created");
910 void *ThreadedTestFunc(void *unused) {
911 // Check if prctl(PR_SET_NAME) is supported. Return if not.
912 if (!TryToSetThreadName("TestFunc"))
914 EXPECT_DEATH(ThreadedTestSpawn(),
916 "WRITE .*thread T. .UseThr."
917 ".*freed by thread T. .FreeThr. here:"
918 ".*previously allocated by thread T. .AllocThr. here:"
919 ".*Thread T. .UseThr. created by T.*TestFunc"
920 ".*Thread T. .FreeThr. created by T"
921 ".*Thread T. .AllocThr. created by T"
926 TEST(AddressSanitizer, ThreadNamesTest) {
927 // Run ThreadedTestFunc in a separate thread because it tries to set a
928 // thread name and we don't want to change the main thread's name.
930 PTHREAD_CREATE(&t, 0, ThreadedTestFunc, 0);
935 TEST(AddressSanitizer, ShadowGapTest) {
936 #if SANITIZER_WORDSIZE == 32
937 char *addr = (char*)0x22000000;
939 # if defined(__powerpc64__)
940 char *addr = (char*)0x024000800000;
942 char *addr = (char*)0x0000100000080000;
945 EXPECT_DEATH(*addr = 1, "AddressSanitizer: SEGV on unknown");
947 #endif // ASAN_NEEDS_SEGV
950 NOINLINE static void UseThenFreeThenUse() {
951 char *x = Ident((char*)malloc(8));
958 TEST(AddressSanitizer, UseThenFreeThenUseTest) {
959 EXPECT_DEATH(UseThenFreeThenUse(), "freed by thread");
962 TEST(AddressSanitizer, StrDupTest) {
963 free(strdup(Ident("123")));
966 // Currently we create and poison redzone at right of global variables.
967 static char static110[110];
968 const char ConstGlob[7] = {1, 2, 3, 4, 5, 6, 7};
969 static const char StaticConstGlob[3] = {9, 8, 7};
971 TEST(AddressSanitizer, GlobalTest) {
972 static char func_static15[15];
984 EXPECT_DEATH(glob5[Ident(5)] = 0,
985 "0 bytes to the right of global variable.*glob5.* size 5");
986 EXPECT_DEATH(glob5[Ident(5+6)] = 0,
987 "6 bytes to the right of global variable.*glob5.* size 5");
988 Ident(static110); // avoid optimizations
989 static110[Ident(0)] = 0;
990 static110[Ident(109)] = 0;
991 EXPECT_DEATH(static110[Ident(110)] = 0,
992 "0 bytes to the right of global variable");
993 EXPECT_DEATH(static110[Ident(110+7)] = 0,
994 "7 bytes to the right of global variable");
996 Ident(func_static15); // avoid optimizations
997 func_static15[Ident(0)] = 0;
998 EXPECT_DEATH(func_static15[Ident(15)] = 0,
999 "0 bytes to the right of global variable");
1000 EXPECT_DEATH(func_static15[Ident(15 + 9)] = 0,
1001 "9 bytes to the right of global variable");
1007 // We don't create left redzones, so this is not 100% guaranteed to fail.
1008 // But most likely will.
1009 EXPECT_DEATH(fs2[Ident(-1)] = 0, "is located.*of global variable");
1011 EXPECT_DEATH(Ident(Ident(ConstGlob)[8]),
1012 "is located 1 bytes to the right of .*ConstGlob");
1013 EXPECT_DEATH(Ident(Ident(StaticConstGlob)[5]),
1014 "is located 2 bytes to the right of .*StaticConstGlob");
1016 // call stuff from another file.
1020 TEST(AddressSanitizer, GlobalStringConstTest) {
1021 static const char *zoo = "FOOBAR123";
1022 const char *p = Ident(zoo);
1023 EXPECT_DEATH(Ident(p[15]), "is ascii string 'FOOBAR123'");
1026 TEST(AddressSanitizer, FileNameInGlobalReportTest) {
1027 static char zoo[10];
1028 const char *p = Ident(zoo);
1029 // The file name should be present in the report.
1030 EXPECT_DEATH(Ident(p[15]), "zoo.*asan_test.");
1033 int *ReturnsPointerToALocalObject() {
1039 TEST(AddressSanitizer, LocalReferenceReturnTest) {
1040 int *(*f)() = Ident(ReturnsPointerToALocalObject);
1042 // Call 'f' a few more times, 'p' should still be poisoned.
1043 for (int i = 0; i < 32; i++)
1045 EXPECT_DEATH(*p = 1, "AddressSanitizer: stack-use-after-return");
1046 EXPECT_DEATH(*p = 1, "is located.*in frame .*ReturnsPointerToALocal");
1050 template <int kSize>
1051 NOINLINE static void FuncWithStack() {
1054 Ident(x)[kSize-1] = 0;
1057 static void LotsOfStackReuse() {
1058 int LargeStack[10000];
1059 Ident(LargeStack)[0] = 0;
1060 for (int i = 0; i < 10000; i++) {
1061 FuncWithStack<128 * 1>();
1062 FuncWithStack<128 * 2>();
1063 FuncWithStack<128 * 4>();
1064 FuncWithStack<128 * 8>();
1065 FuncWithStack<128 * 16>();
1066 FuncWithStack<128 * 32>();
1067 FuncWithStack<128 * 64>();
1068 FuncWithStack<128 * 128>();
1069 FuncWithStack<128 * 256>();
1070 FuncWithStack<128 * 512>();
1071 Ident(LargeStack)[0] = 0;
1075 TEST(AddressSanitizer, StressStackReuseTest) {
1079 TEST(AddressSanitizer, ThreadedStressStackReuseTest) {
1080 const int kNumThreads = 20;
1081 pthread_t t[kNumThreads];
1082 for (int i = 0; i < kNumThreads; i++) {
1083 PTHREAD_CREATE(&t[i], 0, (void* (*)(void *x))LotsOfStackReuse, 0);
1085 for (int i = 0; i < kNumThreads; i++) {
1086 PTHREAD_JOIN(t[i], 0);
1090 static void *PthreadExit(void *a) {
1095 TEST(AddressSanitizer, PthreadExitTest) {
1097 for (int i = 0; i < 1000; i++) {
1098 PTHREAD_CREATE(&t, 0, PthreadExit, 0);
1103 // FIXME: Why does clang-cl define __EXCEPTIONS?
1104 #if defined(__EXCEPTIONS) && !defined(_WIN32)
1105 NOINLINE static void StackReuseAndException() {
1106 int large_stack[1000];
1111 // TODO(kcc): support exceptions with use-after-return.
1112 TEST(AddressSanitizer, DISABLED_StressStackReuseAndExceptionsTest) {
1113 for (int i = 0; i < 10000; i++) {
1115 StackReuseAndException();
1122 #if !defined(_WIN32)
1123 TEST(AddressSanitizer, MlockTest) {
1124 EXPECT_EQ(0, mlockall(MCL_CURRENT));
1125 EXPECT_EQ(0, mlock((void*)0x12345, 0x5678));
1126 EXPECT_EQ(0, munlockall());
1127 EXPECT_EQ(0, munlock((void*)0x987, 0x654));
1131 struct LargeStruct {
1135 // Test for bug http://llvm.org/bugs/show_bug.cgi?id=11763.
1136 // Struct copy should not cause asan warning even if lhs == rhs.
1137 TEST(AddressSanitizer, LargeStructCopyTest) {
1139 *Ident(&a) = *Ident(&a);
1142 ATTRIBUTE_NO_SANITIZE_ADDRESS
1143 static void NoSanitizeAddress() {
1144 char *foo = new char[10];
1149 TEST(AddressSanitizer, AttributeNoSanitizeAddressTest) {
1150 Ident(NoSanitizeAddress)();
1153 // The new/delete/etc mismatch checks don't work on Android,
1154 // as calls to new/delete go through malloc/free.
1155 // OS X support is tracked here:
1156 // https://code.google.com/p/address-sanitizer/issues/detail?id=131
1157 // Windows support is tracked here:
1158 // https://code.google.com/p/address-sanitizer/issues/detail?id=309
1159 #if !defined(__ANDROID__) && \
1160 !defined(__APPLE__) && \
1162 static string MismatchStr(const string &str) {
1163 return string("AddressSanitizer: alloc-dealloc-mismatch \\(") + str;
1166 TEST(AddressSanitizer, AllocDeallocMismatch) {
1167 EXPECT_DEATH(free(Ident(new int)),
1168 MismatchStr("operator new vs free"));
1169 EXPECT_DEATH(free(Ident(new int[2])),
1170 MismatchStr("operator new \\[\\] vs free"));
1171 EXPECT_DEATH(delete (Ident(new int[2])),
1172 MismatchStr("operator new \\[\\] vs operator delete"));
1173 EXPECT_DEATH(delete (Ident((int*)malloc(2 * sizeof(int)))),
1174 MismatchStr("malloc vs operator delete"));
1175 EXPECT_DEATH(delete [] (Ident(new int)),
1176 MismatchStr("operator new vs operator delete \\[\\]"));
1177 EXPECT_DEATH(delete [] (Ident((int*)malloc(2 * sizeof(int)))),
1178 MismatchStr("malloc vs operator delete \\[\\]"));
1182 // ------------------ demo tests; run each one-by-one -------------
1183 // e.g. --gtest_filter=*DemoOOBLeftHigh --gtest_also_run_disabled_tests
1184 TEST(AddressSanitizer, DISABLED_DemoThreadedTest) {
1185 ThreadedTestSpawn();
1188 void *SimpleBugOnSTack(void *x = 0) {
1194 TEST(AddressSanitizer, DISABLED_DemoStackTest) {
1198 TEST(AddressSanitizer, DISABLED_DemoThreadStackTest) {
1200 PTHREAD_CREATE(&t, 0, SimpleBugOnSTack, 0);
1204 TEST(AddressSanitizer, DISABLED_DemoUAFLowIn) {
1205 uaf_test<U1>(10, 0);
1207 TEST(AddressSanitizer, DISABLED_DemoUAFLowLeft) {
1208 uaf_test<U1>(10, -2);
1210 TEST(AddressSanitizer, DISABLED_DemoUAFLowRight) {
1211 uaf_test<U1>(10, 10);
1214 TEST(AddressSanitizer, DISABLED_DemoUAFHigh) {
1215 uaf_test<U1>(kLargeMalloc, 0);
1218 TEST(AddressSanitizer, DISABLED_DemoOOM) {
1219 size_t size = SANITIZER_WORDSIZE == 64 ? (size_t)(1ULL << 40) : (0xf0000000);
1220 printf("%p\n", malloc(size));
1223 TEST(AddressSanitizer, DISABLED_DemoDoubleFreeTest) {
1227 TEST(AddressSanitizer, DISABLED_DemoNullDerefTest) {
1232 TEST(AddressSanitizer, DISABLED_DemoFunctionStaticTest) {
1244 TEST(AddressSanitizer, DISABLED_DemoTooMuchMemoryTest) {
1245 const size_t kAllocSize = (1 << 28) - 1024;
1246 size_t total_size = 0;
1248 void *x = malloc(kAllocSize);
1249 memset(x, 0, kAllocSize);
1250 total_size += kAllocSize;
1251 fprintf(stderr, "total: %ldM %p\n", (long)total_size >> 20, x);
1255 // http://code.google.com/p/address-sanitizer/issues/detail?id=66
1256 TEST(AddressSanitizer, BufferOverflowAfterManyFrees) {
1257 for (int i = 0; i < 1000000; i++) {
1258 delete [] (Ident(new char [8644]));
1260 char *x = new char[8192];
1261 EXPECT_DEATH(x[Ident(8192)] = 0, "AddressSanitizer: heap-buffer-overflow");
1266 // Test that instrumentation of stack allocations takes into account
1267 // AllocSize of a type, and not its StoreSize (16 vs 10 bytes for long double).
1268 // See http://llvm.org/bugs/show_bug.cgi?id=12047 for more details.
1269 TEST(AddressSanitizer, LongDoubleNegativeTest) {
1271 static long double c;
1272 memcpy(Ident(&a), Ident(&b), sizeof(long double));
1273 memcpy(Ident(&c), Ident(&b), sizeof(long double));
1276 #if !defined(_WIN32)
1277 TEST(AddressSanitizer, pthread_getschedparam) {
1279 struct sched_param param;
1281 pthread_getschedparam(pthread_self(), &policy, Ident(¶m) + 2),
1282 "AddressSanitizer: stack-buffer-.*flow");
1284 pthread_getschedparam(pthread_self(), Ident(&policy) - 1, ¶m),
1285 "AddressSanitizer: stack-buffer-.*flow");
1286 int res = pthread_getschedparam(pthread_self(), &policy, ¶m);
1291 #if SANITIZER_TEST_HAS_PRINTF_L
1292 static int vsnprintf_l_wrapper(char *s, size_t n,
1293 locale_t l, const char *format, ...) {
1295 va_start(va, format);
1296 int res = vsnprintf_l(s, n , l, format, va);
1301 TEST(AddressSanitizer, snprintf_l) {
1303 // Check that snprintf_l() works fine with Asan.
1304 int res = snprintf_l(buff, 5,
1305 _LIBCPP_GET_C_LOCALE, "%s", "snprintf_l()");
1307 // Check that vsnprintf_l() works fine with Asan.
1308 res = vsnprintf_l_wrapper(buff, 5,
1309 _LIBCPP_GET_C_LOCALE, "%s", "vsnprintf_l()");
1312 EXPECT_DEATH(snprintf_l(buff, 10,
1313 _LIBCPP_GET_C_LOCALE, "%s", "snprintf_l()"),
1314 "AddressSanitizer: stack-buffer-overflow");
1315 EXPECT_DEATH(vsnprintf_l_wrapper(buff, 10,
1316 _LIBCPP_GET_C_LOCALE, "%s", "vsnprintf_l()"),
1317 "AddressSanitizer: stack-buffer-overflow");