asan_test.cc revision 73700ac2a7ced591261ad11199d9d4a7112304bb
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 "asan_test_utils.h"
14
15NOINLINE void *malloc_fff(size_t size) {
16  void *res = malloc/**/(size); break_optimization(0); return res;}
17NOINLINE void *malloc_eee(size_t size) {
18  void *res = malloc_fff(size); break_optimization(0); return res;}
19NOINLINE void *malloc_ddd(size_t size) {
20  void *res = malloc_eee(size); break_optimization(0); return res;}
21NOINLINE void *malloc_ccc(size_t size) {
22  void *res = malloc_ddd(size); break_optimization(0); return res;}
23NOINLINE void *malloc_bbb(size_t size) {
24  void *res = malloc_ccc(size); break_optimization(0); return res;}
25NOINLINE void *malloc_aaa(size_t size) {
26  void *res = malloc_bbb(size); break_optimization(0); return res;}
27
28#ifndef __APPLE__
29NOINLINE void *memalign_fff(size_t alignment, size_t size) {
30  void *res = memalign/**/(alignment, size); break_optimization(0); return res;}
31NOINLINE void *memalign_eee(size_t alignment, size_t size) {
32  void *res = memalign_fff(alignment, size); break_optimization(0); return res;}
33NOINLINE void *memalign_ddd(size_t alignment, size_t size) {
34  void *res = memalign_eee(alignment, size); break_optimization(0); return res;}
35NOINLINE void *memalign_ccc(size_t alignment, size_t size) {
36  void *res = memalign_ddd(alignment, size); break_optimization(0); return res;}
37NOINLINE void *memalign_bbb(size_t alignment, size_t size) {
38  void *res = memalign_ccc(alignment, size); break_optimization(0); return res;}
39NOINLINE void *memalign_aaa(size_t alignment, size_t size) {
40  void *res = memalign_bbb(alignment, size); break_optimization(0); return res;}
41#endif  // __APPLE__
42
43
44NOINLINE void free_ccc(void *p) { free(p); break_optimization(0);}
45NOINLINE void free_bbb(void *p) { free_ccc(p); break_optimization(0);}
46NOINLINE void free_aaa(void *p) { free_bbb(p); break_optimization(0);}
47
48
49template<typename T>
50NOINLINE void uaf_test(int size, int off) {
51  char *p = (char *)malloc_aaa(size);
52  free_aaa(p);
53  for (int i = 1; i < 100; i++)
54    free_aaa(malloc_aaa(i));
55  fprintf(stderr, "writing %ld byte(s) at %p with offset %d\n",
56          (long)sizeof(T), p, off);
57  asan_write((T*)(p + off));
58}
59
60TEST(AddressSanitizer, HasFeatureAddressSanitizerTest) {
61#if defined(__has_feature) && __has_feature(address_sanitizer)
62  bool asan = 1;
63#elif defined(__SANITIZE_ADDRESS__)
64  bool asan = 1;
65#else
66  bool asan = 0;
67#endif
68  EXPECT_EQ(true, asan);
69}
70
71TEST(AddressSanitizer, SimpleDeathTest) {
72  EXPECT_DEATH(exit(1), "");
73}
74
75TEST(AddressSanitizer, VariousMallocsTest) {
76  int *a = (int*)malloc(100 * sizeof(int));
77  a[50] = 0;
78  free(a);
79
80  int *r = (int*)malloc(10);
81  r = (int*)realloc(r, 2000 * sizeof(int));
82  r[1000] = 0;
83  free(r);
84
85  int *b = new int[100];
86  b[50] = 0;
87  delete [] b;
88
89  int *c = new int;
90  *c = 0;
91  delete c;
92
93#if !defined(__APPLE__) && !defined(ANDROID) && !defined(__ANDROID__)
94  int *pm;
95  int pm_res = posix_memalign((void**)&pm, kPageSize, kPageSize);
96  EXPECT_EQ(0, pm_res);
97  free(pm);
98#endif
99
100#if !defined(__APPLE__)
101  int *ma = (int*)memalign(kPageSize, kPageSize);
102  EXPECT_EQ(0U, (uintptr_t)ma % kPageSize);
103  ma[123] = 0;
104  free(ma);
105#endif  // __APPLE__
106}
107
108TEST(AddressSanitizer, CallocTest) {
109  int *a = (int*)calloc(100, sizeof(int));
110  EXPECT_EQ(0, a[10]);
111  free(a);
112}
113
114TEST(AddressSanitizer, VallocTest) {
115  void *a = valloc(100);
116  EXPECT_EQ(0U, (uintptr_t)a % kPageSize);
117  free(a);
118}
119
120#ifndef __APPLE__
121TEST(AddressSanitizer, PvallocTest) {
122  char *a = (char*)pvalloc(kPageSize + 100);
123  EXPECT_EQ(0U, (uintptr_t)a % kPageSize);
124  a[kPageSize + 101] = 1;  // we should not report an error here.
125  free(a);
126
127  a = (char*)pvalloc(0);  // pvalloc(0) should allocate at least one page.
128  EXPECT_EQ(0U, (uintptr_t)a % kPageSize);
129  a[101] = 1;  // we should not report an error here.
130  free(a);
131}
132#endif  // __APPLE__
133
134void *TSDWorker(void *test_key) {
135  if (test_key) {
136    pthread_setspecific(*(pthread_key_t*)test_key, (void*)0xfeedface);
137  }
138  return NULL;
139}
140
141void TSDDestructor(void *tsd) {
142  // Spawning a thread will check that the current thread id is not -1.
143  pthread_t th;
144  PTHREAD_CREATE(&th, NULL, TSDWorker, NULL);
145  PTHREAD_JOIN(th, NULL);
146}
147
148// This tests triggers the thread-specific data destruction fiasco which occurs
149// if we don't manage the TSD destructors ourselves. We create a new pthread
150// key with a non-NULL destructor which is likely to be put after the destructor
151// of AsanThread in the list of destructors.
152// In this case the TSD for AsanThread will be destroyed before TSDDestructor
153// is called for the child thread, and a CHECK will fail when we call
154// pthread_create() to spawn the grandchild.
155TEST(AddressSanitizer, DISABLED_TSDTest) {
156  pthread_t th;
157  pthread_key_t test_key;
158  pthread_key_create(&test_key, TSDDestructor);
159  PTHREAD_CREATE(&th, NULL, TSDWorker, &test_key);
160  PTHREAD_JOIN(th, NULL);
161  pthread_key_delete(test_key);
162}
163
164TEST(AddressSanitizer, UAF_char) {
165  const char *uaf_string = "AddressSanitizer:.*heap-use-after-free";
166  EXPECT_DEATH(uaf_test<U1>(1, 0), uaf_string);
167  EXPECT_DEATH(uaf_test<U1>(10, 0), uaf_string);
168  EXPECT_DEATH(uaf_test<U1>(10, 10), uaf_string);
169  EXPECT_DEATH(uaf_test<U1>(kLargeMalloc, 0), uaf_string);
170  EXPECT_DEATH(uaf_test<U1>(kLargeMalloc, kLargeMalloc / 2), uaf_string);
171}
172
173#if ASAN_HAS_BLACKLIST
174TEST(AddressSanitizer, IgnoreTest) {
175  int *x = Ident(new int);
176  delete Ident(x);
177  *x = 0;
178}
179#endif  // ASAN_HAS_BLACKLIST
180
181struct StructWithBitField {
182  int bf1:1;
183  int bf2:1;
184  int bf3:1;
185  int bf4:29;
186};
187
188TEST(AddressSanitizer, BitFieldPositiveTest) {
189  StructWithBitField *x = new StructWithBitField;
190  delete Ident(x);
191  EXPECT_DEATH(x->bf1 = 0, "use-after-free");
192  EXPECT_DEATH(x->bf2 = 0, "use-after-free");
193  EXPECT_DEATH(x->bf3 = 0, "use-after-free");
194  EXPECT_DEATH(x->bf4 = 0, "use-after-free");
195}
196
197struct StructWithBitFields_8_24 {
198  int a:8;
199  int b:24;
200};
201
202TEST(AddressSanitizer, BitFieldNegativeTest) {
203  StructWithBitFields_8_24 *x = Ident(new StructWithBitFields_8_24);
204  x->a = 0;
205  x->b = 0;
206  delete Ident(x);
207}
208
209TEST(AddressSanitizer, OutOfMemoryTest) {
210  size_t size = SANITIZER_WORDSIZE == 64 ? (size_t)(1ULL << 48) : (0xf0000000);
211  EXPECT_EQ(0, realloc(0, size));
212  EXPECT_EQ(0, realloc(0, ~Ident(0)));
213  EXPECT_EQ(0, malloc(size));
214  EXPECT_EQ(0, malloc(~Ident(0)));
215  EXPECT_EQ(0, calloc(1, size));
216  EXPECT_EQ(0, calloc(1, ~Ident(0)));
217}
218
219#if ASAN_NEEDS_SEGV
220namespace {
221
222const char kUnknownCrash[] = "AddressSanitizer: SEGV on unknown address";
223const char kOverriddenHandler[] = "ASan signal handler has been overridden\n";
224
225TEST(AddressSanitizer, WildAddressTest) {
226  char *c = (char*)0x123;
227  EXPECT_DEATH(*c = 0, kUnknownCrash);
228}
229
230void my_sigaction_sighandler(int, siginfo_t*, void*) {
231  fprintf(stderr, kOverriddenHandler);
232  exit(1);
233}
234
235void my_signal_sighandler(int signum) {
236  fprintf(stderr, kOverriddenHandler);
237  exit(1);
238}
239
240TEST(AddressSanitizer, SignalTest) {
241  struct sigaction sigact;
242  memset(&sigact, 0, sizeof(sigact));
243  sigact.sa_sigaction = my_sigaction_sighandler;
244  sigact.sa_flags = SA_SIGINFO;
245  // ASan should silently ignore sigaction()...
246  EXPECT_EQ(0, sigaction(SIGSEGV, &sigact, 0));
247#ifdef __APPLE__
248  EXPECT_EQ(0, sigaction(SIGBUS, &sigact, 0));
249#endif
250  char *c = (char*)0x123;
251  EXPECT_DEATH(*c = 0, kUnknownCrash);
252  // ... and signal().
253  EXPECT_EQ(0, signal(SIGSEGV, my_signal_sighandler));
254  EXPECT_DEATH(*c = 0, kUnknownCrash);
255}
256}  // namespace
257#endif
258
259static void MallocStress(size_t n) {
260  uint32_t seed = my_rand();
261  for (size_t iter = 0; iter < 10; iter++) {
262    vector<void *> vec;
263    for (size_t i = 0; i < n; i++) {
264      if ((i % 3) == 0) {
265        if (vec.empty()) continue;
266        size_t idx = my_rand_r(&seed) % vec.size();
267        void *ptr = vec[idx];
268        vec[idx] = vec.back();
269        vec.pop_back();
270        free_aaa(ptr);
271      } else {
272        size_t size = my_rand_r(&seed) % 1000 + 1;
273#ifndef __APPLE__
274        size_t alignment = 1 << (my_rand_r(&seed) % 7 + 3);
275        char *ptr = (char*)memalign_aaa(alignment, size);
276#else
277        char *ptr = (char*) malloc_aaa(size);
278#endif
279        vec.push_back(ptr);
280        ptr[0] = 0;
281        ptr[size-1] = 0;
282        ptr[size/2] = 0;
283      }
284    }
285    for (size_t i = 0; i < vec.size(); i++)
286      free_aaa(vec[i]);
287  }
288}
289
290TEST(AddressSanitizer, MallocStressTest) {
291  MallocStress((ASAN_LOW_MEMORY) ? 20000 : 200000);
292}
293
294static void TestLargeMalloc(size_t size) {
295  char buff[1024];
296  sprintf(buff, "is located 1 bytes to the left of %lu-byte", (long)size);
297  EXPECT_DEATH(Ident((char*)malloc(size))[-1] = 0, buff);
298}
299
300TEST(AddressSanitizer, LargeMallocTest) {
301  for (int i = 113; i < (1 << 28); i = i * 2 + 13) {
302    TestLargeMalloc(i);
303  }
304}
305
306#if ASAN_LOW_MEMORY != 1
307TEST(AddressSanitizer, HugeMallocTest) {
308#ifdef __APPLE__
309  // It was empirically found out that 1215 megabytes is the maximum amount of
310  // memory available to the process under AddressSanitizer on 32-bit Mac 10.6.
311  // 32-bit Mac 10.7 gives even less (< 1G).
312  // (the libSystem malloc() allows allocating up to 2300 megabytes without
313  // ASan).
314  size_t n_megs = SANITIZER_WORDSIZE == 32 ? 500 : 4100;
315#else
316  size_t n_megs = SANITIZER_WORDSIZE == 32 ? 2600 : 4100;
317#endif
318  TestLargeMalloc(n_megs << 20);
319}
320#endif
321
322#ifndef __APPLE__
323void MemalignRun(size_t align, size_t size, int idx) {
324  char *p = (char *)memalign(align, size);
325  Ident(p)[idx] = 0;
326  free(p);
327}
328
329TEST(AddressSanitizer, memalign) {
330  for (int align = 16; align <= (1 << 23); align *= 2) {
331    size_t size = align * 5;
332    EXPECT_DEATH(MemalignRun(align, size, -1),
333                 "is located 1 bytes to the left");
334    EXPECT_DEATH(MemalignRun(align, size, size + 1),
335                 "is located 1 bytes to the right");
336  }
337}
338#endif
339
340TEST(AddressSanitizer, ThreadedMallocStressTest) {
341  const int kNumThreads = 4;
342  const int kNumIterations = (ASAN_LOW_MEMORY) ? 10000 : 100000;
343  pthread_t t[kNumThreads];
344  for (int i = 0; i < kNumThreads; i++) {
345    PTHREAD_CREATE(&t[i], 0, (void* (*)(void *x))MallocStress,
346        (void*)kNumIterations);
347  }
348  for (int i = 0; i < kNumThreads; i++) {
349    PTHREAD_JOIN(t[i], 0);
350  }
351}
352
353void *ManyThreadsWorker(void *a) {
354  for (int iter = 0; iter < 100; iter++) {
355    for (size_t size = 100; size < 2000; size *= 2) {
356      free(Ident(malloc(size)));
357    }
358  }
359  return 0;
360}
361
362TEST(AddressSanitizer, ManyThreadsTest) {
363  const size_t kNumThreads =
364      (SANITIZER_WORDSIZE == 32 || ASAN_AVOID_EXPENSIVE_TESTS) ? 30 : 1000;
365  pthread_t t[kNumThreads];
366  for (size_t i = 0; i < kNumThreads; i++) {
367    PTHREAD_CREATE(&t[i], 0, ManyThreadsWorker, (void*)i);
368  }
369  for (size_t i = 0; i < kNumThreads; i++) {
370    PTHREAD_JOIN(t[i], 0);
371  }
372}
373
374TEST(AddressSanitizer, ReallocTest) {
375  const int kMinElem = 5;
376  int *ptr = (int*)malloc(sizeof(int) * kMinElem);
377  ptr[3] = 3;
378  for (int i = 0; i < 10000; i++) {
379    ptr = (int*)realloc(ptr,
380        (my_rand() % 1000 + kMinElem) * sizeof(int));
381    EXPECT_EQ(3, ptr[3]);
382  }
383  free(ptr);
384  // Realloc pointer returned by malloc(0).
385  int *ptr2 = Ident((int*)malloc(0));
386  ptr2 = Ident((int*)realloc(ptr2, sizeof(*ptr2)));
387  *ptr2 = 42;
388  EXPECT_EQ(42, *ptr2);
389  free(ptr2);
390}
391
392TEST(AddressSanitizer, ZeroSizeMallocTest) {
393  // Test that malloc(0) and similar functions don't return NULL.
394  void *ptr = Ident(malloc(0));
395  EXPECT_TRUE(NULL != ptr);
396  free(ptr);
397#if !defined(__APPLE__) && !defined(ANDROID) && !defined(__ANDROID__)
398  int pm_res = posix_memalign(&ptr, 1<<20, 0);
399  EXPECT_EQ(0, pm_res);
400  EXPECT_TRUE(NULL != ptr);
401  free(ptr);
402#endif
403  int *int_ptr = new int[0];
404  int *int_ptr2 = new int[0];
405  EXPECT_TRUE(NULL != int_ptr);
406  EXPECT_TRUE(NULL != int_ptr2);
407  EXPECT_NE(int_ptr, int_ptr2);
408  delete[] int_ptr;
409  delete[] int_ptr2;
410}
411
412#ifndef __APPLE__
413static const char *kMallocUsableSizeErrorMsg =
414  "AddressSanitizer: attempting to call malloc_usable_size()";
415
416TEST(AddressSanitizer, MallocUsableSizeTest) {
417  const size_t kArraySize = 100;
418  char *array = Ident((char*)malloc(kArraySize));
419  int *int_ptr = Ident(new int);
420  EXPECT_EQ(0U, malloc_usable_size(NULL));
421  EXPECT_EQ(kArraySize, malloc_usable_size(array));
422  EXPECT_EQ(sizeof(int), malloc_usable_size(int_ptr));
423  EXPECT_DEATH(malloc_usable_size((void*)0x123), kMallocUsableSizeErrorMsg);
424  EXPECT_DEATH(malloc_usable_size(array + kArraySize / 2),
425               kMallocUsableSizeErrorMsg);
426  free(array);
427  EXPECT_DEATH(malloc_usable_size(array), kMallocUsableSizeErrorMsg);
428}
429#endif
430
431void WrongFree() {
432  int *x = (int*)malloc(100 * sizeof(int));
433  // Use the allocated memory, otherwise Clang will optimize it out.
434  Ident(x);
435  free(x + 1);
436}
437
438TEST(AddressSanitizer, WrongFreeTest) {
439  EXPECT_DEATH(WrongFree(),
440               "ERROR: AddressSanitizer: attempting free.*not malloc");
441}
442
443void DoubleFree() {
444  int *x = (int*)malloc(100 * sizeof(int));
445  fprintf(stderr, "DoubleFree: x=%p\n", x);
446  free(x);
447  free(x);
448  fprintf(stderr, "should have failed in the second free(%p)\n", x);
449  abort();
450}
451
452TEST(AddressSanitizer, DoubleFreeTest) {
453  EXPECT_DEATH(DoubleFree(), ASAN_PCRE_DOTALL
454               "ERROR: AddressSanitizer: attempting double-free"
455               ".*is located 0 bytes inside of 400-byte region"
456               ".*freed by thread T0 here"
457               ".*previously allocated by thread T0 here");
458}
459
460template<int kSize>
461NOINLINE void SizedStackTest() {
462  char a[kSize];
463  char  *A = Ident((char*)&a);
464  for (size_t i = 0; i < kSize; i++)
465    A[i] = i;
466  EXPECT_DEATH(A[-1] = 0, "");
467  EXPECT_DEATH(A[-20] = 0, "");
468  EXPECT_DEATH(A[-31] = 0, "");
469  EXPECT_DEATH(A[kSize] = 0, "");
470  EXPECT_DEATH(A[kSize + 1] = 0, "");
471  EXPECT_DEATH(A[kSize + 10] = 0, "");
472  EXPECT_DEATH(A[kSize + 31] = 0, "");
473}
474
475TEST(AddressSanitizer, SimpleStackTest) {
476  SizedStackTest<1>();
477  SizedStackTest<2>();
478  SizedStackTest<3>();
479  SizedStackTest<4>();
480  SizedStackTest<5>();
481  SizedStackTest<6>();
482  SizedStackTest<7>();
483  SizedStackTest<16>();
484  SizedStackTest<25>();
485  SizedStackTest<34>();
486  SizedStackTest<43>();
487  SizedStackTest<51>();
488  SizedStackTest<62>();
489  SizedStackTest<64>();
490  SizedStackTest<128>();
491}
492
493TEST(AddressSanitizer, ManyStackObjectsTest) {
494  char XXX[10];
495  char YYY[20];
496  char ZZZ[30];
497  Ident(XXX);
498  Ident(YYY);
499  EXPECT_DEATH(Ident(ZZZ)[-1] = 0, ASAN_PCRE_DOTALL "XXX.*YYY.*ZZZ");
500}
501
502NOINLINE static void Frame0(int frame, char *a, char *b, char *c) {
503  char d[4] = {0};
504  char *D = Ident(d);
505  switch (frame) {
506    case 3: a[5]++; break;
507    case 2: b[5]++; break;
508    case 1: c[5]++; break;
509    case 0: D[5]++; break;
510  }
511}
512NOINLINE static void Frame1(int frame, char *a, char *b) {
513  char c[4] = {0}; Frame0(frame, a, b, c);
514  break_optimization(0);
515}
516NOINLINE static void Frame2(int frame, char *a) {
517  char b[4] = {0}; Frame1(frame, a, b);
518  break_optimization(0);
519}
520NOINLINE static void Frame3(int frame) {
521  char a[4] = {0}; Frame2(frame, a);
522  break_optimization(0);
523}
524
525TEST(AddressSanitizer, GuiltyStackFrame0Test) {
526  EXPECT_DEATH(Frame3(0), "located .*in frame <.*Frame0");
527}
528TEST(AddressSanitizer, GuiltyStackFrame1Test) {
529  EXPECT_DEATH(Frame3(1), "located .*in frame <.*Frame1");
530}
531TEST(AddressSanitizer, GuiltyStackFrame2Test) {
532  EXPECT_DEATH(Frame3(2), "located .*in frame <.*Frame2");
533}
534TEST(AddressSanitizer, GuiltyStackFrame3Test) {
535  EXPECT_DEATH(Frame3(3), "located .*in frame <.*Frame3");
536}
537
538NOINLINE void LongJmpFunc1(jmp_buf buf) {
539  // create three red zones for these two stack objects.
540  int a;
541  int b;
542
543  int *A = Ident(&a);
544  int *B = Ident(&b);
545  *A = *B;
546  longjmp(buf, 1);
547}
548
549NOINLINE void BuiltinLongJmpFunc1(jmp_buf buf) {
550  // create three red zones for these two stack objects.
551  int a;
552  int b;
553
554  int *A = Ident(&a);
555  int *B = Ident(&b);
556  *A = *B;
557  __builtin_longjmp((void**)buf, 1);
558}
559
560NOINLINE void UnderscopeLongJmpFunc1(jmp_buf buf) {
561  // create three red zones for these two stack objects.
562  int a;
563  int b;
564
565  int *A = Ident(&a);
566  int *B = Ident(&b);
567  *A = *B;
568  _longjmp(buf, 1);
569}
570
571NOINLINE void SigLongJmpFunc1(sigjmp_buf buf) {
572  // create three red zones for these two stack objects.
573  int a;
574  int b;
575
576  int *A = Ident(&a);
577  int *B = Ident(&b);
578  *A = *B;
579  siglongjmp(buf, 1);
580}
581
582
583NOINLINE void TouchStackFunc() {
584  int a[100];  // long array will intersect with redzones from LongJmpFunc1.
585  int *A = Ident(a);
586  for (int i = 0; i < 100; i++)
587    A[i] = i*i;
588}
589
590// Test that we handle longjmp and do not report fals positives on stack.
591TEST(AddressSanitizer, LongJmpTest) {
592  static jmp_buf buf;
593  if (!setjmp(buf)) {
594    LongJmpFunc1(buf);
595  } else {
596    TouchStackFunc();
597  }
598}
599
600#if not defined(__ANDROID__)
601TEST(AddressSanitizer, BuiltinLongJmpTest) {
602  static jmp_buf buf;
603  if (!__builtin_setjmp((void**)buf)) {
604    BuiltinLongJmpFunc1(buf);
605  } else {
606    TouchStackFunc();
607  }
608}
609#endif  // not defined(__ANDROID__)
610
611TEST(AddressSanitizer, UnderscopeLongJmpTest) {
612  static jmp_buf buf;
613  if (!_setjmp(buf)) {
614    UnderscopeLongJmpFunc1(buf);
615  } else {
616    TouchStackFunc();
617  }
618}
619
620TEST(AddressSanitizer, SigLongJmpTest) {
621  static sigjmp_buf buf;
622  if (!sigsetjmp(buf, 1)) {
623    SigLongJmpFunc1(buf);
624  } else {
625    TouchStackFunc();
626  }
627}
628
629#ifdef __EXCEPTIONS
630NOINLINE void ThrowFunc() {
631  // create three red zones for these two stack objects.
632  int a;
633  int b;
634
635  int *A = Ident(&a);
636  int *B = Ident(&b);
637  *A = *B;
638  ASAN_THROW(1);
639}
640
641TEST(AddressSanitizer, CxxExceptionTest) {
642  if (ASAN_UAR) return;
643  // TODO(kcc): this test crashes on 32-bit for some reason...
644  if (SANITIZER_WORDSIZE == 32) return;
645  try {
646    ThrowFunc();
647  } catch(...) {}
648  TouchStackFunc();
649}
650#endif
651
652void *ThreadStackReuseFunc1(void *unused) {
653  // create three red zones for these two stack objects.
654  int a;
655  int b;
656
657  int *A = Ident(&a);
658  int *B = Ident(&b);
659  *A = *B;
660  pthread_exit(0);
661  return 0;
662}
663
664void *ThreadStackReuseFunc2(void *unused) {
665  TouchStackFunc();
666  return 0;
667}
668
669TEST(AddressSanitizer, ThreadStackReuseTest) {
670  pthread_t t;
671  PTHREAD_CREATE(&t, 0, ThreadStackReuseFunc1, 0);
672  PTHREAD_JOIN(t, 0);
673  PTHREAD_CREATE(&t, 0, ThreadStackReuseFunc2, 0);
674  PTHREAD_JOIN(t, 0);
675}
676
677#if defined(__i386__) || defined(__x86_64__)
678TEST(AddressSanitizer, Store128Test) {
679  char *a = Ident((char*)malloc(Ident(12)));
680  char *p = a;
681  if (((uintptr_t)a % 16) != 0)
682    p = a + 8;
683  assert(((uintptr_t)p % 16) == 0);
684  __m128i value_wide = _mm_set1_epi16(0x1234);
685  EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
686               "AddressSanitizer: heap-buffer-overflow");
687  EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
688               "WRITE of size 16");
689  EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
690               "located 0 bytes to the right of 12-byte");
691  free(a);
692}
693#endif
694
695string RightOOBErrorMessage(int oob_distance, bool is_write) {
696  assert(oob_distance >= 0);
697  char expected_str[100];
698  sprintf(expected_str, ASAN_PCRE_DOTALL "%s.*located %d bytes to the right",
699          is_write ? "WRITE" : "READ", oob_distance);
700  return string(expected_str);
701}
702
703string RightOOBWriteMessage(int oob_distance) {
704  return RightOOBErrorMessage(oob_distance, /*is_write*/true);
705}
706
707string RightOOBReadMessage(int oob_distance) {
708  return RightOOBErrorMessage(oob_distance, /*is_write*/false);
709}
710
711string LeftOOBErrorMessage(int oob_distance, bool is_write) {
712  assert(oob_distance > 0);
713  char expected_str[100];
714  sprintf(expected_str, ASAN_PCRE_DOTALL "%s.*located %d bytes to the left",
715          is_write ? "WRITE" : "READ", oob_distance);
716  return string(expected_str);
717}
718
719string LeftOOBWriteMessage(int oob_distance) {
720  return LeftOOBErrorMessage(oob_distance, /*is_write*/true);
721}
722
723string LeftOOBReadMessage(int oob_distance) {
724  return LeftOOBErrorMessage(oob_distance, /*is_write*/false);
725}
726
727string LeftOOBAccessMessage(int oob_distance) {
728  assert(oob_distance > 0);
729  char expected_str[100];
730  sprintf(expected_str, "located %d bytes to the left", oob_distance);
731  return string(expected_str);
732}
733
734char* MallocAndMemsetString(size_t size, char ch) {
735  char *s = Ident((char*)malloc(size));
736  memset(s, ch, size);
737  return s;
738}
739
740char* MallocAndMemsetString(size_t size) {
741  return MallocAndMemsetString(size, 'z');
742}
743
744#if defined(__linux__) && !defined(ANDROID) && !defined(__ANDROID__)
745#define READ_TEST(READ_N_BYTES)                                          \
746  char *x = new char[10];                                                \
747  int fd = open("/proc/self/stat", O_RDONLY);                            \
748  ASSERT_GT(fd, 0);                                                      \
749  EXPECT_DEATH(READ_N_BYTES,                                             \
750               ASAN_PCRE_DOTALL                                          \
751               "AddressSanitizer: heap-buffer-overflow"                  \
752               ".* is located 0 bytes to the right of 10-byte region");  \
753  close(fd);                                                             \
754  delete [] x;                                                           \
755
756TEST(AddressSanitizer, pread) {
757  READ_TEST(pread(fd, x, 15, 0));
758}
759
760TEST(AddressSanitizer, pread64) {
761  READ_TEST(pread64(fd, x, 15, 0));
762}
763
764TEST(AddressSanitizer, read) {
765  READ_TEST(read(fd, x, 15));
766}
767#endif  // defined(__linux__) && !defined(ANDROID) && !defined(__ANDROID__)
768
769// This test case fails
770// Clang optimizes memcpy/memset calls which lead to unaligned access
771TEST(AddressSanitizer, DISABLED_MemIntrinsicUnalignedAccessTest) {
772  int size = Ident(4096);
773  char *s = Ident((char*)malloc(size));
774  EXPECT_DEATH(memset(s + size - 1, 0, 2), RightOOBWriteMessage(0));
775  free(s);
776}
777
778// TODO(samsonov): Add a test with malloc(0)
779// TODO(samsonov): Add tests for str* and mem* functions.
780
781NOINLINE static int LargeFunction(bool do_bad_access) {
782  int *x = new int[100];
783  x[0]++;
784  x[1]++;
785  x[2]++;
786  x[3]++;
787  x[4]++;
788  x[5]++;
789  x[6]++;
790  x[7]++;
791  x[8]++;
792  x[9]++;
793
794  x[do_bad_access ? 100 : 0]++; int res = __LINE__;
795
796  x[10]++;
797  x[11]++;
798  x[12]++;
799  x[13]++;
800  x[14]++;
801  x[15]++;
802  x[16]++;
803  x[17]++;
804  x[18]++;
805  x[19]++;
806
807  delete x;
808  return res;
809}
810
811// Test the we have correct debug info for the failing instruction.
812// This test requires the in-process symbolizer to be enabled by default.
813TEST(AddressSanitizer, DISABLED_LargeFunctionSymbolizeTest) {
814  int failing_line = LargeFunction(false);
815  char expected_warning[128];
816  sprintf(expected_warning, "LargeFunction.*asan_test.*:%d", failing_line);
817  EXPECT_DEATH(LargeFunction(true), expected_warning);
818}
819
820// Check that we unwind and symbolize correctly.
821TEST(AddressSanitizer, DISABLED_MallocFreeUnwindAndSymbolizeTest) {
822  int *a = (int*)malloc_aaa(sizeof(int));
823  *a = 1;
824  free_aaa(a);
825  EXPECT_DEATH(*a = 1, "free_ccc.*free_bbb.*free_aaa.*"
826               "malloc_fff.*malloc_eee.*malloc_ddd");
827}
828
829static bool TryToSetThreadName(const char *name) {
830#if defined(__linux__) && defined(PR_SET_NAME)
831  return 0 == prctl(PR_SET_NAME, (unsigned long)name, 0, 0, 0);
832#else
833  return false;
834#endif
835}
836
837void *ThreadedTestAlloc(void *a) {
838  EXPECT_EQ(true, TryToSetThreadName("AllocThr"));
839  int **p = (int**)a;
840  *p = new int;
841  return 0;
842}
843
844void *ThreadedTestFree(void *a) {
845  EXPECT_EQ(true, TryToSetThreadName("FreeThr"));
846  int **p = (int**)a;
847  delete *p;
848  return 0;
849}
850
851void *ThreadedTestUse(void *a) {
852  EXPECT_EQ(true, TryToSetThreadName("UseThr"));
853  int **p = (int**)a;
854  **p = 1;
855  return 0;
856}
857
858void ThreadedTestSpawn() {
859  pthread_t t;
860  int *x;
861  PTHREAD_CREATE(&t, 0, ThreadedTestAlloc, &x);
862  PTHREAD_JOIN(t, 0);
863  PTHREAD_CREATE(&t, 0, ThreadedTestFree, &x);
864  PTHREAD_JOIN(t, 0);
865  PTHREAD_CREATE(&t, 0, ThreadedTestUse, &x);
866  PTHREAD_JOIN(t, 0);
867}
868
869TEST(AddressSanitizer, ThreadedTest) {
870  EXPECT_DEATH(ThreadedTestSpawn(),
871               ASAN_PCRE_DOTALL
872               "Thread T.*created"
873               ".*Thread T.*created"
874               ".*Thread T.*created");
875}
876
877void *ThreadedTestFunc(void *unused) {
878  // Check if prctl(PR_SET_NAME) is supported. Return if not.
879  if (!TryToSetThreadName("TestFunc"))
880    return 0;
881  EXPECT_DEATH(ThreadedTestSpawn(),
882               ASAN_PCRE_DOTALL
883               "WRITE .*thread T. .UseThr."
884               ".*freed by thread T. .FreeThr. here:"
885               ".*previously allocated by thread T. .AllocThr. here:"
886               ".*Thread T. .UseThr. created by T.*TestFunc"
887               ".*Thread T. .FreeThr. created by T"
888               ".*Thread T. .AllocThr. created by T"
889               "");
890  return 0;
891}
892
893TEST(AddressSanitizer, ThreadNamesTest) {
894  // Run ThreadedTestFunc in a separate thread because it tries to set a
895  // thread name and we don't want to change the main thread's name.
896  pthread_t t;
897  PTHREAD_CREATE(&t, 0, ThreadedTestFunc, 0);
898  PTHREAD_JOIN(t, 0);
899}
900
901#if ASAN_NEEDS_SEGV
902TEST(AddressSanitizer, ShadowGapTest) {
903#if SANITIZER_WORDSIZE == 32
904  char *addr = (char*)0x22000000;
905#else
906  char *addr = (char*)0x0000100000080000;
907#endif
908  EXPECT_DEATH(*addr = 1, "AddressSanitizer: SEGV on unknown");
909}
910#endif  // ASAN_NEEDS_SEGV
911
912extern "C" {
913NOINLINE static void UseThenFreeThenUse() {
914  char *x = Ident((char*)malloc(8));
915  *x = 1;
916  free_aaa(x);
917  *x = 2;
918}
919}
920
921TEST(AddressSanitizer, UseThenFreeThenUseTest) {
922  EXPECT_DEATH(UseThenFreeThenUse(), "freed by thread");
923}
924
925TEST(AddressSanitizer, StrDupTest) {
926  free(strdup(Ident("123")));
927}
928
929// Currently we create and poison redzone at right of global variables.
930static char static110[110];
931const char ConstGlob[7] = {1, 2, 3, 4, 5, 6, 7};
932static const char StaticConstGlob[3] = {9, 8, 7};
933
934TEST(AddressSanitizer, GlobalTest) {
935  static char func_static15[15];
936
937  static char fs1[10];
938  static char fs2[10];
939  static char fs3[10];
940
941  glob5[Ident(0)] = 0;
942  glob5[Ident(1)] = 0;
943  glob5[Ident(2)] = 0;
944  glob5[Ident(3)] = 0;
945  glob5[Ident(4)] = 0;
946
947  EXPECT_DEATH(glob5[Ident(5)] = 0,
948               "0 bytes to the right of global variable.*glob5.* size 5");
949  EXPECT_DEATH(glob5[Ident(5+6)] = 0,
950               "6 bytes to the right of global variable.*glob5.* size 5");
951  Ident(static110);  // avoid optimizations
952  static110[Ident(0)] = 0;
953  static110[Ident(109)] = 0;
954  EXPECT_DEATH(static110[Ident(110)] = 0,
955               "0 bytes to the right of global variable");
956  EXPECT_DEATH(static110[Ident(110+7)] = 0,
957               "7 bytes to the right of global variable");
958
959  Ident(func_static15);  // avoid optimizations
960  func_static15[Ident(0)] = 0;
961  EXPECT_DEATH(func_static15[Ident(15)] = 0,
962               "0 bytes to the right of global variable");
963  EXPECT_DEATH(func_static15[Ident(15 + 9)] = 0,
964               "9 bytes to the right of global variable");
965
966  Ident(fs1);
967  Ident(fs2);
968  Ident(fs3);
969
970  // We don't create left redzones, so this is not 100% guaranteed to fail.
971  // But most likely will.
972  EXPECT_DEATH(fs2[Ident(-1)] = 0, "is located.*of global variable");
973
974  EXPECT_DEATH(Ident(Ident(ConstGlob)[8]),
975               "is located 1 bytes to the right of .*ConstGlob");
976  EXPECT_DEATH(Ident(Ident(StaticConstGlob)[5]),
977               "is located 2 bytes to the right of .*StaticConstGlob");
978
979  // call stuff from another file.
980  GlobalsTest(0);
981}
982
983TEST(AddressSanitizer, GlobalStringConstTest) {
984  static const char *zoo = "FOOBAR123";
985  const char *p = Ident(zoo);
986  EXPECT_DEATH(Ident(p[15]), "is ascii string 'FOOBAR123'");
987}
988
989TEST(AddressSanitizer, FileNameInGlobalReportTest) {
990  static char zoo[10];
991  const char *p = Ident(zoo);
992  // The file name should be present in the report.
993  EXPECT_DEATH(Ident(p[15]), "zoo.*asan_test.");
994}
995
996int *ReturnsPointerToALocalObject() {
997  int a = 0;
998  return Ident(&a);
999}
1000
1001#if ASAN_UAR == 1
1002TEST(AddressSanitizer, LocalReferenceReturnTest) {
1003  int *(*f)() = Ident(ReturnsPointerToALocalObject);
1004  int *p = f();
1005  // Call 'f' a few more times, 'p' should still be poisoned.
1006  for (int i = 0; i < 32; i++)
1007    f();
1008  EXPECT_DEATH(*p = 1, "AddressSanitizer: stack-use-after-return");
1009  EXPECT_DEATH(*p = 1, "is located.*in frame .*ReturnsPointerToALocal");
1010}
1011#endif
1012
1013template <int kSize>
1014NOINLINE static void FuncWithStack() {
1015  char x[kSize];
1016  Ident(x)[0] = 0;
1017  Ident(x)[kSize-1] = 0;
1018}
1019
1020static void LotsOfStackReuse() {
1021  int LargeStack[10000];
1022  Ident(LargeStack)[0] = 0;
1023  for (int i = 0; i < 10000; i++) {
1024    FuncWithStack<128 * 1>();
1025    FuncWithStack<128 * 2>();
1026    FuncWithStack<128 * 4>();
1027    FuncWithStack<128 * 8>();
1028    FuncWithStack<128 * 16>();
1029    FuncWithStack<128 * 32>();
1030    FuncWithStack<128 * 64>();
1031    FuncWithStack<128 * 128>();
1032    FuncWithStack<128 * 256>();
1033    FuncWithStack<128 * 512>();
1034    Ident(LargeStack)[0] = 0;
1035  }
1036}
1037
1038TEST(AddressSanitizer, StressStackReuseTest) {
1039  LotsOfStackReuse();
1040}
1041
1042TEST(AddressSanitizer, ThreadedStressStackReuseTest) {
1043  const int kNumThreads = 20;
1044  pthread_t t[kNumThreads];
1045  for (int i = 0; i < kNumThreads; i++) {
1046    PTHREAD_CREATE(&t[i], 0, (void* (*)(void *x))LotsOfStackReuse, 0);
1047  }
1048  for (int i = 0; i < kNumThreads; i++) {
1049    PTHREAD_JOIN(t[i], 0);
1050  }
1051}
1052
1053static void *PthreadExit(void *a) {
1054  pthread_exit(0);
1055  return 0;
1056}
1057
1058TEST(AddressSanitizer, PthreadExitTest) {
1059  pthread_t t;
1060  for (int i = 0; i < 1000; i++) {
1061    PTHREAD_CREATE(&t, 0, PthreadExit, 0);
1062    PTHREAD_JOIN(t, 0);
1063  }
1064}
1065
1066#ifdef __EXCEPTIONS
1067NOINLINE static void StackReuseAndException() {
1068  int large_stack[1000];
1069  Ident(large_stack);
1070  ASAN_THROW(1);
1071}
1072
1073// TODO(kcc): support exceptions with use-after-return.
1074TEST(AddressSanitizer, DISABLED_StressStackReuseAndExceptionsTest) {
1075  for (int i = 0; i < 10000; i++) {
1076    try {
1077    StackReuseAndException();
1078    } catch(...) {
1079    }
1080  }
1081}
1082#endif
1083
1084TEST(AddressSanitizer, MlockTest) {
1085  EXPECT_EQ(0, mlockall(MCL_CURRENT));
1086  EXPECT_EQ(0, mlock((void*)0x12345, 0x5678));
1087  EXPECT_EQ(0, munlockall());
1088  EXPECT_EQ(0, munlock((void*)0x987, 0x654));
1089}
1090
1091struct LargeStruct {
1092  int foo[100];
1093};
1094
1095// Test for bug http://llvm.org/bugs/show_bug.cgi?id=11763.
1096// Struct copy should not cause asan warning even if lhs == rhs.
1097TEST(AddressSanitizer, LargeStructCopyTest) {
1098  LargeStruct a;
1099  *Ident(&a) = *Ident(&a);
1100}
1101
1102ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
1103static void NoAddressSafety() {
1104  char *foo = new char[10];
1105  Ident(foo)[10] = 0;
1106  delete [] foo;
1107}
1108
1109TEST(AddressSanitizer, AttributeNoAddressSafetyTest) {
1110  Ident(NoAddressSafety)();
1111}
1112
1113// TODO(glider): Enable this test on Mac.
1114// It doesn't work on Android, as calls to new/delete go through malloc/free.
1115#if !defined(__APPLE__) && !defined(ANDROID) && !defined(__ANDROID__)
1116static string MismatchStr(const string &str) {
1117  return string("AddressSanitizer: alloc-dealloc-mismatch \\(") + str;
1118}
1119
1120TEST(AddressSanitizer, AllocDeallocMismatch) {
1121  EXPECT_DEATH(free(Ident(new int)),
1122               MismatchStr("operator new vs free"));
1123  EXPECT_DEATH(free(Ident(new int[2])),
1124               MismatchStr("operator new \\[\\] vs free"));
1125  EXPECT_DEATH(delete (Ident(new int[2])),
1126               MismatchStr("operator new \\[\\] vs operator delete"));
1127  EXPECT_DEATH(delete (Ident((int*)malloc(2 * sizeof(int)))),
1128               MismatchStr("malloc vs operator delete"));
1129  EXPECT_DEATH(delete [] (Ident(new int)),
1130               MismatchStr("operator new vs operator delete \\[\\]"));
1131  EXPECT_DEATH(delete [] (Ident((int*)malloc(2 * sizeof(int)))),
1132               MismatchStr("malloc vs operator delete \\[\\]"));
1133}
1134#endif
1135
1136// ------------------ demo tests; run each one-by-one -------------
1137// e.g. --gtest_filter=*DemoOOBLeftHigh --gtest_also_run_disabled_tests
1138TEST(AddressSanitizer, DISABLED_DemoThreadedTest) {
1139  ThreadedTestSpawn();
1140}
1141
1142void *SimpleBugOnSTack(void *x = 0) {
1143  char a[20];
1144  Ident(a)[20] = 0;
1145  return 0;
1146}
1147
1148TEST(AddressSanitizer, DISABLED_DemoStackTest) {
1149  SimpleBugOnSTack();
1150}
1151
1152TEST(AddressSanitizer, DISABLED_DemoThreadStackTest) {
1153  pthread_t t;
1154  PTHREAD_CREATE(&t, 0, SimpleBugOnSTack, 0);
1155  PTHREAD_JOIN(t, 0);
1156}
1157
1158TEST(AddressSanitizer, DISABLED_DemoUAFLowIn) {
1159  uaf_test<U1>(10, 0);
1160}
1161TEST(AddressSanitizer, DISABLED_DemoUAFLowLeft) {
1162  uaf_test<U1>(10, -2);
1163}
1164TEST(AddressSanitizer, DISABLED_DemoUAFLowRight) {
1165  uaf_test<U1>(10, 10);
1166}
1167
1168TEST(AddressSanitizer, DISABLED_DemoUAFHigh) {
1169  uaf_test<U1>(kLargeMalloc, 0);
1170}
1171
1172TEST(AddressSanitizer, DISABLED_DemoOOM) {
1173  size_t size = SANITIZER_WORDSIZE == 64 ? (size_t)(1ULL << 40) : (0xf0000000);
1174  printf("%p\n", malloc(size));
1175}
1176
1177TEST(AddressSanitizer, DISABLED_DemoDoubleFreeTest) {
1178  DoubleFree();
1179}
1180
1181TEST(AddressSanitizer, DISABLED_DemoNullDerefTest) {
1182  int *a = 0;
1183  Ident(a)[10] = 0;
1184}
1185
1186TEST(AddressSanitizer, DISABLED_DemoFunctionStaticTest) {
1187  static char a[100];
1188  static char b[100];
1189  static char c[100];
1190  Ident(a);
1191  Ident(b);
1192  Ident(c);
1193  Ident(a)[5] = 0;
1194  Ident(b)[105] = 0;
1195  Ident(a)[5] = 0;
1196}
1197
1198TEST(AddressSanitizer, DISABLED_DemoTooMuchMemoryTest) {
1199  const size_t kAllocSize = (1 << 28) - 1024;
1200  size_t total_size = 0;
1201  while (true) {
1202    char *x = (char*)malloc(kAllocSize);
1203    memset(x, 0, kAllocSize);
1204    total_size += kAllocSize;
1205    fprintf(stderr, "total: %ldM %p\n", (long)total_size >> 20, x);
1206  }
1207}
1208
1209// http://code.google.com/p/address-sanitizer/issues/detail?id=66
1210TEST(AddressSanitizer, BufferOverflowAfterManyFrees) {
1211  for (int i = 0; i < 1000000; i++) {
1212    delete [] (Ident(new char [8644]));
1213  }
1214  char *x = new char[8192];
1215  EXPECT_DEATH(x[Ident(8192)] = 0, "AddressSanitizer: heap-buffer-overflow");
1216  delete [] Ident(x);
1217}
1218
1219
1220// Test that instrumentation of stack allocations takes into account
1221// AllocSize of a type, and not its StoreSize (16 vs 10 bytes for long double).
1222// See http://llvm.org/bugs/show_bug.cgi?id=12047 for more details.
1223TEST(AddressSanitizer, LongDoubleNegativeTest) {
1224  long double a, b;
1225  static long double c;
1226  memcpy(Ident(&a), Ident(&b), sizeof(long double));
1227  memcpy(Ident(&c), Ident(&b), sizeof(long double));
1228}
1229