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