1 //===-- asan_test.cpp -----------------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file is a part of AddressSanitizer, an address sanity checker.
11 //===----------------------------------------------------------------------===//
12 #include "asan_test_utils.h"
17 #ifdef _LIBCPP_GET_C_LOCALE
18 #define SANITIZER_GET_C_LOCALE _LIBCPP_GET_C_LOCALE
20 #if defined(__FreeBSD__)
21 #define SANITIZER_GET_C_LOCALE 0
22 #elif defined(__NetBSD__)
23 #define SANITIZER_GET_C_LOCALE LC_C_LOCALE
27 #if defined(__sun__) && defined(__svr4__)
32 NOINLINE
void *malloc_fff(size_t size
) {
33 void *res
= malloc
/**/(size
); break_optimization(0); return res
;}
34 NOINLINE
void *malloc_eee(size_t size
) {
35 void *res
= malloc_fff(size
); break_optimization(0); return res
;}
36 NOINLINE
void *malloc_ddd(size_t size
) {
37 void *res
= malloc_eee(size
); break_optimization(0); return res
;}
38 NOINLINE
void *malloc_ccc(size_t size
) {
39 void *res
= malloc_ddd(size
); break_optimization(0); return res
;}
40 NOINLINE
void *malloc_bbb(size_t size
) {
41 void *res
= malloc_ccc(size
); break_optimization(0); return res
;}
42 NOINLINE
void *malloc_aaa(size_t size
) {
43 void *res
= malloc_bbb(size
); break_optimization(0); return res
;}
45 NOINLINE
void free_ccc(void *p
) { free(p
); break_optimization(0);}
46 NOINLINE
void free_bbb(void *p
) { free_ccc(p
); break_optimization(0);}
47 NOINLINE
void free_aaa(void *p
) { free_bbb(p
); break_optimization(0);}
50 NOINLINE
void uaf_test(int size
, int off
) {
51 void *p
= malloc_aaa(size
);
53 for (int i
= 1; i
< 100; i
++)
54 free_aaa(malloc_aaa(i
));
55 fprintf(stderr
, "writing %ld byte(s) at %p with offset %d\n",
56 (long)sizeof(T
), p
, off
);
57 asan_write((T
*)((char *)p
+ off
));
60 TEST(AddressSanitizer
, HasFeatureAddressSanitizerTest
) {
61 #if defined(__has_feature) && __has_feature(address_sanitizer)
63 #elif defined(__SANITIZE_ADDRESS__)
68 EXPECT_EQ(true, asan
);
71 TEST(AddressSanitizer
, SimpleDeathTest
) {
72 EXPECT_DEATH(exit(1), "");
75 TEST(AddressSanitizer
, VariousMallocsTest
) {
76 int *a
= (int*)malloc(100 * sizeof(int));
80 int *r
= (int*)malloc(10);
81 r
= (int*)realloc(r
, 2000 * sizeof(int));
85 int *b
= new int[100];
93 #if SANITIZER_TEST_HAS_POSIX_MEMALIGN
96 int pm_res
= posix_memalign(&pm
, kPageSize
, kPageSize
);
98 EXPECT_NE(nullptr, pm
);
100 #endif // SANITIZER_TEST_HAS_POSIX_MEMALIGN
102 #if SANITIZER_TEST_HAS_MEMALIGN
103 int *ma
= (int*)memalign(kPageSize
, kPageSize
);
104 EXPECT_EQ(0U, (uintptr_t)ma
% kPageSize
);
107 #endif // SANITIZER_TEST_HAS_MEMALIGN
110 TEST(AddressSanitizer
, CallocTest
) {
111 int *a
= (int*)calloc(100, sizeof(int));
116 TEST(AddressSanitizer
, CallocReturnsZeroMem
) {
117 size_t sizes
[] = {16, 1000, 10000, 100000, 2100000};
118 for (size_t s
= 0; s
< sizeof(sizes
)/sizeof(sizes
[0]); s
++) {
119 size_t size
= sizes
[s
];
120 for (size_t iter
= 0; iter
< 5; iter
++) {
121 char *x
= Ident((char*)calloc(1, size
));
123 EXPECT_EQ(x
[size
- 1], 0);
124 EXPECT_EQ(x
[size
/ 2], 0);
125 EXPECT_EQ(x
[size
/ 3], 0);
126 EXPECT_EQ(x
[size
/ 4], 0);
127 memset(x
, 0x42, size
);
130 // FIXME: OOM on Windows. We should just make this a lit test
131 // with quarantine size set to 1.
132 free(Ident(malloc(Ident(1 << 27)))); // Try to drain the quarantine.
138 // No valloc on Windows or Android.
139 #if !defined(_WIN32) && !defined(__ANDROID__)
140 TEST(AddressSanitizer
, VallocTest
) {
141 void *a
= valloc(100);
142 EXPECT_EQ(0U, (uintptr_t)a
% kPageSize
);
147 #if SANITIZER_TEST_HAS_PVALLOC
148 TEST(AddressSanitizer
, PvallocTest
) {
149 char *a
= (char*)pvalloc(kPageSize
+ 100);
150 EXPECT_EQ(0U, (uintptr_t)a
% kPageSize
);
151 a
[kPageSize
+ 101] = 1; // we should not report an error here.
154 a
= (char*)pvalloc(0); // pvalloc(0) should allocate at least one page.
155 EXPECT_EQ(0U, (uintptr_t)a
% kPageSize
);
156 a
[101] = 1; // we should not report an error here.
159 #endif // SANITIZER_TEST_HAS_PVALLOC
162 // FIXME: Use an equivalent of pthread_setspecific on Windows.
163 void *TSDWorker(void *test_key
) {
165 pthread_setspecific(*(pthread_key_t
*)test_key
, (void*)0xfeedface);
170 void TSDDestructor(void *tsd
) {
171 // Spawning a thread will check that the current thread id is not -1.
173 PTHREAD_CREATE(&th
, NULL
, TSDWorker
, NULL
);
174 PTHREAD_JOIN(th
, NULL
);
177 // This tests triggers the thread-specific data destruction fiasco which occurs
178 // if we don't manage the TSD destructors ourselves. We create a new pthread
179 // key with a non-NULL destructor which is likely to be put after the destructor
180 // of AsanThread in the list of destructors.
181 // In this case the TSD for AsanThread will be destroyed before TSDDestructor
182 // is called for the child thread, and a CHECK will fail when we call
183 // pthread_create() to spawn the grandchild.
184 TEST(AddressSanitizer
, DISABLED_TSDTest
) {
186 pthread_key_t test_key
;
187 pthread_key_create(&test_key
, TSDDestructor
);
188 PTHREAD_CREATE(&th
, NULL
, TSDWorker
, &test_key
);
189 PTHREAD_JOIN(th
, NULL
);
190 pthread_key_delete(test_key
);
194 TEST(AddressSanitizer
, UAF_char
) {
195 const char *uaf_string
= "AddressSanitizer:.*heap-use-after-free";
196 EXPECT_DEATH(uaf_test
<U1
>(1, 0), uaf_string
);
197 EXPECT_DEATH(uaf_test
<U1
>(10, 0), uaf_string
);
198 EXPECT_DEATH(uaf_test
<U1
>(10, 10), uaf_string
);
199 EXPECT_DEATH(uaf_test
<U1
>(kLargeMalloc
, 0), uaf_string
);
200 EXPECT_DEATH(uaf_test
<U1
>(kLargeMalloc
, kLargeMalloc
/ 2), uaf_string
);
203 TEST(AddressSanitizer
, UAF_long_double
) {
204 if (sizeof(long double) == sizeof(double)) return;
205 long double *p
= Ident(new long double[10]);
207 // https://google.github.io/googletest/advanced.html#regular-expression-syntax
208 // GoogleTest's regular expression engine on Windows does not support `[]`
210 EXPECT_DEATH(Ident(p
)[12] = 0, "WRITE of size 10");
211 EXPECT_DEATH(Ident(p
)[0] = Ident(p
)[12], "READ of size 10");
213 EXPECT_DEATH(Ident(p
)[12] = 0, "WRITE of size 1[026]");
214 EXPECT_DEATH(Ident(p
)[0] = Ident(p
)[12], "READ of size 1[026]");
223 } __attribute__((packed
));
225 # pragma pack(push, 1)
233 TEST(AddressSanitizer
, UAF_Packed5
) {
234 static_assert(sizeof(Packed5
) == 5, "Please check the keywords used");
235 Packed5
*p
= Ident(new Packed5
[2]);
236 EXPECT_DEATH(p
[0] = p
[3], "READ of size 5");
237 EXPECT_DEATH(p
[3] = p
[0], "WRITE of size 5");
241 #if ASAN_HAS_IGNORELIST
242 TEST(AddressSanitizer
, IgnoreTest
) {
243 int *x
= Ident(new int);
247 #endif // ASAN_HAS_IGNORELIST
249 struct StructWithBitField
{
256 TEST(AddressSanitizer
, BitFieldPositiveTest
) {
257 StructWithBitField
*x
= new StructWithBitField
;
259 EXPECT_DEATH(x
->bf1
= 0, "use-after-free");
260 EXPECT_DEATH(x
->bf2
= 0, "use-after-free");
261 EXPECT_DEATH(x
->bf3
= 0, "use-after-free");
262 EXPECT_DEATH(x
->bf4
= 0, "use-after-free");
265 struct StructWithBitFields_8_24
{
270 TEST(AddressSanitizer
, BitFieldNegativeTest
) {
271 StructWithBitFields_8_24
*x
= Ident(new StructWithBitFields_8_24
);
280 const char kSEGVCrash
[] = "AddressSanitizer: SEGV on unknown address";
281 const char kOverriddenSigactionHandler
[] = "Test sigaction handler\n";
282 const char kOverriddenSignalHandler
[] = "Test signal handler\n";
284 TEST(AddressSanitizer
, WildAddressTest
) {
285 char *c
= (char*)0x123;
286 EXPECT_DEATH(*c
= 0, kSEGVCrash
);
289 void my_sigaction_sighandler(int, siginfo_t
*, void*) {
290 fprintf(stderr
, kOverriddenSigactionHandler
);
294 void my_signal_sighandler(int signum
) {
295 fprintf(stderr
, kOverriddenSignalHandler
);
299 TEST(AddressSanitizer
, SignalTest
) {
300 struct sigaction sigact
;
301 memset(&sigact
, 0, sizeof(sigact
));
302 sigact
.sa_sigaction
= my_sigaction_sighandler
;
303 sigact
.sa_flags
= SA_SIGINFO
;
304 char *c
= (char *)0x123;
306 EXPECT_DEATH(*c
= 0, kSEGVCrash
);
308 // ASan should allow to set sigaction()...
309 EXPECT_EQ(0, sigaction(SIGSEGV
, &sigact
, 0));
311 EXPECT_EQ(0, sigaction(SIGBUS
, &sigact
, 0));
313 EXPECT_DEATH(*c
= 0, kOverriddenSigactionHandler
);
316 EXPECT_NE(SIG_ERR
, signal(SIGSEGV
, my_signal_sighandler
));
317 EXPECT_DEATH(*c
= 0, kOverriddenSignalHandler
);
322 static void TestLargeMalloc(size_t size
) {
324 sprintf(buff
, "is located 1 bytes before %lu-byte", (long)size
);
325 EXPECT_DEATH(Ident((char*)malloc(size
))[-1] = 0, buff
);
328 TEST(AddressSanitizer
, LargeMallocTest
) {
329 const int max_size
= (SANITIZER_WORDSIZE
== 32) ? 1 << 26 : 1 << 28;
330 for (int i
= 113; i
< max_size
; i
= i
* 2 + 13) {
335 #if !GTEST_USES_SIMPLE_RE
336 TEST(AddressSanitizer
, HugeMallocTest
) {
337 if (SANITIZER_WORDSIZE
!= 64 || ASAN_AVOID_EXPENSIVE_TESTS
) return;
338 size_t n_megs
= 4100;
339 EXPECT_DEATH(Ident((char*)malloc(n_megs
<< 20))[-1] = 0,
340 "is located 1 bytes before|"
341 "AddressSanitizer failed to allocate");
345 #if SANITIZER_TEST_HAS_MEMALIGN
346 void MemalignRun(size_t align
, size_t size
, int idx
) {
347 char *p
= (char *)memalign(align
, size
);
352 TEST(AddressSanitizer
, memalign
) {
353 for (int align
= 16; align
<= (1 << 23); align
*= 2) {
354 size_t size
= align
* 5;
355 EXPECT_DEATH(MemalignRun(align
, size
, -1),
356 "is located 1 bytes before");
357 EXPECT_DEATH(MemalignRun(align
, size
, size
+ 1),
358 "is located 1 bytes after");
361 #endif // SANITIZER_TEST_HAS_MEMALIGN
363 void *ManyThreadsWorker(void *a
) {
364 for (int iter
= 0; iter
< 100; iter
++) {
365 for (size_t size
= 100; size
< 2000; size
*= 2) {
366 free(Ident(malloc(size
)));
372 #if !defined(__aarch64__) && !defined(__powerpc64__)
373 // FIXME: Infinite loop in AArch64 (PR24389).
374 // FIXME: Also occasional hang on powerpc. Maybe same problem as on AArch64?
375 TEST(AddressSanitizer
, ManyThreadsTest
) {
376 const size_t kNumThreads
=
377 (SANITIZER_WORDSIZE
== 32 || ASAN_AVOID_EXPENSIVE_TESTS
) ? 30 : 1000;
378 pthread_t t
[kNumThreads
];
379 for (size_t i
= 0; i
< kNumThreads
; i
++) {
380 PTHREAD_CREATE(&t
[i
], 0, ManyThreadsWorker
, (void*)i
);
382 for (size_t i
= 0; i
< kNumThreads
; i
++) {
383 PTHREAD_JOIN(t
[i
], 0);
388 TEST(AddressSanitizer
, ReallocTest
) {
389 const int kMinElem
= 5;
390 int *ptr
= (int*)malloc(sizeof(int) * kMinElem
);
392 for (int i
= 0; i
< 10000; i
++) {
393 ptr
= (int*)realloc(ptr
,
394 (my_rand() % 1000 + kMinElem
) * sizeof(int));
395 EXPECT_EQ(3, ptr
[3]);
398 // Realloc pointer returned by malloc(0).
399 int *ptr2
= Ident((int*)malloc(0));
400 ptr2
= Ident((int*)realloc(ptr2
, sizeof(*ptr2
)));
402 EXPECT_EQ(42, *ptr2
);
406 TEST(AddressSanitizer
, ReallocFreedPointerTest
) {
407 void *ptr
= Ident(malloc(42));
408 ASSERT_TRUE(NULL
!= ptr
);
410 EXPECT_DEATH(ptr
= realloc(ptr
, 77), "attempting double-free");
413 TEST(AddressSanitizer
, ReallocInvalidPointerTest
) {
414 void *ptr
= Ident(malloc(42));
415 EXPECT_DEATH(ptr
= realloc((int*)ptr
+ 1, 77), "attempting free.*not malloc");
419 TEST(AddressSanitizer
, ZeroSizeMallocTest
) {
420 // Test that malloc(0) and similar functions don't return NULL.
421 void *ptr
= Ident(malloc(0));
422 EXPECT_TRUE(NULL
!= ptr
);
424 #if SANITIZER_TEST_HAS_POSIX_MEMALIGN
425 int pm_res
= posix_memalign(&ptr
, 1<<20, 0);
426 EXPECT_EQ(0, pm_res
);
427 EXPECT_TRUE(NULL
!= ptr
);
429 #endif // SANITIZER_TEST_HAS_POSIX_MEMALIGN
430 int *int_ptr
= new int[0];
431 int *int_ptr2
= new int[0];
432 EXPECT_TRUE(NULL
!= int_ptr
);
433 EXPECT_TRUE(NULL
!= int_ptr2
);
434 EXPECT_NE(int_ptr
, int_ptr2
);
439 #if SANITIZER_TEST_HAS_MALLOC_USABLE_SIZE
440 static const char *kMallocUsableSizeErrorMsg
=
441 "AddressSanitizer: attempting to call malloc_usable_size()";
443 TEST(AddressSanitizer
, MallocUsableSizeTest
) {
444 const size_t kArraySize
= 100;
445 char *array
= Ident((char*)malloc(kArraySize
));
446 int *int_ptr
= Ident(new int);
447 EXPECT_EQ(0U, malloc_usable_size(NULL
));
448 EXPECT_EQ(kArraySize
, malloc_usable_size(array
));
449 EXPECT_EQ(sizeof(int), malloc_usable_size(int_ptr
));
450 EXPECT_DEATH(malloc_usable_size((void*)0x123), kMallocUsableSizeErrorMsg
);
451 EXPECT_DEATH(malloc_usable_size(array
+ kArraySize
/ 2),
452 kMallocUsableSizeErrorMsg
);
454 EXPECT_DEATH(malloc_usable_size(array
), kMallocUsableSizeErrorMsg
);
457 #endif // SANITIZER_TEST_HAS_MALLOC_USABLE_SIZE
460 int *x
= (int*)malloc(100 * sizeof(int));
461 // Use the allocated memory, otherwise Clang will optimize it out.
466 #if !defined(_WIN32) // FIXME: This should be a lit test.
467 TEST(AddressSanitizer
, WrongFreeTest
) {
468 EXPECT_DEATH(WrongFree(), ASAN_PCRE_DOTALL
469 "ERROR: AddressSanitizer: attempting free.*not malloc"
470 ".*is located 4 bytes inside of 400-byte region"
471 ".*allocated by thread");
476 int *x
= (int*)malloc(100 * sizeof(int));
477 fprintf(stderr
, "DoubleFree: x=%p\n", (void *)x
);
480 fprintf(stderr
, "should have failed in the second free(%p)\n", (void *)x
);
484 #if !defined(_WIN32) // FIXME: This should be a lit test.
485 TEST(AddressSanitizer
, DoubleFreeTest
) {
486 EXPECT_DEATH(DoubleFree(), ASAN_PCRE_DOTALL
487 "ERROR: AddressSanitizer: attempting double-free"
488 ".*is located 0 bytes inside of 400-byte region"
489 ".*freed by thread T0 here"
490 ".*previously allocated by thread T0 here");
495 NOINLINE
void SizedStackTest() {
497 char *A
= Ident((char*)&a
);
498 const char *expected_death
= "AddressSanitizer: stack-buffer-";
499 for (size_t i
= 0; i
< kSize
; i
++)
501 EXPECT_DEATH(A
[-1] = 0, expected_death
);
502 EXPECT_DEATH(A
[-5] = 0, expected_death
);
503 EXPECT_DEATH(A
[kSize
] = 0, expected_death
);
504 EXPECT_DEATH(A
[kSize
+ 1] = 0, expected_death
);
505 EXPECT_DEATH(A
[kSize
+ 5] = 0, expected_death
);
507 EXPECT_DEATH(A
[kSize
+ 31] = 0, expected_death
);
510 TEST(AddressSanitizer
, SimpleStackTest
) {
518 SizedStackTest
<16>();
519 SizedStackTest
<25>();
520 SizedStackTest
<34>();
521 SizedStackTest
<43>();
522 SizedStackTest
<51>();
523 SizedStackTest
<62>();
524 SizedStackTest
<64>();
525 SizedStackTest
<128>();
529 // FIXME: It's a bit hard to write multi-line death test expectations
530 // in a portable way. Anyways, this should just be turned into a lit test.
531 TEST(AddressSanitizer
, ManyStackObjectsTest
) {
537 EXPECT_DEATH(Ident(ZZZ
)[-1] = 0, ASAN_PCRE_DOTALL
"XXX.*YYY.*ZZZ");
541 #if 0 // This test requires online symbolizer.
542 // Moved to lit_tests/stack-oob-frames.cpp.
543 // Reenable here once we have online symbolizer by default.
544 NOINLINE
static void Frame0(int frame
, char *a
, char *b
, char *c
) {
548 case 3: a
[5]++; break;
549 case 2: b
[5]++; break;
550 case 1: c
[5]++; break;
551 case 0: D
[5]++; break;
554 NOINLINE
static void Frame1(int frame
, char *a
, char *b
) {
555 char c
[4] = {0}; Frame0(frame
, a
, b
, c
);
556 break_optimization(0);
558 NOINLINE
static void Frame2(int frame
, char *a
) {
559 char b
[4] = {0}; Frame1(frame
, a
, b
);
560 break_optimization(0);
562 NOINLINE
static void Frame3(int frame
) {
563 char a
[4] = {0}; Frame2(frame
, a
);
564 break_optimization(0);
567 TEST(AddressSanitizer
, GuiltyStackFrame0Test
) {
568 EXPECT_DEATH(Frame3(0), "located .*in frame <.*Frame0");
570 TEST(AddressSanitizer
, GuiltyStackFrame1Test
) {
571 EXPECT_DEATH(Frame3(1), "located .*in frame <.*Frame1");
573 TEST(AddressSanitizer
, GuiltyStackFrame2Test
) {
574 EXPECT_DEATH(Frame3(2), "located .*in frame <.*Frame2");
576 TEST(AddressSanitizer
, GuiltyStackFrame3Test
) {
577 EXPECT_DEATH(Frame3(3), "located .*in frame <.*Frame3");
581 NOINLINE
void LongJmpFunc1(jmp_buf buf
) {
582 // create three red zones for these two stack objects.
592 NOINLINE
void TouchStackFunc() {
593 int a
[100]; // long array will intersect with redzones from LongJmpFunc1.
595 for (int i
= 0; i
< 100; i
++)
599 // Test that we handle longjmp and do not report false positives on stack.
600 TEST(AddressSanitizer
, LongJmpTest
) {
609 #if !defined(_WIN32) // Only basic longjmp is available on Windows.
610 NOINLINE
void UnderscopeLongJmpFunc1(jmp_buf buf
) {
611 // create three red zones for these two stack objects.
621 NOINLINE
void SigLongJmpFunc1(sigjmp_buf buf
) {
622 // create three red zones for these two stack objects.
632 #if !defined(__ANDROID__) && !defined(__arm__) && !defined(__aarch64__) && \
633 !defined(__mips__) && !defined(__mips64) && !defined(__s390__) && \
634 !defined(__riscv) && !defined(__loongarch__)
635 NOINLINE
void BuiltinLongJmpFunc1(jmp_buf buf
) {
636 // create three red zones for these two stack objects.
643 __builtin_longjmp((void**)buf
, 1);
646 // Does not work on ARM:
647 // https://github.com/google/sanitizers/issues/185
648 TEST(AddressSanitizer
, BuiltinLongJmpTest
) {
650 if (!__builtin_setjmp((void**)buf
)) {
651 BuiltinLongJmpFunc1(buf
);
656 #endif // !defined(__ANDROID__) && !defined(__arm__) &&
657 // !defined(__aarch64__) && !defined(__mips__) &&
658 // !defined(__mips64) && !defined(__s390__) &&
659 // !defined(__riscv) && !defined(__loongarch__)
661 TEST(AddressSanitizer
, UnderscopeLongJmpTest
) {
664 UnderscopeLongJmpFunc1(buf
);
670 TEST(AddressSanitizer
, SigLongJmpTest
) {
671 static sigjmp_buf buf
;
672 if (!sigsetjmp(buf
, 1)) {
673 SigLongJmpFunc1(buf
);
680 // FIXME: Why does clang-cl define __EXCEPTIONS?
681 #if defined(__EXCEPTIONS) && !defined(_WIN32)
682 NOINLINE
void ThrowFunc() {
683 // create three red zones for these two stack objects.
693 TEST(AddressSanitizer
, CxxExceptionTest
) {
694 if (ASAN_UAR
) return;
695 // TODO(kcc): this test crashes on 32-bit for some reason...
696 if (SANITIZER_WORDSIZE
== 32) return;
704 void *ThreadStackReuseFunc1(void *unused
) {
705 // create three red zones for these two stack objects.
716 void *ThreadStackReuseFunc2(void *unused
) {
721 #if !defined(__thumb__)
722 TEST(AddressSanitizer
, ThreadStackReuseTest
) {
724 PTHREAD_CREATE(&t
, 0, ThreadStackReuseFunc1
, 0);
726 PTHREAD_CREATE(&t
, 0, ThreadStackReuseFunc2
, 0);
731 #if defined(__SSE2__)
732 #include <emmintrin.h>
733 TEST(AddressSanitizer
, Store128Test
) {
734 char *a
= Ident((char*)malloc(Ident(12)));
736 if (((uintptr_t)a
% 16) != 0)
738 assert(((uintptr_t)p
% 16) == 0);
739 __m128i value_wide
= _mm_set1_epi16(0x1234);
740 EXPECT_DEATH(_mm_store_si128((__m128i
*)p
, value_wide
),
741 "AddressSanitizer: heap-buffer-overflow");
742 EXPECT_DEATH(_mm_store_si128((__m128i
*)p
, value_wide
),
744 EXPECT_DEATH(_mm_store_si128((__m128i
*)p
, value_wide
),
745 "located 0 bytes after 12-byte");
750 // FIXME: All tests that use this function should be turned into lit tests.
751 std::string
RightOOBErrorMessage(int oob_distance
, bool is_write
) {
752 assert(oob_distance
>= 0);
753 char expected_str
[100];
754 sprintf(expected_str
, ASAN_PCRE_DOTALL
755 #if !GTEST_USES_SIMPLE_RE
756 "buffer-overflow.*%s.*"
758 "located %d bytes after",
759 #if !GTEST_USES_SIMPLE_RE
760 is_write
? "WRITE" : "READ",
763 return std::string(expected_str
);
766 std::string
RightOOBWriteMessage(int oob_distance
) {
767 return RightOOBErrorMessage(oob_distance
, /*is_write*/true);
770 std::string
RightOOBReadMessage(int oob_distance
) {
771 return RightOOBErrorMessage(oob_distance
, /*is_write*/false);
774 // FIXME: All tests that use this function should be turned into lit tests.
775 std::string
LeftOOBErrorMessage(int oob_distance
, bool is_write
) {
776 assert(oob_distance
> 0);
777 char expected_str
[100];
778 sprintf(expected_str
,
779 #if !GTEST_USES_SIMPLE_RE
780 ASAN_PCRE_DOTALL
"%s.*"
782 "located %d bytes before",
783 #if !GTEST_USES_SIMPLE_RE
784 is_write
? "WRITE" : "READ",
787 return std::string(expected_str
);
790 std::string
LeftOOBWriteMessage(int oob_distance
) {
791 return LeftOOBErrorMessage(oob_distance
, /*is_write*/true);
794 std::string
LeftOOBReadMessage(int oob_distance
) {
795 return LeftOOBErrorMessage(oob_distance
, /*is_write*/false);
798 std::string
LeftOOBAccessMessage(int oob_distance
) {
799 assert(oob_distance
> 0);
800 char expected_str
[100];
801 sprintf(expected_str
, "located %d bytes before", oob_distance
);
802 return std::string(expected_str
);
805 char* MallocAndMemsetString(size_t size
, char ch
) {
806 char *s
= Ident((char*)malloc(size
));
811 char* MallocAndMemsetString(size_t size
) {
812 return MallocAndMemsetString(size
, 'z');
816 #define READ_TEST(READ_N_BYTES) \
817 char *x = new char[10]; \
818 int fd = open("/proc/self/stat", O_RDONLY); \
820 EXPECT_DEATH(READ_N_BYTES, \
822 "AddressSanitizer: heap-buffer-overflow" \
823 ".* is located 0 bytes after 10-byte region"); \
827 TEST(AddressSanitizer, pread) {
828 READ_TEST(pread(fd
, x
, 15, 0));
831 TEST(AddressSanitizer
, pread64
) {
832 READ_TEST(pread64(fd
, x
, 15, 0));
835 TEST(AddressSanitizer
, read
) {
836 READ_TEST(read(fd
, x
, 15));
838 #endif // SANITIZER_GLIBC
840 // This test case fails
841 // Clang optimizes memcpy/memset calls which lead to unaligned access
842 TEST(AddressSanitizer
, DISABLED_MemIntrinsicUnalignedAccessTest
) {
843 int size
= Ident(4096);
844 char *s
= Ident((char*)malloc(size
));
845 EXPECT_DEATH(memset(s
+ size
- 1, 0, 2), RightOOBWriteMessage(0));
849 NOINLINE
static int LargeFunction(bool do_bad_access
) {
850 int *x
= new int[100];
862 x
[do_bad_access
? 100 : 0]++; int res
= __LINE__
;
879 // Test the we have correct debug info for the failing instruction.
880 // This test requires the in-process symbolizer to be enabled by default.
881 TEST(AddressSanitizer
, DISABLED_LargeFunctionSymbolizeTest
) {
882 int failing_line
= LargeFunction(false);
883 char expected_warning
[128];
884 sprintf(expected_warning
, "LargeFunction.*asan_test.*:%d", failing_line
);
885 EXPECT_DEATH(LargeFunction(true), expected_warning
);
888 // Check that we unwind and symbolize correctly.
889 TEST(AddressSanitizer
, DISABLED_MallocFreeUnwindAndSymbolizeTest
) {
890 int *a
= (int*)malloc_aaa(sizeof(int));
893 EXPECT_DEATH(*a
= 1, "free_ccc.*free_bbb.*free_aaa.*"
894 "malloc_fff.*malloc_eee.*malloc_ddd");
897 static bool TryToSetThreadName(const char *name
) {
898 #if defined(__linux__) && defined(PR_SET_NAME)
899 return 0 == prctl(PR_SET_NAME
, (unsigned long)name
, 0, 0, 0);
905 void *ThreadedTestAlloc(void *a
) {
906 EXPECT_EQ(true, TryToSetThreadName("AllocThr"));
912 void *ThreadedTestFree(void *a
) {
913 EXPECT_EQ(true, TryToSetThreadName("FreeThr"));
919 void *ThreadedTestUse(void *a
) {
920 EXPECT_EQ(true, TryToSetThreadName("UseThr"));
926 void ThreadedTestSpawn() {
929 PTHREAD_CREATE(&t
, 0, ThreadedTestAlloc
, &x
);
931 PTHREAD_CREATE(&t
, 0, ThreadedTestFree
, &x
);
933 PTHREAD_CREATE(&t
, 0, ThreadedTestUse
, &x
);
937 #if !defined(_WIN32) // FIXME: This should be a lit test.
938 TEST(AddressSanitizer
, ThreadedTest
) {
939 EXPECT_DEATH(ThreadedTestSpawn(),
942 ".*Thread T.*created"
943 ".*Thread T.*created");
947 void *ThreadedTestFunc(void *unused
) {
948 // Check if prctl(PR_SET_NAME) is supported. Return if not.
949 if (!TryToSetThreadName("TestFunc"))
951 EXPECT_DEATH(ThreadedTestSpawn(),
953 "WRITE .*thread T. .UseThr."
954 ".*freed by thread T. .FreeThr. here:"
955 ".*previously allocated by thread T. .AllocThr. here:"
956 ".*Thread T. .UseThr. created by T.*TestFunc"
957 ".*Thread T. .FreeThr. created by T"
958 ".*Thread T. .AllocThr. created by T"
963 TEST(AddressSanitizer
, ThreadNamesTest
) {
964 // Run ThreadedTestFunc in a separate thread because it tries to set a
965 // thread name and we don't want to change the main thread's name.
967 PTHREAD_CREATE(&t
, 0, ThreadedTestFunc
, 0);
972 TEST(AddressSanitizer
, ShadowGapTest
) {
973 #if SANITIZER_WORDSIZE == 32
974 char *addr
= (char*)0x23000000;
976 # if defined(__powerpc64__)
977 char *addr
= (char*)0x024000800000;
978 # elif defined(__s390x__)
979 char *addr
= (char*)0x11000000000000;
981 char *addr
= (char*)0x0000100000080000;
984 EXPECT_DEATH(*addr
= 1, "AddressSanitizer: (SEGV|BUS) on unknown");
986 #endif // ASAN_NEEDS_SEGV
989 NOINLINE
static void UseThenFreeThenUse() {
990 char *x
= Ident((char*)malloc(8));
997 TEST(AddressSanitizer
, UseThenFreeThenUseTest
) {
998 EXPECT_DEATH(UseThenFreeThenUse(), "freed by thread");
1001 TEST(AddressSanitizer
, StrDupTest
) {
1002 free(strdup(Ident("123")));
1005 // Currently we create and poison redzone at right of global variables.
1006 static char static110
[110];
1007 const char ConstGlob
[7] = {1, 2, 3, 4, 5, 6, 7};
1008 static const char StaticConstGlob
[3] = {9, 8, 7};
1010 TEST(AddressSanitizer
, GlobalTest
) {
1011 static char func_static15
[15];
1013 static char fs1
[10];
1014 static char fs2
[10];
1015 static char fs3
[10];
1017 glob5
[Ident(0)] = 0;
1018 glob5
[Ident(1)] = 0;
1019 glob5
[Ident(2)] = 0;
1020 glob5
[Ident(3)] = 0;
1021 glob5
[Ident(4)] = 0;
1023 EXPECT_DEATH(glob5
[Ident(5)] = 0,
1024 "0 bytes after global variable.*glob5.* size 5");
1025 EXPECT_DEATH(glob5
[Ident(5+6)] = 0,
1026 "6 bytes after global variable.*glob5.* size 5");
1027 Ident(static110
); // avoid optimizations
1028 static110
[Ident(0)] = 0;
1029 static110
[Ident(109)] = 0;
1030 EXPECT_DEATH(static110
[Ident(110)] = 0,
1031 "0 bytes after global variable");
1032 EXPECT_DEATH(static110
[Ident(110+7)] = 0,
1033 "7 bytes after global variable");
1035 Ident(func_static15
); // avoid optimizations
1036 func_static15
[Ident(0)] = 0;
1037 EXPECT_DEATH(func_static15
[Ident(15)] = 0,
1038 "0 bytes after global variable");
1039 EXPECT_DEATH(func_static15
[Ident(15 + 9)] = 0,
1040 "9 bytes after global variable");
1046 // We don't create left redzones, so this is not 100% guaranteed to fail.
1047 // But most likely will.
1048 EXPECT_DEATH(fs2
[Ident(-1)] = 0, "is located.* global variable");
1050 EXPECT_DEATH(Ident(Ident(ConstGlob
)[8]),
1051 "is located 1 bytes after .*ConstGlob");
1052 EXPECT_DEATH(Ident(Ident(StaticConstGlob
)[5]),
1053 "is located 2 bytes after .*StaticConstGlob");
1055 // call stuff from another file.
1059 TEST(AddressSanitizer
, GlobalStringConstTest
) {
1060 static const char *zoo
= "FOOBAR123";
1061 const char *p
= Ident(zoo
);
1062 EXPECT_DEATH(Ident(p
[15]), "is ascii string 'FOOBAR123'");
1065 TEST(AddressSanitizer
, FileNameInGlobalReportTest
) {
1066 static char zoo
[10];
1067 const char *p
= Ident(zoo
);
1068 // The file name should be present in the report.
1069 EXPECT_DEATH(Ident(p
[15]), "zoo.*asan_test.");
1072 int *ReturnsPointerToALocalObject() {
1078 TEST(AddressSanitizer
, LocalReferenceReturnTest
) {
1079 int *(*f
)() = Ident(ReturnsPointerToALocalObject
);
1081 // Call 'f' a few more times, 'p' should still be poisoned.
1082 for (int i
= 0; i
< 32; i
++)
1084 EXPECT_DEATH(*p
= 1, "AddressSanitizer: stack-use-after-return");
1085 EXPECT_DEATH(*p
= 1, "is located.*in frame .*ReturnsPointerToALocal");
1089 template <int kSize
>
1090 NOINLINE
static void FuncWithStack() {
1093 Ident(x
)[kSize
-1] = 0;
1096 static void LotsOfStackReuse() {
1097 int LargeStack
[10000];
1098 Ident(LargeStack
)[0] = 0;
1099 for (int i
= 0; i
< 10000; i
++) {
1100 FuncWithStack
<128 * 1>();
1101 FuncWithStack
<128 * 2>();
1102 FuncWithStack
<128 * 4>();
1103 FuncWithStack
<128 * 8>();
1104 FuncWithStack
<128 * 16>();
1105 FuncWithStack
<128 * 32>();
1106 FuncWithStack
<128 * 64>();
1107 FuncWithStack
<128 * 128>();
1108 FuncWithStack
<128 * 256>();
1109 FuncWithStack
<128 * 512>();
1110 Ident(LargeStack
)[0] = 0;
1114 TEST(AddressSanitizer
, StressStackReuseTest
) {
1118 TEST(AddressSanitizer
, ThreadedStressStackReuseTest
) {
1119 const int kNumThreads
= 20;
1120 pthread_t t
[kNumThreads
];
1121 for (int i
= 0; i
< kNumThreads
; i
++) {
1122 PTHREAD_CREATE(&t
[i
], 0, (void* (*)(void *x
))LotsOfStackReuse
, 0);
1124 for (int i
= 0; i
< kNumThreads
; i
++) {
1125 PTHREAD_JOIN(t
[i
], 0);
1129 // pthread_exit tries to perform unwinding stuff that leads to dlopen'ing
1130 // libgcc_s.so. dlopen in its turn calls malloc to store "libgcc_s.so" string
1131 // that confuses LSan on Thumb because it fails to understand that this
1132 // allocation happens in dynamic linker and should be ignored.
1133 #if !defined(__thumb__)
1134 static void *PthreadExit(void *a
) {
1139 TEST(AddressSanitizer
, PthreadExitTest
) {
1141 for (int i
= 0; i
< 1000; i
++) {
1142 PTHREAD_CREATE(&t
, 0, PthreadExit
, 0);
1148 // FIXME: Why does clang-cl define __EXCEPTIONS?
1149 #if defined(__EXCEPTIONS) && !defined(_WIN32)
1150 NOINLINE
static void StackReuseAndException() {
1151 int large_stack
[1000];
1156 // TODO(kcc): support exceptions with use-after-return.
1157 TEST(AddressSanitizer
, DISABLED_StressStackReuseAndExceptionsTest
) {
1158 for (int i
= 0; i
< 10000; i
++) {
1160 StackReuseAndException();
1167 #if !defined(_WIN32)
1168 TEST(AddressSanitizer
, MlockTest
) {
1169 #if !defined(__ANDROID__) || __ANDROID_API__ >= 17
1170 EXPECT_EQ(0, mlockall(MCL_CURRENT
));
1172 EXPECT_EQ(0, mlock((void*)0x12345, 0x5678));
1173 #if !defined(__ANDROID__) || __ANDROID_API__ >= 17
1174 EXPECT_EQ(0, munlockall());
1176 EXPECT_EQ(0, munlock((void*)0x987, 0x654));
1180 struct LargeStruct
{
1184 // Test for bug http://llvm.org/bugs/show_bug.cgi?id=11763.
1185 // Struct copy should not cause asan warning even if lhs == rhs.
1186 TEST(AddressSanitizer
, LargeStructCopyTest
) {
1188 *Ident(&a
) = *Ident(&a
);
1191 ATTRIBUTE_NO_SANITIZE_ADDRESS
1192 static void NoSanitizeAddress() {
1193 char *foo
= new char[10];
1198 TEST(AddressSanitizer
, AttributeNoSanitizeAddressTest
) {
1199 Ident(NoSanitizeAddress
)();
1202 // The new/delete/etc mismatch checks don't work on Android,
1203 // as calls to new/delete go through malloc/free.
1204 // OS X support is tracked here:
1205 // https://github.com/google/sanitizers/issues/131
1206 // Windows support is tracked here:
1207 // https://github.com/google/sanitizers/issues/309
1208 #if !defined(__ANDROID__) && \
1209 !defined(__APPLE__) && \
1211 static std::string
MismatchStr(const std::string
&str
) {
1212 return std::string("AddressSanitizer: alloc-dealloc-mismatch \\(") + str
;
1215 static std::string
MismatchOrNewDeleteTypeStr(const std::string
&mismatch_str
) {
1216 return "(" + MismatchStr(mismatch_str
) +
1217 ")|(AddressSanitizer: new-delete-type-mismatch)";
1220 TEST(AddressSanitizer
, AllocDeallocMismatch
) {
1221 EXPECT_DEATH(free(Ident(new int)),
1222 MismatchStr("operator new vs free"));
1223 EXPECT_DEATH(free(Ident(new int[2])),
1224 MismatchStr("operator new \\[\\] vs free"));
1226 delete (Ident(new int[2])),
1227 MismatchOrNewDeleteTypeStr("operator new \\[\\] vs operator delete"));
1228 EXPECT_DEATH(delete (Ident((int *)malloc(2 * sizeof(int)))),
1229 MismatchOrNewDeleteTypeStr("malloc vs operator delete"));
1230 EXPECT_DEATH(delete [] (Ident(new int)),
1231 MismatchStr("operator new vs operator delete \\[\\]"));
1232 EXPECT_DEATH(delete [] (Ident((int*)malloc(2 * sizeof(int)))),
1233 MismatchStr("malloc vs operator delete \\[\\]"));
1237 // ------------------ demo tests; run each one-by-one -------------
1238 // e.g. --gtest_filter=*DemoOOBLeftHigh --gtest_also_run_disabled_tests
1239 TEST(AddressSanitizer
, DISABLED_DemoThreadedTest
) {
1240 ThreadedTestSpawn();
1243 void *SimpleBugOnSTack(void *x
= 0) {
1249 TEST(AddressSanitizer
, DISABLED_DemoStackTest
) {
1253 TEST(AddressSanitizer
, DISABLED_DemoThreadStackTest
) {
1255 PTHREAD_CREATE(&t
, 0, SimpleBugOnSTack
, 0);
1259 TEST(AddressSanitizer
, DISABLED_DemoUAFLowIn
) {
1260 uaf_test
<U1
>(10, 0);
1262 TEST(AddressSanitizer
, DISABLED_DemoUAFLowLeft
) {
1263 uaf_test
<U1
>(10, -2);
1265 TEST(AddressSanitizer
, DISABLED_DemoUAFLowRight
) {
1266 uaf_test
<U1
>(10, 10);
1269 TEST(AddressSanitizer
, DISABLED_DemoUAFHigh
) {
1270 uaf_test
<U1
>(kLargeMalloc
, 0);
1273 TEST(AddressSanitizer
, DISABLED_DemoOOM
) {
1274 size_t size
= SANITIZER_WORDSIZE
== 64 ? (size_t)(1ULL << 40) : (0xf0000000);
1275 printf("%p\n", malloc(size
));
1278 TEST(AddressSanitizer
, DISABLED_DemoDoubleFreeTest
) {
1282 TEST(AddressSanitizer
, DISABLED_DemoNullDerefTest
) {
1287 TEST(AddressSanitizer
, DISABLED_DemoFunctionStaticTest
) {
1299 TEST(AddressSanitizer
, DISABLED_DemoTooMuchMemoryTest
) {
1300 const size_t kAllocSize
= (1 << 28) - 1024;
1301 size_t total_size
= 0;
1303 void *x
= malloc(kAllocSize
);
1304 memset(x
, 0, kAllocSize
);
1305 total_size
+= kAllocSize
;
1306 fprintf(stderr
, "total: %ldM %p\n", (long)total_size
>> 20, x
);
1310 #if !defined(__NetBSD__) && !defined(__i386__)
1311 // https://github.com/google/sanitizers/issues/66
1312 TEST(AddressSanitizer
, BufferOverflowAfterManyFrees
) {
1313 for (int i
= 0; i
< 1000000; i
++) {
1314 delete [] (Ident(new char [8644]));
1316 char *x
= new char[8192];
1317 EXPECT_DEATH(x
[Ident(8192)] = 0, "AddressSanitizer: heap-buffer-overflow");
1323 // Test that instrumentation of stack allocations takes into account
1324 // AllocSize of a type, and not its StoreSize (16 vs 10 bytes for long double).
1325 // See http://llvm.org/bugs/show_bug.cgi?id=12047 for more details.
1326 TEST(AddressSanitizer
, LongDoubleNegativeTest
) {
1328 static long double c
;
1329 memcpy(Ident(&a
), Ident(&b
), sizeof(long double));
1330 memcpy(Ident(&c
), Ident(&b
), sizeof(long double));
1333 #if !defined(_WIN32)
1334 TEST(AddressSanitizer
, pthread_getschedparam
) {
1336 struct sched_param param
;
1338 pthread_getschedparam(pthread_self(), &policy
, Ident(¶m
) + 2),
1339 "AddressSanitizer: stack-buffer-.*flow");
1341 pthread_getschedparam(pthread_self(), Ident(&policy
) - 1, ¶m
),
1342 "AddressSanitizer: stack-buffer-.*flow");
1343 int res
= pthread_getschedparam(pthread_self(), &policy
, ¶m
);
1348 #if SANITIZER_TEST_HAS_PRINTF_L
1349 static int vsnprintf_l_wrapper(char *s
, size_t n
,
1350 locale_t l
, const char *format
, ...) {
1352 va_start(va
, format
);
1353 int res
= vsnprintf_l(s
, n
, l
, format
, va
);
1358 TEST(AddressSanitizer
, snprintf_l
) {
1360 // Check that snprintf_l() works fine with Asan.
1361 int res
= snprintf_l(buff
, 5, SANITIZER_GET_C_LOCALE
, "%s", "snprintf_l()");
1363 // Check that vsnprintf_l() works fine with Asan.
1364 res
= vsnprintf_l_wrapper(buff
, 5, SANITIZER_GET_C_LOCALE
, "%s",
1369 snprintf_l(buff
, 10, SANITIZER_GET_C_LOCALE
, "%s", "snprintf_l()"),
1370 "AddressSanitizer: stack-buffer-overflow");
1371 EXPECT_DEATH(vsnprintf_l_wrapper(buff
, 10, SANITIZER_GET_C_LOCALE
, "%s",
1373 "AddressSanitizer: stack-buffer-overflow");