asan_test.cc revision 7c2a3bbabc7d3bcc66ad7a076bed9a4b86a3626d
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. 11// 12//===----------------------------------------------------------------------===// 13#include "asan_test_utils.h" 14 15NOINLINE void *malloc_fff(size_t size) { 16 void *res = malloc/**/(size); break_optimization(0); return res;} 17NOINLINE void *malloc_eee(size_t size) { 18 void *res = malloc_fff(size); break_optimization(0); return res;} 19NOINLINE void *malloc_ddd(size_t size) { 20 void *res = malloc_eee(size); break_optimization(0); return res;} 21NOINLINE void *malloc_ccc(size_t size) { 22 void *res = malloc_ddd(size); break_optimization(0); return res;} 23NOINLINE void *malloc_bbb(size_t size) { 24 void *res = malloc_ccc(size); break_optimization(0); return res;} 25NOINLINE void *malloc_aaa(size_t size) { 26 void *res = malloc_bbb(size); break_optimization(0); return res;} 27 28#ifndef __APPLE__ 29NOINLINE void *memalign_fff(size_t alignment, size_t size) { 30 void *res = memalign/**/(alignment, size); break_optimization(0); return res;} 31NOINLINE void *memalign_eee(size_t alignment, size_t size) { 32 void *res = memalign_fff(alignment, size); break_optimization(0); return res;} 33NOINLINE void *memalign_ddd(size_t alignment, size_t size) { 34 void *res = memalign_eee(alignment, size); break_optimization(0); return res;} 35NOINLINE void *memalign_ccc(size_t alignment, size_t size) { 36 void *res = memalign_ddd(alignment, size); break_optimization(0); return res;} 37NOINLINE void *memalign_bbb(size_t alignment, size_t size) { 38 void *res = memalign_ccc(alignment, size); break_optimization(0); return res;} 39NOINLINE void *memalign_aaa(size_t alignment, size_t size) { 40 void *res = memalign_bbb(alignment, size); break_optimization(0); return res;} 41#endif // __APPLE__ 42 43 44NOINLINE void free_ccc(void *p) { free(p); break_optimization(0);} 45NOINLINE void free_bbb(void *p) { free_ccc(p); break_optimization(0);} 46NOINLINE void free_aaa(void *p) { free_bbb(p); break_optimization(0);} 47 48 49template<typename T> 50NOINLINE void uaf_test(int size, int off) { 51 char *p = (char *)malloc_aaa(size); 52 free_aaa(p); 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*)(p + off)); 58} 59 60TEST(AddressSanitizer, HasFeatureAddressSanitizerTest) { 61#if defined(__has_feature) && __has_feature(address_sanitizer) 62 bool asan = 1; 63#elif defined(__SANITIZE_ADDRESS__) 64 bool asan = 1; 65#else 66 bool asan = 0; 67#endif 68 EXPECT_EQ(true, asan); 69} 70 71TEST(AddressSanitizer, SimpleDeathTest) { 72 EXPECT_DEATH(exit(1), ""); 73} 74 75TEST(AddressSanitizer, VariousMallocsTest) { 76 int *a = (int*)malloc(100 * sizeof(int)); 77 a[50] = 0; 78 free(a); 79 80 int *r = (int*)malloc(10); 81 r = (int*)realloc(r, 2000 * sizeof(int)); 82 r[1000] = 0; 83 free(r); 84 85 int *b = new int[100]; 86 b[50] = 0; 87 delete [] b; 88 89 int *c = new int; 90 *c = 0; 91 delete c; 92 93#if !defined(__APPLE__) && !defined(ANDROID) && !defined(__ANDROID__) 94 int *pm; 95 int pm_res = posix_memalign((void**)&pm, kPageSize, kPageSize); 96 EXPECT_EQ(0, pm_res); 97 free(pm); 98#endif 99 100#if !defined(__APPLE__) 101 int *ma = (int*)memalign(kPageSize, kPageSize); 102 EXPECT_EQ(0U, (uintptr_t)ma % kPageSize); 103 ma[123] = 0; 104 free(ma); 105#endif // __APPLE__ 106} 107 108TEST(AddressSanitizer, CallocTest) { 109 int *a = (int*)calloc(100, sizeof(int)); 110 EXPECT_EQ(0, a[10]); 111 free(a); 112} 113 114TEST(AddressSanitizer, VallocTest) { 115 void *a = valloc(100); 116 EXPECT_EQ(0U, (uintptr_t)a % kPageSize); 117 free(a); 118} 119 120#ifndef __APPLE__ 121TEST(AddressSanitizer, PvallocTest) { 122 char *a = (char*)pvalloc(kPageSize + 100); 123 EXPECT_EQ(0U, (uintptr_t)a % kPageSize); 124 a[kPageSize + 101] = 1; // we should not report an error here. 125 free(a); 126 127 a = (char*)pvalloc(0); // pvalloc(0) should allocate at least one page. 128 EXPECT_EQ(0U, (uintptr_t)a % kPageSize); 129 a[101] = 1; // we should not report an error here. 130 free(a); 131} 132#endif // __APPLE__ 133 134void *TSDWorker(void *test_key) { 135 if (test_key) { 136 pthread_setspecific(*(pthread_key_t*)test_key, (void*)0xfeedface); 137 } 138 return NULL; 139} 140 141void TSDDestructor(void *tsd) { 142 // Spawning a thread will check that the current thread id is not -1. 143 pthread_t th; 144 PTHREAD_CREATE(&th, NULL, TSDWorker, NULL); 145 PTHREAD_JOIN(th, NULL); 146} 147 148// This tests triggers the thread-specific data destruction fiasco which occurs 149// if we don't manage the TSD destructors ourselves. We create a new pthread 150// key with a non-NULL destructor which is likely to be put after the destructor 151// of AsanThread in the list of destructors. 152// In this case the TSD for AsanThread will be destroyed before TSDDestructor 153// is called for the child thread, and a CHECK will fail when we call 154// pthread_create() to spawn the grandchild. 155TEST(AddressSanitizer, DISABLED_TSDTest) { 156 pthread_t th; 157 pthread_key_t test_key; 158 pthread_key_create(&test_key, TSDDestructor); 159 PTHREAD_CREATE(&th, NULL, TSDWorker, &test_key); 160 PTHREAD_JOIN(th, NULL); 161 pthread_key_delete(test_key); 162} 163 164TEST(AddressSanitizer, UAF_char) { 165 const char *uaf_string = "AddressSanitizer:.*heap-use-after-free"; 166 EXPECT_DEATH(uaf_test<U1>(1, 0), uaf_string); 167 EXPECT_DEATH(uaf_test<U1>(10, 0), uaf_string); 168 EXPECT_DEATH(uaf_test<U1>(10, 10), uaf_string); 169 EXPECT_DEATH(uaf_test<U1>(kLargeMalloc, 0), uaf_string); 170 EXPECT_DEATH(uaf_test<U1>(kLargeMalloc, kLargeMalloc / 2), uaf_string); 171} 172 173TEST(AddressSanitizer, UAF_long_double) { 174 if (sizeof(long double) == sizeof(double)) return; 175 long double *p = Ident(new long double[10]); 176 EXPECT_DEATH(Ident(p)[12] = 0, "WRITE of size 10"); 177 EXPECT_DEATH(Ident(p)[0] = Ident(p)[12], "READ of size 10"); 178 delete [] Ident(p); 179} 180 181struct Packed5 { 182 int x; 183 char c; 184} __attribute__((packed)); 185 186 187TEST(AddressSanitizer, UAF_Packed5) { 188 Packed5 *p = Ident(new Packed5[2]); 189 EXPECT_DEATH(p[0] = p[3], "READ of size 5"); 190 EXPECT_DEATH(p[3] = p[0], "WRITE of size 5"); 191 delete [] Ident(p); 192} 193 194#if ASAN_HAS_BLACKLIST 195TEST(AddressSanitizer, IgnoreTest) { 196 int *x = Ident(new int); 197 delete Ident(x); 198 *x = 0; 199} 200#endif // ASAN_HAS_BLACKLIST 201 202struct StructWithBitField { 203 int bf1:1; 204 int bf2:1; 205 int bf3:1; 206 int bf4:29; 207}; 208 209TEST(AddressSanitizer, BitFieldPositiveTest) { 210 StructWithBitField *x = new StructWithBitField; 211 delete Ident(x); 212 EXPECT_DEATH(x->bf1 = 0, "use-after-free"); 213 EXPECT_DEATH(x->bf2 = 0, "use-after-free"); 214 EXPECT_DEATH(x->bf3 = 0, "use-after-free"); 215 EXPECT_DEATH(x->bf4 = 0, "use-after-free"); 216} 217 218struct StructWithBitFields_8_24 { 219 int a:8; 220 int b:24; 221}; 222 223TEST(AddressSanitizer, BitFieldNegativeTest) { 224 StructWithBitFields_8_24 *x = Ident(new StructWithBitFields_8_24); 225 x->a = 0; 226 x->b = 0; 227 delete Ident(x); 228} 229 230TEST(AddressSanitizer, OutOfMemoryTest) { 231 size_t size = SANITIZER_WORDSIZE == 64 ? (size_t)(1ULL << 48) : (0xf0000000); 232 EXPECT_EQ(0, realloc(0, size)); 233 EXPECT_EQ(0, realloc(0, ~Ident(0))); 234 EXPECT_EQ(0, malloc(size)); 235 EXPECT_EQ(0, malloc(~Ident(0))); 236 EXPECT_EQ(0, calloc(1, size)); 237 EXPECT_EQ(0, calloc(1, ~Ident(0))); 238} 239 240#if ASAN_NEEDS_SEGV 241namespace { 242 243const char kUnknownCrash[] = "AddressSanitizer: SEGV on unknown address"; 244const char kOverriddenHandler[] = "ASan signal handler has been overridden\n"; 245 246TEST(AddressSanitizer, WildAddressTest) { 247 char *c = (char*)0x123; 248 EXPECT_DEATH(*c = 0, kUnknownCrash); 249} 250 251void my_sigaction_sighandler(int, siginfo_t*, void*) { 252 fprintf(stderr, kOverriddenHandler); 253 exit(1); 254} 255 256void my_signal_sighandler(int signum) { 257 fprintf(stderr, kOverriddenHandler); 258 exit(1); 259} 260 261TEST(AddressSanitizer, SignalTest) { 262 struct sigaction sigact; 263 memset(&sigact, 0, sizeof(sigact)); 264 sigact.sa_sigaction = my_sigaction_sighandler; 265 sigact.sa_flags = SA_SIGINFO; 266 // ASan should silently ignore sigaction()... 267 EXPECT_EQ(0, sigaction(SIGSEGV, &sigact, 0)); 268#ifdef __APPLE__ 269 EXPECT_EQ(0, sigaction(SIGBUS, &sigact, 0)); 270#endif 271 char *c = (char*)0x123; 272 EXPECT_DEATH(*c = 0, kUnknownCrash); 273 // ... and signal(). 274 EXPECT_EQ(0, signal(SIGSEGV, my_signal_sighandler)); 275 EXPECT_DEATH(*c = 0, kUnknownCrash); 276} 277} // namespace 278#endif 279 280static void MallocStress(size_t n) { 281 uint32_t seed = my_rand(); 282 for (size_t iter = 0; iter < 10; iter++) { 283 vector<void *> vec; 284 for (size_t i = 0; i < n; i++) { 285 if ((i % 3) == 0) { 286 if (vec.empty()) continue; 287 size_t idx = my_rand_r(&seed) % vec.size(); 288 void *ptr = vec[idx]; 289 vec[idx] = vec.back(); 290 vec.pop_back(); 291 free_aaa(ptr); 292 } else { 293 size_t size = my_rand_r(&seed) % 1000 + 1; 294#ifndef __APPLE__ 295 size_t alignment = 1 << (my_rand_r(&seed) % 7 + 3); 296 char *ptr = (char*)memalign_aaa(alignment, size); 297#else 298 char *ptr = (char*) malloc_aaa(size); 299#endif 300 vec.push_back(ptr); 301 ptr[0] = 0; 302 ptr[size-1] = 0; 303 ptr[size/2] = 0; 304 } 305 } 306 for (size_t i = 0; i < vec.size(); i++) 307 free_aaa(vec[i]); 308 } 309} 310 311TEST(AddressSanitizer, MallocStressTest) { 312 MallocStress((ASAN_LOW_MEMORY) ? 20000 : 200000); 313} 314 315static void TestLargeMalloc(size_t size) { 316 char buff[1024]; 317 sprintf(buff, "is located 1 bytes to the left of %lu-byte", (long)size); 318 EXPECT_DEATH(Ident((char*)malloc(size))[-1] = 0, buff); 319} 320 321TEST(AddressSanitizer, LargeMallocTest) { 322 for (int i = 113; i < (1 << 28); i = i * 2 + 13) { 323 TestLargeMalloc(i); 324 } 325} 326 327#if ASAN_LOW_MEMORY != 1 328TEST(AddressSanitizer, HugeMallocTest) { 329#ifdef __APPLE__ 330 // It was empirically found out that 1215 megabytes is the maximum amount of 331 // memory available to the process under AddressSanitizer on 32-bit Mac 10.6. 332 // 32-bit Mac 10.7 gives even less (< 1G). 333 // (the libSystem malloc() allows allocating up to 2300 megabytes without 334 // ASan). 335 size_t n_megs = SANITIZER_WORDSIZE == 32 ? 500 : 4100; 336#else 337 size_t n_megs = SANITIZER_WORDSIZE == 32 ? 2600 : 4100; 338#endif 339 TestLargeMalloc(n_megs << 20); 340} 341#endif 342 343#ifndef __APPLE__ 344void MemalignRun(size_t align, size_t size, int idx) { 345 char *p = (char *)memalign(align, size); 346 Ident(p)[idx] = 0; 347 free(p); 348} 349 350TEST(AddressSanitizer, memalign) { 351 for (int align = 16; align <= (1 << 23); align *= 2) { 352 size_t size = align * 5; 353 EXPECT_DEATH(MemalignRun(align, size, -1), 354 "is located 1 bytes to the left"); 355 EXPECT_DEATH(MemalignRun(align, size, size + 1), 356 "is located 1 bytes to the right"); 357 } 358} 359#endif 360 361TEST(AddressSanitizer, ThreadedMallocStressTest) { 362 const int kNumThreads = 4; 363 const int kNumIterations = (ASAN_LOW_MEMORY) ? 10000 : 100000; 364 pthread_t t[kNumThreads]; 365 for (int i = 0; i < kNumThreads; i++) { 366 PTHREAD_CREATE(&t[i], 0, (void* (*)(void *x))MallocStress, 367 (void*)kNumIterations); 368 } 369 for (int i = 0; i < kNumThreads; i++) { 370 PTHREAD_JOIN(t[i], 0); 371 } 372} 373 374void *ManyThreadsWorker(void *a) { 375 for (int iter = 0; iter < 100; iter++) { 376 for (size_t size = 100; size < 2000; size *= 2) { 377 free(Ident(malloc(size))); 378 } 379 } 380 return 0; 381} 382 383TEST(AddressSanitizer, ManyThreadsTest) { 384 const size_t kNumThreads = 385 (SANITIZER_WORDSIZE == 32 || ASAN_AVOID_EXPENSIVE_TESTS) ? 30 : 1000; 386 pthread_t t[kNumThreads]; 387 for (size_t i = 0; i < kNumThreads; i++) { 388 PTHREAD_CREATE(&t[i], 0, ManyThreadsWorker, (void*)i); 389 } 390 for (size_t i = 0; i < kNumThreads; i++) { 391 PTHREAD_JOIN(t[i], 0); 392 } 393} 394 395TEST(AddressSanitizer, ReallocTest) { 396 const int kMinElem = 5; 397 int *ptr = (int*)malloc(sizeof(int) * kMinElem); 398 ptr[3] = 3; 399 for (int i = 0; i < 10000; i++) { 400 ptr = (int*)realloc(ptr, 401 (my_rand() % 1000 + kMinElem) * sizeof(int)); 402 EXPECT_EQ(3, ptr[3]); 403 } 404 free(ptr); 405 // Realloc pointer returned by malloc(0). 406 int *ptr2 = Ident((int*)malloc(0)); 407 ptr2 = Ident((int*)realloc(ptr2, sizeof(*ptr2))); 408 *ptr2 = 42; 409 EXPECT_EQ(42, *ptr2); 410 free(ptr2); 411} 412 413TEST(AddressSanitizer, ZeroSizeMallocTest) { 414 // Test that malloc(0) and similar functions don't return NULL. 415 void *ptr = Ident(malloc(0)); 416 EXPECT_TRUE(NULL != ptr); 417 free(ptr); 418#if !defined(__APPLE__) && !defined(ANDROID) && !defined(__ANDROID__) 419 int pm_res = posix_memalign(&ptr, 1<<20, 0); 420 EXPECT_EQ(0, pm_res); 421 EXPECT_TRUE(NULL != ptr); 422 free(ptr); 423#endif 424 int *int_ptr = new int[0]; 425 int *int_ptr2 = new int[0]; 426 EXPECT_TRUE(NULL != int_ptr); 427 EXPECT_TRUE(NULL != int_ptr2); 428 EXPECT_NE(int_ptr, int_ptr2); 429 delete[] int_ptr; 430 delete[] int_ptr2; 431} 432 433#ifndef __APPLE__ 434static const char *kMallocUsableSizeErrorMsg = 435 "AddressSanitizer: attempting to call malloc_usable_size()"; 436 437TEST(AddressSanitizer, MallocUsableSizeTest) { 438 const size_t kArraySize = 100; 439 char *array = Ident((char*)malloc(kArraySize)); 440 int *int_ptr = Ident(new int); 441 EXPECT_EQ(0U, malloc_usable_size(NULL)); 442 EXPECT_EQ(kArraySize, malloc_usable_size(array)); 443 EXPECT_EQ(sizeof(int), malloc_usable_size(int_ptr)); 444 EXPECT_DEATH(malloc_usable_size((void*)0x123), kMallocUsableSizeErrorMsg); 445 EXPECT_DEATH(malloc_usable_size(array + kArraySize / 2), 446 kMallocUsableSizeErrorMsg); 447 free(array); 448 EXPECT_DEATH(malloc_usable_size(array), kMallocUsableSizeErrorMsg); 449} 450#endif 451 452void WrongFree() { 453 int *x = (int*)malloc(100 * sizeof(int)); 454 // Use the allocated memory, otherwise Clang will optimize it out. 455 Ident(x); 456 free(x + 1); 457} 458 459TEST(AddressSanitizer, WrongFreeTest) { 460 EXPECT_DEATH(WrongFree(), 461 "ERROR: AddressSanitizer: attempting free.*not malloc"); 462} 463 464void DoubleFree() { 465 int *x = (int*)malloc(100 * sizeof(int)); 466 fprintf(stderr, "DoubleFree: x=%p\n", x); 467 free(x); 468 free(x); 469 fprintf(stderr, "should have failed in the second free(%p)\n", x); 470 abort(); 471} 472 473TEST(AddressSanitizer, DoubleFreeTest) { 474 EXPECT_DEATH(DoubleFree(), ASAN_PCRE_DOTALL 475 "ERROR: AddressSanitizer: attempting double-free" 476 ".*is located 0 bytes inside of 400-byte region" 477 ".*freed by thread T0 here" 478 ".*previously allocated by thread T0 here"); 479} 480 481template<int kSize> 482NOINLINE void SizedStackTest() { 483 char a[kSize]; 484 char *A = Ident((char*)&a); 485 for (size_t i = 0; i < kSize; i++) 486 A[i] = i; 487 EXPECT_DEATH(A[-1] = 0, ""); 488 EXPECT_DEATH(A[-20] = 0, ""); 489 EXPECT_DEATH(A[-31] = 0, ""); 490 EXPECT_DEATH(A[kSize] = 0, ""); 491 EXPECT_DEATH(A[kSize + 1] = 0, ""); 492 EXPECT_DEATH(A[kSize + 10] = 0, ""); 493 EXPECT_DEATH(A[kSize + 31] = 0, ""); 494} 495 496TEST(AddressSanitizer, SimpleStackTest) { 497 SizedStackTest<1>(); 498 SizedStackTest<2>(); 499 SizedStackTest<3>(); 500 SizedStackTest<4>(); 501 SizedStackTest<5>(); 502 SizedStackTest<6>(); 503 SizedStackTest<7>(); 504 SizedStackTest<16>(); 505 SizedStackTest<25>(); 506 SizedStackTest<34>(); 507 SizedStackTest<43>(); 508 SizedStackTest<51>(); 509 SizedStackTest<62>(); 510 SizedStackTest<64>(); 511 SizedStackTest<128>(); 512} 513 514TEST(AddressSanitizer, ManyStackObjectsTest) { 515 char XXX[10]; 516 char YYY[20]; 517 char ZZZ[30]; 518 Ident(XXX); 519 Ident(YYY); 520 EXPECT_DEATH(Ident(ZZZ)[-1] = 0, ASAN_PCRE_DOTALL "XXX.*YYY.*ZZZ"); 521} 522 523NOINLINE static void Frame0(int frame, char *a, char *b, char *c) { 524 char d[4] = {0}; 525 char *D = Ident(d); 526 switch (frame) { 527 case 3: a[5]++; break; 528 case 2: b[5]++; break; 529 case 1: c[5]++; break; 530 case 0: D[5]++; break; 531 } 532} 533NOINLINE static void Frame1(int frame, char *a, char *b) { 534 char c[4] = {0}; Frame0(frame, a, b, c); 535 break_optimization(0); 536} 537NOINLINE static void Frame2(int frame, char *a) { 538 char b[4] = {0}; Frame1(frame, a, b); 539 break_optimization(0); 540} 541NOINLINE static void Frame3(int frame) { 542 char a[4] = {0}; Frame2(frame, a); 543 break_optimization(0); 544} 545 546TEST(AddressSanitizer, GuiltyStackFrame0Test) { 547 EXPECT_DEATH(Frame3(0), "located .*in frame <.*Frame0"); 548} 549TEST(AddressSanitizer, GuiltyStackFrame1Test) { 550 EXPECT_DEATH(Frame3(1), "located .*in frame <.*Frame1"); 551} 552TEST(AddressSanitizer, GuiltyStackFrame2Test) { 553 EXPECT_DEATH(Frame3(2), "located .*in frame <.*Frame2"); 554} 555TEST(AddressSanitizer, GuiltyStackFrame3Test) { 556 EXPECT_DEATH(Frame3(3), "located .*in frame <.*Frame3"); 557} 558 559NOINLINE void LongJmpFunc1(jmp_buf buf) { 560 // create three red zones for these two stack objects. 561 int a; 562 int b; 563 564 int *A = Ident(&a); 565 int *B = Ident(&b); 566 *A = *B; 567 longjmp(buf, 1); 568} 569 570NOINLINE void BuiltinLongJmpFunc1(jmp_buf buf) { 571 // create three red zones for these two stack objects. 572 int a; 573 int b; 574 575 int *A = Ident(&a); 576 int *B = Ident(&b); 577 *A = *B; 578 __builtin_longjmp((void**)buf, 1); 579} 580 581NOINLINE void UnderscopeLongJmpFunc1(jmp_buf buf) { 582 // create three red zones for these two stack objects. 583 int a; 584 int b; 585 586 int *A = Ident(&a); 587 int *B = Ident(&b); 588 *A = *B; 589 _longjmp(buf, 1); 590} 591 592NOINLINE void SigLongJmpFunc1(sigjmp_buf buf) { 593 // create three red zones for these two stack objects. 594 int a; 595 int b; 596 597 int *A = Ident(&a); 598 int *B = Ident(&b); 599 *A = *B; 600 siglongjmp(buf, 1); 601} 602 603 604NOINLINE void TouchStackFunc() { 605 int a[100]; // long array will intersect with redzones from LongJmpFunc1. 606 int *A = Ident(a); 607 for (int i = 0; i < 100; i++) 608 A[i] = i*i; 609} 610 611// Test that we handle longjmp and do not report fals positives on stack. 612TEST(AddressSanitizer, LongJmpTest) { 613 static jmp_buf buf; 614 if (!setjmp(buf)) { 615 LongJmpFunc1(buf); 616 } else { 617 TouchStackFunc(); 618 } 619} 620 621#if not defined(__ANDROID__) 622TEST(AddressSanitizer, BuiltinLongJmpTest) { 623 static jmp_buf buf; 624 if (!__builtin_setjmp((void**)buf)) { 625 BuiltinLongJmpFunc1(buf); 626 } else { 627 TouchStackFunc(); 628 } 629} 630#endif // not defined(__ANDROID__) 631 632TEST(AddressSanitizer, UnderscopeLongJmpTest) { 633 static jmp_buf buf; 634 if (!_setjmp(buf)) { 635 UnderscopeLongJmpFunc1(buf); 636 } else { 637 TouchStackFunc(); 638 } 639} 640 641TEST(AddressSanitizer, SigLongJmpTest) { 642 static sigjmp_buf buf; 643 if (!sigsetjmp(buf, 1)) { 644 SigLongJmpFunc1(buf); 645 } else { 646 TouchStackFunc(); 647 } 648} 649 650#ifdef __EXCEPTIONS 651NOINLINE void ThrowFunc() { 652 // create three red zones for these two stack objects. 653 int a; 654 int b; 655 656 int *A = Ident(&a); 657 int *B = Ident(&b); 658 *A = *B; 659 ASAN_THROW(1); 660} 661 662TEST(AddressSanitizer, CxxExceptionTest) { 663 if (ASAN_UAR) return; 664 // TODO(kcc): this test crashes on 32-bit for some reason... 665 if (SANITIZER_WORDSIZE == 32) return; 666 try { 667 ThrowFunc(); 668 } catch(...) {} 669 TouchStackFunc(); 670} 671#endif 672 673void *ThreadStackReuseFunc1(void *unused) { 674 // create three red zones for these two stack objects. 675 int a; 676 int b; 677 678 int *A = Ident(&a); 679 int *B = Ident(&b); 680 *A = *B; 681 pthread_exit(0); 682 return 0; 683} 684 685void *ThreadStackReuseFunc2(void *unused) { 686 TouchStackFunc(); 687 return 0; 688} 689 690TEST(AddressSanitizer, ThreadStackReuseTest) { 691 pthread_t t; 692 PTHREAD_CREATE(&t, 0, ThreadStackReuseFunc1, 0); 693 PTHREAD_JOIN(t, 0); 694 PTHREAD_CREATE(&t, 0, ThreadStackReuseFunc2, 0); 695 PTHREAD_JOIN(t, 0); 696} 697 698#if defined(__i386__) || defined(__x86_64__) 699TEST(AddressSanitizer, Store128Test) { 700 char *a = Ident((char*)malloc(Ident(12))); 701 char *p = a; 702 if (((uintptr_t)a % 16) != 0) 703 p = a + 8; 704 assert(((uintptr_t)p % 16) == 0); 705 __m128i value_wide = _mm_set1_epi16(0x1234); 706 EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide), 707 "AddressSanitizer: heap-buffer-overflow"); 708 EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide), 709 "WRITE of size 16"); 710 EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide), 711 "located 0 bytes to the right of 12-byte"); 712 free(a); 713} 714#endif 715 716string RightOOBErrorMessage(int oob_distance, bool is_write) { 717 assert(oob_distance >= 0); 718 char expected_str[100]; 719 sprintf(expected_str, ASAN_PCRE_DOTALL "%s.*located %d bytes to the right", 720 is_write ? "WRITE" : "READ", oob_distance); 721 return string(expected_str); 722} 723 724string RightOOBWriteMessage(int oob_distance) { 725 return RightOOBErrorMessage(oob_distance, /*is_write*/true); 726} 727 728string RightOOBReadMessage(int oob_distance) { 729 return RightOOBErrorMessage(oob_distance, /*is_write*/false); 730} 731 732string LeftOOBErrorMessage(int oob_distance, bool is_write) { 733 assert(oob_distance > 0); 734 char expected_str[100]; 735 sprintf(expected_str, ASAN_PCRE_DOTALL "%s.*located %d bytes to the left", 736 is_write ? "WRITE" : "READ", oob_distance); 737 return string(expected_str); 738} 739 740string LeftOOBWriteMessage(int oob_distance) { 741 return LeftOOBErrorMessage(oob_distance, /*is_write*/true); 742} 743 744string LeftOOBReadMessage(int oob_distance) { 745 return LeftOOBErrorMessage(oob_distance, /*is_write*/false); 746} 747 748string LeftOOBAccessMessage(int oob_distance) { 749 assert(oob_distance > 0); 750 char expected_str[100]; 751 sprintf(expected_str, "located %d bytes to the left", oob_distance); 752 return string(expected_str); 753} 754 755char* MallocAndMemsetString(size_t size, char ch) { 756 char *s = Ident((char*)malloc(size)); 757 memset(s, ch, size); 758 return s; 759} 760 761char* MallocAndMemsetString(size_t size) { 762 return MallocAndMemsetString(size, 'z'); 763} 764 765#if defined(__linux__) && !defined(ANDROID) && !defined(__ANDROID__) 766#define READ_TEST(READ_N_BYTES) \ 767 char *x = new char[10]; \ 768 int fd = open("/proc/self/stat", O_RDONLY); \ 769 ASSERT_GT(fd, 0); \ 770 EXPECT_DEATH(READ_N_BYTES, \ 771 ASAN_PCRE_DOTALL \ 772 "AddressSanitizer: heap-buffer-overflow" \ 773 ".* is located 0 bytes to the right of 10-byte region"); \ 774 close(fd); \ 775 delete [] x; \ 776 777TEST(AddressSanitizer, pread) { 778 READ_TEST(pread(fd, x, 15, 0)); 779} 780 781TEST(AddressSanitizer, pread64) { 782 READ_TEST(pread64(fd, x, 15, 0)); 783} 784 785TEST(AddressSanitizer, read) { 786 READ_TEST(read(fd, x, 15)); 787} 788#endif // defined(__linux__) && !defined(ANDROID) && !defined(__ANDROID__) 789 790// This test case fails 791// Clang optimizes memcpy/memset calls which lead to unaligned access 792TEST(AddressSanitizer, DISABLED_MemIntrinsicUnalignedAccessTest) { 793 int size = Ident(4096); 794 char *s = Ident((char*)malloc(size)); 795 EXPECT_DEATH(memset(s + size - 1, 0, 2), RightOOBWriteMessage(0)); 796 free(s); 797} 798 799// TODO(samsonov): Add a test with malloc(0) 800// TODO(samsonov): Add tests for str* and mem* functions. 801 802NOINLINE static int LargeFunction(bool do_bad_access) { 803 int *x = new int[100]; 804 x[0]++; 805 x[1]++; 806 x[2]++; 807 x[3]++; 808 x[4]++; 809 x[5]++; 810 x[6]++; 811 x[7]++; 812 x[8]++; 813 x[9]++; 814 815 x[do_bad_access ? 100 : 0]++; int res = __LINE__; 816 817 x[10]++; 818 x[11]++; 819 x[12]++; 820 x[13]++; 821 x[14]++; 822 x[15]++; 823 x[16]++; 824 x[17]++; 825 x[18]++; 826 x[19]++; 827 828 delete x; 829 return res; 830} 831 832// Test the we have correct debug info for the failing instruction. 833// This test requires the in-process symbolizer to be enabled by default. 834TEST(AddressSanitizer, DISABLED_LargeFunctionSymbolizeTest) { 835 int failing_line = LargeFunction(false); 836 char expected_warning[128]; 837 sprintf(expected_warning, "LargeFunction.*asan_test.*:%d", failing_line); 838 EXPECT_DEATH(LargeFunction(true), expected_warning); 839} 840 841// Check that we unwind and symbolize correctly. 842TEST(AddressSanitizer, DISABLED_MallocFreeUnwindAndSymbolizeTest) { 843 int *a = (int*)malloc_aaa(sizeof(int)); 844 *a = 1; 845 free_aaa(a); 846 EXPECT_DEATH(*a = 1, "free_ccc.*free_bbb.*free_aaa.*" 847 "malloc_fff.*malloc_eee.*malloc_ddd"); 848} 849 850static bool TryToSetThreadName(const char *name) { 851#if defined(__linux__) && defined(PR_SET_NAME) 852 return 0 == prctl(PR_SET_NAME, (unsigned long)name, 0, 0, 0); 853#else 854 return false; 855#endif 856} 857 858void *ThreadedTestAlloc(void *a) { 859 EXPECT_EQ(true, TryToSetThreadName("AllocThr")); 860 int **p = (int**)a; 861 *p = new int; 862 return 0; 863} 864 865void *ThreadedTestFree(void *a) { 866 EXPECT_EQ(true, TryToSetThreadName("FreeThr")); 867 int **p = (int**)a; 868 delete *p; 869 return 0; 870} 871 872void *ThreadedTestUse(void *a) { 873 EXPECT_EQ(true, TryToSetThreadName("UseThr")); 874 int **p = (int**)a; 875 **p = 1; 876 return 0; 877} 878 879void ThreadedTestSpawn() { 880 pthread_t t; 881 int *x; 882 PTHREAD_CREATE(&t, 0, ThreadedTestAlloc, &x); 883 PTHREAD_JOIN(t, 0); 884 PTHREAD_CREATE(&t, 0, ThreadedTestFree, &x); 885 PTHREAD_JOIN(t, 0); 886 PTHREAD_CREATE(&t, 0, ThreadedTestUse, &x); 887 PTHREAD_JOIN(t, 0); 888} 889 890TEST(AddressSanitizer, ThreadedTest) { 891 EXPECT_DEATH(ThreadedTestSpawn(), 892 ASAN_PCRE_DOTALL 893 "Thread T.*created" 894 ".*Thread T.*created" 895 ".*Thread T.*created"); 896} 897 898void *ThreadedTestFunc(void *unused) { 899 // Check if prctl(PR_SET_NAME) is supported. Return if not. 900 if (!TryToSetThreadName("TestFunc")) 901 return 0; 902 EXPECT_DEATH(ThreadedTestSpawn(), 903 ASAN_PCRE_DOTALL 904 "WRITE .*thread T. .UseThr." 905 ".*freed by thread T. .FreeThr. here:" 906 ".*previously allocated by thread T. .AllocThr. here:" 907 ".*Thread T. .UseThr. created by T.*TestFunc" 908 ".*Thread T. .FreeThr. created by T" 909 ".*Thread T. .AllocThr. created by T" 910 ""); 911 return 0; 912} 913 914TEST(AddressSanitizer, ThreadNamesTest) { 915 // Run ThreadedTestFunc in a separate thread because it tries to set a 916 // thread name and we don't want to change the main thread's name. 917 pthread_t t; 918 PTHREAD_CREATE(&t, 0, ThreadedTestFunc, 0); 919 PTHREAD_JOIN(t, 0); 920} 921 922#if ASAN_NEEDS_SEGV 923TEST(AddressSanitizer, ShadowGapTest) { 924#if SANITIZER_WORDSIZE == 32 925 char *addr = (char*)0x22000000; 926#else 927 char *addr = (char*)0x0000100000080000; 928#endif 929 EXPECT_DEATH(*addr = 1, "AddressSanitizer: SEGV on unknown"); 930} 931#endif // ASAN_NEEDS_SEGV 932 933extern "C" { 934NOINLINE static void UseThenFreeThenUse() { 935 char *x = Ident((char*)malloc(8)); 936 *x = 1; 937 free_aaa(x); 938 *x = 2; 939} 940} 941 942TEST(AddressSanitizer, UseThenFreeThenUseTest) { 943 EXPECT_DEATH(UseThenFreeThenUse(), "freed by thread"); 944} 945 946TEST(AddressSanitizer, StrDupTest) { 947 free(strdup(Ident("123"))); 948} 949 950// Currently we create and poison redzone at right of global variables. 951static char static110[110]; 952const char ConstGlob[7] = {1, 2, 3, 4, 5, 6, 7}; 953static const char StaticConstGlob[3] = {9, 8, 7}; 954 955TEST(AddressSanitizer, GlobalTest) { 956 static char func_static15[15]; 957 958 static char fs1[10]; 959 static char fs2[10]; 960 static char fs3[10]; 961 962 glob5[Ident(0)] = 0; 963 glob5[Ident(1)] = 0; 964 glob5[Ident(2)] = 0; 965 glob5[Ident(3)] = 0; 966 glob5[Ident(4)] = 0; 967 968 EXPECT_DEATH(glob5[Ident(5)] = 0, 969 "0 bytes to the right of global variable.*glob5.* size 5"); 970 EXPECT_DEATH(glob5[Ident(5+6)] = 0, 971 "6 bytes to the right of global variable.*glob5.* size 5"); 972 Ident(static110); // avoid optimizations 973 static110[Ident(0)] = 0; 974 static110[Ident(109)] = 0; 975 EXPECT_DEATH(static110[Ident(110)] = 0, 976 "0 bytes to the right of global variable"); 977 EXPECT_DEATH(static110[Ident(110+7)] = 0, 978 "7 bytes to the right of global variable"); 979 980 Ident(func_static15); // avoid optimizations 981 func_static15[Ident(0)] = 0; 982 EXPECT_DEATH(func_static15[Ident(15)] = 0, 983 "0 bytes to the right of global variable"); 984 EXPECT_DEATH(func_static15[Ident(15 + 9)] = 0, 985 "9 bytes to the right of global variable"); 986 987 Ident(fs1); 988 Ident(fs2); 989 Ident(fs3); 990 991 // We don't create left redzones, so this is not 100% guaranteed to fail. 992 // But most likely will. 993 EXPECT_DEATH(fs2[Ident(-1)] = 0, "is located.*of global variable"); 994 995 EXPECT_DEATH(Ident(Ident(ConstGlob)[8]), 996 "is located 1 bytes to the right of .*ConstGlob"); 997 EXPECT_DEATH(Ident(Ident(StaticConstGlob)[5]), 998 "is located 2 bytes to the right of .*StaticConstGlob"); 999 1000 // call stuff from another file. 1001 GlobalsTest(0); 1002} 1003 1004TEST(AddressSanitizer, GlobalStringConstTest) { 1005 static const char *zoo = "FOOBAR123"; 1006 const char *p = Ident(zoo); 1007 EXPECT_DEATH(Ident(p[15]), "is ascii string 'FOOBAR123'"); 1008} 1009 1010TEST(AddressSanitizer, FileNameInGlobalReportTest) { 1011 static char zoo[10]; 1012 const char *p = Ident(zoo); 1013 // The file name should be present in the report. 1014 EXPECT_DEATH(Ident(p[15]), "zoo.*asan_test."); 1015} 1016 1017int *ReturnsPointerToALocalObject() { 1018 int a = 0; 1019 return Ident(&a); 1020} 1021 1022#if ASAN_UAR == 1 1023TEST(AddressSanitizer, LocalReferenceReturnTest) { 1024 int *(*f)() = Ident(ReturnsPointerToALocalObject); 1025 int *p = f(); 1026 // Call 'f' a few more times, 'p' should still be poisoned. 1027 for (int i = 0; i < 32; i++) 1028 f(); 1029 EXPECT_DEATH(*p = 1, "AddressSanitizer: stack-use-after-return"); 1030 EXPECT_DEATH(*p = 1, "is located.*in frame .*ReturnsPointerToALocal"); 1031} 1032#endif 1033 1034template <int kSize> 1035NOINLINE static void FuncWithStack() { 1036 char x[kSize]; 1037 Ident(x)[0] = 0; 1038 Ident(x)[kSize-1] = 0; 1039} 1040 1041static void LotsOfStackReuse() { 1042 int LargeStack[10000]; 1043 Ident(LargeStack)[0] = 0; 1044 for (int i = 0; i < 10000; i++) { 1045 FuncWithStack<128 * 1>(); 1046 FuncWithStack<128 * 2>(); 1047 FuncWithStack<128 * 4>(); 1048 FuncWithStack<128 * 8>(); 1049 FuncWithStack<128 * 16>(); 1050 FuncWithStack<128 * 32>(); 1051 FuncWithStack<128 * 64>(); 1052 FuncWithStack<128 * 128>(); 1053 FuncWithStack<128 * 256>(); 1054 FuncWithStack<128 * 512>(); 1055 Ident(LargeStack)[0] = 0; 1056 } 1057} 1058 1059TEST(AddressSanitizer, StressStackReuseTest) { 1060 LotsOfStackReuse(); 1061} 1062 1063TEST(AddressSanitizer, ThreadedStressStackReuseTest) { 1064 const int kNumThreads = 20; 1065 pthread_t t[kNumThreads]; 1066 for (int i = 0; i < kNumThreads; i++) { 1067 PTHREAD_CREATE(&t[i], 0, (void* (*)(void *x))LotsOfStackReuse, 0); 1068 } 1069 for (int i = 0; i < kNumThreads; i++) { 1070 PTHREAD_JOIN(t[i], 0); 1071 } 1072} 1073 1074static void *PthreadExit(void *a) { 1075 pthread_exit(0); 1076 return 0; 1077} 1078 1079TEST(AddressSanitizer, PthreadExitTest) { 1080 pthread_t t; 1081 for (int i = 0; i < 1000; i++) { 1082 PTHREAD_CREATE(&t, 0, PthreadExit, 0); 1083 PTHREAD_JOIN(t, 0); 1084 } 1085} 1086 1087#ifdef __EXCEPTIONS 1088NOINLINE static void StackReuseAndException() { 1089 int large_stack[1000]; 1090 Ident(large_stack); 1091 ASAN_THROW(1); 1092} 1093 1094// TODO(kcc): support exceptions with use-after-return. 1095TEST(AddressSanitizer, DISABLED_StressStackReuseAndExceptionsTest) { 1096 for (int i = 0; i < 10000; i++) { 1097 try { 1098 StackReuseAndException(); 1099 } catch(...) { 1100 } 1101 } 1102} 1103#endif 1104 1105TEST(AddressSanitizer, MlockTest) { 1106 EXPECT_EQ(0, mlockall(MCL_CURRENT)); 1107 EXPECT_EQ(0, mlock((void*)0x12345, 0x5678)); 1108 EXPECT_EQ(0, munlockall()); 1109 EXPECT_EQ(0, munlock((void*)0x987, 0x654)); 1110} 1111 1112struct LargeStruct { 1113 int foo[100]; 1114}; 1115 1116// Test for bug http://llvm.org/bugs/show_bug.cgi?id=11763. 1117// Struct copy should not cause asan warning even if lhs == rhs. 1118TEST(AddressSanitizer, LargeStructCopyTest) { 1119 LargeStruct a; 1120 *Ident(&a) = *Ident(&a); 1121} 1122 1123ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS 1124static void NoAddressSafety() { 1125 char *foo = new char[10]; 1126 Ident(foo)[10] = 0; 1127 delete [] foo; 1128} 1129 1130TEST(AddressSanitizer, AttributeNoAddressSafetyTest) { 1131 Ident(NoAddressSafety)(); 1132} 1133 1134// It doesn't work on Android, as calls to new/delete go through malloc/free. 1135#if !defined(ANDROID) && !defined(__ANDROID__) 1136#if 0 1137static string MismatchStr(const string &str) { 1138 return string("AddressSanitizer: alloc-dealloc-mismatch \\(") + str; 1139} 1140#endif 1141 1142TEST(AddressSanitizer, AllocDeallocMismatch) { 1143 free(Ident(new int)); 1144#if 0 1145 EXPECT_DEATH(free(Ident(new int)), 1146 MismatchStr("operator new vs free")); 1147 EXPECT_DEATH(free(Ident(new int[2])), 1148 MismatchStr("operator new \\[\\] vs free")); 1149 EXPECT_DEATH(delete (Ident(new int[2])), 1150 MismatchStr("operator new \\[\\] vs operator delete")); 1151 EXPECT_DEATH(delete (Ident((int*)malloc(2 * sizeof(int)))), 1152 MismatchStr("malloc vs operator delete")); 1153 EXPECT_DEATH(delete [] (Ident(new int)), 1154 MismatchStr("operator new vs operator delete \\[\\]")); 1155 EXPECT_DEATH(delete [] (Ident((int*)malloc(2 * sizeof(int)))), 1156 MismatchStr("malloc vs operator delete \\[\\]")); 1157#endif 1158} 1159#endif 1160 1161// ------------------ demo tests; run each one-by-one ------------- 1162// e.g. --gtest_filter=*DemoOOBLeftHigh --gtest_also_run_disabled_tests 1163TEST(AddressSanitizer, DISABLED_DemoThreadedTest) { 1164 ThreadedTestSpawn(); 1165} 1166 1167void *SimpleBugOnSTack(void *x = 0) { 1168 char a[20]; 1169 Ident(a)[20] = 0; 1170 return 0; 1171} 1172 1173TEST(AddressSanitizer, DISABLED_DemoStackTest) { 1174 SimpleBugOnSTack(); 1175} 1176 1177TEST(AddressSanitizer, DISABLED_DemoThreadStackTest) { 1178 pthread_t t; 1179 PTHREAD_CREATE(&t, 0, SimpleBugOnSTack, 0); 1180 PTHREAD_JOIN(t, 0); 1181} 1182 1183TEST(AddressSanitizer, DISABLED_DemoUAFLowIn) { 1184 uaf_test<U1>(10, 0); 1185} 1186TEST(AddressSanitizer, DISABLED_DemoUAFLowLeft) { 1187 uaf_test<U1>(10, -2); 1188} 1189TEST(AddressSanitizer, DISABLED_DemoUAFLowRight) { 1190 uaf_test<U1>(10, 10); 1191} 1192 1193TEST(AddressSanitizer, DISABLED_DemoUAFHigh) { 1194 uaf_test<U1>(kLargeMalloc, 0); 1195} 1196 1197TEST(AddressSanitizer, DISABLED_DemoOOM) { 1198 size_t size = SANITIZER_WORDSIZE == 64 ? (size_t)(1ULL << 40) : (0xf0000000); 1199 printf("%p\n", malloc(size)); 1200} 1201 1202TEST(AddressSanitizer, DISABLED_DemoDoubleFreeTest) { 1203 DoubleFree(); 1204} 1205 1206TEST(AddressSanitizer, DISABLED_DemoNullDerefTest) { 1207 int *a = 0; 1208 Ident(a)[10] = 0; 1209} 1210 1211TEST(AddressSanitizer, DISABLED_DemoFunctionStaticTest) { 1212 static char a[100]; 1213 static char b[100]; 1214 static char c[100]; 1215 Ident(a); 1216 Ident(b); 1217 Ident(c); 1218 Ident(a)[5] = 0; 1219 Ident(b)[105] = 0; 1220 Ident(a)[5] = 0; 1221} 1222 1223TEST(AddressSanitizer, DISABLED_DemoTooMuchMemoryTest) { 1224 const size_t kAllocSize = (1 << 28) - 1024; 1225 size_t total_size = 0; 1226 while (true) { 1227 char *x = (char*)malloc(kAllocSize); 1228 memset(x, 0, kAllocSize); 1229 total_size += kAllocSize; 1230 fprintf(stderr, "total: %ldM %p\n", (long)total_size >> 20, x); 1231 } 1232} 1233 1234// http://code.google.com/p/address-sanitizer/issues/detail?id=66 1235TEST(AddressSanitizer, BufferOverflowAfterManyFrees) { 1236 for (int i = 0; i < 1000000; i++) { 1237 delete [] (Ident(new char [8644])); 1238 } 1239 char *x = new char[8192]; 1240 EXPECT_DEATH(x[Ident(8192)] = 0, "AddressSanitizer: heap-buffer-overflow"); 1241 delete [] Ident(x); 1242} 1243 1244 1245// Test that instrumentation of stack allocations takes into account 1246// AllocSize of a type, and not its StoreSize (16 vs 10 bytes for long double). 1247// See http://llvm.org/bugs/show_bug.cgi?id=12047 for more details. 1248TEST(AddressSanitizer, LongDoubleNegativeTest) { 1249 long double a, b; 1250 static long double c; 1251 memcpy(Ident(&a), Ident(&b), sizeof(long double)); 1252 memcpy(Ident(&c), Ident(&b), sizeof(long double)); 1253} 1254