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