[ASan] Better way to disable tests for functions unavailable on certain platforms
[blocksruntime.git] / lib / asan / tests / asan_test.cc
blob7a2e98afd401557bfe8b15fee6cbba910bdbc5fa
1 //===-- asan_test.cc ------------------------------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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);}
32 template<typename T>
33 NOINLINE void uaf_test(int size, int off) {
34 char *p = (char *)malloc_aaa(size);
35 free_aaa(p);
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*)(p + off));
43 TEST(AddressSanitizer, HasFeatureAddressSanitizerTest) {
44 #if defined(__has_feature) && __has_feature(address_sanitizer)
45 bool asan = 1;
46 #elif defined(__SANITIZE_ADDRESS__)
47 bool asan = 1;
48 #else
49 bool asan = 0;
50 #endif
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));
60 a[50] = 0;
61 free(a);
63 int *r = (int*)malloc(10);
64 r = (int*)realloc(r, 2000 * sizeof(int));
65 r[1000] = 0;
66 free(r);
68 int *b = new int[100];
69 b[50] = 0;
70 delete [] b;
72 int *c = new int;
73 *c = 0;
74 delete c;
76 #if SANITIZER_TEST_HAS_POSIX_MEMALIGN
77 int *pm;
78 int pm_res = posix_memalign((void**)&pm, kPageSize, kPageSize);
79 EXPECT_EQ(0, pm_res);
80 free(pm);
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);
86 ma[123] = 0;
87 free(ma);
88 #endif // SANITIZER_TEST_HAS_MEMALIGN
91 TEST(AddressSanitizer, CallocTest) {
92 int *a = (int*)calloc(100, sizeof(int));
93 EXPECT_EQ(0, a[10]);
94 free(a);
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));
103 EXPECT_EQ(x[0], 0);
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);
109 free(Ident(x));
110 free(Ident(malloc(Ident(1 << 27)))); // Try to drain the quarantine.
115 TEST(AddressSanitizer, VallocTest) {
116 void *a = valloc(100);
117 EXPECT_EQ(0U, (uintptr_t)a % kPageSize);
118 free(a);
121 #if SANITIZER_TEST_HAS_PVALLOC
122 TEST(AddressSanitizer, PvallocTest) {
123 char *a = (char*)pvalloc(kPageSize + 100);
124 EXPECT_EQ(0U, (uintptr_t)a % kPageSize);
125 a[kPageSize + 101] = 1; // we should not report an error here.
126 free(a);
128 a = (char*)pvalloc(0); // pvalloc(0) should allocate at least one page.
129 EXPECT_EQ(0U, (uintptr_t)a % kPageSize);
130 a[101] = 1; // we should not report an error here.
131 free(a);
133 #endif // SANITIZER_TEST_HAS_PVALLOC
135 void *TSDWorker(void *test_key) {
136 if (test_key) {
137 pthread_setspecific(*(pthread_key_t*)test_key, (void*)0xfeedface);
139 return NULL;
142 void TSDDestructor(void *tsd) {
143 // Spawning a thread will check that the current thread id is not -1.
144 pthread_t th;
145 PTHREAD_CREATE(&th, NULL, TSDWorker, NULL);
146 PTHREAD_JOIN(th, NULL);
149 // This tests triggers the thread-specific data destruction fiasco which occurs
150 // if we don't manage the TSD destructors ourselves. We create a new pthread
151 // key with a non-NULL destructor which is likely to be put after the destructor
152 // of AsanThread in the list of destructors.
153 // In this case the TSD for AsanThread will be destroyed before TSDDestructor
154 // is called for the child thread, and a CHECK will fail when we call
155 // pthread_create() to spawn the grandchild.
156 TEST(AddressSanitizer, DISABLED_TSDTest) {
157 pthread_t th;
158 pthread_key_t test_key;
159 pthread_key_create(&test_key, TSDDestructor);
160 PTHREAD_CREATE(&th, NULL, TSDWorker, &test_key);
161 PTHREAD_JOIN(th, NULL);
162 pthread_key_delete(test_key);
165 TEST(AddressSanitizer, UAF_char) {
166 const char *uaf_string = "AddressSanitizer:.*heap-use-after-free";
167 EXPECT_DEATH(uaf_test<U1>(1, 0), uaf_string);
168 EXPECT_DEATH(uaf_test<U1>(10, 0), uaf_string);
169 EXPECT_DEATH(uaf_test<U1>(10, 10), uaf_string);
170 EXPECT_DEATH(uaf_test<U1>(kLargeMalloc, 0), uaf_string);
171 EXPECT_DEATH(uaf_test<U1>(kLargeMalloc, kLargeMalloc / 2), uaf_string);
174 TEST(AddressSanitizer, UAF_long_double) {
175 if (sizeof(long double) == sizeof(double)) return;
176 long double *p = Ident(new long double[10]);
177 EXPECT_DEATH(Ident(p)[12] = 0, "WRITE of size 1[06]");
178 EXPECT_DEATH(Ident(p)[0] = Ident(p)[12], "READ of size 1[06]");
179 delete [] Ident(p);
182 struct Packed5 {
183 int x;
184 char c;
185 } __attribute__((packed));
188 TEST(AddressSanitizer, UAF_Packed5) {
189 Packed5 *p = Ident(new Packed5[2]);
190 EXPECT_DEATH(p[0] = p[3], "READ of size 5");
191 EXPECT_DEATH(p[3] = p[0], "WRITE of size 5");
192 delete [] Ident(p);
195 #if ASAN_HAS_BLACKLIST
196 TEST(AddressSanitizer, IgnoreTest) {
197 int *x = Ident(new int);
198 delete Ident(x);
199 *x = 0;
201 #endif // ASAN_HAS_BLACKLIST
203 struct StructWithBitField {
204 int bf1:1;
205 int bf2:1;
206 int bf3:1;
207 int bf4:29;
210 TEST(AddressSanitizer, BitFieldPositiveTest) {
211 StructWithBitField *x = new StructWithBitField;
212 delete Ident(x);
213 EXPECT_DEATH(x->bf1 = 0, "use-after-free");
214 EXPECT_DEATH(x->bf2 = 0, "use-after-free");
215 EXPECT_DEATH(x->bf3 = 0, "use-after-free");
216 EXPECT_DEATH(x->bf4 = 0, "use-after-free");
219 struct StructWithBitFields_8_24 {
220 int a:8;
221 int b:24;
224 TEST(AddressSanitizer, BitFieldNegativeTest) {
225 StructWithBitFields_8_24 *x = Ident(new StructWithBitFields_8_24);
226 x->a = 0;
227 x->b = 0;
228 delete Ident(x);
231 #if ASAN_NEEDS_SEGV
232 namespace {
234 const char kUnknownCrash[] = "AddressSanitizer: SEGV on unknown address";
235 const char kOverriddenHandler[] = "ASan signal handler has been overridden\n";
237 TEST(AddressSanitizer, WildAddressTest) {
238 char *c = (char*)0x123;
239 EXPECT_DEATH(*c = 0, kUnknownCrash);
242 void my_sigaction_sighandler(int, siginfo_t*, void*) {
243 fprintf(stderr, kOverriddenHandler);
244 exit(1);
247 void my_signal_sighandler(int signum) {
248 fprintf(stderr, kOverriddenHandler);
249 exit(1);
252 TEST(AddressSanitizer, SignalTest) {
253 struct sigaction sigact;
254 memset(&sigact, 0, sizeof(sigact));
255 sigact.sa_sigaction = my_sigaction_sighandler;
256 sigact.sa_flags = SA_SIGINFO;
257 // ASan should silently ignore sigaction()...
258 EXPECT_EQ(0, sigaction(SIGSEGV, &sigact, 0));
259 #ifdef __APPLE__
260 EXPECT_EQ(0, sigaction(SIGBUS, &sigact, 0));
261 #endif
262 char *c = (char*)0x123;
263 EXPECT_DEATH(*c = 0, kUnknownCrash);
264 // ... and signal().
265 EXPECT_EQ(0, signal(SIGSEGV, my_signal_sighandler));
266 EXPECT_DEATH(*c = 0, kUnknownCrash);
268 } // namespace
269 #endif
271 static void TestLargeMalloc(size_t size) {
272 char buff[1024];
273 sprintf(buff, "is located 1 bytes to the left of %lu-byte", (long)size);
274 EXPECT_DEATH(Ident((char*)malloc(size))[-1] = 0, buff);
277 TEST(AddressSanitizer, LargeMallocTest) {
278 const int max_size = (SANITIZER_WORDSIZE == 32) ? 1 << 26 : 1 << 28;
279 for (int i = 113; i < max_size; i = i * 2 + 13) {
280 TestLargeMalloc(i);
284 TEST(AddressSanitizer, HugeMallocTest) {
285 if (SANITIZER_WORDSIZE != 64 || ASAN_AVOID_EXPENSIVE_TESTS) return;
286 size_t n_megs = 4100;
287 EXPECT_DEATH(Ident((char*)malloc(n_megs << 20))[-1] = 0,
288 "is located 1 bytes to the left|"
289 "AddressSanitizer failed to allocate");
292 #if SANITIZER_TEST_HAS_MEMALIGN
293 void MemalignRun(size_t align, size_t size, int idx) {
294 char *p = (char *)memalign(align, size);
295 Ident(p)[idx] = 0;
296 free(p);
299 TEST(AddressSanitizer, memalign) {
300 for (int align = 16; align <= (1 << 23); align *= 2) {
301 size_t size = align * 5;
302 EXPECT_DEATH(MemalignRun(align, size, -1),
303 "is located 1 bytes to the left");
304 EXPECT_DEATH(MemalignRun(align, size, size + 1),
305 "is located 1 bytes to the right");
308 #endif // SANITIZER_TEST_HAS_MEMALIGN
310 void *ManyThreadsWorker(void *a) {
311 for (int iter = 0; iter < 100; iter++) {
312 for (size_t size = 100; size < 2000; size *= 2) {
313 free(Ident(malloc(size)));
316 return 0;
319 TEST(AddressSanitizer, ManyThreadsTest) {
320 const size_t kNumThreads =
321 (SANITIZER_WORDSIZE == 32 || ASAN_AVOID_EXPENSIVE_TESTS) ? 30 : 1000;
322 pthread_t t[kNumThreads];
323 for (size_t i = 0; i < kNumThreads; i++) {
324 PTHREAD_CREATE(&t[i], 0, ManyThreadsWorker, (void*)i);
326 for (size_t i = 0; i < kNumThreads; i++) {
327 PTHREAD_JOIN(t[i], 0);
331 TEST(AddressSanitizer, ReallocTest) {
332 const int kMinElem = 5;
333 int *ptr = (int*)malloc(sizeof(int) * kMinElem);
334 ptr[3] = 3;
335 for (int i = 0; i < 10000; i++) {
336 ptr = (int*)realloc(ptr,
337 (my_rand() % 1000 + kMinElem) * sizeof(int));
338 EXPECT_EQ(3, ptr[3]);
340 free(ptr);
341 // Realloc pointer returned by malloc(0).
342 int *ptr2 = Ident((int*)malloc(0));
343 ptr2 = Ident((int*)realloc(ptr2, sizeof(*ptr2)));
344 *ptr2 = 42;
345 EXPECT_EQ(42, *ptr2);
346 free(ptr2);
349 TEST(AddressSanitizer, ReallocFreedPointerTest) {
350 void *ptr = Ident(malloc(42));
351 ASSERT_TRUE(NULL != ptr);
352 free(ptr);
353 EXPECT_DEATH(ptr = realloc(ptr, 77), "attempting double-free");
356 TEST(AddressSanitizer, ReallocInvalidPointerTest) {
357 void *ptr = Ident(malloc(42));
358 EXPECT_DEATH(ptr = realloc((int*)ptr + 1, 77), "attempting free.*not malloc");
359 free(ptr);
362 TEST(AddressSanitizer, ZeroSizeMallocTest) {
363 // Test that malloc(0) and similar functions don't return NULL.
364 void *ptr = Ident(malloc(0));
365 EXPECT_TRUE(NULL != ptr);
366 free(ptr);
367 #if SANITIZER_TEST_HAS_POSIX_MEMALIGN
368 int pm_res = posix_memalign(&ptr, 1<<20, 0);
369 EXPECT_EQ(0, pm_res);
370 EXPECT_TRUE(NULL != ptr);
371 free(ptr);
372 #endif // SANITIZER_TEST_HAS_POSIX_MEMALIGN
373 int *int_ptr = new int[0];
374 int *int_ptr2 = new int[0];
375 EXPECT_TRUE(NULL != int_ptr);
376 EXPECT_TRUE(NULL != int_ptr2);
377 EXPECT_NE(int_ptr, int_ptr2);
378 delete[] int_ptr;
379 delete[] int_ptr2;
382 #if SANITIZER_TEST_HAS_MALLOC_USABLE_SIZE
383 static const char *kMallocUsableSizeErrorMsg =
384 "AddressSanitizer: attempting to call malloc_usable_size()";
386 TEST(AddressSanitizer, MallocUsableSizeTest) {
387 const size_t kArraySize = 100;
388 char *array = Ident((char*)malloc(kArraySize));
389 int *int_ptr = Ident(new int);
390 EXPECT_EQ(0U, malloc_usable_size(NULL));
391 EXPECT_EQ(kArraySize, malloc_usable_size(array));
392 EXPECT_EQ(sizeof(int), malloc_usable_size(int_ptr));
393 EXPECT_DEATH(malloc_usable_size((void*)0x123), kMallocUsableSizeErrorMsg);
394 EXPECT_DEATH(malloc_usable_size(array + kArraySize / 2),
395 kMallocUsableSizeErrorMsg);
396 free(array);
397 EXPECT_DEATH(malloc_usable_size(array), kMallocUsableSizeErrorMsg);
398 delete int_ptr;
400 #endif // SANITIZER_TEST_HAS_MALLOC_USABLE_SIZE
402 void WrongFree() {
403 int *x = (int*)malloc(100 * sizeof(int));
404 // Use the allocated memory, otherwise Clang will optimize it out.
405 Ident(x);
406 free(x + 1);
409 TEST(AddressSanitizer, WrongFreeTest) {
410 EXPECT_DEATH(WrongFree(), ASAN_PCRE_DOTALL
411 "ERROR: AddressSanitizer: attempting free.*not malloc"
412 ".*is located 4 bytes inside of 400-byte region"
413 ".*allocated by thread");
416 void DoubleFree() {
417 int *x = (int*)malloc(100 * sizeof(int));
418 fprintf(stderr, "DoubleFree: x=%p\n", x);
419 free(x);
420 free(x);
421 fprintf(stderr, "should have failed in the second free(%p)\n", x);
422 abort();
425 TEST(AddressSanitizer, DoubleFreeTest) {
426 EXPECT_DEATH(DoubleFree(), ASAN_PCRE_DOTALL
427 "ERROR: AddressSanitizer: attempting double-free"
428 ".*is located 0 bytes inside of 400-byte region"
429 ".*freed by thread T0 here"
430 ".*previously allocated by thread T0 here");
433 template<int kSize>
434 NOINLINE void SizedStackTest() {
435 char a[kSize];
436 char *A = Ident((char*)&a);
437 const char *expected_death = "AddressSanitizer: stack-buffer-";
438 for (size_t i = 0; i < kSize; i++)
439 A[i] = i;
440 EXPECT_DEATH(A[-1] = 0, expected_death);
441 EXPECT_DEATH(A[-5] = 0, expected_death);
442 EXPECT_DEATH(A[kSize] = 0, expected_death);
443 EXPECT_DEATH(A[kSize + 1] = 0, expected_death);
444 EXPECT_DEATH(A[kSize + 5] = 0, expected_death);
445 if (kSize > 16)
446 EXPECT_DEATH(A[kSize + 31] = 0, expected_death);
449 TEST(AddressSanitizer, SimpleStackTest) {
450 SizedStackTest<1>();
451 SizedStackTest<2>();
452 SizedStackTest<3>();
453 SizedStackTest<4>();
454 SizedStackTest<5>();
455 SizedStackTest<6>();
456 SizedStackTest<7>();
457 SizedStackTest<16>();
458 SizedStackTest<25>();
459 SizedStackTest<34>();
460 SizedStackTest<43>();
461 SizedStackTest<51>();
462 SizedStackTest<62>();
463 SizedStackTest<64>();
464 SizedStackTest<128>();
467 TEST(AddressSanitizer, ManyStackObjectsTest) {
468 char XXX[10];
469 char YYY[20];
470 char ZZZ[30];
471 Ident(XXX);
472 Ident(YYY);
473 EXPECT_DEATH(Ident(ZZZ)[-1] = 0, ASAN_PCRE_DOTALL "XXX.*YYY.*ZZZ");
476 #if 0 // This test requires online symbolizer.
477 // Moved to lit_tests/stack-oob-frames.cc.
478 // Reenable here once we have online symbolizer by default.
479 NOINLINE static void Frame0(int frame, char *a, char *b, char *c) {
480 char d[4] = {0};
481 char *D = Ident(d);
482 switch (frame) {
483 case 3: a[5]++; break;
484 case 2: b[5]++; break;
485 case 1: c[5]++; break;
486 case 0: D[5]++; break;
489 NOINLINE static void Frame1(int frame, char *a, char *b) {
490 char c[4] = {0}; Frame0(frame, a, b, c);
491 break_optimization(0);
493 NOINLINE static void Frame2(int frame, char *a) {
494 char b[4] = {0}; Frame1(frame, a, b);
495 break_optimization(0);
497 NOINLINE static void Frame3(int frame) {
498 char a[4] = {0}; Frame2(frame, a);
499 break_optimization(0);
502 TEST(AddressSanitizer, GuiltyStackFrame0Test) {
503 EXPECT_DEATH(Frame3(0), "located .*in frame <.*Frame0");
505 TEST(AddressSanitizer, GuiltyStackFrame1Test) {
506 EXPECT_DEATH(Frame3(1), "located .*in frame <.*Frame1");
508 TEST(AddressSanitizer, GuiltyStackFrame2Test) {
509 EXPECT_DEATH(Frame3(2), "located .*in frame <.*Frame2");
511 TEST(AddressSanitizer, GuiltyStackFrame3Test) {
512 EXPECT_DEATH(Frame3(3), "located .*in frame <.*Frame3");
514 #endif
516 NOINLINE void LongJmpFunc1(jmp_buf buf) {
517 // create three red zones for these two stack objects.
518 int a;
519 int b;
521 int *A = Ident(&a);
522 int *B = Ident(&b);
523 *A = *B;
524 longjmp(buf, 1);
527 NOINLINE void BuiltinLongJmpFunc1(jmp_buf buf) {
528 // create three red zones for these two stack objects.
529 int a;
530 int b;
532 int *A = Ident(&a);
533 int *B = Ident(&b);
534 *A = *B;
535 __builtin_longjmp((void**)buf, 1);
538 NOINLINE void UnderscopeLongJmpFunc1(jmp_buf buf) {
539 // create three red zones for these two stack objects.
540 int a;
541 int b;
543 int *A = Ident(&a);
544 int *B = Ident(&b);
545 *A = *B;
546 _longjmp(buf, 1);
549 NOINLINE void SigLongJmpFunc1(sigjmp_buf buf) {
550 // create three red zones for these two stack objects.
551 int a;
552 int b;
554 int *A = Ident(&a);
555 int *B = Ident(&b);
556 *A = *B;
557 siglongjmp(buf, 1);
561 NOINLINE void TouchStackFunc() {
562 int a[100]; // long array will intersect with redzones from LongJmpFunc1.
563 int *A = Ident(a);
564 for (int i = 0; i < 100; i++)
565 A[i] = i*i;
568 // Test that we handle longjmp and do not report fals positives on stack.
569 TEST(AddressSanitizer, LongJmpTest) {
570 static jmp_buf buf;
571 if (!setjmp(buf)) {
572 LongJmpFunc1(buf);
573 } else {
574 TouchStackFunc();
578 #if !defined(__ANDROID__) && \
579 !defined(__powerpc64__) && !defined(__powerpc__)
580 // Does not work on Power:
581 // https://code.google.com/p/address-sanitizer/issues/detail?id=185
582 TEST(AddressSanitizer, BuiltinLongJmpTest) {
583 static jmp_buf buf;
584 if (!__builtin_setjmp((void**)buf)) {
585 BuiltinLongJmpFunc1(buf);
586 } else {
587 TouchStackFunc();
590 #endif // not defined(__ANDROID__)
592 TEST(AddressSanitizer, UnderscopeLongJmpTest) {
593 static jmp_buf buf;
594 if (!_setjmp(buf)) {
595 UnderscopeLongJmpFunc1(buf);
596 } else {
597 TouchStackFunc();
601 TEST(AddressSanitizer, SigLongJmpTest) {
602 static sigjmp_buf buf;
603 if (!sigsetjmp(buf, 1)) {
604 SigLongJmpFunc1(buf);
605 } else {
606 TouchStackFunc();
610 #ifdef __EXCEPTIONS
611 NOINLINE void ThrowFunc() {
612 // create three red zones for these two stack objects.
613 int a;
614 int b;
616 int *A = Ident(&a);
617 int *B = Ident(&b);
618 *A = *B;
619 ASAN_THROW(1);
622 TEST(AddressSanitizer, CxxExceptionTest) {
623 if (ASAN_UAR) return;
624 // TODO(kcc): this test crashes on 32-bit for some reason...
625 if (SANITIZER_WORDSIZE == 32) return;
626 try {
627 ThrowFunc();
628 } catch(...) {}
629 TouchStackFunc();
631 #endif
633 void *ThreadStackReuseFunc1(void *unused) {
634 // create three red zones for these two stack objects.
635 int a;
636 int b;
638 int *A = Ident(&a);
639 int *B = Ident(&b);
640 *A = *B;
641 pthread_exit(0);
642 return 0;
645 void *ThreadStackReuseFunc2(void *unused) {
646 TouchStackFunc();
647 return 0;
650 TEST(AddressSanitizer, ThreadStackReuseTest) {
651 pthread_t t;
652 PTHREAD_CREATE(&t, 0, ThreadStackReuseFunc1, 0);
653 PTHREAD_JOIN(t, 0);
654 PTHREAD_CREATE(&t, 0, ThreadStackReuseFunc2, 0);
655 PTHREAD_JOIN(t, 0);
658 #if defined(__i686__) || defined(__x86_64__)
659 #include <emmintrin.h>
660 TEST(AddressSanitizer, Store128Test) {
661 char *a = Ident((char*)malloc(Ident(12)));
662 char *p = a;
663 if (((uintptr_t)a % 16) != 0)
664 p = a + 8;
665 assert(((uintptr_t)p % 16) == 0);
666 __m128i value_wide = _mm_set1_epi16(0x1234);
667 EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
668 "AddressSanitizer: heap-buffer-overflow");
669 EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
670 "WRITE of size 16");
671 EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
672 "located 0 bytes to the right of 12-byte");
673 free(a);
675 #endif
677 string RightOOBErrorMessage(int oob_distance, bool is_write) {
678 assert(oob_distance >= 0);
679 char expected_str[100];
680 sprintf(expected_str, ASAN_PCRE_DOTALL
681 "buffer-overflow.*%s.*located %d bytes to the right",
682 is_write ? "WRITE" : "READ", oob_distance);
683 return string(expected_str);
686 string RightOOBWriteMessage(int oob_distance) {
687 return RightOOBErrorMessage(oob_distance, /*is_write*/true);
690 string RightOOBReadMessage(int oob_distance) {
691 return RightOOBErrorMessage(oob_distance, /*is_write*/false);
694 string LeftOOBErrorMessage(int oob_distance, bool is_write) {
695 assert(oob_distance > 0);
696 char expected_str[100];
697 sprintf(expected_str, ASAN_PCRE_DOTALL "%s.*located %d bytes to the left",
698 is_write ? "WRITE" : "READ", oob_distance);
699 return string(expected_str);
702 string LeftOOBWriteMessage(int oob_distance) {
703 return LeftOOBErrorMessage(oob_distance, /*is_write*/true);
706 string LeftOOBReadMessage(int oob_distance) {
707 return LeftOOBErrorMessage(oob_distance, /*is_write*/false);
710 string LeftOOBAccessMessage(int oob_distance) {
711 assert(oob_distance > 0);
712 char expected_str[100];
713 sprintf(expected_str, "located %d bytes to the left", oob_distance);
714 return string(expected_str);
717 char* MallocAndMemsetString(size_t size, char ch) {
718 char *s = Ident((char*)malloc(size));
719 memset(s, ch, size);
720 return s;
723 char* MallocAndMemsetString(size_t size) {
724 return MallocAndMemsetString(size, 'z');
727 #if defined(__linux__) && !defined(ANDROID) && !defined(__ANDROID__)
728 #define READ_TEST(READ_N_BYTES) \
729 char *x = new char[10]; \
730 int fd = open("/proc/self/stat", O_RDONLY); \
731 ASSERT_GT(fd, 0); \
732 EXPECT_DEATH(READ_N_BYTES, \
733 ASAN_PCRE_DOTALL \
734 "AddressSanitizer: heap-buffer-overflow" \
735 ".* is located 0 bytes to the right of 10-byte region"); \
736 close(fd); \
737 delete [] x; \
739 TEST(AddressSanitizer, pread) {
740 READ_TEST(pread(fd, x, 15, 0));
743 TEST(AddressSanitizer, pread64) {
744 READ_TEST(pread64(fd, x, 15, 0));
747 TEST(AddressSanitizer, read) {
748 READ_TEST(read(fd, x, 15));
750 #endif // defined(__linux__) && !defined(ANDROID) && !defined(__ANDROID__)
752 // This test case fails
753 // Clang optimizes memcpy/memset calls which lead to unaligned access
754 TEST(AddressSanitizer, DISABLED_MemIntrinsicUnalignedAccessTest) {
755 int size = Ident(4096);
756 char *s = Ident((char*)malloc(size));
757 EXPECT_DEATH(memset(s + size - 1, 0, 2), RightOOBWriteMessage(0));
758 free(s);
761 // TODO(samsonov): Add a test with malloc(0)
762 // TODO(samsonov): Add tests for str* and mem* functions.
764 NOINLINE static int LargeFunction(bool do_bad_access) {
765 int *x = new int[100];
766 x[0]++;
767 x[1]++;
768 x[2]++;
769 x[3]++;
770 x[4]++;
771 x[5]++;
772 x[6]++;
773 x[7]++;
774 x[8]++;
775 x[9]++;
777 x[do_bad_access ? 100 : 0]++; int res = __LINE__;
779 x[10]++;
780 x[11]++;
781 x[12]++;
782 x[13]++;
783 x[14]++;
784 x[15]++;
785 x[16]++;
786 x[17]++;
787 x[18]++;
788 x[19]++;
790 delete x;
791 return res;
794 // Test the we have correct debug info for the failing instruction.
795 // This test requires the in-process symbolizer to be enabled by default.
796 TEST(AddressSanitizer, DISABLED_LargeFunctionSymbolizeTest) {
797 int failing_line = LargeFunction(false);
798 char expected_warning[128];
799 sprintf(expected_warning, "LargeFunction.*asan_test.*:%d", failing_line);
800 EXPECT_DEATH(LargeFunction(true), expected_warning);
803 // Check that we unwind and symbolize correctly.
804 TEST(AddressSanitizer, DISABLED_MallocFreeUnwindAndSymbolizeTest) {
805 int *a = (int*)malloc_aaa(sizeof(int));
806 *a = 1;
807 free_aaa(a);
808 EXPECT_DEATH(*a = 1, "free_ccc.*free_bbb.*free_aaa.*"
809 "malloc_fff.*malloc_eee.*malloc_ddd");
812 static bool TryToSetThreadName(const char *name) {
813 #if defined(__linux__) && defined(PR_SET_NAME)
814 return 0 == prctl(PR_SET_NAME, (unsigned long)name, 0, 0, 0);
815 #else
816 return false;
817 #endif
820 void *ThreadedTestAlloc(void *a) {
821 EXPECT_EQ(true, TryToSetThreadName("AllocThr"));
822 int **p = (int**)a;
823 *p = new int;
824 return 0;
827 void *ThreadedTestFree(void *a) {
828 EXPECT_EQ(true, TryToSetThreadName("FreeThr"));
829 int **p = (int**)a;
830 delete *p;
831 return 0;
834 void *ThreadedTestUse(void *a) {
835 EXPECT_EQ(true, TryToSetThreadName("UseThr"));
836 int **p = (int**)a;
837 **p = 1;
838 return 0;
841 void ThreadedTestSpawn() {
842 pthread_t t;
843 int *x;
844 PTHREAD_CREATE(&t, 0, ThreadedTestAlloc, &x);
845 PTHREAD_JOIN(t, 0);
846 PTHREAD_CREATE(&t, 0, ThreadedTestFree, &x);
847 PTHREAD_JOIN(t, 0);
848 PTHREAD_CREATE(&t, 0, ThreadedTestUse, &x);
849 PTHREAD_JOIN(t, 0);
852 TEST(AddressSanitizer, ThreadedTest) {
853 EXPECT_DEATH(ThreadedTestSpawn(),
854 ASAN_PCRE_DOTALL
855 "Thread T.*created"
856 ".*Thread T.*created"
857 ".*Thread T.*created");
860 void *ThreadedTestFunc(void *unused) {
861 // Check if prctl(PR_SET_NAME) is supported. Return if not.
862 if (!TryToSetThreadName("TestFunc"))
863 return 0;
864 EXPECT_DEATH(ThreadedTestSpawn(),
865 ASAN_PCRE_DOTALL
866 "WRITE .*thread T. .UseThr."
867 ".*freed by thread T. .FreeThr. here:"
868 ".*previously allocated by thread T. .AllocThr. here:"
869 ".*Thread T. .UseThr. created by T.*TestFunc"
870 ".*Thread T. .FreeThr. created by T"
871 ".*Thread T. .AllocThr. created by T"
872 "");
873 return 0;
876 TEST(AddressSanitizer, ThreadNamesTest) {
877 // Run ThreadedTestFunc in a separate thread because it tries to set a
878 // thread name and we don't want to change the main thread's name.
879 pthread_t t;
880 PTHREAD_CREATE(&t, 0, ThreadedTestFunc, 0);
881 PTHREAD_JOIN(t, 0);
884 #if ASAN_NEEDS_SEGV
885 TEST(AddressSanitizer, ShadowGapTest) {
886 #if SANITIZER_WORDSIZE == 32
887 char *addr = (char*)0x22000000;
888 #else
889 # if defined(__powerpc64__)
890 char *addr = (char*)0x024000800000;
891 # else
892 char *addr = (char*)0x0000100000080000;
893 # endif
894 #endif
895 EXPECT_DEATH(*addr = 1, "AddressSanitizer: SEGV on unknown");
897 #endif // ASAN_NEEDS_SEGV
899 extern "C" {
900 NOINLINE static void UseThenFreeThenUse() {
901 char *x = Ident((char*)malloc(8));
902 *x = 1;
903 free_aaa(x);
904 *x = 2;
908 TEST(AddressSanitizer, UseThenFreeThenUseTest) {
909 EXPECT_DEATH(UseThenFreeThenUse(), "freed by thread");
912 TEST(AddressSanitizer, StrDupTest) {
913 free(strdup(Ident("123")));
916 // Currently we create and poison redzone at right of global variables.
917 static char static110[110];
918 const char ConstGlob[7] = {1, 2, 3, 4, 5, 6, 7};
919 static const char StaticConstGlob[3] = {9, 8, 7};
921 TEST(AddressSanitizer, GlobalTest) {
922 static char func_static15[15];
924 static char fs1[10];
925 static char fs2[10];
926 static char fs3[10];
928 glob5[Ident(0)] = 0;
929 glob5[Ident(1)] = 0;
930 glob5[Ident(2)] = 0;
931 glob5[Ident(3)] = 0;
932 glob5[Ident(4)] = 0;
934 EXPECT_DEATH(glob5[Ident(5)] = 0,
935 "0 bytes to the right of global variable.*glob5.* size 5");
936 EXPECT_DEATH(glob5[Ident(5+6)] = 0,
937 "6 bytes to the right of global variable.*glob5.* size 5");
938 Ident(static110); // avoid optimizations
939 static110[Ident(0)] = 0;
940 static110[Ident(109)] = 0;
941 EXPECT_DEATH(static110[Ident(110)] = 0,
942 "0 bytes to the right of global variable");
943 EXPECT_DEATH(static110[Ident(110+7)] = 0,
944 "7 bytes to the right of global variable");
946 Ident(func_static15); // avoid optimizations
947 func_static15[Ident(0)] = 0;
948 EXPECT_DEATH(func_static15[Ident(15)] = 0,
949 "0 bytes to the right of global variable");
950 EXPECT_DEATH(func_static15[Ident(15 + 9)] = 0,
951 "9 bytes to the right of global variable");
953 Ident(fs1);
954 Ident(fs2);
955 Ident(fs3);
957 // We don't create left redzones, so this is not 100% guaranteed to fail.
958 // But most likely will.
959 EXPECT_DEATH(fs2[Ident(-1)] = 0, "is located.*of global variable");
961 EXPECT_DEATH(Ident(Ident(ConstGlob)[8]),
962 "is located 1 bytes to the right of .*ConstGlob");
963 EXPECT_DEATH(Ident(Ident(StaticConstGlob)[5]),
964 "is located 2 bytes to the right of .*StaticConstGlob");
966 // call stuff from another file.
967 GlobalsTest(0);
970 TEST(AddressSanitizer, GlobalStringConstTest) {
971 static const char *zoo = "FOOBAR123";
972 const char *p = Ident(zoo);
973 EXPECT_DEATH(Ident(p[15]), "is ascii string 'FOOBAR123'");
976 TEST(AddressSanitizer, FileNameInGlobalReportTest) {
977 static char zoo[10];
978 const char *p = Ident(zoo);
979 // The file name should be present in the report.
980 EXPECT_DEATH(Ident(p[15]), "zoo.*asan_test.");
983 int *ReturnsPointerToALocalObject() {
984 int a = 0;
985 return Ident(&a);
988 #if ASAN_UAR == 1
989 TEST(AddressSanitizer, LocalReferenceReturnTest) {
990 int *(*f)() = Ident(ReturnsPointerToALocalObject);
991 int *p = f();
992 // Call 'f' a few more times, 'p' should still be poisoned.
993 for (int i = 0; i < 32; i++)
994 f();
995 EXPECT_DEATH(*p = 1, "AddressSanitizer: stack-use-after-return");
996 EXPECT_DEATH(*p = 1, "is located.*in frame .*ReturnsPointerToALocal");
998 #endif
1000 template <int kSize>
1001 NOINLINE static void FuncWithStack() {
1002 char x[kSize];
1003 Ident(x)[0] = 0;
1004 Ident(x)[kSize-1] = 0;
1007 static void LotsOfStackReuse() {
1008 int LargeStack[10000];
1009 Ident(LargeStack)[0] = 0;
1010 for (int i = 0; i < 10000; i++) {
1011 FuncWithStack<128 * 1>();
1012 FuncWithStack<128 * 2>();
1013 FuncWithStack<128 * 4>();
1014 FuncWithStack<128 * 8>();
1015 FuncWithStack<128 * 16>();
1016 FuncWithStack<128 * 32>();
1017 FuncWithStack<128 * 64>();
1018 FuncWithStack<128 * 128>();
1019 FuncWithStack<128 * 256>();
1020 FuncWithStack<128 * 512>();
1021 Ident(LargeStack)[0] = 0;
1025 TEST(AddressSanitizer, StressStackReuseTest) {
1026 LotsOfStackReuse();
1029 TEST(AddressSanitizer, ThreadedStressStackReuseTest) {
1030 const int kNumThreads = 20;
1031 pthread_t t[kNumThreads];
1032 for (int i = 0; i < kNumThreads; i++) {
1033 PTHREAD_CREATE(&t[i], 0, (void* (*)(void *x))LotsOfStackReuse, 0);
1035 for (int i = 0; i < kNumThreads; i++) {
1036 PTHREAD_JOIN(t[i], 0);
1040 static void *PthreadExit(void *a) {
1041 pthread_exit(0);
1042 return 0;
1045 TEST(AddressSanitizer, PthreadExitTest) {
1046 pthread_t t;
1047 for (int i = 0; i < 1000; i++) {
1048 PTHREAD_CREATE(&t, 0, PthreadExit, 0);
1049 PTHREAD_JOIN(t, 0);
1053 #ifdef __EXCEPTIONS
1054 NOINLINE static void StackReuseAndException() {
1055 int large_stack[1000];
1056 Ident(large_stack);
1057 ASAN_THROW(1);
1060 // TODO(kcc): support exceptions with use-after-return.
1061 TEST(AddressSanitizer, DISABLED_StressStackReuseAndExceptionsTest) {
1062 for (int i = 0; i < 10000; i++) {
1063 try {
1064 StackReuseAndException();
1065 } catch(...) {
1069 #endif
1071 TEST(AddressSanitizer, MlockTest) {
1072 EXPECT_EQ(0, mlockall(MCL_CURRENT));
1073 EXPECT_EQ(0, mlock((void*)0x12345, 0x5678));
1074 EXPECT_EQ(0, munlockall());
1075 EXPECT_EQ(0, munlock((void*)0x987, 0x654));
1078 struct LargeStruct {
1079 int foo[100];
1082 // Test for bug http://llvm.org/bugs/show_bug.cgi?id=11763.
1083 // Struct copy should not cause asan warning even if lhs == rhs.
1084 TEST(AddressSanitizer, LargeStructCopyTest) {
1085 LargeStruct a;
1086 *Ident(&a) = *Ident(&a);
1089 ATTRIBUTE_NO_SANITIZE_ADDRESS
1090 static void NoSanitizeAddress() {
1091 char *foo = new char[10];
1092 Ident(foo)[10] = 0;
1093 delete [] foo;
1096 TEST(AddressSanitizer, AttributeNoSanitizeAddressTest) {
1097 Ident(NoSanitizeAddress)();
1100 // It doesn't work on Android, as calls to new/delete go through malloc/free.
1101 // Neither it does on OS X, see
1102 // https://code.google.com/p/address-sanitizer/issues/detail?id=131.
1103 #if !defined(ANDROID) && !defined(__ANDROID__) && !defined(__APPLE__)
1104 static string MismatchStr(const string &str) {
1105 return string("AddressSanitizer: alloc-dealloc-mismatch \\(") + str;
1108 TEST(AddressSanitizer, AllocDeallocMismatch) {
1109 EXPECT_DEATH(free(Ident(new int)),
1110 MismatchStr("operator new vs free"));
1111 EXPECT_DEATH(free(Ident(new int[2])),
1112 MismatchStr("operator new \\[\\] vs free"));
1113 EXPECT_DEATH(delete (Ident(new int[2])),
1114 MismatchStr("operator new \\[\\] vs operator delete"));
1115 EXPECT_DEATH(delete (Ident((int*)malloc(2 * sizeof(int)))),
1116 MismatchStr("malloc vs operator delete"));
1117 EXPECT_DEATH(delete [] (Ident(new int)),
1118 MismatchStr("operator new vs operator delete \\[\\]"));
1119 EXPECT_DEATH(delete [] (Ident((int*)malloc(2 * sizeof(int)))),
1120 MismatchStr("malloc vs operator delete \\[\\]"));
1122 #endif
1124 // ------------------ demo tests; run each one-by-one -------------
1125 // e.g. --gtest_filter=*DemoOOBLeftHigh --gtest_also_run_disabled_tests
1126 TEST(AddressSanitizer, DISABLED_DemoThreadedTest) {
1127 ThreadedTestSpawn();
1130 void *SimpleBugOnSTack(void *x = 0) {
1131 char a[20];
1132 Ident(a)[20] = 0;
1133 return 0;
1136 TEST(AddressSanitizer, DISABLED_DemoStackTest) {
1137 SimpleBugOnSTack();
1140 TEST(AddressSanitizer, DISABLED_DemoThreadStackTest) {
1141 pthread_t t;
1142 PTHREAD_CREATE(&t, 0, SimpleBugOnSTack, 0);
1143 PTHREAD_JOIN(t, 0);
1146 TEST(AddressSanitizer, DISABLED_DemoUAFLowIn) {
1147 uaf_test<U1>(10, 0);
1149 TEST(AddressSanitizer, DISABLED_DemoUAFLowLeft) {
1150 uaf_test<U1>(10, -2);
1152 TEST(AddressSanitizer, DISABLED_DemoUAFLowRight) {
1153 uaf_test<U1>(10, 10);
1156 TEST(AddressSanitizer, DISABLED_DemoUAFHigh) {
1157 uaf_test<U1>(kLargeMalloc, 0);
1160 TEST(AddressSanitizer, DISABLED_DemoOOM) {
1161 size_t size = SANITIZER_WORDSIZE == 64 ? (size_t)(1ULL << 40) : (0xf0000000);
1162 printf("%p\n", malloc(size));
1165 TEST(AddressSanitizer, DISABLED_DemoDoubleFreeTest) {
1166 DoubleFree();
1169 TEST(AddressSanitizer, DISABLED_DemoNullDerefTest) {
1170 int *a = 0;
1171 Ident(a)[10] = 0;
1174 TEST(AddressSanitizer, DISABLED_DemoFunctionStaticTest) {
1175 static char a[100];
1176 static char b[100];
1177 static char c[100];
1178 Ident(a);
1179 Ident(b);
1180 Ident(c);
1181 Ident(a)[5] = 0;
1182 Ident(b)[105] = 0;
1183 Ident(a)[5] = 0;
1186 TEST(AddressSanitizer, DISABLED_DemoTooMuchMemoryTest) {
1187 const size_t kAllocSize = (1 << 28) - 1024;
1188 size_t total_size = 0;
1189 while (true) {
1190 char *x = (char*)malloc(kAllocSize);
1191 memset(x, 0, kAllocSize);
1192 total_size += kAllocSize;
1193 fprintf(stderr, "total: %ldM %p\n", (long)total_size >> 20, x);
1197 // http://code.google.com/p/address-sanitizer/issues/detail?id=66
1198 TEST(AddressSanitizer, BufferOverflowAfterManyFrees) {
1199 for (int i = 0; i < 1000000; i++) {
1200 delete [] (Ident(new char [8644]));
1202 char *x = new char[8192];
1203 EXPECT_DEATH(x[Ident(8192)] = 0, "AddressSanitizer: heap-buffer-overflow");
1204 delete [] Ident(x);
1208 // Test that instrumentation of stack allocations takes into account
1209 // AllocSize of a type, and not its StoreSize (16 vs 10 bytes for long double).
1210 // See http://llvm.org/bugs/show_bug.cgi?id=12047 for more details.
1211 TEST(AddressSanitizer, LongDoubleNegativeTest) {
1212 long double a, b;
1213 static long double c;
1214 memcpy(Ident(&a), Ident(&b), sizeof(long double));
1215 memcpy(Ident(&c), Ident(&b), sizeof(long double));
1218 TEST(AddressSanitizer, pthread_getschedparam) {
1219 int policy;
1220 struct sched_param param;
1221 EXPECT_DEATH(
1222 pthread_getschedparam(pthread_self(), &policy, Ident(&param) + 2),
1223 "AddressSanitizer: stack-buffer-.*flow");
1224 EXPECT_DEATH(
1225 pthread_getschedparam(pthread_self(), Ident(&policy) - 1, &param),
1226 "AddressSanitizer: stack-buffer-.*flow");
1227 int res = pthread_getschedparam(pthread_self(), &policy, &param);
1228 ASSERT_EQ(0, res);