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