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