1 //===-- asan_test.cc ------------------------------------------------------===//
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
6 //===----------------------------------------------------------------------===//
8 // This file is a part of AddressSanitizer, an address sanity checker.
10 //===----------------------------------------------------------------------===//
11 #include "asan_test_utils.h"
13 NOINLINE
void *malloc_fff(size_t size
) {
14 void *res
= malloc
/**/(size
); break_optimization(0); return res
;}
15 NOINLINE
void *malloc_eee(size_t size
) {
16 void *res
= malloc_fff(size
); break_optimization(0); return res
;}
17 NOINLINE
void *malloc_ddd(size_t size
) {
18 void *res
= malloc_eee(size
); break_optimization(0); return res
;}
19 NOINLINE
void *malloc_ccc(size_t size
) {
20 void *res
= malloc_ddd(size
); break_optimization(0); return res
;}
21 NOINLINE
void *malloc_bbb(size_t size
) {
22 void *res
= malloc_ccc(size
); break_optimization(0); return res
;}
23 NOINLINE
void *malloc_aaa(size_t size
) {
24 void *res
= malloc_bbb(size
); break_optimization(0); return res
;}
26 NOINLINE
void free_ccc(void *p
) { free(p
); break_optimization(0);}
27 NOINLINE
void free_bbb(void *p
) { free_ccc(p
); break_optimization(0);}
28 NOINLINE
void free_aaa(void *p
) { free_bbb(p
); break_optimization(0);}
31 NOINLINE
void uaf_test(int size
, int off
) {
32 char *p
= (char *)malloc_aaa(size
);
34 for (int i
= 1; i
< 100; i
++)
35 free_aaa(malloc_aaa(i
));
36 fprintf(stderr
, "writing %ld byte(s) at %p with offset %d\n",
37 (long)sizeof(T
), p
, off
);
38 asan_write((T
*)(p
+ off
));
41 TEST(AddressSanitizer
, HasFeatureAddressSanitizerTest
) {
42 #if defined(__has_feature) && __has_feature(address_sanitizer)
44 #elif defined(__SANITIZE_ADDRESS__)
49 EXPECT_EQ(true, asan
);
52 TEST(AddressSanitizer
, SimpleDeathTest
) {
53 EXPECT_DEATH(exit(1), "");
56 TEST(AddressSanitizer
, VariousMallocsTest
) {
57 int *a
= (int*)malloc(100 * sizeof(int));
61 int *r
= (int*)malloc(10);
62 r
= (int*)realloc(r
, 2000 * sizeof(int));
66 int *b
= new int[100];
74 #if SANITIZER_TEST_HAS_POSIX_MEMALIGN
76 int pm_res
= posix_memalign((void**)&pm
, kPageSize
, kPageSize
);
79 #endif // SANITIZER_TEST_HAS_POSIX_MEMALIGN
81 #if SANITIZER_TEST_HAS_MEMALIGN
82 int *ma
= (int*)memalign(kPageSize
, kPageSize
);
83 EXPECT_EQ(0U, (uintptr_t)ma
% kPageSize
);
86 #endif // SANITIZER_TEST_HAS_MEMALIGN
89 TEST(AddressSanitizer
, CallocTest
) {
90 int *a
= (int*)calloc(100, sizeof(int));
95 TEST(AddressSanitizer
, CallocReturnsZeroMem
) {
96 size_t sizes
[] = {16, 1000, 10000, 100000, 2100000};
97 for (size_t s
= 0; s
< sizeof(sizes
)/sizeof(sizes
[0]); s
++) {
98 size_t size
= sizes
[s
];
99 for (size_t iter
= 0; iter
< 5; iter
++) {
100 char *x
= Ident((char*)calloc(1, size
));
102 EXPECT_EQ(x
[size
- 1], 0);
103 EXPECT_EQ(x
[size
/ 2], 0);
104 EXPECT_EQ(x
[size
/ 3], 0);
105 EXPECT_EQ(x
[size
/ 4], 0);
106 memset(x
, 0x42, size
);
109 // FIXME: OOM on Windows. We should just make this a lit test
110 // with quarantine size set to 1.
111 free(Ident(malloc(Ident(1 << 27)))); // Try to drain the quarantine.
117 #if !defined(_WIN32) // No valloc on Windows.
118 TEST(AddressSanitizer
, VallocTest
) {
119 void *a
= valloc(100);
120 EXPECT_EQ(0U, (uintptr_t)a
% kPageSize
);
125 #if SANITIZER_TEST_HAS_PVALLOC
126 TEST(AddressSanitizer
, PvallocTest
) {
127 char *a
= (char*)pvalloc(kPageSize
+ 100);
128 EXPECT_EQ(0U, (uintptr_t)a
% kPageSize
);
129 a
[kPageSize
+ 101] = 1; // we should not report an error here.
132 a
= (char*)pvalloc(0); // pvalloc(0) should allocate at least one page.
133 EXPECT_EQ(0U, (uintptr_t)a
% kPageSize
);
134 a
[101] = 1; // we should not report an error here.
137 #endif // SANITIZER_TEST_HAS_PVALLOC
140 // FIXME: Use an equivalent of pthread_setspecific on Windows.
141 void *TSDWorker(void *test_key
) {
143 pthread_setspecific(*(pthread_key_t
*)test_key
, (void*)0xfeedface);
148 void TSDDestructor(void *tsd
) {
149 // Spawning a thread will check that the current thread id is not -1.
151 PTHREAD_CREATE(&th
, NULL
, TSDWorker
, NULL
);
152 PTHREAD_JOIN(th
, NULL
);
155 // This tests triggers the thread-specific data destruction fiasco which occurs
156 // if we don't manage the TSD destructors ourselves. We create a new pthread
157 // key with a non-NULL destructor which is likely to be put after the destructor
158 // of AsanThread in the list of destructors.
159 // In this case the TSD for AsanThread will be destroyed before TSDDestructor
160 // is called for the child thread, and a CHECK will fail when we call
161 // pthread_create() to spawn the grandchild.
162 TEST(AddressSanitizer
, DISABLED_TSDTest
) {
164 pthread_key_t test_key
;
165 pthread_key_create(&test_key
, TSDDestructor
);
166 PTHREAD_CREATE(&th
, NULL
, TSDWorker
, &test_key
);
167 PTHREAD_JOIN(th
, NULL
);
168 pthread_key_delete(test_key
);
172 TEST(AddressSanitizer
, UAF_char
) {
173 const char *uaf_string
= "AddressSanitizer:.*heap-use-after-free";
174 EXPECT_DEATH(uaf_test
<U1
>(1, 0), uaf_string
);
175 EXPECT_DEATH(uaf_test
<U1
>(10, 0), uaf_string
);
176 EXPECT_DEATH(uaf_test
<U1
>(10, 10), uaf_string
);
177 EXPECT_DEATH(uaf_test
<U1
>(kLargeMalloc
, 0), uaf_string
);
178 EXPECT_DEATH(uaf_test
<U1
>(kLargeMalloc
, kLargeMalloc
/ 2), uaf_string
);
181 TEST(AddressSanitizer
, UAF_long_double
) {
182 if (sizeof(long double) == sizeof(double)) return;
183 long double *p
= Ident(new long double[10]);
184 EXPECT_DEATH(Ident(p
)[12] = 0, "WRITE of size 1[026]");
185 EXPECT_DEATH(Ident(p
)[0] = Ident(p
)[12], "READ of size 1[026]");
193 } __attribute__((packed
));
195 # pragma pack(push, 1)
203 TEST(AddressSanitizer
, UAF_Packed5
) {
204 static_assert(sizeof(Packed5
) == 5, "Please check the keywords used");
205 Packed5
*p
= Ident(new Packed5
[2]);
206 EXPECT_DEATH(p
[0] = p
[3], "READ of size 5");
207 EXPECT_DEATH(p
[3] = p
[0], "WRITE of size 5");
211 #if ASAN_HAS_BLACKLIST
212 TEST(AddressSanitizer
, IgnoreTest
) {
213 int *x
= Ident(new int);
217 #endif // ASAN_HAS_BLACKLIST
219 struct StructWithBitField
{
226 TEST(AddressSanitizer
, BitFieldPositiveTest
) {
227 StructWithBitField
*x
= new StructWithBitField
;
229 EXPECT_DEATH(x
->bf1
= 0, "use-after-free");
230 EXPECT_DEATH(x
->bf2
= 0, "use-after-free");
231 EXPECT_DEATH(x
->bf3
= 0, "use-after-free");
232 EXPECT_DEATH(x
->bf4
= 0, "use-after-free");
235 struct StructWithBitFields_8_24
{
240 TEST(AddressSanitizer
, BitFieldNegativeTest
) {
241 StructWithBitFields_8_24
*x
= Ident(new StructWithBitFields_8_24
);
250 const char kUnknownCrash
[] = "AddressSanitizer: SEGV on unknown address";
251 const char kOverriddenHandler
[] = "ASan signal handler has been overridden\n";
253 TEST(AddressSanitizer
, WildAddressTest
) {
254 char *c
= (char*)0x123;
255 EXPECT_DEATH(*c
= 0, kUnknownCrash
);
258 void my_sigaction_sighandler(int, siginfo_t
*, void*) {
259 fprintf(stderr
, kOverriddenHandler
);
263 void my_signal_sighandler(int signum
) {
264 fprintf(stderr
, kOverriddenHandler
);
268 TEST(AddressSanitizer
, SignalTest
) {
269 struct sigaction sigact
;
270 memset(&sigact
, 0, sizeof(sigact
));
271 sigact
.sa_sigaction
= my_sigaction_sighandler
;
272 sigact
.sa_flags
= SA_SIGINFO
;
273 // ASan should silently ignore sigaction()...
274 EXPECT_EQ(0, sigaction(SIGSEGV
, &sigact
, 0));
276 EXPECT_EQ(0, sigaction(SIGBUS
, &sigact
, 0));
278 char *c
= (char*)0x123;
279 EXPECT_DEATH(*c
= 0, kUnknownCrash
);
281 EXPECT_EQ(0, signal(SIGSEGV
, my_signal_sighandler
));
282 EXPECT_DEATH(*c
= 0, kUnknownCrash
);
287 static void TestLargeMalloc(size_t size
) {
289 sprintf(buff
, "is located 1 bytes to the left of %lu-byte", (long)size
);
290 EXPECT_DEATH(Ident((char*)malloc(size
))[-1] = 0, buff
);
293 TEST(AddressSanitizer
, LargeMallocTest
) {
294 const int max_size
= (SANITIZER_WORDSIZE
== 32) ? 1 << 26 : 1 << 28;
295 for (int i
= 113; i
< max_size
; i
= i
* 2 + 13) {
300 TEST(AddressSanitizer
, HugeMallocTest
) {
301 if (SANITIZER_WORDSIZE
!= 64 || ASAN_AVOID_EXPENSIVE_TESTS
) return;
302 size_t n_megs
= 4100;
303 EXPECT_DEATH(Ident((char*)malloc(n_megs
<< 20))[-1] = 0,
304 "is located 1 bytes to the left|"
305 "AddressSanitizer failed to allocate");
308 #if SANITIZER_TEST_HAS_MEMALIGN
309 void MemalignRun(size_t align
, size_t size
, int idx
) {
310 char *p
= (char *)memalign(align
, size
);
315 TEST(AddressSanitizer
, memalign
) {
316 for (int align
= 16; align
<= (1 << 23); align
*= 2) {
317 size_t size
= align
* 5;
318 EXPECT_DEATH(MemalignRun(align
, size
, -1),
319 "is located 1 bytes to the left");
320 EXPECT_DEATH(MemalignRun(align
, size
, size
+ 1),
321 "is located 1 bytes to the right");
324 #endif // SANITIZER_TEST_HAS_MEMALIGN
326 void *ManyThreadsWorker(void *a
) {
327 for (int iter
= 0; iter
< 100; iter
++) {
328 for (size_t size
= 100; size
< 2000; size
*= 2) {
329 free(Ident(malloc(size
)));
335 TEST(AddressSanitizer
, ManyThreadsTest
) {
336 const size_t kNumThreads
=
337 (SANITIZER_WORDSIZE
== 32 || ASAN_AVOID_EXPENSIVE_TESTS
) ? 30 : 1000;
338 pthread_t t
[kNumThreads
];
339 for (size_t i
= 0; i
< kNumThreads
; i
++) {
340 PTHREAD_CREATE(&t
[i
], 0, ManyThreadsWorker
, (void*)i
);
342 for (size_t i
= 0; i
< kNumThreads
; i
++) {
343 PTHREAD_JOIN(t
[i
], 0);
347 TEST(AddressSanitizer
, ReallocTest
) {
348 const int kMinElem
= 5;
349 int *ptr
= (int*)malloc(sizeof(int) * kMinElem
);
351 for (int i
= 0; i
< 10000; i
++) {
352 ptr
= (int*)realloc(ptr
,
353 (my_rand() % 1000 + kMinElem
) * sizeof(int));
354 EXPECT_EQ(3, ptr
[3]);
357 // Realloc pointer returned by malloc(0).
358 int *ptr2
= Ident((int*)malloc(0));
359 ptr2
= Ident((int*)realloc(ptr2
, sizeof(*ptr2
)));
361 EXPECT_EQ(42, *ptr2
);
365 TEST(AddressSanitizer
, ReallocFreedPointerTest
) {
366 void *ptr
= Ident(malloc(42));
367 ASSERT_TRUE(NULL
!= ptr
);
369 EXPECT_DEATH(ptr
= realloc(ptr
, 77), "attempting double-free");
372 TEST(AddressSanitizer
, ReallocInvalidPointerTest
) {
373 void *ptr
= Ident(malloc(42));
374 EXPECT_DEATH(ptr
= realloc((int*)ptr
+ 1, 77), "attempting free.*not malloc");
378 TEST(AddressSanitizer
, ZeroSizeMallocTest
) {
379 // Test that malloc(0) and similar functions don't return NULL.
380 void *ptr
= Ident(malloc(0));
381 EXPECT_TRUE(NULL
!= ptr
);
383 #if SANITIZER_TEST_HAS_POSIX_MEMALIGN
384 int pm_res
= posix_memalign(&ptr
, 1<<20, 0);
385 EXPECT_EQ(0, pm_res
);
386 EXPECT_TRUE(NULL
!= ptr
);
388 #endif // SANITIZER_TEST_HAS_POSIX_MEMALIGN
389 int *int_ptr
= new int[0];
390 int *int_ptr2
= new int[0];
391 EXPECT_TRUE(NULL
!= int_ptr
);
392 EXPECT_TRUE(NULL
!= int_ptr2
);
393 EXPECT_NE(int_ptr
, int_ptr2
);
398 #if SANITIZER_TEST_HAS_MALLOC_USABLE_SIZE
399 static const char *kMallocUsableSizeErrorMsg
=
400 "AddressSanitizer: attempting to call malloc_usable_size()";
402 TEST(AddressSanitizer
, MallocUsableSizeTest
) {
403 const size_t kArraySize
= 100;
404 char *array
= Ident((char*)malloc(kArraySize
));
405 int *int_ptr
= Ident(new int);
406 EXPECT_EQ(0U, malloc_usable_size(NULL
));
407 EXPECT_EQ(kArraySize
, malloc_usable_size(array
));
408 EXPECT_EQ(sizeof(int), malloc_usable_size(int_ptr
));
409 EXPECT_DEATH(malloc_usable_size((void*)0x123), kMallocUsableSizeErrorMsg
);
410 EXPECT_DEATH(malloc_usable_size(array
+ kArraySize
/ 2),
411 kMallocUsableSizeErrorMsg
);
413 EXPECT_DEATH(malloc_usable_size(array
), kMallocUsableSizeErrorMsg
);
416 #endif // SANITIZER_TEST_HAS_MALLOC_USABLE_SIZE
419 int *x
= (int*)malloc(100 * sizeof(int));
420 // Use the allocated memory, otherwise Clang will optimize it out.
425 #if !defined(_WIN32) // FIXME: This should be a lit test.
426 TEST(AddressSanitizer
, WrongFreeTest
) {
427 EXPECT_DEATH(WrongFree(), ASAN_PCRE_DOTALL
428 "ERROR: AddressSanitizer: attempting free.*not malloc"
429 ".*is located 4 bytes inside of 400-byte region"
430 ".*allocated by thread");
435 int *x
= (int*)malloc(100 * sizeof(int));
436 fprintf(stderr
, "DoubleFree: x=%p\n", x
);
439 fprintf(stderr
, "should have failed in the second free(%p)\n", x
);
443 #if !defined(_WIN32) // FIXME: This should be a lit test.
444 TEST(AddressSanitizer
, DoubleFreeTest
) {
445 EXPECT_DEATH(DoubleFree(), ASAN_PCRE_DOTALL
446 "ERROR: AddressSanitizer: attempting double-free"
447 ".*is located 0 bytes inside of 400-byte region"
448 ".*freed by thread T0 here"
449 ".*previously allocated by thread T0 here");
454 NOINLINE
void SizedStackTest() {
456 char *A
= Ident((char*)&a
);
457 const char *expected_death
= "AddressSanitizer: stack-buffer-";
458 for (size_t i
= 0; i
< kSize
; i
++)
460 EXPECT_DEATH(A
[-1] = 0, expected_death
);
461 EXPECT_DEATH(A
[-5] = 0, expected_death
);
462 EXPECT_DEATH(A
[kSize
] = 0, expected_death
);
463 EXPECT_DEATH(A
[kSize
+ 1] = 0, expected_death
);
464 EXPECT_DEATH(A
[kSize
+ 5] = 0, expected_death
);
466 EXPECT_DEATH(A
[kSize
+ 31] = 0, expected_death
);
469 TEST(AddressSanitizer
, SimpleStackTest
) {
477 SizedStackTest
<16>();
478 SizedStackTest
<25>();
479 SizedStackTest
<34>();
480 SizedStackTest
<43>();
481 SizedStackTest
<51>();
482 SizedStackTest
<62>();
483 SizedStackTest
<64>();
484 SizedStackTest
<128>();
488 // FIXME: It's a bit hard to write multi-line death test expectations
489 // in a portable way. Anyways, this should just be turned into a lit test.
490 TEST(AddressSanitizer
, ManyStackObjectsTest
) {
496 EXPECT_DEATH(Ident(ZZZ
)[-1] = 0, ASAN_PCRE_DOTALL
"XXX.*YYY.*ZZZ");
500 #if 0 // This test requires online symbolizer.
501 // Moved to lit_tests/stack-oob-frames.cc.
502 // Reenable here once we have online symbolizer by default.
503 NOINLINE
static void Frame0(int frame
, char *a
, char *b
, char *c
) {
507 case 3: a
[5]++; break;
508 case 2: b
[5]++; break;
509 case 1: c
[5]++; break;
510 case 0: D
[5]++; break;
513 NOINLINE
static void Frame1(int frame
, char *a
, char *b
) {
514 char c
[4] = {0}; Frame0(frame
, a
, b
, c
);
515 break_optimization(0);
517 NOINLINE
static void Frame2(int frame
, char *a
) {
518 char b
[4] = {0}; Frame1(frame
, a
, b
);
519 break_optimization(0);
521 NOINLINE
static void Frame3(int frame
) {
522 char a
[4] = {0}; Frame2(frame
, a
);
523 break_optimization(0);
526 TEST(AddressSanitizer
, GuiltyStackFrame0Test
) {
527 EXPECT_DEATH(Frame3(0), "located .*in frame <.*Frame0");
529 TEST(AddressSanitizer
, GuiltyStackFrame1Test
) {
530 EXPECT_DEATH(Frame3(1), "located .*in frame <.*Frame1");
532 TEST(AddressSanitizer
, GuiltyStackFrame2Test
) {
533 EXPECT_DEATH(Frame3(2), "located .*in frame <.*Frame2");
535 TEST(AddressSanitizer
, GuiltyStackFrame3Test
) {
536 EXPECT_DEATH(Frame3(3), "located .*in frame <.*Frame3");
540 NOINLINE
void LongJmpFunc1(jmp_buf buf
) {
541 // create three red zones for these two stack objects.
551 NOINLINE
void TouchStackFunc() {
552 int a
[100]; // long array will intersect with redzones from LongJmpFunc1.
554 for (int i
= 0; i
< 100; i
++)
558 // Test that we handle longjmp and do not report false positives on stack.
559 TEST(AddressSanitizer
, LongJmpTest
) {
568 #if !defined(_WIN32) // Only basic longjmp is available on Windows.
569 NOINLINE
void BuiltinLongJmpFunc1(jmp_buf buf
) {
570 // create three red zones for these two stack objects.
577 __builtin_longjmp((void**)buf
, 1);
580 NOINLINE
void UnderscopeLongJmpFunc1(jmp_buf buf
) {
581 // create three red zones for these two stack objects.
591 NOINLINE
void SigLongJmpFunc1(sigjmp_buf buf
) {
592 // create three red zones for these two stack objects.
602 #if !defined(__ANDROID__) && \
603 !defined(__powerpc64__) && !defined(__powerpc__)
604 // Does not work on Power:
605 // https://code.google.com/p/address-sanitizer/issues/detail?id=185
606 TEST(AddressSanitizer
, BuiltinLongJmpTest
) {
608 if (!__builtin_setjmp((void**)buf
)) {
609 BuiltinLongJmpFunc1(buf
);
614 #endif // !defined(__ANDROID__) && !defined(__powerpc64__) &&
615 // !defined(__powerpc__)
617 TEST(AddressSanitizer
, UnderscopeLongJmpTest
) {
620 UnderscopeLongJmpFunc1(buf
);
626 TEST(AddressSanitizer
, SigLongJmpTest
) {
627 static sigjmp_buf buf
;
628 if (!sigsetjmp(buf
, 1)) {
629 SigLongJmpFunc1(buf
);
636 // FIXME: Why does clang-cl define __EXCEPTIONS?
637 #if defined(__EXCEPTIONS) && !defined(_WIN32)
638 NOINLINE
void ThrowFunc() {
639 // create three red zones for these two stack objects.
649 TEST(AddressSanitizer
, CxxExceptionTest
) {
650 if (ASAN_UAR
) return;
651 // TODO(kcc): this test crashes on 32-bit for some reason...
652 if (SANITIZER_WORDSIZE
== 32) return;
660 void *ThreadStackReuseFunc1(void *unused
) {
661 // create three red zones for these two stack objects.
672 void *ThreadStackReuseFunc2(void *unused
) {
677 TEST(AddressSanitizer
, ThreadStackReuseTest
) {
679 PTHREAD_CREATE(&t
, 0, ThreadStackReuseFunc1
, 0);
681 PTHREAD_CREATE(&t
, 0, ThreadStackReuseFunc2
, 0);
685 #if defined(__i686__) || defined(__x86_64__)
686 #include <emmintrin.h>
687 TEST(AddressSanitizer
, Store128Test
) {
688 char *a
= Ident((char*)malloc(Ident(12)));
690 if (((uintptr_t)a
% 16) != 0)
692 assert(((uintptr_t)p
% 16) == 0);
693 __m128i value_wide
= _mm_set1_epi16(0x1234);
694 EXPECT_DEATH(_mm_store_si128((__m128i
*)p
, value_wide
),
695 "AddressSanitizer: heap-buffer-overflow");
696 EXPECT_DEATH(_mm_store_si128((__m128i
*)p
, value_wide
),
698 EXPECT_DEATH(_mm_store_si128((__m128i
*)p
, value_wide
),
699 "located 0 bytes to the right of 12-byte");
704 // FIXME: All tests that use this function should be turned into lit tests.
705 string
RightOOBErrorMessage(int oob_distance
, bool is_write
) {
706 assert(oob_distance
>= 0);
707 char expected_str
[100];
708 sprintf(expected_str
, ASAN_PCRE_DOTALL
709 #if !GTEST_USES_SIMPLE_RE
710 "buffer-overflow.*%s.*"
712 "located %d bytes to the right",
713 #if !GTEST_USES_SIMPLE_RE
714 is_write
? "WRITE" : "READ",
717 return string(expected_str
);
720 string
RightOOBWriteMessage(int oob_distance
) {
721 return RightOOBErrorMessage(oob_distance
, /*is_write*/true);
724 string
RightOOBReadMessage(int oob_distance
) {
725 return RightOOBErrorMessage(oob_distance
, /*is_write*/false);
728 // FIXME: All tests that use this function should be turned into lit tests.
729 string
LeftOOBErrorMessage(int oob_distance
, bool is_write
) {
730 assert(oob_distance
> 0);
731 char expected_str
[100];
732 sprintf(expected_str
,
733 #if !GTEST_USES_SIMPLE_RE
734 ASAN_PCRE_DOTALL
"%s.*"
736 "located %d bytes to the left",
737 #if !GTEST_USES_SIMPLE_RE
738 is_write
? "WRITE" : "READ",
741 return string(expected_str
);
744 string
LeftOOBWriteMessage(int oob_distance
) {
745 return LeftOOBErrorMessage(oob_distance
, /*is_write*/true);
748 string
LeftOOBReadMessage(int oob_distance
) {
749 return LeftOOBErrorMessage(oob_distance
, /*is_write*/false);
752 string
LeftOOBAccessMessage(int oob_distance
) {
753 assert(oob_distance
> 0);
754 char expected_str
[100];
755 sprintf(expected_str
, "located %d bytes to the left", oob_distance
);
756 return string(expected_str
);
759 char* MallocAndMemsetString(size_t size
, char ch
) {
760 char *s
= Ident((char*)malloc(size
));
765 char* MallocAndMemsetString(size_t size
) {
766 return MallocAndMemsetString(size
, 'z');
769 #if defined(__linux__) && !defined(ANDROID) && !defined(__ANDROID__)
770 #define READ_TEST(READ_N_BYTES) \
771 char *x = new char[10]; \
772 int fd = open("/proc/self/stat", O_RDONLY); \
774 EXPECT_DEATH(READ_N_BYTES, \
776 "AddressSanitizer: heap-buffer-overflow" \
777 ".* is located 0 bytes to the right of 10-byte region"); \
781 TEST(AddressSanitizer, pread) {
782 READ_TEST(pread(fd
, x
, 15, 0));
785 TEST(AddressSanitizer
, pread64
) {
786 READ_TEST(pread64(fd
, x
, 15, 0));
789 TEST(AddressSanitizer
, read
) {
790 READ_TEST(read(fd
, x
, 15));
792 #endif // defined(__linux__) && !defined(ANDROID) && !defined(__ANDROID__)
794 // This test case fails
795 // Clang optimizes memcpy/memset calls which lead to unaligned access
796 TEST(AddressSanitizer
, DISABLED_MemIntrinsicUnalignedAccessTest
) {
797 int size
= Ident(4096);
798 char *s
= Ident((char*)malloc(size
));
799 EXPECT_DEATH(memset(s
+ size
- 1, 0, 2), RightOOBWriteMessage(0));
803 // TODO(samsonov): Add a test with malloc(0)
804 // TODO(samsonov): Add tests for str* and mem* functions.
806 NOINLINE
static int LargeFunction(bool do_bad_access
) {
807 int *x
= new int[100];
819 x
[do_bad_access
? 100 : 0]++; int res
= __LINE__
;
836 // Test the we have correct debug info for the failing instruction.
837 // This test requires the in-process symbolizer to be enabled by default.
838 TEST(AddressSanitizer
, DISABLED_LargeFunctionSymbolizeTest
) {
839 int failing_line
= LargeFunction(false);
840 char expected_warning
[128];
841 sprintf(expected_warning
, "LargeFunction.*asan_test.*:%d", failing_line
);
842 EXPECT_DEATH(LargeFunction(true), expected_warning
);
845 // Check that we unwind and symbolize correctly.
846 TEST(AddressSanitizer
, DISABLED_MallocFreeUnwindAndSymbolizeTest
) {
847 int *a
= (int*)malloc_aaa(sizeof(int));
850 EXPECT_DEATH(*a
= 1, "free_ccc.*free_bbb.*free_aaa.*"
851 "malloc_fff.*malloc_eee.*malloc_ddd");
854 static bool TryToSetThreadName(const char *name
) {
855 #if defined(__linux__) && defined(PR_SET_NAME)
856 return 0 == prctl(PR_SET_NAME
, (unsigned long)name
, 0, 0, 0);
862 void *ThreadedTestAlloc(void *a
) {
863 EXPECT_EQ(true, TryToSetThreadName("AllocThr"));
869 void *ThreadedTestFree(void *a
) {
870 EXPECT_EQ(true, TryToSetThreadName("FreeThr"));
876 void *ThreadedTestUse(void *a
) {
877 EXPECT_EQ(true, TryToSetThreadName("UseThr"));
883 void ThreadedTestSpawn() {
886 PTHREAD_CREATE(&t
, 0, ThreadedTestAlloc
, &x
);
888 PTHREAD_CREATE(&t
, 0, ThreadedTestFree
, &x
);
890 PTHREAD_CREATE(&t
, 0, ThreadedTestUse
, &x
);
894 #if !defined(_WIN32) // FIXME: This should be a lit test.
895 TEST(AddressSanitizer
, ThreadedTest
) {
896 EXPECT_DEATH(ThreadedTestSpawn(),
899 ".*Thread T.*created"
900 ".*Thread T.*created");
904 void *ThreadedTestFunc(void *unused
) {
905 // Check if prctl(PR_SET_NAME) is supported. Return if not.
906 if (!TryToSetThreadName("TestFunc"))
908 EXPECT_DEATH(ThreadedTestSpawn(),
910 "WRITE .*thread T. .UseThr."
911 ".*freed by thread T. .FreeThr. here:"
912 ".*previously allocated by thread T. .AllocThr. here:"
913 ".*Thread T. .UseThr. created by T.*TestFunc"
914 ".*Thread T. .FreeThr. created by T"
915 ".*Thread T. .AllocThr. created by T"
920 TEST(AddressSanitizer
, ThreadNamesTest
) {
921 // Run ThreadedTestFunc in a separate thread because it tries to set a
922 // thread name and we don't want to change the main thread's name.
924 PTHREAD_CREATE(&t
, 0, ThreadedTestFunc
, 0);
929 TEST(AddressSanitizer
, ShadowGapTest
) {
930 #if SANITIZER_WORDSIZE == 32
931 char *addr
= (char*)0x22000000;
933 # if defined(__powerpc64__)
934 char *addr
= (char*)0x024000800000;
936 char *addr
= (char*)0x0000100000080000;
939 EXPECT_DEATH(*addr
= 1, "AddressSanitizer: SEGV on unknown");
941 #endif // ASAN_NEEDS_SEGV
944 NOINLINE
static void UseThenFreeThenUse() {
945 char *x
= Ident((char*)malloc(8));
952 TEST(AddressSanitizer
, UseThenFreeThenUseTest
) {
953 EXPECT_DEATH(UseThenFreeThenUse(), "freed by thread");
956 TEST(AddressSanitizer
, StrDupTest
) {
957 free(strdup(Ident("123")));
960 // Currently we create and poison redzone at right of global variables.
961 static char static110
[110];
962 const char ConstGlob
[7] = {1, 2, 3, 4, 5, 6, 7};
963 static const char StaticConstGlob
[3] = {9, 8, 7};
965 TEST(AddressSanitizer
, GlobalTest
) {
966 static char func_static15
[15];
978 EXPECT_DEATH(glob5
[Ident(5)] = 0,
979 "0 bytes to the right of global variable.*glob5.* size 5");
980 EXPECT_DEATH(glob5
[Ident(5+6)] = 0,
981 "6 bytes to the right of global variable.*glob5.* size 5");
982 Ident(static110
); // avoid optimizations
983 static110
[Ident(0)] = 0;
984 static110
[Ident(109)] = 0;
985 EXPECT_DEATH(static110
[Ident(110)] = 0,
986 "0 bytes to the right of global variable");
987 EXPECT_DEATH(static110
[Ident(110+7)] = 0,
988 "7 bytes to the right of global variable");
990 Ident(func_static15
); // avoid optimizations
991 func_static15
[Ident(0)] = 0;
992 EXPECT_DEATH(func_static15
[Ident(15)] = 0,
993 "0 bytes to the right of global variable");
994 EXPECT_DEATH(func_static15
[Ident(15 + 9)] = 0,
995 "9 bytes to the right of global variable");
1001 // We don't create left redzones, so this is not 100% guaranteed to fail.
1002 // But most likely will.
1003 EXPECT_DEATH(fs2
[Ident(-1)] = 0, "is located.*of global variable");
1005 EXPECT_DEATH(Ident(Ident(ConstGlob
)[8]),
1006 "is located 1 bytes to the right of .*ConstGlob");
1007 EXPECT_DEATH(Ident(Ident(StaticConstGlob
)[5]),
1008 "is located 2 bytes to the right of .*StaticConstGlob");
1010 // call stuff from another file.
1014 TEST(AddressSanitizer
, GlobalStringConstTest
) {
1015 static const char *zoo
= "FOOBAR123";
1016 const char *p
= Ident(zoo
);
1017 EXPECT_DEATH(Ident(p
[15]), "is ascii string 'FOOBAR123'");
1020 TEST(AddressSanitizer
, FileNameInGlobalReportTest
) {
1021 static char zoo
[10];
1022 const char *p
= Ident(zoo
);
1023 // The file name should be present in the report.
1024 EXPECT_DEATH(Ident(p
[15]), "zoo.*asan_test.");
1027 int *ReturnsPointerToALocalObject() {
1033 TEST(AddressSanitizer
, LocalReferenceReturnTest
) {
1034 int *(*f
)() = Ident(ReturnsPointerToALocalObject
);
1036 // Call 'f' a few more times, 'p' should still be poisoned.
1037 for (int i
= 0; i
< 32; i
++)
1039 EXPECT_DEATH(*p
= 1, "AddressSanitizer: stack-use-after-return");
1040 EXPECT_DEATH(*p
= 1, "is located.*in frame .*ReturnsPointerToALocal");
1044 template <int kSize
>
1045 NOINLINE
static void FuncWithStack() {
1048 Ident(x
)[kSize
-1] = 0;
1051 static void LotsOfStackReuse() {
1052 int LargeStack
[10000];
1053 Ident(LargeStack
)[0] = 0;
1054 for (int i
= 0; i
< 10000; i
++) {
1055 FuncWithStack
<128 * 1>();
1056 FuncWithStack
<128 * 2>();
1057 FuncWithStack
<128 * 4>();
1058 FuncWithStack
<128 * 8>();
1059 FuncWithStack
<128 * 16>();
1060 FuncWithStack
<128 * 32>();
1061 FuncWithStack
<128 * 64>();
1062 FuncWithStack
<128 * 128>();
1063 FuncWithStack
<128 * 256>();
1064 FuncWithStack
<128 * 512>();
1065 Ident(LargeStack
)[0] = 0;
1069 TEST(AddressSanitizer
, StressStackReuseTest
) {
1073 TEST(AddressSanitizer
, ThreadedStressStackReuseTest
) {
1074 const int kNumThreads
= 20;
1075 pthread_t t
[kNumThreads
];
1076 for (int i
= 0; i
< kNumThreads
; i
++) {
1077 PTHREAD_CREATE(&t
[i
], 0, (void* (*)(void *x
))LotsOfStackReuse
, 0);
1079 for (int i
= 0; i
< kNumThreads
; i
++) {
1080 PTHREAD_JOIN(t
[i
], 0);
1084 static void *PthreadExit(void *a
) {
1089 TEST(AddressSanitizer
, PthreadExitTest
) {
1091 for (int i
= 0; i
< 1000; i
++) {
1092 PTHREAD_CREATE(&t
, 0, PthreadExit
, 0);
1097 // FIXME: Why does clang-cl define __EXCEPTIONS?
1098 #if defined(__EXCEPTIONS) && !defined(_WIN32)
1099 NOINLINE
static void StackReuseAndException() {
1100 int large_stack
[1000];
1105 // TODO(kcc): support exceptions with use-after-return.
1106 TEST(AddressSanitizer
, DISABLED_StressStackReuseAndExceptionsTest
) {
1107 for (int i
= 0; i
< 10000; i
++) {
1109 StackReuseAndException();
1116 #if !defined(_WIN32)
1117 TEST(AddressSanitizer
, MlockTest
) {
1118 EXPECT_EQ(0, mlockall(MCL_CURRENT
));
1119 EXPECT_EQ(0, mlock((void*)0x12345, 0x5678));
1120 EXPECT_EQ(0, munlockall());
1121 EXPECT_EQ(0, munlock((void*)0x987, 0x654));
1125 struct LargeStruct
{
1129 // Test for bug http://llvm.org/bugs/show_bug.cgi?id=11763.
1130 // Struct copy should not cause asan warning even if lhs == rhs.
1131 TEST(AddressSanitizer
, LargeStructCopyTest
) {
1133 *Ident(&a
) = *Ident(&a
);
1136 ATTRIBUTE_NO_SANITIZE_ADDRESS
1137 static void NoSanitizeAddress() {
1138 char *foo
= new char[10];
1143 TEST(AddressSanitizer
, AttributeNoSanitizeAddressTest
) {
1144 Ident(NoSanitizeAddress
)();
1147 // The new/delete/etc mismatch checks don't work on Android,
1148 // as calls to new/delete go through malloc/free.
1149 // OS X support is tracked here:
1150 // https://code.google.com/p/address-sanitizer/issues/detail?id=131
1151 // Windows support is tracked here:
1152 // https://code.google.com/p/address-sanitizer/issues/detail?id=309
1153 #if !defined(ANDROID) && !defined(__ANDROID__) && \
1154 !defined(__APPLE__) && \
1156 static string
MismatchStr(const string
&str
) {
1157 return string("AddressSanitizer: alloc-dealloc-mismatch \\(") + str
;
1160 TEST(AddressSanitizer
, AllocDeallocMismatch
) {
1161 EXPECT_DEATH(free(Ident(new int)),
1162 MismatchStr("operator new vs free"));
1163 EXPECT_DEATH(free(Ident(new int[2])),
1164 MismatchStr("operator new \\[\\] vs free"));
1165 EXPECT_DEATH(delete (Ident(new int[2])),
1166 MismatchStr("operator new \\[\\] vs operator delete"));
1167 EXPECT_DEATH(delete (Ident((int*)malloc(2 * sizeof(int)))),
1168 MismatchStr("malloc vs operator delete"));
1169 EXPECT_DEATH(delete [] (Ident(new int)),
1170 MismatchStr("operator new vs operator delete \\[\\]"));
1171 EXPECT_DEATH(delete [] (Ident((int*)malloc(2 * sizeof(int)))),
1172 MismatchStr("malloc vs operator delete \\[\\]"));
1176 // ------------------ demo tests; run each one-by-one -------------
1177 // e.g. --gtest_filter=*DemoOOBLeftHigh --gtest_also_run_disabled_tests
1178 TEST(AddressSanitizer
, DISABLED_DemoThreadedTest
) {
1179 ThreadedTestSpawn();
1182 void *SimpleBugOnSTack(void *x
= 0) {
1188 TEST(AddressSanitizer
, DISABLED_DemoStackTest
) {
1192 TEST(AddressSanitizer
, DISABLED_DemoThreadStackTest
) {
1194 PTHREAD_CREATE(&t
, 0, SimpleBugOnSTack
, 0);
1198 TEST(AddressSanitizer
, DISABLED_DemoUAFLowIn
) {
1199 uaf_test
<U1
>(10, 0);
1201 TEST(AddressSanitizer
, DISABLED_DemoUAFLowLeft
) {
1202 uaf_test
<U1
>(10, -2);
1204 TEST(AddressSanitizer
, DISABLED_DemoUAFLowRight
) {
1205 uaf_test
<U1
>(10, 10);
1208 TEST(AddressSanitizer
, DISABLED_DemoUAFHigh
) {
1209 uaf_test
<U1
>(kLargeMalloc
, 0);
1212 TEST(AddressSanitizer
, DISABLED_DemoOOM
) {
1213 size_t size
= SANITIZER_WORDSIZE
== 64 ? (size_t)(1ULL << 40) : (0xf0000000);
1214 printf("%p\n", malloc(size
));
1217 TEST(AddressSanitizer
, DISABLED_DemoDoubleFreeTest
) {
1221 TEST(AddressSanitizer
, DISABLED_DemoNullDerefTest
) {
1226 TEST(AddressSanitizer
, DISABLED_DemoFunctionStaticTest
) {
1238 TEST(AddressSanitizer
, DISABLED_DemoTooMuchMemoryTest
) {
1239 const size_t kAllocSize
= (1 << 28) - 1024;
1240 size_t total_size
= 0;
1242 char *x
= (char*)malloc(kAllocSize
);
1243 memset(x
, 0, kAllocSize
);
1244 total_size
+= kAllocSize
;
1245 fprintf(stderr
, "total: %ldM %p\n", (long)total_size
>> 20, x
);
1249 // http://code.google.com/p/address-sanitizer/issues/detail?id=66
1250 TEST(AddressSanitizer
, BufferOverflowAfterManyFrees
) {
1251 for (int i
= 0; i
< 1000000; i
++) {
1252 delete [] (Ident(new char [8644]));
1254 char *x
= new char[8192];
1255 EXPECT_DEATH(x
[Ident(8192)] = 0, "AddressSanitizer: heap-buffer-overflow");
1260 // Test that instrumentation of stack allocations takes into account
1261 // AllocSize of a type, and not its StoreSize (16 vs 10 bytes for long double).
1262 // See http://llvm.org/bugs/show_bug.cgi?id=12047 for more details.
1263 TEST(AddressSanitizer
, LongDoubleNegativeTest
) {
1265 static long double c
;
1266 memcpy(Ident(&a
), Ident(&b
), sizeof(long double));
1267 memcpy(Ident(&c
), Ident(&b
), sizeof(long double));
1270 #if !defined(_WIN32)
1271 TEST(AddressSanitizer
, pthread_getschedparam
) {
1273 struct sched_param param
;
1275 pthread_getschedparam(pthread_self(), &policy
, Ident(¶m
) + 2),
1276 "AddressSanitizer: stack-buffer-.*flow");
1278 pthread_getschedparam(pthread_self(), Ident(&policy
) - 1, ¶m
),
1279 "AddressSanitizer: stack-buffer-.*flow");
1280 int res
= pthread_getschedparam(pthread_self(), &policy
, ¶m
);