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