1 //===-- asan_test.cc ------------*- C++ -*-===// 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 <stdio.h> 14 #include <signal.h> 15 #include <stdlib.h> 16 #include <string.h> 17 #include <strings.h> 18 #include <pthread.h> 19 #include <stdint.h> 20 #include <setjmp.h> 21 #include <assert.h> 22 23 #if defined(__i386__) || defined(__x86_64__) 24 #include <emmintrin.h> 25 #endif 26 27 #include "asan_test_config.h" 28 #include "asan_test_utils.h" 29 30 #ifndef __APPLE__ 31 #include <malloc.h> 32 #else 33 #include <AvailabilityMacros.h> // For MAC_OS_X_VERSION_* 34 #include <CoreFoundation/CFString.h> 35 #endif // __APPLE__ 36 37 #ifdef __APPLE__ 38 static bool APPLE = true; 39 #else 40 static bool APPLE = false; 41 #endif 42 43 #if ASAN_HAS_EXCEPTIONS 44 # define ASAN_THROW(x) throw (x) 45 #else 46 # define ASAN_THROW(x) 47 #endif 48 49 #include <sys/mman.h> 50 51 typedef uint8_t U1; 52 typedef uint16_t U2; 53 typedef uint32_t U4; 54 typedef uint64_t U8; 55 56 static const char *progname; 57 static const int kPageSize = 4096; 58 59 // Simple stand-alone pseudorandom number generator. 60 // Current algorithm is ANSI C linear congruential PRNG. 61 static inline uint32_t my_rand(uint32_t* state) { 62 return (*state = *state * 1103515245 + 12345) >> 16; 63 } 64 65 static uint32_t global_seed = 0; 66 67 const size_t kLargeMalloc = 1 << 24; 68 69 template<typename T> 70 NOINLINE void asan_write(T *a) { 71 *a = 0; 72 } 73 74 NOINLINE void asan_write_sized_aligned(uint8_t *p, size_t size) { 75 EXPECT_EQ(0, ((uintptr_t)p % size)); 76 if (size == 1) asan_write((uint8_t*)p); 77 else if (size == 2) asan_write((uint16_t*)p); 78 else if (size == 4) asan_write((uint32_t*)p); 79 else if (size == 8) asan_write((uint64_t*)p); 80 } 81 82 NOINLINE void *malloc_fff(size_t size) { 83 void *res = malloc/**/(size); break_optimization(0); return res;} 84 NOINLINE void *malloc_eee(size_t size) { 85 void *res = malloc_fff(size); break_optimization(0); return res;} 86 NOINLINE void *malloc_ddd(size_t size) { 87 void *res = malloc_eee(size); break_optimization(0); return res;} 88 NOINLINE void *malloc_ccc(size_t size) { 89 void *res = malloc_ddd(size); break_optimization(0); return res;} 90 NOINLINE void *malloc_bbb(size_t size) { 91 void *res = malloc_ccc(size); break_optimization(0); return res;} 92 NOINLINE void *malloc_aaa(size_t size) { 93 void *res = malloc_bbb(size); break_optimization(0); return res;} 94 95 #ifndef __APPLE__ 96 NOINLINE void *memalign_fff(size_t alignment, size_t size) { 97 void *res = memalign/**/(alignment, size); break_optimization(0); return res;} 98 NOINLINE void *memalign_eee(size_t alignment, size_t size) { 99 void *res = memalign_fff(alignment, size); break_optimization(0); return res;} 100 NOINLINE void *memalign_ddd(size_t alignment, size_t size) { 101 void *res = memalign_eee(alignment, size); break_optimization(0); return res;} 102 NOINLINE void *memalign_ccc(size_t alignment, size_t size) { 103 void *res = memalign_ddd(alignment, size); break_optimization(0); return res;} 104 NOINLINE void *memalign_bbb(size_t alignment, size_t size) { 105 void *res = memalign_ccc(alignment, size); break_optimization(0); return res;} 106 NOINLINE void *memalign_aaa(size_t alignment, size_t size) { 107 void *res = memalign_bbb(alignment, size); break_optimization(0); return res;} 108 #endif // __APPLE__ 109 110 111 NOINLINE void free_ccc(void *p) { free(p); break_optimization(0);} 112 NOINLINE void free_bbb(void *p) { free_ccc(p); break_optimization(0);} 113 NOINLINE void free_aaa(void *p) { free_bbb(p); break_optimization(0);} 114 115 template<typename T> 116 NOINLINE void oob_test(int size, int off) { 117 char *p = (char*)malloc_aaa(size); 118 // fprintf(stderr, "writing %d byte(s) into [%p,%p) with offset %d\n", 119 // sizeof(T), p, p + size, off); 120 asan_write((T*)(p + off)); 121 free_aaa(p); 122 } 123 124 125 template<typename T> 126 NOINLINE void uaf_test(int size, int off) { 127 char *p = (char *)malloc_aaa(size); 128 free_aaa(p); 129 for (int i = 1; i < 100; i++) 130 free_aaa(malloc_aaa(i)); 131 fprintf(stderr, "writing %ld byte(s) at %p with offset %d\n", 132 (long)sizeof(T), p, off); 133 asan_write((T*)(p + off)); 134 } 135 136 TEST(AddressSanitizer, HasFeatureAddressSanitizerTest) { 137 #if defined(__has_feature) && __has_feature(address_sanitizer) 138 bool asan = 1; 139 #else 140 bool asan = 0; 141 #endif 142 EXPECT_EQ(true, asan); 143 } 144 145 TEST(AddressSanitizer, SimpleDeathTest) { 146 EXPECT_DEATH(exit(1), ""); 147 } 148 149 TEST(AddressSanitizer, VariousMallocsTest) { 150 // fprintf(stderr, "malloc:\n"); 151 int *a = (int*)malloc(100 * sizeof(int)); 152 a[50] = 0; 153 free(a); 154 155 // fprintf(stderr, "realloc:\n"); 156 int *r = (int*)malloc(10); 157 r = (int*)realloc(r, 2000 * sizeof(int)); 158 r[1000] = 0; 159 free(r); 160 161 // fprintf(stderr, "operator new []\n"); 162 int *b = new int[100]; 163 b[50] = 0; 164 delete [] b; 165 166 // fprintf(stderr, "operator new\n"); 167 int *c = new int; 168 *c = 0; 169 delete c; 170 171 #if !defined(__APPLE__) && !defined(ANDROID) 172 // fprintf(stderr, "posix_memalign\n"); 173 int *pm; 174 int pm_res = posix_memalign((void**)&pm, kPageSize, kPageSize); 175 EXPECT_EQ(0, pm_res); 176 free(pm); 177 #endif 178 179 #if !defined(__APPLE__) 180 int *ma = (int*)memalign(kPageSize, kPageSize); 181 EXPECT_EQ(0, (uintptr_t)ma % kPageSize); 182 ma[123] = 0; 183 free(ma); 184 #endif // __APPLE__ 185 } 186 187 TEST(AddressSanitizer, CallocTest) { 188 int *a = (int*)calloc(100, sizeof(int)); 189 EXPECT_EQ(0, a[10]); 190 free(a); 191 } 192 193 TEST(AddressSanitizer, VallocTest) { 194 void *a = valloc(100); 195 EXPECT_EQ(0, (uintptr_t)a % kPageSize); 196 free(a); 197 } 198 199 #ifndef __APPLE__ 200 TEST(AddressSanitizer, PvallocTest) { 201 char *a = (char*)pvalloc(kPageSize + 100); 202 EXPECT_EQ(0, (uintptr_t)a % kPageSize); 203 a[kPageSize + 101] = 1; // we should not report an error here. 204 free(a); 205 206 a = (char*)pvalloc(0); // pvalloc(0) should allocate at least one page. 207 EXPECT_EQ(0, (uintptr_t)a % kPageSize); 208 a[101] = 1; // we should not report an error here. 209 free(a); 210 } 211 #endif // __APPLE__ 212 213 void *TSDWorker(void *test_key) { 214 if (test_key) { 215 pthread_setspecific(*(pthread_key_t*)test_key, (void*)0xfeedface); 216 } 217 return NULL; 218 } 219 220 void TSDDestructor(void *tsd) { 221 // Spawning a thread will check that the current thread id is not -1. 222 pthread_t th; 223 pthread_create(&th, NULL, TSDWorker, NULL); 224 pthread_join(th, NULL); 225 } 226 227 // This tests triggers the thread-specific data destruction fiasco which occurs 228 // if we don't manage the TSD destructors ourselves. We create a new pthread 229 // key with a non-NULL destructor which is likely to be put after the destructor 230 // of AsanThread in the list of destructors. 231 // In this case the TSD for AsanThread will be destroyed before TSDDestructor 232 // is called for the child thread, and a CHECK will fail when we call 233 // pthread_create() to spawn the grandchild. 234 TEST(AddressSanitizer, DISABLED_TSDTest) { 235 pthread_t th; 236 pthread_key_t test_key; 237 pthread_key_create(&test_key, TSDDestructor); 238 pthread_create(&th, NULL, TSDWorker, &test_key); 239 pthread_join(th, NULL); 240 pthread_key_delete(test_key); 241 } 242 243 template<typename T> 244 void OOBTest() { 245 char expected_str[100]; 246 for (int size = sizeof(T); size < 20; size += 5) { 247 for (int i = -5; i < 0; i++) { 248 const char *str = 249 "is located.*%d byte.*to the left"; 250 sprintf(expected_str, str, abs(i)); 251 EXPECT_DEATH(oob_test<T>(size, i), expected_str); 252 } 253 254 for (int i = 0; i < size - sizeof(T) + 1; i++) 255 oob_test<T>(size, i); 256 257 for (int i = size - sizeof(T) + 1; i <= size + 3 * sizeof(T); i++) { 258 const char *str = 259 "is located.*%d byte.*to the right"; 260 int off = i >= size ? (i - size) : 0; 261 // we don't catch unaligned partially OOB accesses. 262 if (i % sizeof(T)) continue; 263 sprintf(expected_str, str, off); 264 EXPECT_DEATH(oob_test<T>(size, i), expected_str); 265 } 266 } 267 268 EXPECT_DEATH(oob_test<T>(kLargeMalloc, -1), 269 "is located.*1 byte.*to the left"); 270 EXPECT_DEATH(oob_test<T>(kLargeMalloc, kLargeMalloc), 271 "is located.*0 byte.*to the right"); 272 } 273 274 // TODO(glider): the following tests are EXTREMELY slow on Darwin: 275 // AddressSanitizer.OOB_char (125503 ms) 276 // AddressSanitizer.OOB_int (126890 ms) 277 // AddressSanitizer.OOBRightTest (315605 ms) 278 // AddressSanitizer.SimpleStackTest (366559 ms) 279 280 TEST(AddressSanitizer, OOB_char) { 281 OOBTest<U1>(); 282 } 283 284 TEST(AddressSanitizer, OOB_int) { 285 OOBTest<U4>(); 286 } 287 288 TEST(AddressSanitizer, OOBRightTest) { 289 for (size_t access_size = 1; access_size <= 8; access_size *= 2) { 290 for (size_t alloc_size = 1; alloc_size <= 8; alloc_size++) { 291 for (size_t offset = 0; offset <= 8; offset += access_size) { 292 void *p = malloc(alloc_size); 293 // allocated: [p, p + alloc_size) 294 // accessed: [p + offset, p + offset + access_size) 295 uint8_t *addr = (uint8_t*)p + offset; 296 if (offset + access_size <= alloc_size) { 297 asan_write_sized_aligned(addr, access_size); 298 } else { 299 int outside_bytes = offset > alloc_size ? (offset - alloc_size) : 0; 300 const char *str = 301 "is located.%d *byte.*to the right"; 302 char expected_str[100]; 303 sprintf(expected_str, str, outside_bytes); 304 EXPECT_DEATH(asan_write_sized_aligned(addr, access_size), 305 expected_str); 306 } 307 free(p); 308 } 309 } 310 } 311 } 312 313 TEST(AddressSanitizer, UAF_char) { 314 const char *uaf_string = "AddressSanitizer.*heap-use-after-free"; 315 EXPECT_DEATH(uaf_test<U1>(1, 0), uaf_string); 316 EXPECT_DEATH(uaf_test<U1>(10, 0), uaf_string); 317 EXPECT_DEATH(uaf_test<U1>(10, 10), uaf_string); 318 EXPECT_DEATH(uaf_test<U1>(kLargeMalloc, 0), uaf_string); 319 EXPECT_DEATH(uaf_test<U1>(kLargeMalloc, kLargeMalloc / 2), uaf_string); 320 } 321 322 #if ASAN_HAS_BLACKLIST 323 TEST(AddressSanitizer, IgnoreTest) { 324 int *x = Ident(new int); 325 delete Ident(x); 326 *x = 0; 327 } 328 #endif // ASAN_HAS_BLACKLIST 329 330 struct StructWithBitField { 331 int bf1:1; 332 int bf2:1; 333 int bf3:1; 334 int bf4:29; 335 }; 336 337 TEST(AddressSanitizer, BitFieldPositiveTest) { 338 StructWithBitField *x = new StructWithBitField; 339 delete Ident(x); 340 EXPECT_DEATH(x->bf1 = 0, "use-after-free"); 341 EXPECT_DEATH(x->bf2 = 0, "use-after-free"); 342 EXPECT_DEATH(x->bf3 = 0, "use-after-free"); 343 EXPECT_DEATH(x->bf4 = 0, "use-after-free"); 344 }; 345 346 struct StructWithBitFields_8_24 { 347 int a:8; 348 int b:24; 349 }; 350 351 TEST(AddressSanitizer, BitFieldNegativeTest) { 352 StructWithBitFields_8_24 *x = Ident(new StructWithBitFields_8_24); 353 x->a = 0; 354 x->b = 0; 355 delete Ident(x); 356 } 357 358 TEST(AddressSanitizer, OutOfMemoryTest) { 359 size_t size = __WORDSIZE == 64 ? (size_t)(1ULL << 48) : (0xf0000000); 360 EXPECT_EQ(0, realloc(0, size)); 361 EXPECT_EQ(0, realloc(0, ~Ident(0))); 362 EXPECT_EQ(0, malloc(size)); 363 EXPECT_EQ(0, malloc(~Ident(0))); 364 EXPECT_EQ(0, calloc(1, size)); 365 EXPECT_EQ(0, calloc(1, ~Ident(0))); 366 } 367 368 #if ASAN_NEEDS_SEGV 369 TEST(AddressSanitizer, WildAddressTest) { 370 char *c = (char*)0x123; 371 EXPECT_DEATH(*c = 0, "AddressSanitizer crashed on unknown address"); 372 } 373 #endif 374 375 static void MallocStress(size_t n) { 376 uint32_t seed = my_rand(&global_seed); 377 for (size_t iter = 0; iter < 10; iter++) { 378 vector<void *> vec; 379 for (size_t i = 0; i < n; i++) { 380 if ((i % 3) == 0) { 381 if (vec.empty()) continue; 382 size_t idx = my_rand(&seed) % vec.size(); 383 void *ptr = vec[idx]; 384 vec[idx] = vec.back(); 385 vec.pop_back(); 386 free_aaa(ptr); 387 } else { 388 size_t size = my_rand(&seed) % 1000 + 1; 389 #ifndef __APPLE__ 390 size_t alignment = 1 << (my_rand(&seed) % 7 + 3); 391 char *ptr = (char*)memalign_aaa(alignment, size); 392 #else 393 char *ptr = (char*) malloc_aaa(size); 394 #endif 395 vec.push_back(ptr); 396 ptr[0] = 0; 397 ptr[size-1] = 0; 398 ptr[size/2] = 0; 399 } 400 } 401 for (size_t i = 0; i < vec.size(); i++) 402 free_aaa(vec[i]); 403 } 404 } 405 406 TEST(AddressSanitizer, MallocStressTest) { 407 MallocStress((ASAN_LOW_MEMORY) ? 20000 : 200000); 408 } 409 410 static void TestLargeMalloc(size_t size) { 411 char buff[1024]; 412 sprintf(buff, "is located 1 bytes to the left of %lu-byte", (long)size); 413 EXPECT_DEATH(Ident((char*)malloc(size))[-1] = 0, buff); 414 } 415 416 TEST(AddressSanitizer, LargeMallocTest) { 417 for (int i = 113; i < (1 << 28); i = i * 2 + 13) { 418 TestLargeMalloc(i); 419 } 420 } 421 422 #if ASAN_LOW_MEMORY != 1 423 TEST(AddressSanitizer, HugeMallocTest) { 424 #ifdef __APPLE__ 425 // It was empirically found out that 1215 megabytes is the maximum amount of 426 // memory available to the process under AddressSanitizer on Darwin. 427 // (the libSystem malloc() allows allocating up to 2300 megabytes without 428 // ASan). 429 size_t n_megs = __WORDSIZE == 32 ? 1200 : 4100; 430 #else 431 size_t n_megs = __WORDSIZE == 32 ? 2600 : 4100; 432 #endif 433 TestLargeMalloc(n_megs << 20); 434 } 435 #endif 436 437 TEST(AddressSanitizer, ThreadedMallocStressTest) { 438 const int kNumThreads = 4; 439 const int kNumIterations = (ASAN_LOW_MEMORY) ? 10000 : 100000; 440 pthread_t t[kNumThreads]; 441 for (int i = 0; i < kNumThreads; i++) { 442 pthread_create(&t[i], 0, (void* (*)(void *x))MallocStress, 443 (void*)kNumIterations); 444 } 445 for (int i = 0; i < kNumThreads; i++) { 446 pthread_join(t[i], 0); 447 } 448 } 449 450 void *ManyThreadsWorker(void *a) { 451 for (int iter = 0; iter < 100; iter++) { 452 for (size_t size = 100; size < 2000; size *= 2) { 453 free(Ident(malloc(size))); 454 } 455 } 456 return 0; 457 } 458 459 TEST(AddressSanitizer, ManyThreadsTest) { 460 const size_t kNumThreads = __WORDSIZE == 32 ? 30 : 1000; 461 pthread_t t[kNumThreads]; 462 for (size_t i = 0; i < kNumThreads; i++) { 463 pthread_create(&t[i], 0, (void* (*)(void *x))ManyThreadsWorker, (void*)i); 464 } 465 for (size_t i = 0; i < kNumThreads; i++) { 466 pthread_join(t[i], 0); 467 } 468 } 469 470 TEST(AddressSanitizer, ReallocTest) { 471 const int kMinElem = 5; 472 int *ptr = (int*)malloc(sizeof(int) * kMinElem); 473 ptr[3] = 3; 474 for (int i = 0; i < 10000; i++) { 475 ptr = (int*)realloc(ptr, 476 (my_rand(&global_seed) % 1000 + kMinElem) * sizeof(int)); 477 EXPECT_EQ(3, ptr[3]); 478 } 479 } 480 481 #ifndef __APPLE__ 482 static const char *kMallocUsableSizeErrorMsg = 483 "AddressSanitizer attempting to call malloc_usable_size()"; 484 485 TEST(AddressSanitizer, MallocUsableSizeTest) { 486 const size_t kArraySize = 100; 487 char *array = Ident((char*)malloc(kArraySize)); 488 int *int_ptr = Ident(new int); 489 EXPECT_EQ(0, malloc_usable_size(NULL)); 490 EXPECT_EQ(kArraySize, malloc_usable_size(array)); 491 EXPECT_EQ(sizeof(int), malloc_usable_size(int_ptr)); 492 EXPECT_DEATH(malloc_usable_size((void*)0x123), kMallocUsableSizeErrorMsg); 493 EXPECT_DEATH(malloc_usable_size(array + kArraySize / 2), 494 kMallocUsableSizeErrorMsg); 495 free(array); 496 EXPECT_DEATH(malloc_usable_size(array), kMallocUsableSizeErrorMsg); 497 } 498 #endif 499 500 void WrongFree() { 501 int *x = (int*)malloc(100 * sizeof(int)); 502 // Use the allocated memory, otherwise Clang will optimize it out. 503 Ident(x); 504 free(x + 1); 505 } 506 507 TEST(AddressSanitizer, WrongFreeTest) { 508 EXPECT_DEATH(WrongFree(), 509 "ERROR: AddressSanitizer attempting free.*not malloc"); 510 } 511 512 void DoubleFree() { 513 int *x = (int*)malloc(100 * sizeof(int)); 514 fprintf(stderr, "DoubleFree: x=%p\n", x); 515 free(x); 516 free(x); 517 fprintf(stderr, "should have failed in the second free(%p)\n", x); 518 abort(); 519 } 520 521 TEST(AddressSanitizer, DoubleFreeTest) { 522 EXPECT_DEATH(DoubleFree(), ASAN_PCRE_DOTALL 523 "ERROR: AddressSanitizer attempting double-free" 524 ".*is located 0 bytes inside of 400-byte region" 525 ".*freed by thread T0 here" 526 ".*previously allocated by thread T0 here"); 527 } 528 529 template<int kSize> 530 NOINLINE void SizedStackTest() { 531 char a[kSize]; 532 char *A = Ident((char*)&a); 533 for (size_t i = 0; i < kSize; i++) 534 A[i] = i; 535 EXPECT_DEATH(A[-1] = 0, ""); 536 EXPECT_DEATH(A[-20] = 0, ""); 537 EXPECT_DEATH(A[-31] = 0, ""); 538 EXPECT_DEATH(A[kSize] = 0, ""); 539 EXPECT_DEATH(A[kSize + 1] = 0, ""); 540 EXPECT_DEATH(A[kSize + 10] = 0, ""); 541 EXPECT_DEATH(A[kSize + 31] = 0, ""); 542 } 543 544 TEST(AddressSanitizer, SimpleStackTest) { 545 SizedStackTest<1>(); 546 SizedStackTest<2>(); 547 SizedStackTest<3>(); 548 SizedStackTest<4>(); 549 SizedStackTest<5>(); 550 SizedStackTest<6>(); 551 SizedStackTest<7>(); 552 SizedStackTest<16>(); 553 SizedStackTest<25>(); 554 SizedStackTest<34>(); 555 SizedStackTest<43>(); 556 SizedStackTest<51>(); 557 SizedStackTest<62>(); 558 SizedStackTest<64>(); 559 SizedStackTest<128>(); 560 } 561 562 TEST(AddressSanitizer, ManyStackObjectsTest) { 563 char XXX[10]; 564 char YYY[20]; 565 char ZZZ[30]; 566 Ident(XXX); 567 Ident(YYY); 568 EXPECT_DEATH(Ident(ZZZ)[-1] = 0, ASAN_PCRE_DOTALL "XXX.*YYY.*ZZZ"); 569 } 570 571 NOINLINE static void Frame0(int frame, char *a, char *b, char *c) { 572 char d[4] = {0}; 573 char *D = Ident(d); 574 switch (frame) { 575 case 3: a[5]++; break; 576 case 2: b[5]++; break; 577 case 1: c[5]++; break; 578 case 0: D[5]++; break; 579 } 580 } 581 NOINLINE static void Frame1(int frame, char *a, char *b) { 582 char c[4] = {0}; Frame0(frame, a, b, c); 583 break_optimization(0); 584 } 585 NOINLINE static void Frame2(int frame, char *a) { 586 char b[4] = {0}; Frame1(frame, a, b); 587 break_optimization(0); 588 } 589 NOINLINE static void Frame3(int frame) { 590 char a[4] = {0}; Frame2(frame, a); 591 break_optimization(0); 592 } 593 594 TEST(AddressSanitizer, GuiltyStackFrame0Test) { 595 EXPECT_DEATH(Frame3(0), "located .*in frame <.*Frame0"); 596 } 597 TEST(AddressSanitizer, GuiltyStackFrame1Test) { 598 EXPECT_DEATH(Frame3(1), "located .*in frame <.*Frame1"); 599 } 600 TEST(AddressSanitizer, GuiltyStackFrame2Test) { 601 EXPECT_DEATH(Frame3(2), "located .*in frame <.*Frame2"); 602 } 603 TEST(AddressSanitizer, GuiltyStackFrame3Test) { 604 EXPECT_DEATH(Frame3(3), "located .*in frame <.*Frame3"); 605 } 606 607 NOINLINE void LongJmpFunc1(jmp_buf buf) { 608 // create three red zones for these two stack objects. 609 int a; 610 int b; 611 612 int *A = Ident(&a); 613 int *B = Ident(&b); 614 *A = *B; 615 longjmp(buf, 1); 616 } 617 618 NOINLINE void UnderscopeLongJmpFunc1(jmp_buf buf) { 619 // create three red zones for these two stack objects. 620 int a; 621 int b; 622 623 int *A = Ident(&a); 624 int *B = Ident(&b); 625 *A = *B; 626 _longjmp(buf, 1); 627 } 628 629 NOINLINE void SigLongJmpFunc1(sigjmp_buf buf) { 630 // create three red zones for these two stack objects. 631 int a; 632 int b; 633 634 int *A = Ident(&a); 635 int *B = Ident(&b); 636 *A = *B; 637 siglongjmp(buf, 1); 638 } 639 640 641 NOINLINE void TouchStackFunc() { 642 int a[100]; // long array will intersect with redzones from LongJmpFunc1. 643 int *A = Ident(a); 644 for (int i = 0; i < 100; i++) 645 A[i] = i*i; 646 } 647 648 // Test that we handle longjmp and do not report fals positives on stack. 649 TEST(AddressSanitizer, LongJmpTest) { 650 static jmp_buf buf; 651 if (!setjmp(buf)) { 652 LongJmpFunc1(buf); 653 } else { 654 TouchStackFunc(); 655 } 656 } 657 658 TEST(AddressSanitizer, UnderscopeLongJmpTest) { 659 static jmp_buf buf; 660 if (!_setjmp(buf)) { 661 UnderscopeLongJmpFunc1(buf); 662 } else { 663 TouchStackFunc(); 664 } 665 } 666 667 TEST(AddressSanitizer, SigLongJmpTest) { 668 static sigjmp_buf buf; 669 if (!sigsetjmp(buf, 1)) { 670 SigLongJmpFunc1(buf); 671 } else { 672 TouchStackFunc(); 673 } 674 } 675 676 #ifdef __EXCEPTIONS 677 NOINLINE void ThrowFunc() { 678 // create three red zones for these two stack objects. 679 int a; 680 int b; 681 682 int *A = Ident(&a); 683 int *B = Ident(&b); 684 *A = *B; 685 ASAN_THROW(1); 686 } 687 688 TEST(AddressSanitizer, CxxExceptionTest) { 689 if (ASAN_UAR) return; 690 // TODO(kcc): this test crashes on 32-bit for some reason... 691 if (__WORDSIZE == 32) return; 692 try { 693 ThrowFunc(); 694 } catch(...) {} 695 TouchStackFunc(); 696 } 697 #endif 698 699 void *ThreadStackReuseFunc1(void *unused) { 700 // create three red zones for these two stack objects. 701 int a; 702 int b; 703 704 int *A = Ident(&a); 705 int *B = Ident(&b); 706 *A = *B; 707 pthread_exit(0); 708 return 0; 709 } 710 711 void *ThreadStackReuseFunc2(void *unused) { 712 TouchStackFunc(); 713 return 0; 714 } 715 716 TEST(AddressSanitizer, ThreadStackReuseTest) { 717 pthread_t t; 718 pthread_create(&t, 0, ThreadStackReuseFunc1, 0); 719 pthread_join(t, 0); 720 pthread_create(&t, 0, ThreadStackReuseFunc2, 0); 721 pthread_join(t, 0); 722 } 723 724 #if defined(__i386__) || defined(__x86_64__) 725 TEST(AddressSanitizer, Store128Test) { 726 char *a = Ident((char*)malloc(Ident(12))); 727 char *p = a; 728 if (((uintptr_t)a % 16) != 0) 729 p = a + 8; 730 assert(((uintptr_t)p % 16) == 0); 731 __m128i value_wide = _mm_set1_epi16(0x1234); 732 EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide), 733 "AddressSanitizer heap-buffer-overflow"); 734 EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide), 735 "WRITE of size 16"); 736 EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide), 737 "located 0 bytes to the right of 12-byte"); 738 free(a); 739 } 740 #endif 741 742 static string RightOOBErrorMessage(int oob_distance) { 743 assert(oob_distance >= 0); 744 char expected_str[100]; 745 sprintf(expected_str, "located %d bytes to the right", oob_distance); 746 return string(expected_str); 747 } 748 749 static string LeftOOBErrorMessage(int oob_distance) { 750 assert(oob_distance > 0); 751 char expected_str[100]; 752 sprintf(expected_str, "located %d bytes to the left", oob_distance); 753 return string(expected_str); 754 } 755 756 template<typename T> 757 void MemSetOOBTestTemplate(size_t length) { 758 if (length == 0) return; 759 size_t size = Ident(sizeof(T) * length); 760 T *array = Ident((T*)malloc(size)); 761 int element = Ident(42); 762 int zero = Ident(0); 763 // memset interval inside array 764 memset(array, element, size); 765 memset(array, element, size - 1); 766 memset(array + length - 1, element, sizeof(T)); 767 memset(array, element, 1); 768 769 // memset 0 bytes 770 memset(array - 10, element, zero); 771 memset(array - 1, element, zero); 772 memset(array, element, zero); 773 memset(array + length, 0, zero); 774 memset(array + length + 1, 0, zero); 775 776 // try to memset bytes to the right of array 777 EXPECT_DEATH(memset(array, 0, size + 1), 778 RightOOBErrorMessage(0)); 779 EXPECT_DEATH(memset((char*)(array + length) - 1, element, 6), 780 RightOOBErrorMessage(4)); 781 EXPECT_DEATH(memset(array + 1, element, size + sizeof(T)), 782 RightOOBErrorMessage(2 * sizeof(T) - 1)); 783 // whole interval is to the right 784 EXPECT_DEATH(memset(array + length + 1, 0, 10), 785 RightOOBErrorMessage(sizeof(T))); 786 787 // try to memset bytes to the left of array 788 EXPECT_DEATH(memset((char*)array - 1, element, size), 789 LeftOOBErrorMessage(1)); 790 EXPECT_DEATH(memset((char*)array - 5, 0, 6), 791 LeftOOBErrorMessage(5)); 792 EXPECT_DEATH(memset(array - 5, element, size + 5 * sizeof(T)), 793 LeftOOBErrorMessage(5 * sizeof(T))); 794 // whole interval is to the left 795 EXPECT_DEATH(memset(array - 2, 0, sizeof(T)), 796 LeftOOBErrorMessage(2 * sizeof(T))); 797 798 // try to memset bytes both to the left & to the right 799 EXPECT_DEATH(memset((char*)array - 2, element, size + 4), 800 LeftOOBErrorMessage(2)); 801 802 free(array); 803 } 804 805 TEST(AddressSanitizer, MemSetOOBTest) { 806 MemSetOOBTestTemplate<char>(100); 807 MemSetOOBTestTemplate<int>(5); 808 MemSetOOBTestTemplate<double>(256); 809 // We can test arrays of structres/classes here, but what for? 810 } 811 812 // Same test for memcpy and memmove functions 813 template <typename T, class M> 814 void MemTransferOOBTestTemplate(size_t length) { 815 if (length == 0) return; 816 size_t size = Ident(sizeof(T) * length); 817 T *src = Ident((T*)malloc(size)); 818 T *dest = Ident((T*)malloc(size)); 819 int zero = Ident(0); 820 821 // valid transfer of bytes between arrays 822 M::transfer(dest, src, size); 823 M::transfer(dest + 1, src, size - sizeof(T)); 824 M::transfer(dest, src + length - 1, sizeof(T)); 825 M::transfer(dest, src, 1); 826 827 // transfer zero bytes 828 M::transfer(dest - 1, src, 0); 829 M::transfer(dest + length, src, zero); 830 M::transfer(dest, src - 1, zero); 831 M::transfer(dest, src, zero); 832 833 // try to change mem to the right of dest 834 EXPECT_DEATH(M::transfer(dest + 1, src, size), 835 RightOOBErrorMessage(sizeof(T) - 1)); 836 EXPECT_DEATH(M::transfer((char*)(dest + length) - 1, src, 5), 837 RightOOBErrorMessage(3)); 838 839 // try to change mem to the left of dest 840 EXPECT_DEATH(M::transfer(dest - 2, src, size), 841 LeftOOBErrorMessage(2 * sizeof(T))); 842 EXPECT_DEATH(M::transfer((char*)dest - 3, src, 4), 843 LeftOOBErrorMessage(3)); 844 845 // try to access mem to the right of src 846 EXPECT_DEATH(M::transfer(dest, src + 2, size), 847 RightOOBErrorMessage(2 * sizeof(T) - 1)); 848 EXPECT_DEATH(M::transfer(dest, (char*)(src + length) - 3, 6), 849 RightOOBErrorMessage(2)); 850 851 // try to access mem to the left of src 852 EXPECT_DEATH(M::transfer(dest, src - 1, size), 853 LeftOOBErrorMessage(sizeof(T))); 854 EXPECT_DEATH(M::transfer(dest, (char*)src - 6, 7), 855 LeftOOBErrorMessage(6)); 856 857 // Generally we don't need to test cases where both accessing src and writing 858 // to dest address to poisoned memory. 859 860 T *big_src = Ident((T*)malloc(size * 2)); 861 T *big_dest = Ident((T*)malloc(size * 2)); 862 // try to change mem to both sides of dest 863 EXPECT_DEATH(M::transfer(dest - 1, big_src, size * 2), 864 LeftOOBErrorMessage(sizeof(T))); 865 // try to access mem to both sides of src 866 EXPECT_DEATH(M::transfer(big_dest, src - 2, size * 2), 867 LeftOOBErrorMessage(2 * sizeof(T))); 868 869 free(src); 870 free(dest); 871 free(big_src); 872 free(big_dest); 873 } 874 875 class MemCpyWrapper { 876 public: 877 static void* transfer(void *to, const void *from, size_t size) { 878 return memcpy(to, from, size); 879 } 880 }; 881 TEST(AddressSanitizer, MemCpyOOBTest) { 882 MemTransferOOBTestTemplate<char, MemCpyWrapper>(100); 883 MemTransferOOBTestTemplate<int, MemCpyWrapper>(1024); 884 } 885 886 class MemMoveWrapper { 887 public: 888 static void* transfer(void *to, const void *from, size_t size) { 889 return memmove(to, from, size); 890 } 891 }; 892 TEST(AddressSanitizer, MemMoveOOBTest) { 893 MemTransferOOBTestTemplate<char, MemMoveWrapper>(100); 894 MemTransferOOBTestTemplate<int, MemMoveWrapper>(1024); 895 } 896 897 // Tests for string functions 898 899 // Used for string functions tests 900 static char global_string[] = "global"; 901 static size_t global_string_length = 6; 902 903 // Input to a test is a zero-terminated string str with given length 904 // Accesses to the bytes to the left and to the right of str 905 // are presumed to produce OOB errors 906 void StrLenOOBTestTemplate(char *str, size_t length, bool is_global) { 907 // Normal strlen calls 908 EXPECT_EQ(strlen(str), length); 909 if (length > 0) { 910 EXPECT_EQ(strlen(str + 1), length - 1); 911 EXPECT_EQ(strlen(str + length), 0); 912 } 913 // Arg of strlen is not malloced, OOB access 914 if (!is_global) { 915 // We don't insert RedZones to the left of global variables 916 EXPECT_DEATH(Ident(strlen(str - 1)), LeftOOBErrorMessage(1)); 917 EXPECT_DEATH(Ident(strlen(str - 5)), LeftOOBErrorMessage(5)); 918 } 919 EXPECT_DEATH(Ident(strlen(str + length + 1)), RightOOBErrorMessage(0)); 920 // Overwrite terminator 921 str[length] = 'a'; 922 // String is not zero-terminated, strlen will lead to OOB access 923 EXPECT_DEATH(Ident(strlen(str)), RightOOBErrorMessage(0)); 924 EXPECT_DEATH(Ident(strlen(str + length)), RightOOBErrorMessage(0)); 925 // Restore terminator 926 str[length] = 0; 927 } 928 TEST(AddressSanitizer, StrLenOOBTest) { 929 // Check heap-allocated string 930 size_t length = Ident(10); 931 char *heap_string = Ident((char*)malloc(length + 1)); 932 char stack_string[10 + 1]; 933 for (int i = 0; i < length; i++) { 934 heap_string[i] = 'a'; 935 stack_string[i] = 'b'; 936 } 937 heap_string[length] = 0; 938 stack_string[length] = 0; 939 StrLenOOBTestTemplate(heap_string, length, false); 940 // TODO(samsonov): Fix expected messages in StrLenOOBTestTemplate to 941 // make test for stack_string work. Or move it to output tests. 942 // StrLenOOBTestTemplate(stack_string, length, false); 943 StrLenOOBTestTemplate(global_string, global_string_length, true); 944 free(heap_string); 945 } 946 947 static inline char* MallocAndMemsetString(size_t size, char ch) { 948 char *s = Ident((char*)malloc(size)); 949 memset(s, ch, size); 950 return s; 951 } 952 static inline char* MallocAndMemsetString(size_t size) { 953 return MallocAndMemsetString(size, 'z'); 954 } 955 956 #ifndef __APPLE__ 957 TEST(AddressSanitizer, StrNLenOOBTest) { 958 size_t size = Ident(123); 959 char *str = MallocAndMemsetString(size); 960 // Normal strnlen calls. 961 Ident(strnlen(str - 1, 0)); 962 Ident(strnlen(str, size)); 963 Ident(strnlen(str + size - 1, 1)); 964 str[size - 1] = '\0'; 965 Ident(strnlen(str, 2 * size)); 966 // Argument points to not allocated memory. 967 EXPECT_DEATH(Ident(strnlen(str - 1, 1)), LeftOOBErrorMessage(1)); 968 EXPECT_DEATH(Ident(strnlen(str + size, 1)), RightOOBErrorMessage(0)); 969 // Overwrite the terminating '\0' and hit unallocated memory. 970 str[size - 1] = 'z'; 971 EXPECT_DEATH(Ident(strnlen(str, size + 1)), RightOOBErrorMessage(0)); 972 free(str); 973 } 974 #endif 975 976 TEST(AddressSanitizer, StrDupOOBTest) { 977 size_t size = Ident(42); 978 char *str = MallocAndMemsetString(size); 979 char *new_str; 980 // Normal strdup calls. 981 str[size - 1] = '\0'; 982 new_str = strdup(str); 983 free(new_str); 984 new_str = strdup(str + size - 1); 985 free(new_str); 986 // Argument points to not allocated memory. 987 EXPECT_DEATH(Ident(strdup(str - 1)), LeftOOBErrorMessage(1)); 988 EXPECT_DEATH(Ident(strdup(str + size)), RightOOBErrorMessage(0)); 989 // Overwrite the terminating '\0' and hit unallocated memory. 990 str[size - 1] = 'z'; 991 EXPECT_DEATH(Ident(strdup(str)), RightOOBErrorMessage(0)); 992 free(str); 993 } 994 995 TEST(AddressSanitizer, StrCpyOOBTest) { 996 size_t to_size = Ident(30); 997 size_t from_size = Ident(6); // less than to_size 998 char *to = Ident((char*)malloc(to_size)); 999 char *from = Ident((char*)malloc(from_size)); 1000 // Normal strcpy calls. 1001 strcpy(from, "hello"); 1002 strcpy(to, from); 1003 strcpy(to + to_size - from_size, from); 1004 // Length of "from" is too small. 1005 EXPECT_DEATH(Ident(strcpy(from, "hello2")), RightOOBErrorMessage(0)); 1006 // "to" or "from" points to not allocated memory. 1007 EXPECT_DEATH(Ident(strcpy(to - 1, from)), LeftOOBErrorMessage(1)); 1008 EXPECT_DEATH(Ident(strcpy(to, from - 1)), LeftOOBErrorMessage(1)); 1009 EXPECT_DEATH(Ident(strcpy(to, from + from_size)), RightOOBErrorMessage(0)); 1010 EXPECT_DEATH(Ident(strcpy(to + to_size, from)), RightOOBErrorMessage(0)); 1011 // Overwrite the terminating '\0' character and hit unallocated memory. 1012 from[from_size - 1] = '!'; 1013 EXPECT_DEATH(Ident(strcpy(to, from)), RightOOBErrorMessage(0)); 1014 free(to); 1015 free(from); 1016 } 1017 1018 TEST(AddressSanitizer, StrNCpyOOBTest) { 1019 size_t to_size = Ident(20); 1020 size_t from_size = Ident(6); // less than to_size 1021 char *to = Ident((char*)malloc(to_size)); 1022 // From is a zero-terminated string "hello\0" of length 6 1023 char *from = Ident((char*)malloc(from_size)); 1024 strcpy(from, "hello"); 1025 // copy 0 bytes 1026 strncpy(to, from, 0); 1027 strncpy(to - 1, from - 1, 0); 1028 // normal strncpy calls 1029 strncpy(to, from, from_size); 1030 strncpy(to, from, to_size); 1031 strncpy(to, from + from_size - 1, to_size); 1032 strncpy(to + to_size - 1, from, 1); 1033 // One of {to, from} points to not allocated memory 1034 EXPECT_DEATH(Ident(strncpy(to, from - 1, from_size)), 1035 LeftOOBErrorMessage(1)); 1036 EXPECT_DEATH(Ident(strncpy(to - 1, from, from_size)), 1037 LeftOOBErrorMessage(1)); 1038 EXPECT_DEATH(Ident(strncpy(to, from + from_size, 1)), 1039 RightOOBErrorMessage(0)); 1040 EXPECT_DEATH(Ident(strncpy(to + to_size, from, 1)), 1041 RightOOBErrorMessage(0)); 1042 // Length of "to" is too small 1043 EXPECT_DEATH(Ident(strncpy(to + to_size - from_size + 1, from, from_size)), 1044 RightOOBErrorMessage(0)); 1045 EXPECT_DEATH(Ident(strncpy(to + 1, from, to_size)), 1046 RightOOBErrorMessage(0)); 1047 // Overwrite terminator in from 1048 from[from_size - 1] = '!'; 1049 // normal strncpy call 1050 strncpy(to, from, from_size); 1051 // Length of "from" is too small 1052 EXPECT_DEATH(Ident(strncpy(to, from, to_size)), 1053 RightOOBErrorMessage(0)); 1054 free(to); 1055 free(from); 1056 } 1057 1058 typedef char*(*PointerToStrChr)(const char*, int); 1059 void RunStrChrTest(PointerToStrChr StrChr) { 1060 size_t size = Ident(100); 1061 char *str = MallocAndMemsetString(size); 1062 str[10] = 'q'; 1063 str[11] = '\0'; 1064 EXPECT_EQ(str, StrChr(str, 'z')); 1065 EXPECT_EQ(str + 10, StrChr(str, 'q')); 1066 EXPECT_EQ(NULL, StrChr(str, 'a')); 1067 // StrChr argument points to not allocated memory. 1068 EXPECT_DEATH(Ident(StrChr(str - 1, 'z')), LeftOOBErrorMessage(1)); 1069 EXPECT_DEATH(Ident(StrChr(str + size, 'z')), RightOOBErrorMessage(0)); 1070 // Overwrite the terminator and hit not allocated memory. 1071 str[11] = 'z'; 1072 EXPECT_DEATH(Ident(StrChr(str, 'a')), RightOOBErrorMessage(0)); 1073 free(str); 1074 } 1075 TEST(AddressSanitizer, StrChrAndIndexOOBTest) { 1076 RunStrChrTest(&strchr); 1077 RunStrChrTest(&index); 1078 } 1079 1080 TEST(AddressSanitizer, StrCmpAndFriendsLogicTest) { 1081 // strcmp 1082 EXPECT_EQ(0, strcmp("", "")); 1083 EXPECT_EQ(0, strcmp("abcd", "abcd")); 1084 EXPECT_GT(0, strcmp("ab", "ac")); 1085 EXPECT_GT(0, strcmp("abc", "abcd")); 1086 EXPECT_LT(0, strcmp("acc", "abc")); 1087 EXPECT_LT(0, strcmp("abcd", "abc")); 1088 1089 // strncmp 1090 EXPECT_EQ(0, strncmp("a", "b", 0)); 1091 EXPECT_EQ(0, strncmp("abcd", "abcd", 10)); 1092 EXPECT_EQ(0, strncmp("abcd", "abcef", 3)); 1093 EXPECT_GT(0, strncmp("abcde", "abcfa", 4)); 1094 EXPECT_GT(0, strncmp("a", "b", 5)); 1095 EXPECT_GT(0, strncmp("bc", "bcde", 4)); 1096 EXPECT_LT(0, strncmp("xyz", "xyy", 10)); 1097 EXPECT_LT(0, strncmp("baa", "aaa", 1)); 1098 EXPECT_LT(0, strncmp("zyx", "", 2)); 1099 1100 // strcasecmp 1101 EXPECT_EQ(0, strcasecmp("", "")); 1102 EXPECT_EQ(0, strcasecmp("zzz", "zzz")); 1103 EXPECT_EQ(0, strcasecmp("abCD", "ABcd")); 1104 EXPECT_GT(0, strcasecmp("aB", "Ac")); 1105 EXPECT_GT(0, strcasecmp("ABC", "ABCd")); 1106 EXPECT_LT(0, strcasecmp("acc", "abc")); 1107 EXPECT_LT(0, strcasecmp("ABCd", "abc")); 1108 1109 // strncasecmp 1110 EXPECT_EQ(0, strncasecmp("a", "b", 0)); 1111 EXPECT_EQ(0, strncasecmp("abCD", "ABcd", 10)); 1112 EXPECT_EQ(0, strncasecmp("abCd", "ABcef", 3)); 1113 EXPECT_GT(0, strncasecmp("abcde", "ABCfa", 4)); 1114 EXPECT_GT(0, strncasecmp("a", "B", 5)); 1115 EXPECT_GT(0, strncasecmp("bc", "BCde", 4)); 1116 EXPECT_LT(0, strncasecmp("xyz", "xyy", 10)); 1117 EXPECT_LT(0, strncasecmp("Baa", "aaa", 1)); 1118 EXPECT_LT(0, strncasecmp("zyx", "", 2)); 1119 1120 // memcmp 1121 EXPECT_EQ(0, memcmp("a", "b", 0)); 1122 EXPECT_EQ(0, memcmp("ab\0c", "ab\0c", 4)); 1123 EXPECT_GT(0, memcmp("\0ab", "\0ac", 3)); 1124 EXPECT_GT(0, memcmp("abb\0", "abba", 4)); 1125 EXPECT_LT(0, memcmp("ab\0cd", "ab\0c\0", 5)); 1126 EXPECT_LT(0, memcmp("zza", "zyx", 3)); 1127 } 1128 1129 typedef int(*PointerToStrCmp)(const char*, const char*); 1130 void RunStrCmpTest(PointerToStrCmp StrCmp) { 1131 size_t size = Ident(100); 1132 char *s1 = MallocAndMemsetString(size); 1133 char *s2 = MallocAndMemsetString(size); 1134 s1[size - 1] = '\0'; 1135 s2[size - 1] = '\0'; 1136 // Normal StrCmp calls 1137 Ident(StrCmp(s1, s2)); 1138 Ident(StrCmp(s1, s2 + size - 1)); 1139 Ident(StrCmp(s1 + size - 1, s2 + size - 1)); 1140 s1[size - 1] = 'z'; 1141 s2[size - 1] = 'x'; 1142 Ident(StrCmp(s1, s2)); 1143 // One of arguments points to not allocated memory. 1144 EXPECT_DEATH(Ident(StrCmp)(s1 - 1, s2), LeftOOBErrorMessage(1)); 1145 EXPECT_DEATH(Ident(StrCmp)(s1, s2 - 1), LeftOOBErrorMessage(1)); 1146 EXPECT_DEATH(Ident(StrCmp)(s1 + size, s2), RightOOBErrorMessage(0)); 1147 EXPECT_DEATH(Ident(StrCmp)(s1, s2 + size), RightOOBErrorMessage(0)); 1148 // Hit unallocated memory and die. 1149 s2[size - 1] = 'z'; 1150 EXPECT_DEATH(Ident(StrCmp)(s1, s1), RightOOBErrorMessage(0)); 1151 EXPECT_DEATH(Ident(StrCmp)(s1 + size - 1, s2), RightOOBErrorMessage(0)); 1152 free(s1); 1153 free(s2); 1154 } 1155 1156 TEST(AddressSanitizer, StrCmpOOBTest) { 1157 RunStrCmpTest(&strcmp); 1158 } 1159 1160 TEST(AddressSanitizer, StrCaseCmpOOBTest) { 1161 RunStrCmpTest(&strcasecmp); 1162 } 1163 1164 typedef int(*PointerToStrNCmp)(const char*, const char*, size_t); 1165 void RunStrNCmpTest(PointerToStrNCmp StrNCmp) { 1166 size_t size = Ident(100); 1167 char *s1 = MallocAndMemsetString(size); 1168 char *s2 = MallocAndMemsetString(size); 1169 s1[size - 1] = '\0'; 1170 s2[size - 1] = '\0'; 1171 // Normal StrNCmp calls 1172 Ident(StrNCmp(s1, s2, size + 2)); 1173 s1[size - 1] = 'z'; 1174 s2[size - 1] = 'x'; 1175 Ident(StrNCmp(s1 + size - 2, s2 + size - 2, size)); 1176 s2[size - 1] = 'z'; 1177 Ident(StrNCmp(s1 - 1, s2 - 1, 0)); 1178 Ident(StrNCmp(s1 + size - 1, s2 + size - 1, 1)); 1179 // One of arguments points to not allocated memory. 1180 EXPECT_DEATH(Ident(StrNCmp)(s1 - 1, s2, 1), LeftOOBErrorMessage(1)); 1181 EXPECT_DEATH(Ident(StrNCmp)(s1, s2 - 1, 1), LeftOOBErrorMessage(1)); 1182 EXPECT_DEATH(Ident(StrNCmp)(s1 + size, s2, 1), RightOOBErrorMessage(0)); 1183 EXPECT_DEATH(Ident(StrNCmp)(s1, s2 + size, 1), RightOOBErrorMessage(0)); 1184 // Hit unallocated memory and die. 1185 EXPECT_DEATH(Ident(StrNCmp)(s1 + 1, s2 + 1, size), RightOOBErrorMessage(0)); 1186 EXPECT_DEATH(Ident(StrNCmp)(s1 + size - 1, s2, 2), RightOOBErrorMessage(0)); 1187 free(s1); 1188 free(s2); 1189 } 1190 1191 TEST(AddressSanitizer, StrNCmpOOBTest) { 1192 RunStrNCmpTest(&strncmp); 1193 } 1194 1195 TEST(AddressSanitizer, StrNCaseCmpOOBTest) { 1196 RunStrNCmpTest(&strncasecmp); 1197 } 1198 1199 TEST(AddressSanitizer, MemCmpOOBTest) { 1200 size_t size = Ident(100); 1201 char *s1 = MallocAndMemsetString(size); 1202 char *s2 = MallocAndMemsetString(size); 1203 // Normal memcmp calls. 1204 Ident(memcmp(s1, s2, size)); 1205 Ident(memcmp(s1 + size - 1, s2 + size - 1, 1)); 1206 Ident(memcmp(s1 - 1, s2 - 1, 0)); 1207 // One of arguments points to not allocated memory. 1208 EXPECT_DEATH(Ident(memcmp)(s1 - 1, s2, 1), LeftOOBErrorMessage(1)); 1209 EXPECT_DEATH(Ident(memcmp)(s1, s2 - 1, 1), LeftOOBErrorMessage(1)); 1210 EXPECT_DEATH(Ident(memcmp)(s1 + size, s2, 1), RightOOBErrorMessage(0)); 1211 EXPECT_DEATH(Ident(memcmp)(s1, s2 + size, 1), RightOOBErrorMessage(0)); 1212 // Hit unallocated memory and die. 1213 EXPECT_DEATH(Ident(memcmp)(s1 + 1, s2 + 1, size), RightOOBErrorMessage(0)); 1214 EXPECT_DEATH(Ident(memcmp)(s1 + size - 1, s2, 2), RightOOBErrorMessage(0)); 1215 // Zero bytes are not terminators and don't prevent from OOB. 1216 s1[size - 1] = '\0'; 1217 s2[size - 1] = '\0'; 1218 EXPECT_DEATH(Ident(memcmp)(s1, s2, size + 1), RightOOBErrorMessage(0)); 1219 free(s1); 1220 free(s2); 1221 } 1222 1223 TEST(AddressSanitizer, StrCatOOBTest) { 1224 size_t to_size = Ident(100); 1225 char *to = MallocAndMemsetString(to_size); 1226 to[0] = '\0'; 1227 size_t from_size = Ident(20); 1228 char *from = MallocAndMemsetString(from_size); 1229 from[from_size - 1] = '\0'; 1230 // Normal strcat calls. 1231 strcat(to, from); 1232 strcat(to, from); 1233 strcat(to + from_size, from + from_size - 2); 1234 // Catenate empty string is not always an error. 1235 strcat(to - 1, from + from_size - 1); 1236 // One of arguments points to not allocated memory. 1237 EXPECT_DEATH(strcat(to - 1, from), LeftOOBErrorMessage(1)); 1238 EXPECT_DEATH(strcat(to, from - 1), LeftOOBErrorMessage(1)); 1239 EXPECT_DEATH(strcat(to + to_size, from), RightOOBErrorMessage(0)); 1240 EXPECT_DEATH(strcat(to, from + from_size), RightOOBErrorMessage(0)); 1241 1242 // "from" is not zero-terminated. 1243 from[from_size - 1] = 'z'; 1244 EXPECT_DEATH(strcat(to, from), RightOOBErrorMessage(0)); 1245 from[from_size - 1] = '\0'; 1246 // "to" is not zero-terminated. 1247 memset(to, 'z', to_size); 1248 EXPECT_DEATH(strcat(to, from), RightOOBErrorMessage(0)); 1249 // "to" is too short to fit "from". 1250 to[to_size - from_size + 1] = '\0'; 1251 EXPECT_DEATH(strcat(to, from), RightOOBErrorMessage(0)); 1252 // length of "to" is just enough. 1253 strcat(to, from + 1); 1254 } 1255 1256 static string OverlapErrorMessage(const string &func) { 1257 return func + "-param-overlap"; 1258 } 1259 1260 TEST(AddressSanitizer, StrArgsOverlapTest) { 1261 size_t size = Ident(100); 1262 char *str = Ident((char*)malloc(size)); 1263 1264 // Do not check memcpy() on OS X 10.7 and later, where it actually aliases 1265 // memmove(). 1266 #if !defined(__APPLE__) || !defined(MAC_OS_X_VERSION_10_7) || \ 1267 (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7) 1268 // Check "memcpy". Use Ident() to avoid inlining. 1269 memset(str, 'z', size); 1270 Ident(memcpy)(str + 1, str + 11, 10); 1271 Ident(memcpy)(str, str, 0); 1272 EXPECT_DEATH(Ident(memcpy)(str, str + 14, 15), OverlapErrorMessage("memcpy")); 1273 EXPECT_DEATH(Ident(memcpy)(str + 14, str, 15), OverlapErrorMessage("memcpy")); 1274 #endif 1275 1276 // We do not treat memcpy with to==from as a bug. 1277 // See http://llvm.org/bugs/show_bug.cgi?id=11763. 1278 // EXPECT_DEATH(Ident(memcpy)(str + 20, str + 20, 1), 1279 // OverlapErrorMessage("memcpy")); 1280 1281 // Check "strcpy". 1282 memset(str, 'z', size); 1283 str[9] = '\0'; 1284 strcpy(str + 10, str); 1285 EXPECT_DEATH(strcpy(str + 9, str), OverlapErrorMessage("strcpy")); 1286 EXPECT_DEATH(strcpy(str, str + 4), OverlapErrorMessage("strcpy")); 1287 strcpy(str, str + 5); 1288 1289 // Check "strncpy". 1290 memset(str, 'z', size); 1291 strncpy(str, str + 10, 10); 1292 EXPECT_DEATH(strncpy(str, str + 9, 10), OverlapErrorMessage("strncpy")); 1293 EXPECT_DEATH(strncpy(str + 9, str, 10), OverlapErrorMessage("strncpy")); 1294 str[10] = '\0'; 1295 strncpy(str + 11, str, 20); 1296 EXPECT_DEATH(strncpy(str + 10, str, 20), OverlapErrorMessage("strncpy")); 1297 1298 // Check "strcat". 1299 memset(str, 'z', size); 1300 str[10] = '\0'; 1301 str[20] = '\0'; 1302 strcat(str, str + 10); 1303 strcat(str, str + 11); 1304 str[10] = '\0'; 1305 strcat(str + 11, str); 1306 EXPECT_DEATH(strcat(str, str + 9), OverlapErrorMessage("strcat")); 1307 EXPECT_DEATH(strcat(str + 9, str), OverlapErrorMessage("strcat")); 1308 EXPECT_DEATH(strcat(str + 10, str), OverlapErrorMessage("strcat")); 1309 1310 free(str); 1311 } 1312 1313 void CallAtoi(const char *nptr) { 1314 Ident(atoi(nptr)); 1315 } 1316 void CallAtol(const char *nptr) { 1317 Ident(atol(nptr)); 1318 } 1319 void CallAtoll(const char *nptr) { 1320 Ident(atoll(nptr)); 1321 } 1322 typedef void(*PointerToCallAtoi)(const char*); 1323 1324 void RunAtoiOOBTest(PointerToCallAtoi Atoi) { 1325 char *array = MallocAndMemsetString(10, '1'); 1326 // Invalid pointer to the string. 1327 EXPECT_DEATH(Atoi(array + 11), RightOOBErrorMessage(1)); 1328 EXPECT_DEATH(Atoi(array - 1), LeftOOBErrorMessage(1)); 1329 // Die if a buffer doesn't have terminating NULL. 1330 EXPECT_DEATH(Atoi(array), RightOOBErrorMessage(0)); 1331 // Make last symbol a terminating NULL or other non-digit. 1332 array[9] = '\0'; 1333 Atoi(array); 1334 array[9] = 'a'; 1335 Atoi(array); 1336 Atoi(array + 9); 1337 // Sometimes we need to detect overflow if no digits are found. 1338 memset(array, ' ', 10); 1339 EXPECT_DEATH(Atoi(array), RightOOBErrorMessage(0)); 1340 array[9] = '-'; 1341 EXPECT_DEATH(Atoi(array), RightOOBErrorMessage(0)); 1342 EXPECT_DEATH(Atoi(array + 9), RightOOBErrorMessage(0)); 1343 array[8] = '-'; 1344 Atoi(array); 1345 delete array; 1346 } 1347 1348 TEST(AddressSanitizer, AtoiAndFriendsOOBTest) { 1349 RunAtoiOOBTest(&CallAtoi); 1350 RunAtoiOOBTest(&CallAtol); 1351 RunAtoiOOBTest(&CallAtoll); 1352 } 1353 1354 void CallStrtol(const char *nptr, char **endptr, int base) { 1355 Ident(strtol(nptr, endptr, base)); 1356 } 1357 void CallStrtoll(const char *nptr, char **endptr, int base) { 1358 Ident(strtoll(nptr, endptr, base)); 1359 } 1360 typedef void(*PointerToCallStrtol)(const char*, char**, int); 1361 1362 void RunStrtolOOBTest(PointerToCallStrtol Strtol) { 1363 char *array = MallocAndMemsetString(3); 1364 char *endptr = NULL; 1365 array[0] = '1'; 1366 array[1] = '2'; 1367 array[2] = '3'; 1368 // Invalid pointer to the string. 1369 EXPECT_DEATH(Strtol(array + 3, NULL, 0), RightOOBErrorMessage(0)); 1370 EXPECT_DEATH(Strtol(array - 1, NULL, 0), LeftOOBErrorMessage(1)); 1371 // Buffer overflow if there is no terminating null (depends on base). 1372 Strtol(array, &endptr, 3); 1373 EXPECT_EQ(array + 2, endptr); 1374 EXPECT_DEATH(Strtol(array, NULL, 0), RightOOBErrorMessage(0)); 1375 array[2] = 'z'; 1376 Strtol(array, &endptr, 35); 1377 EXPECT_EQ(array + 2, endptr); 1378 EXPECT_DEATH(Strtol(array, NULL, 36), RightOOBErrorMessage(0)); 1379 // Add terminating zero to get rid of overflow. 1380 array[2] = '\0'; 1381 Strtol(array, NULL, 36); 1382 // Don't check for overflow if base is invalid. 1383 Strtol(array - 1, NULL, -1); 1384 Strtol(array + 3, NULL, 1); 1385 // Sometimes we need to detect overflow if no digits are found. 1386 array[0] = array[1] = array[2] = ' '; 1387 EXPECT_DEATH(Strtol(array, NULL, 0), RightOOBErrorMessage(0)); 1388 array[2] = '+'; 1389 EXPECT_DEATH(Strtol(array, NULL, 0), RightOOBErrorMessage(0)); 1390 array[2] = '-'; 1391 EXPECT_DEATH(Strtol(array, NULL, 0), RightOOBErrorMessage(0)); 1392 array[1] = '+'; 1393 Strtol(array, NULL, 0); 1394 array[1] = array[2] = 'z'; 1395 Strtol(array, &endptr, 0); 1396 EXPECT_EQ(array, endptr); 1397 Strtol(array + 2, NULL, 0); 1398 EXPECT_EQ(array, endptr); 1399 delete array; 1400 } 1401 1402 TEST(AddressSanitizer, StrtollOOBTest) { 1403 RunStrtolOOBTest(&CallStrtoll); 1404 } 1405 TEST(AddressSanitizer, StrtolOOBTest) { 1406 RunStrtolOOBTest(&CallStrtol); 1407 } 1408 1409 // At the moment we instrument memcpy/memove/memset calls at compile time so we 1410 // can't handle OOB error if these functions are called by pointer, see disabled 1411 // MemIntrinsicCallByPointerTest below 1412 typedef void*(*PointerToMemTransfer)(void*, const void*, size_t); 1413 typedef void*(*PointerToMemSet)(void*, int, size_t); 1414 1415 void CallMemSetByPointer(PointerToMemSet MemSet) { 1416 size_t size = Ident(100); 1417 char *array = Ident((char*)malloc(size)); 1418 EXPECT_DEATH(MemSet(array, 0, 101), RightOOBErrorMessage(0)); 1419 free(array); 1420 } 1421 1422 void CallMemTransferByPointer(PointerToMemTransfer MemTransfer) { 1423 size_t size = Ident(100); 1424 char *src = Ident((char*)malloc(size)); 1425 char *dst = Ident((char*)malloc(size)); 1426 EXPECT_DEATH(MemTransfer(dst, src, 101), RightOOBErrorMessage(0)); 1427 free(src); 1428 free(dst); 1429 } 1430 1431 TEST(AddressSanitizer, DISABLED_MemIntrinsicCallByPointerTest) { 1432 CallMemSetByPointer(&memset); 1433 CallMemTransferByPointer(&memcpy); 1434 CallMemTransferByPointer(&memmove); 1435 } 1436 1437 // This test case fails 1438 // Clang optimizes memcpy/memset calls which lead to unaligned access 1439 TEST(AddressSanitizer, DISABLED_MemIntrinsicUnalignedAccessTest) { 1440 int size = Ident(4096); 1441 char *s = Ident((char*)malloc(size)); 1442 EXPECT_DEATH(memset(s + size - 1, 0, 2), RightOOBErrorMessage(0)); 1443 free(s); 1444 } 1445 1446 // TODO(samsonov): Add a test with malloc(0) 1447 // TODO(samsonov): Add tests for str* and mem* functions. 1448 1449 NOINLINE static int LargeFunction(bool do_bad_access) { 1450 int *x = new int[100]; 1451 x[0]++; 1452 x[1]++; 1453 x[2]++; 1454 x[3]++; 1455 x[4]++; 1456 x[5]++; 1457 x[6]++; 1458 x[7]++; 1459 x[8]++; 1460 x[9]++; 1461 1462 x[do_bad_access ? 100 : 0]++; int res = __LINE__; 1463 1464 x[10]++; 1465 x[11]++; 1466 x[12]++; 1467 x[13]++; 1468 x[14]++; 1469 x[15]++; 1470 x[16]++; 1471 x[17]++; 1472 x[18]++; 1473 x[19]++; 1474 1475 delete x; 1476 return res; 1477 } 1478 1479 // Test the we have correct debug info for the failing instruction. 1480 // This test requires the in-process symbolizer to be enabled by default. 1481 TEST(AddressSanitizer, DISABLED_LargeFunctionSymbolizeTest) { 1482 int failing_line = LargeFunction(false); 1483 char expected_warning[128]; 1484 sprintf(expected_warning, "LargeFunction.*asan_test.cc:%d", failing_line); 1485 EXPECT_DEATH(LargeFunction(true), expected_warning); 1486 } 1487 1488 // Check that we unwind and symbolize correctly. 1489 TEST(AddressSanitizer, DISABLED_MallocFreeUnwindAndSymbolizeTest) { 1490 int *a = (int*)malloc_aaa(sizeof(int)); 1491 *a = 1; 1492 free_aaa(a); 1493 EXPECT_DEATH(*a = 1, "free_ccc.*free_bbb.*free_aaa.*" 1494 "malloc_fff.*malloc_eee.*malloc_ddd"); 1495 } 1496 1497 void *ThreadedTestAlloc(void *a) { 1498 int **p = (int**)a; 1499 *p = new int; 1500 return 0; 1501 } 1502 1503 void *ThreadedTestFree(void *a) { 1504 int **p = (int**)a; 1505 delete *p; 1506 return 0; 1507 } 1508 1509 void *ThreadedTestUse(void *a) { 1510 int **p = (int**)a; 1511 **p = 1; 1512 return 0; 1513 } 1514 1515 void ThreadedTestSpawn() { 1516 pthread_t t; 1517 int *x; 1518 pthread_create(&t, 0, ThreadedTestAlloc, &x); 1519 pthread_join(t, 0); 1520 pthread_create(&t, 0, ThreadedTestFree, &x); 1521 pthread_join(t, 0); 1522 pthread_create(&t, 0, ThreadedTestUse, &x); 1523 pthread_join(t, 0); 1524 } 1525 1526 TEST(AddressSanitizer, ThreadedTest) { 1527 EXPECT_DEATH(ThreadedTestSpawn(), 1528 ASAN_PCRE_DOTALL 1529 "Thread T.*created" 1530 ".*Thread T.*created" 1531 ".*Thread T.*created"); 1532 } 1533 1534 #if ASAN_NEEDS_SEGV 1535 TEST(AddressSanitizer, ShadowGapTest) { 1536 #if __WORDSIZE == 32 1537 char *addr = (char*)0x22000000; 1538 #else 1539 char *addr = (char*)0x0000100000080000; 1540 #endif 1541 EXPECT_DEATH(*addr = 1, "AddressSanitizer crashed on unknown"); 1542 } 1543 #endif // ASAN_NEEDS_SEGV 1544 1545 extern "C" { 1546 NOINLINE static void UseThenFreeThenUse() { 1547 char *x = Ident((char*)malloc(8)); 1548 *x = 1; 1549 free_aaa(x); 1550 *x = 2; 1551 } 1552 } 1553 1554 TEST(AddressSanitizer, UseThenFreeThenUseTest) { 1555 EXPECT_DEATH(UseThenFreeThenUse(), "freed by thread"); 1556 } 1557 1558 TEST(AddressSanitizer, StrDupTest) { 1559 free(strdup(Ident("123"))); 1560 } 1561 1562 // Currently we create and poison redzone at right of global variables. 1563 char glob5[5]; 1564 static char static110[110]; 1565 const char ConstGlob[7] = {1, 2, 3, 4, 5, 6, 7}; 1566 static const char StaticConstGlob[3] = {9, 8, 7}; 1567 extern int GlobalsTest(int x); 1568 1569 TEST(AddressSanitizer, GlobalTest) { 1570 static char func_static15[15]; 1571 1572 static char fs1[10]; 1573 static char fs2[10]; 1574 static char fs3[10]; 1575 1576 glob5[Ident(0)] = 0; 1577 glob5[Ident(1)] = 0; 1578 glob5[Ident(2)] = 0; 1579 glob5[Ident(3)] = 0; 1580 glob5[Ident(4)] = 0; 1581 1582 EXPECT_DEATH(glob5[Ident(5)] = 0, 1583 "0 bytes to the right of global variable.*glob5.* size 5"); 1584 EXPECT_DEATH(glob5[Ident(5+6)] = 0, 1585 "6 bytes to the right of global variable.*glob5.* size 5"); 1586 Ident(static110); // avoid optimizations 1587 static110[Ident(0)] = 0; 1588 static110[Ident(109)] = 0; 1589 EXPECT_DEATH(static110[Ident(110)] = 0, 1590 "0 bytes to the right of global variable"); 1591 EXPECT_DEATH(static110[Ident(110+7)] = 0, 1592 "7 bytes to the right of global variable"); 1593 1594 Ident(func_static15); // avoid optimizations 1595 func_static15[Ident(0)] = 0; 1596 EXPECT_DEATH(func_static15[Ident(15)] = 0, 1597 "0 bytes to the right of global variable"); 1598 EXPECT_DEATH(func_static15[Ident(15 + 9)] = 0, 1599 "9 bytes to the right of global variable"); 1600 1601 Ident(fs1); 1602 Ident(fs2); 1603 Ident(fs3); 1604 1605 // We don't create left redzones, so this is not 100% guaranteed to fail. 1606 // But most likely will. 1607 EXPECT_DEATH(fs2[Ident(-1)] = 0, "is located.*of global variable"); 1608 1609 EXPECT_DEATH(Ident(Ident(ConstGlob)[8]), 1610 "is located 1 bytes to the right of .*ConstGlob"); 1611 EXPECT_DEATH(Ident(Ident(StaticConstGlob)[5]), 1612 "is located 2 bytes to the right of .*StaticConstGlob"); 1613 1614 // call stuff from another file. 1615 GlobalsTest(0); 1616 } 1617 1618 TEST(AddressSanitizer, GlobalStringConstTest) { 1619 static const char *zoo = "FOOBAR123"; 1620 const char *p = Ident(zoo); 1621 EXPECT_DEATH(Ident(p[15]), "is ascii string 'FOOBAR123'"); 1622 } 1623 1624 TEST(AddressSanitizer, FileNameInGlobalReportTest) { 1625 static char zoo[10]; 1626 const char *p = Ident(zoo); 1627 // The file name should be present in the report. 1628 EXPECT_DEATH(Ident(p[15]), "zoo.*asan_test.cc"); 1629 } 1630 1631 int *ReturnsPointerToALocalObject() { 1632 int a = 0; 1633 return Ident(&a); 1634 } 1635 1636 #if ASAN_UAR == 1 1637 TEST(AddressSanitizer, LocalReferenceReturnTest) { 1638 int *(*f)() = Ident(ReturnsPointerToALocalObject); 1639 int *p = f(); 1640 // Call 'f' a few more times, 'p' should still be poisoned. 1641 for (int i = 0; i < 32; i++) 1642 f(); 1643 EXPECT_DEATH(*p = 1, "AddressSanitizer stack-use-after-return"); 1644 EXPECT_DEATH(*p = 1, "is located.*in frame .*ReturnsPointerToALocal"); 1645 } 1646 #endif 1647 1648 template <int kSize> 1649 NOINLINE static void FuncWithStack() { 1650 char x[kSize]; 1651 Ident(x)[0] = 0; 1652 Ident(x)[kSize-1] = 0; 1653 } 1654 1655 static void LotsOfStackReuse() { 1656 int LargeStack[10000]; 1657 Ident(LargeStack)[0] = 0; 1658 for (int i = 0; i < 10000; i++) { 1659 FuncWithStack<128 * 1>(); 1660 FuncWithStack<128 * 2>(); 1661 FuncWithStack<128 * 4>(); 1662 FuncWithStack<128 * 8>(); 1663 FuncWithStack<128 * 16>(); 1664 FuncWithStack<128 * 32>(); 1665 FuncWithStack<128 * 64>(); 1666 FuncWithStack<128 * 128>(); 1667 FuncWithStack<128 * 256>(); 1668 FuncWithStack<128 * 512>(); 1669 Ident(LargeStack)[0] = 0; 1670 } 1671 } 1672 1673 TEST(AddressSanitizer, StressStackReuseTest) { 1674 LotsOfStackReuse(); 1675 } 1676 1677 TEST(AddressSanitizer, ThreadedStressStackReuseTest) { 1678 const int kNumThreads = 20; 1679 pthread_t t[kNumThreads]; 1680 for (int i = 0; i < kNumThreads; i++) { 1681 pthread_create(&t[i], 0, (void* (*)(void *x))LotsOfStackReuse, 0); 1682 } 1683 for (int i = 0; i < kNumThreads; i++) { 1684 pthread_join(t[i], 0); 1685 } 1686 } 1687 1688 static void *PthreadExit(void *a) { 1689 pthread_exit(0); 1690 return 0; 1691 } 1692 1693 TEST(AddressSanitizer, PthreadExitTest) { 1694 pthread_t t; 1695 for (int i = 0; i < 1000; i++) { 1696 pthread_create(&t, 0, PthreadExit, 0); 1697 pthread_join(t, 0); 1698 } 1699 } 1700 1701 #ifdef __EXCEPTIONS 1702 NOINLINE static void StackReuseAndException() { 1703 int large_stack[1000]; 1704 Ident(large_stack); 1705 ASAN_THROW(1); 1706 } 1707 1708 // TODO(kcc): support exceptions with use-after-return. 1709 TEST(AddressSanitizer, DISABLED_StressStackReuseAndExceptionsTest) { 1710 for (int i = 0; i < 10000; i++) { 1711 try { 1712 StackReuseAndException(); 1713 } catch(...) { 1714 } 1715 } 1716 } 1717 #endif 1718 1719 TEST(AddressSanitizer, MlockTest) { 1720 EXPECT_EQ(0, mlockall(MCL_CURRENT)); 1721 EXPECT_EQ(0, mlock((void*)0x12345, 0x5678)); 1722 EXPECT_EQ(0, munlockall()); 1723 EXPECT_EQ(0, munlock((void*)0x987, 0x654)); 1724 } 1725 1726 struct LargeStruct { 1727 int foo[100]; 1728 }; 1729 1730 // Test for bug http://llvm.org/bugs/show_bug.cgi?id=11763. 1731 // Struct copy should not cause asan warning even if lhs == rhs. 1732 TEST(AddressSanitizer, LargeStructCopyTest) { 1733 LargeStruct a; 1734 *Ident(&a) = *Ident(&a); 1735 } 1736 1737 __attribute__((no_address_safety_analysis)) 1738 static void NoAddressSafety() { 1739 char *foo = new char[10]; 1740 Ident(foo)[10] = 0; 1741 delete [] foo; 1742 } 1743 1744 TEST(AddressSanitizer, AttributeNoAddressSafetyTest) { 1745 Ident(NoAddressSafety)(); 1746 } 1747 1748 // ------------------ demo tests; run each one-by-one ------------- 1749 // e.g. --gtest_filter=*DemoOOBLeftHigh --gtest_also_run_disabled_tests 1750 TEST(AddressSanitizer, DISABLED_DemoThreadedTest) { 1751 ThreadedTestSpawn(); 1752 } 1753 1754 void *SimpleBugOnSTack(void *x = 0) { 1755 char a[20]; 1756 Ident(a)[20] = 0; 1757 return 0; 1758 } 1759 1760 TEST(AddressSanitizer, DISABLED_DemoStackTest) { 1761 SimpleBugOnSTack(); 1762 } 1763 1764 TEST(AddressSanitizer, DISABLED_DemoThreadStackTest) { 1765 pthread_t t; 1766 pthread_create(&t, 0, SimpleBugOnSTack, 0); 1767 pthread_join(t, 0); 1768 } 1769 1770 TEST(AddressSanitizer, DISABLED_DemoUAFLowIn) { 1771 uaf_test<U1>(10, 0); 1772 } 1773 TEST(AddressSanitizer, DISABLED_DemoUAFLowLeft) { 1774 uaf_test<U1>(10, -2); 1775 } 1776 TEST(AddressSanitizer, DISABLED_DemoUAFLowRight) { 1777 uaf_test<U1>(10, 10); 1778 } 1779 1780 TEST(AddressSanitizer, DISABLED_DemoUAFHigh) { 1781 uaf_test<U1>(kLargeMalloc, 0); 1782 } 1783 1784 TEST(AddressSanitizer, DISABLED_DemoOOBLeftLow) { 1785 oob_test<U1>(10, -1); 1786 } 1787 1788 TEST(AddressSanitizer, DISABLED_DemoOOBLeftHigh) { 1789 oob_test<U1>(kLargeMalloc, -1); 1790 } 1791 1792 TEST(AddressSanitizer, DISABLED_DemoOOBRightLow) { 1793 oob_test<U1>(10, 10); 1794 } 1795 1796 TEST(AddressSanitizer, DISABLED_DemoOOBRightHigh) { 1797 oob_test<U1>(kLargeMalloc, kLargeMalloc); 1798 } 1799 1800 TEST(AddressSanitizer, DISABLED_DemoOOM) { 1801 size_t size = __WORDSIZE == 64 ? (size_t)(1ULL << 40) : (0xf0000000); 1802 printf("%p\n", malloc(size)); 1803 } 1804 1805 TEST(AddressSanitizer, DISABLED_DemoDoubleFreeTest) { 1806 DoubleFree(); 1807 } 1808 1809 TEST(AddressSanitizer, DISABLED_DemoNullDerefTest) { 1810 int *a = 0; 1811 Ident(a)[10] = 0; 1812 } 1813 1814 TEST(AddressSanitizer, DISABLED_DemoFunctionStaticTest) { 1815 static char a[100]; 1816 static char b[100]; 1817 static char c[100]; 1818 Ident(a); 1819 Ident(b); 1820 Ident(c); 1821 Ident(a)[5] = 0; 1822 Ident(b)[105] = 0; 1823 Ident(a)[5] = 0; 1824 } 1825 1826 TEST(AddressSanitizer, DISABLED_DemoTooMuchMemoryTest) { 1827 const size_t kAllocSize = (1 << 28) - 1024; 1828 size_t total_size = 0; 1829 while (true) { 1830 char *x = (char*)malloc(kAllocSize); 1831 memset(x, 0, kAllocSize); 1832 total_size += kAllocSize; 1833 fprintf(stderr, "total: %ldM\n", (long)total_size >> 20); 1834 } 1835 } 1836 1837 #ifdef __APPLE__ 1838 #include "asan_mac_test.h" 1839 // TODO(glider): figure out whether we still need these tests. Is it correct 1840 // to intercept CFAllocator? 1841 TEST(AddressSanitizerMac, DISABLED_CFAllocatorDefaultDoubleFree) { 1842 EXPECT_DEATH( 1843 CFAllocatorDefaultDoubleFree(), 1844 "attempting double-free"); 1845 } 1846 1847 TEST(AddressSanitizerMac, DISABLED_CFAllocatorSystemDefaultDoubleFree) { 1848 EXPECT_DEATH( 1849 CFAllocatorSystemDefaultDoubleFree(), 1850 "attempting double-free"); 1851 } 1852 1853 TEST(AddressSanitizerMac, DISABLED_CFAllocatorMallocDoubleFree) { 1854 EXPECT_DEATH(CFAllocatorMallocDoubleFree(), "attempting double-free"); 1855 } 1856 1857 TEST(AddressSanitizerMac, DISABLED_CFAllocatorMallocZoneDoubleFree) { 1858 EXPECT_DEATH(CFAllocatorMallocZoneDoubleFree(), "attempting double-free"); 1859 } 1860 1861 TEST(AddressSanitizerMac, GCDDispatchAsync) { 1862 // Make sure the whole ASan report is printed, i.e. that we don't die 1863 // on a CHECK. 1864 EXPECT_DEATH(TestGCDDispatchAsync(), "Shadow byte and word"); 1865 } 1866 1867 TEST(AddressSanitizerMac, GCDDispatchSync) { 1868 // Make sure the whole ASan report is printed, i.e. that we don't die 1869 // on a CHECK. 1870 EXPECT_DEATH(TestGCDDispatchSync(), "Shadow byte and word"); 1871 } 1872 1873 1874 TEST(AddressSanitizerMac, GCDReuseWqthreadsAsync) { 1875 // Make sure the whole ASan report is printed, i.e. that we don't die 1876 // on a CHECK. 1877 EXPECT_DEATH(TestGCDReuseWqthreadsAsync(), "Shadow byte and word"); 1878 } 1879 1880 TEST(AddressSanitizerMac, GCDReuseWqthreadsSync) { 1881 // Make sure the whole ASan report is printed, i.e. that we don't die 1882 // on a CHECK. 1883 EXPECT_DEATH(TestGCDReuseWqthreadsSync(), "Shadow byte and word"); 1884 } 1885 1886 TEST(AddressSanitizerMac, GCDDispatchAfter) { 1887 // Make sure the whole ASan report is printed, i.e. that we don't die 1888 // on a CHECK. 1889 EXPECT_DEATH(TestGCDDispatchAfter(), "Shadow byte and word"); 1890 } 1891 1892 TEST(AddressSanitizerMac, GCDSourceEvent) { 1893 // Make sure the whole ASan report is printed, i.e. that we don't die 1894 // on a CHECK. 1895 EXPECT_DEATH(TestGCDSourceEvent(), "Shadow byte and word"); 1896 } 1897 1898 TEST(AddressSanitizerMac, GCDSourceCancel) { 1899 // Make sure the whole ASan report is printed, i.e. that we don't die 1900 // on a CHECK. 1901 EXPECT_DEATH(TestGCDSourceCancel(), "Shadow byte and word"); 1902 } 1903 1904 TEST(AddressSanitizerMac, GCDGroupAsync) { 1905 // Make sure the whole ASan report is printed, i.e. that we don't die 1906 // on a CHECK. 1907 EXPECT_DEATH(TestGCDGroupAsync(), "Shadow byte and word"); 1908 } 1909 1910 void *MallocIntrospectionLockWorker(void *_) { 1911 const int kNumPointers = 100; 1912 int i; 1913 void *pointers[kNumPointers]; 1914 for (i = 0; i < kNumPointers; i++) { 1915 pointers[i] = malloc(i + 1); 1916 } 1917 for (i = 0; i < kNumPointers; i++) { 1918 free(pointers[i]); 1919 } 1920 1921 return NULL; 1922 } 1923 1924 void *MallocIntrospectionLockForker(void *_) { 1925 pid_t result = fork(); 1926 if (result == -1) { 1927 perror("fork"); 1928 } 1929 assert(result != -1); 1930 if (result == 0) { 1931 // Call malloc in the child process to make sure we won't deadlock. 1932 void *ptr = malloc(42); 1933 free(ptr); 1934 exit(0); 1935 } else { 1936 // Return in the parent process. 1937 return NULL; 1938 } 1939 } 1940 1941 TEST(AddressSanitizerMac, MallocIntrospectionLock) { 1942 // Incorrect implementation of force_lock and force_unlock in our malloc zone 1943 // will cause forked processes to deadlock. 1944 // TODO(glider): need to detect that none of the child processes deadlocked. 1945 const int kNumWorkers = 5, kNumIterations = 100; 1946 int i, iter; 1947 for (iter = 0; iter < kNumIterations; iter++) { 1948 pthread_t workers[kNumWorkers], forker; 1949 for (i = 0; i < kNumWorkers; i++) { 1950 pthread_create(&workers[i], 0, MallocIntrospectionLockWorker, 0); 1951 } 1952 pthread_create(&forker, 0, MallocIntrospectionLockForker, 0); 1953 for (i = 0; i < kNumWorkers; i++) { 1954 pthread_join(workers[i], 0); 1955 } 1956 pthread_join(forker, 0); 1957 } 1958 } 1959 1960 void *TSDAllocWorker(void *test_key) { 1961 if (test_key) { 1962 void *mem = malloc(10); 1963 pthread_setspecific(*(pthread_key_t*)test_key, mem); 1964 } 1965 return NULL; 1966 } 1967 1968 TEST(AddressSanitizerMac, DISABLED_TSDWorkqueueTest) { 1969 pthread_t th; 1970 pthread_key_t test_key; 1971 pthread_key_create(&test_key, CallFreeOnWorkqueue); 1972 pthread_create(&th, NULL, TSDAllocWorker, &test_key); 1973 pthread_join(th, NULL); 1974 pthread_key_delete(test_key); 1975 } 1976 1977 // Test that CFStringCreateCopy does not copy constant strings. 1978 TEST(AddressSanitizerMac, CFStringCreateCopy) { 1979 CFStringRef str = CFSTR("Hello world!\n"); 1980 CFStringRef str2 = CFStringCreateCopy(0, str); 1981 EXPECT_EQ(str, str2); 1982 } 1983 1984 TEST(AddressSanitizerMac, NSObjectOOB) { 1985 // Make sure that our allocators are used for NSObjects. 1986 EXPECT_DEATH(TestOOBNSObjects(), "heap-buffer-overflow"); 1987 } 1988 #endif // __APPLE__ 1989 1990 // Test that instrumentation of stack allocations takes into account 1991 // AllocSize of a type, and not its StoreSize (16 vs 10 bytes for long double). 1992 // See http://llvm.org/bugs/show_bug.cgi?id=12047 for more details. 1993 TEST(AddressSanitizer, LongDoubleNegativeTest) { 1994 long double a, b; 1995 static long double c; 1996 memcpy(Ident(&a), Ident(&b), sizeof(long double)); 1997 memcpy(Ident(&c), Ident(&b), sizeof(long double)); 1998 }; 1999 2000 int main(int argc, char **argv) { 2001 progname = argv[0]; 2002 testing::GTEST_FLAG(death_test_style) = "threadsafe"; 2003 testing::InitGoogleTest(&argc, argv); 2004 return RUN_ALL_TESTS(); 2005 } 2006