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