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