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