asan_test.cc revision a180078ee0120c049f9fb495f930053f80f105aa
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  fprintf(stderr, "Malloc(0): %p\n", ptr2);
387  ptr2 = Ident((int*)realloc(ptr2, sizeof(*ptr2)));
388  fprintf(stderr, "Realloc(0, 4): %p\n", ptr2);
389  *ptr2 = 42;
390  EXPECT_EQ(42, *ptr2);
391  free(ptr2);
392}
393
394TEST(AddressSanitizer, ZeroSizeMallocTest) {
395  // Test that malloc(0) and similar functions don't return NULL.
396  void *ptr = Ident(malloc(0));
397  EXPECT_TRUE(NULL != ptr);
398  free(ptr);
399#if !defined(__APPLE__) && !defined(ANDROID) && !defined(__ANDROID__)
400  int pm_res = posix_memalign(&ptr, 1<<20, 0);
401  EXPECT_EQ(0, pm_res);
402  EXPECT_TRUE(NULL != ptr);
403  free(ptr);
404#endif
405  int *int_ptr = new int[0];
406  int *int_ptr2 = new int[0];
407  EXPECT_TRUE(NULL != int_ptr);
408  EXPECT_TRUE(NULL != int_ptr2);
409  EXPECT_NE(int_ptr, int_ptr2);
410  delete[] int_ptr;
411  delete[] int_ptr2;
412}
413
414#ifndef __APPLE__
415static const char *kMallocUsableSizeErrorMsg =
416  "AddressSanitizer: attempting to call malloc_usable_size()";
417
418TEST(AddressSanitizer, MallocUsableSizeTest) {
419  const size_t kArraySize = 100;
420  char *array = Ident((char*)malloc(kArraySize));
421  int *int_ptr = Ident(new int);
422  EXPECT_EQ(0U, malloc_usable_size(NULL));
423  EXPECT_EQ(kArraySize, malloc_usable_size(array));
424  EXPECT_EQ(sizeof(int), malloc_usable_size(int_ptr));
425  EXPECT_DEATH(malloc_usable_size((void*)0x123), kMallocUsableSizeErrorMsg);
426  EXPECT_DEATH(malloc_usable_size(array + kArraySize / 2),
427               kMallocUsableSizeErrorMsg);
428  free(array);
429  EXPECT_DEATH(malloc_usable_size(array), kMallocUsableSizeErrorMsg);
430}
431#endif
432
433void WrongFree() {
434  int *x = (int*)malloc(100 * sizeof(int));
435  // Use the allocated memory, otherwise Clang will optimize it out.
436  Ident(x);
437  free(x + 1);
438}
439
440TEST(AddressSanitizer, WrongFreeTest) {
441  EXPECT_DEATH(WrongFree(),
442               "ERROR: AddressSanitizer: attempting free.*not malloc");
443}
444
445void DoubleFree() {
446  int *x = (int*)malloc(100 * sizeof(int));
447  fprintf(stderr, "DoubleFree: x=%p\n", x);
448  free(x);
449  free(x);
450  fprintf(stderr, "should have failed in the second free(%p)\n", x);
451  abort();
452}
453
454TEST(AddressSanitizer, DoubleFreeTest) {
455  EXPECT_DEATH(DoubleFree(), ASAN_PCRE_DOTALL
456               "ERROR: AddressSanitizer: attempting double-free"
457               ".*is located 0 bytes inside of 400-byte region"
458               ".*freed by thread T0 here"
459               ".*previously allocated by thread T0 here");
460}
461
462template<int kSize>
463NOINLINE void SizedStackTest() {
464  char a[kSize];
465  char  *A = Ident((char*)&a);
466  for (size_t i = 0; i < kSize; i++)
467    A[i] = i;
468  EXPECT_DEATH(A[-1] = 0, "");
469  EXPECT_DEATH(A[-20] = 0, "");
470  EXPECT_DEATH(A[-31] = 0, "");
471  EXPECT_DEATH(A[kSize] = 0, "");
472  EXPECT_DEATH(A[kSize + 1] = 0, "");
473  EXPECT_DEATH(A[kSize + 10] = 0, "");
474  EXPECT_DEATH(A[kSize + 31] = 0, "");
475}
476
477TEST(AddressSanitizer, SimpleStackTest) {
478  SizedStackTest<1>();
479  SizedStackTest<2>();
480  SizedStackTest<3>();
481  SizedStackTest<4>();
482  SizedStackTest<5>();
483  SizedStackTest<6>();
484  SizedStackTest<7>();
485  SizedStackTest<16>();
486  SizedStackTest<25>();
487  SizedStackTest<34>();
488  SizedStackTest<43>();
489  SizedStackTest<51>();
490  SizedStackTest<62>();
491  SizedStackTest<64>();
492  SizedStackTest<128>();
493}
494
495TEST(AddressSanitizer, ManyStackObjectsTest) {
496  char XXX[10];
497  char YYY[20];
498  char ZZZ[30];
499  Ident(XXX);
500  Ident(YYY);
501  EXPECT_DEATH(Ident(ZZZ)[-1] = 0, ASAN_PCRE_DOTALL "XXX.*YYY.*ZZZ");
502}
503
504NOINLINE static void Frame0(int frame, char *a, char *b, char *c) {
505  char d[4] = {0};
506  char *D = Ident(d);
507  switch (frame) {
508    case 3: a[5]++; break;
509    case 2: b[5]++; break;
510    case 1: c[5]++; break;
511    case 0: D[5]++; break;
512  }
513}
514NOINLINE static void Frame1(int frame, char *a, char *b) {
515  char c[4] = {0}; Frame0(frame, a, b, c);
516  break_optimization(0);
517}
518NOINLINE static void Frame2(int frame, char *a) {
519  char b[4] = {0}; Frame1(frame, a, b);
520  break_optimization(0);
521}
522NOINLINE static void Frame3(int frame) {
523  char a[4] = {0}; Frame2(frame, a);
524  break_optimization(0);
525}
526
527TEST(AddressSanitizer, GuiltyStackFrame0Test) {
528  EXPECT_DEATH(Frame3(0), "located .*in frame <.*Frame0");
529}
530TEST(AddressSanitizer, GuiltyStackFrame1Test) {
531  EXPECT_DEATH(Frame3(1), "located .*in frame <.*Frame1");
532}
533TEST(AddressSanitizer, GuiltyStackFrame2Test) {
534  EXPECT_DEATH(Frame3(2), "located .*in frame <.*Frame2");
535}
536TEST(AddressSanitizer, GuiltyStackFrame3Test) {
537  EXPECT_DEATH(Frame3(3), "located .*in frame <.*Frame3");
538}
539
540NOINLINE void LongJmpFunc1(jmp_buf buf) {
541  // create three red zones for these two stack objects.
542  int a;
543  int b;
544
545  int *A = Ident(&a);
546  int *B = Ident(&b);
547  *A = *B;
548  longjmp(buf, 1);
549}
550
551NOINLINE void BuiltinLongJmpFunc1(jmp_buf buf) {
552  // create three red zones for these two stack objects.
553  int a;
554  int b;
555
556  int *A = Ident(&a);
557  int *B = Ident(&b);
558  *A = *B;
559  __builtin_longjmp((void**)buf, 1);
560}
561
562NOINLINE void UnderscopeLongJmpFunc1(jmp_buf buf) {
563  // create three red zones for these two stack objects.
564  int a;
565  int b;
566
567  int *A = Ident(&a);
568  int *B = Ident(&b);
569  *A = *B;
570  _longjmp(buf, 1);
571}
572
573NOINLINE void SigLongJmpFunc1(sigjmp_buf buf) {
574  // create three red zones for these two stack objects.
575  int a;
576  int b;
577
578  int *A = Ident(&a);
579  int *B = Ident(&b);
580  *A = *B;
581  siglongjmp(buf, 1);
582}
583
584
585NOINLINE void TouchStackFunc() {
586  int a[100];  // long array will intersect with redzones from LongJmpFunc1.
587  int *A = Ident(a);
588  for (int i = 0; i < 100; i++)
589    A[i] = i*i;
590}
591
592// Test that we handle longjmp and do not report fals positives on stack.
593TEST(AddressSanitizer, LongJmpTest) {
594  static jmp_buf buf;
595  if (!setjmp(buf)) {
596    LongJmpFunc1(buf);
597  } else {
598    TouchStackFunc();
599  }
600}
601
602#if not defined(__ANDROID__)
603TEST(AddressSanitizer, BuiltinLongJmpTest) {
604  static jmp_buf buf;
605  if (!__builtin_setjmp((void**)buf)) {
606    BuiltinLongJmpFunc1(buf);
607  } else {
608    TouchStackFunc();
609  }
610}
611#endif  // not defined(__ANDROID__)
612
613TEST(AddressSanitizer, UnderscopeLongJmpTest) {
614  static jmp_buf buf;
615  if (!_setjmp(buf)) {
616    UnderscopeLongJmpFunc1(buf);
617  } else {
618    TouchStackFunc();
619  }
620}
621
622TEST(AddressSanitizer, SigLongJmpTest) {
623  static sigjmp_buf buf;
624  if (!sigsetjmp(buf, 1)) {
625    SigLongJmpFunc1(buf);
626  } else {
627    TouchStackFunc();
628  }
629}
630
631#ifdef __EXCEPTIONS
632NOINLINE void ThrowFunc() {
633  // create three red zones for these two stack objects.
634  int a;
635  int b;
636
637  int *A = Ident(&a);
638  int *B = Ident(&b);
639  *A = *B;
640  ASAN_THROW(1);
641}
642
643TEST(AddressSanitizer, CxxExceptionTest) {
644  if (ASAN_UAR) return;
645  // TODO(kcc): this test crashes on 32-bit for some reason...
646  if (SANITIZER_WORDSIZE == 32) return;
647  try {
648    ThrowFunc();
649  } catch(...) {}
650  TouchStackFunc();
651}
652#endif
653
654void *ThreadStackReuseFunc1(void *unused) {
655  // create three red zones for these two stack objects.
656  int a;
657  int b;
658
659  int *A = Ident(&a);
660  int *B = Ident(&b);
661  *A = *B;
662  pthread_exit(0);
663  return 0;
664}
665
666void *ThreadStackReuseFunc2(void *unused) {
667  TouchStackFunc();
668  return 0;
669}
670
671TEST(AddressSanitizer, ThreadStackReuseTest) {
672  pthread_t t;
673  PTHREAD_CREATE(&t, 0, ThreadStackReuseFunc1, 0);
674  PTHREAD_JOIN(t, 0);
675  PTHREAD_CREATE(&t, 0, ThreadStackReuseFunc2, 0);
676  PTHREAD_JOIN(t, 0);
677}
678
679#if defined(__i386__) || defined(__x86_64__)
680TEST(AddressSanitizer, Store128Test) {
681  char *a = Ident((char*)malloc(Ident(12)));
682  char *p = a;
683  if (((uintptr_t)a % 16) != 0)
684    p = a + 8;
685  assert(((uintptr_t)p % 16) == 0);
686  __m128i value_wide = _mm_set1_epi16(0x1234);
687  EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
688               "AddressSanitizer: heap-buffer-overflow");
689  EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
690               "WRITE of size 16");
691  EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
692               "located 0 bytes to the right of 12-byte");
693  free(a);
694}
695#endif
696
697string RightOOBErrorMessage(int oob_distance, bool is_write) {
698  assert(oob_distance >= 0);
699  char expected_str[100];
700  sprintf(expected_str, ASAN_PCRE_DOTALL "%s.*located %d bytes to the right",
701          is_write ? "WRITE" : "READ", oob_distance);
702  return string(expected_str);
703}
704
705string RightOOBWriteMessage(int oob_distance) {
706  return RightOOBErrorMessage(oob_distance, /*is_write*/true);
707}
708
709string RightOOBReadMessage(int oob_distance) {
710  return RightOOBErrorMessage(oob_distance, /*is_write*/false);
711}
712
713string LeftOOBErrorMessage(int oob_distance, bool is_write) {
714  assert(oob_distance > 0);
715  char expected_str[100];
716  sprintf(expected_str, ASAN_PCRE_DOTALL "%s.*located %d bytes to the left",
717          is_write ? "WRITE" : "READ", oob_distance);
718  return string(expected_str);
719}
720
721string LeftOOBWriteMessage(int oob_distance) {
722  return LeftOOBErrorMessage(oob_distance, /*is_write*/true);
723}
724
725string LeftOOBReadMessage(int oob_distance) {
726  return LeftOOBErrorMessage(oob_distance, /*is_write*/false);
727}
728
729string LeftOOBAccessMessage(int oob_distance) {
730  assert(oob_distance > 0);
731  char expected_str[100];
732  sprintf(expected_str, "located %d bytes to the left", oob_distance);
733  return string(expected_str);
734}
735
736char* MallocAndMemsetString(size_t size, char ch) {
737  char *s = Ident((char*)malloc(size));
738  memset(s, ch, size);
739  return s;
740}
741
742char* MallocAndMemsetString(size_t size) {
743  return MallocAndMemsetString(size, 'z');
744}
745
746#if defined(__linux__) && !defined(ANDROID) && !defined(__ANDROID__)
747#define READ_TEST(READ_N_BYTES)                                          \
748  char *x = new char[10];                                                \
749  int fd = open("/proc/self/stat", O_RDONLY);                            \
750  ASSERT_GT(fd, 0);                                                      \
751  EXPECT_DEATH(READ_N_BYTES,                                             \
752               ASAN_PCRE_DOTALL                                          \
753               "AddressSanitizer: heap-buffer-overflow"                  \
754               ".* is located 0 bytes to the right of 10-byte region");  \
755  close(fd);                                                             \
756  delete [] x;                                                           \
757
758TEST(AddressSanitizer, pread) {
759  READ_TEST(pread(fd, x, 15, 0));
760}
761
762TEST(AddressSanitizer, pread64) {
763  READ_TEST(pread64(fd, x, 15, 0));
764}
765
766TEST(AddressSanitizer, read) {
767  READ_TEST(read(fd, x, 15));
768}
769#endif  // defined(__linux__) && !defined(ANDROID) && !defined(__ANDROID__)
770
771// This test case fails
772// Clang optimizes memcpy/memset calls which lead to unaligned access
773TEST(AddressSanitizer, DISABLED_MemIntrinsicUnalignedAccessTest) {
774  int size = Ident(4096);
775  char *s = Ident((char*)malloc(size));
776  EXPECT_DEATH(memset(s + size - 1, 0, 2), RightOOBWriteMessage(0));
777  free(s);
778}
779
780// TODO(samsonov): Add a test with malloc(0)
781// TODO(samsonov): Add tests for str* and mem* functions.
782
783NOINLINE static int LargeFunction(bool do_bad_access) {
784  int *x = new int[100];
785  x[0]++;
786  x[1]++;
787  x[2]++;
788  x[3]++;
789  x[4]++;
790  x[5]++;
791  x[6]++;
792  x[7]++;
793  x[8]++;
794  x[9]++;
795
796  x[do_bad_access ? 100 : 0]++; int res = __LINE__;
797
798  x[10]++;
799  x[11]++;
800  x[12]++;
801  x[13]++;
802  x[14]++;
803  x[15]++;
804  x[16]++;
805  x[17]++;
806  x[18]++;
807  x[19]++;
808
809  delete x;
810  return res;
811}
812
813// Test the we have correct debug info for the failing instruction.
814// This test requires the in-process symbolizer to be enabled by default.
815TEST(AddressSanitizer, DISABLED_LargeFunctionSymbolizeTest) {
816  int failing_line = LargeFunction(false);
817  char expected_warning[128];
818  sprintf(expected_warning, "LargeFunction.*asan_test.*:%d", failing_line);
819  EXPECT_DEATH(LargeFunction(true), expected_warning);
820}
821
822// Check that we unwind and symbolize correctly.
823TEST(AddressSanitizer, DISABLED_MallocFreeUnwindAndSymbolizeTest) {
824  int *a = (int*)malloc_aaa(sizeof(int));
825  *a = 1;
826  free_aaa(a);
827  EXPECT_DEATH(*a = 1, "free_ccc.*free_bbb.*free_aaa.*"
828               "malloc_fff.*malloc_eee.*malloc_ddd");
829}
830
831static bool TryToSetThreadName(const char *name) {
832#if defined(__linux__) && defined(PR_SET_NAME)
833  return 0 == prctl(PR_SET_NAME, (unsigned long)name, 0, 0, 0);
834#else
835  return false;
836#endif
837}
838
839void *ThreadedTestAlloc(void *a) {
840  EXPECT_EQ(true, TryToSetThreadName("AllocThr"));
841  int **p = (int**)a;
842  *p = new int;
843  return 0;
844}
845
846void *ThreadedTestFree(void *a) {
847  EXPECT_EQ(true, TryToSetThreadName("FreeThr"));
848  int **p = (int**)a;
849  delete *p;
850  return 0;
851}
852
853void *ThreadedTestUse(void *a) {
854  EXPECT_EQ(true, TryToSetThreadName("UseThr"));
855  int **p = (int**)a;
856  **p = 1;
857  return 0;
858}
859
860void ThreadedTestSpawn() {
861  pthread_t t;
862  int *x;
863  PTHREAD_CREATE(&t, 0, ThreadedTestAlloc, &x);
864  PTHREAD_JOIN(t, 0);
865  PTHREAD_CREATE(&t, 0, ThreadedTestFree, &x);
866  PTHREAD_JOIN(t, 0);
867  PTHREAD_CREATE(&t, 0, ThreadedTestUse, &x);
868  PTHREAD_JOIN(t, 0);
869}
870
871TEST(AddressSanitizer, ThreadedTest) {
872  EXPECT_DEATH(ThreadedTestSpawn(),
873               ASAN_PCRE_DOTALL
874               "Thread T.*created"
875               ".*Thread T.*created"
876               ".*Thread T.*created");
877}
878
879void *ThreadedTestFunc(void *unused) {
880  // Check if prctl(PR_SET_NAME) is supported. Return if not.
881  if (!TryToSetThreadName("TestFunc"))
882    return 0;
883  EXPECT_DEATH(ThreadedTestSpawn(),
884               ASAN_PCRE_DOTALL
885               "WRITE .*thread T. .UseThr."
886               ".*freed by thread T. .FreeThr. here:"
887               ".*previously allocated by thread T. .AllocThr. here:"
888               ".*Thread T. .UseThr. created by T.*TestFunc"
889               ".*Thread T. .FreeThr. created by T"
890               ".*Thread T. .AllocThr. created by T"
891               "");
892  return 0;
893}
894
895TEST(AddressSanitizer, ThreadNamesTest) {
896  // Run ThreadedTestFunc in a separate thread because it tries to set a
897  // thread name and we don't want to change the main thread's name.
898  pthread_t t;
899  PTHREAD_CREATE(&t, 0, ThreadedTestFunc, 0);
900  PTHREAD_JOIN(t, 0);
901}
902
903#if ASAN_NEEDS_SEGV
904TEST(AddressSanitizer, ShadowGapTest) {
905#if SANITIZER_WORDSIZE == 32
906  char *addr = (char*)0x22000000;
907#else
908  char *addr = (char*)0x0000100000080000;
909#endif
910  EXPECT_DEATH(*addr = 1, "AddressSanitizer: SEGV on unknown");
911}
912#endif  // ASAN_NEEDS_SEGV
913
914extern "C" {
915NOINLINE static void UseThenFreeThenUse() {
916  char *x = Ident((char*)malloc(8));
917  *x = 1;
918  free_aaa(x);
919  *x = 2;
920}
921}
922
923TEST(AddressSanitizer, UseThenFreeThenUseTest) {
924  EXPECT_DEATH(UseThenFreeThenUse(), "freed by thread");
925}
926
927TEST(AddressSanitizer, StrDupTest) {
928  free(strdup(Ident("123")));
929}
930
931// Currently we create and poison redzone at right of global variables.
932static char static110[110];
933const char ConstGlob[7] = {1, 2, 3, 4, 5, 6, 7};
934static const char StaticConstGlob[3] = {9, 8, 7};
935
936TEST(AddressSanitizer, GlobalTest) {
937  static char func_static15[15];
938
939  static char fs1[10];
940  static char fs2[10];
941  static char fs3[10];
942
943  glob5[Ident(0)] = 0;
944  glob5[Ident(1)] = 0;
945  glob5[Ident(2)] = 0;
946  glob5[Ident(3)] = 0;
947  glob5[Ident(4)] = 0;
948
949  EXPECT_DEATH(glob5[Ident(5)] = 0,
950               "0 bytes to the right of global variable.*glob5.* size 5");
951  EXPECT_DEATH(glob5[Ident(5+6)] = 0,
952               "6 bytes to the right of global variable.*glob5.* size 5");
953  Ident(static110);  // avoid optimizations
954  static110[Ident(0)] = 0;
955  static110[Ident(109)] = 0;
956  EXPECT_DEATH(static110[Ident(110)] = 0,
957               "0 bytes to the right of global variable");
958  EXPECT_DEATH(static110[Ident(110+7)] = 0,
959               "7 bytes to the right of global variable");
960
961  Ident(func_static15);  // avoid optimizations
962  func_static15[Ident(0)] = 0;
963  EXPECT_DEATH(func_static15[Ident(15)] = 0,
964               "0 bytes to the right of global variable");
965  EXPECT_DEATH(func_static15[Ident(15 + 9)] = 0,
966               "9 bytes to the right of global variable");
967
968  Ident(fs1);
969  Ident(fs2);
970  Ident(fs3);
971
972  // We don't create left redzones, so this is not 100% guaranteed to fail.
973  // But most likely will.
974  EXPECT_DEATH(fs2[Ident(-1)] = 0, "is located.*of global variable");
975
976  EXPECT_DEATH(Ident(Ident(ConstGlob)[8]),
977               "is located 1 bytes to the right of .*ConstGlob");
978  EXPECT_DEATH(Ident(Ident(StaticConstGlob)[5]),
979               "is located 2 bytes to the right of .*StaticConstGlob");
980
981  // call stuff from another file.
982  GlobalsTest(0);
983}
984
985TEST(AddressSanitizer, GlobalStringConstTest) {
986  static const char *zoo = "FOOBAR123";
987  const char *p = Ident(zoo);
988  EXPECT_DEATH(Ident(p[15]), "is ascii string 'FOOBAR123'");
989}
990
991TEST(AddressSanitizer, FileNameInGlobalReportTest) {
992  static char zoo[10];
993  const char *p = Ident(zoo);
994  // The file name should be present in the report.
995  EXPECT_DEATH(Ident(p[15]), "zoo.*asan_test.");
996}
997
998int *ReturnsPointerToALocalObject() {
999  int a = 0;
1000  return Ident(&a);
1001}
1002
1003#if ASAN_UAR == 1
1004TEST(AddressSanitizer, LocalReferenceReturnTest) {
1005  int *(*f)() = Ident(ReturnsPointerToALocalObject);
1006  int *p = f();
1007  // Call 'f' a few more times, 'p' should still be poisoned.
1008  for (int i = 0; i < 32; i++)
1009    f();
1010  EXPECT_DEATH(*p = 1, "AddressSanitizer: stack-use-after-return");
1011  EXPECT_DEATH(*p = 1, "is located.*in frame .*ReturnsPointerToALocal");
1012}
1013#endif
1014
1015template <int kSize>
1016NOINLINE static void FuncWithStack() {
1017  char x[kSize];
1018  Ident(x)[0] = 0;
1019  Ident(x)[kSize-1] = 0;
1020}
1021
1022static void LotsOfStackReuse() {
1023  int LargeStack[10000];
1024  Ident(LargeStack)[0] = 0;
1025  for (int i = 0; i < 10000; i++) {
1026    FuncWithStack<128 * 1>();
1027    FuncWithStack<128 * 2>();
1028    FuncWithStack<128 * 4>();
1029    FuncWithStack<128 * 8>();
1030    FuncWithStack<128 * 16>();
1031    FuncWithStack<128 * 32>();
1032    FuncWithStack<128 * 64>();
1033    FuncWithStack<128 * 128>();
1034    FuncWithStack<128 * 256>();
1035    FuncWithStack<128 * 512>();
1036    Ident(LargeStack)[0] = 0;
1037  }
1038}
1039
1040TEST(AddressSanitizer, StressStackReuseTest) {
1041  LotsOfStackReuse();
1042}
1043
1044TEST(AddressSanitizer, ThreadedStressStackReuseTest) {
1045  const int kNumThreads = 20;
1046  pthread_t t[kNumThreads];
1047  for (int i = 0; i < kNumThreads; i++) {
1048    PTHREAD_CREATE(&t[i], 0, (void* (*)(void *x))LotsOfStackReuse, 0);
1049  }
1050  for (int i = 0; i < kNumThreads; i++) {
1051    PTHREAD_JOIN(t[i], 0);
1052  }
1053}
1054
1055static void *PthreadExit(void *a) {
1056  pthread_exit(0);
1057  return 0;
1058}
1059
1060TEST(AddressSanitizer, PthreadExitTest) {
1061  pthread_t t;
1062  for (int i = 0; i < 1000; i++) {
1063    PTHREAD_CREATE(&t, 0, PthreadExit, 0);
1064    PTHREAD_JOIN(t, 0);
1065  }
1066}
1067
1068#ifdef __EXCEPTIONS
1069NOINLINE static void StackReuseAndException() {
1070  int large_stack[1000];
1071  Ident(large_stack);
1072  ASAN_THROW(1);
1073}
1074
1075// TODO(kcc): support exceptions with use-after-return.
1076TEST(AddressSanitizer, DISABLED_StressStackReuseAndExceptionsTest) {
1077  for (int i = 0; i < 10000; i++) {
1078    try {
1079    StackReuseAndException();
1080    } catch(...) {
1081    }
1082  }
1083}
1084#endif
1085
1086TEST(AddressSanitizer, MlockTest) {
1087  EXPECT_EQ(0, mlockall(MCL_CURRENT));
1088  EXPECT_EQ(0, mlock((void*)0x12345, 0x5678));
1089  EXPECT_EQ(0, munlockall());
1090  EXPECT_EQ(0, munlock((void*)0x987, 0x654));
1091}
1092
1093struct LargeStruct {
1094  int foo[100];
1095};
1096
1097// Test for bug http://llvm.org/bugs/show_bug.cgi?id=11763.
1098// Struct copy should not cause asan warning even if lhs == rhs.
1099TEST(AddressSanitizer, LargeStructCopyTest) {
1100  LargeStruct a;
1101  *Ident(&a) = *Ident(&a);
1102}
1103
1104ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
1105static void NoAddressSafety() {
1106  char *foo = new char[10];
1107  Ident(foo)[10] = 0;
1108  delete [] foo;
1109}
1110
1111TEST(AddressSanitizer, AttributeNoAddressSafetyTest) {
1112  Ident(NoAddressSafety)();
1113}
1114
1115// TODO(glider): Enable this test on Mac.
1116// It doesn't work on Android, as calls to new/delete go through malloc/free.
1117#if !defined(__APPLE__) && !defined(ANDROID) && !defined(__ANDROID__)
1118static string MismatchStr(const string &str) {
1119  return string("AddressSanitizer: alloc-dealloc-mismatch \\(") + str;
1120}
1121
1122TEST(AddressSanitizer, AllocDeallocMismatch) {
1123  EXPECT_DEATH(free(Ident(new int)),
1124               MismatchStr("operator new vs free"));
1125  EXPECT_DEATH(free(Ident(new int[2])),
1126               MismatchStr("operator new \\[\\] vs free"));
1127  EXPECT_DEATH(delete (Ident(new int[2])),
1128               MismatchStr("operator new \\[\\] vs operator delete"));
1129  EXPECT_DEATH(delete (Ident((int*)malloc(2 * sizeof(int)))),
1130               MismatchStr("malloc vs operator delete"));
1131  EXPECT_DEATH(delete [] (Ident(new int)),
1132               MismatchStr("operator new vs operator delete \\[\\]"));
1133  EXPECT_DEATH(delete [] (Ident((int*)malloc(2 * sizeof(int)))),
1134               MismatchStr("malloc vs operator delete \\[\\]"));
1135}
1136#endif
1137
1138// ------------------ demo tests; run each one-by-one -------------
1139// e.g. --gtest_filter=*DemoOOBLeftHigh --gtest_also_run_disabled_tests
1140TEST(AddressSanitizer, DISABLED_DemoThreadedTest) {
1141  ThreadedTestSpawn();
1142}
1143
1144void *SimpleBugOnSTack(void *x = 0) {
1145  char a[20];
1146  Ident(a)[20] = 0;
1147  return 0;
1148}
1149
1150TEST(AddressSanitizer, DISABLED_DemoStackTest) {
1151  SimpleBugOnSTack();
1152}
1153
1154TEST(AddressSanitizer, DISABLED_DemoThreadStackTest) {
1155  pthread_t t;
1156  PTHREAD_CREATE(&t, 0, SimpleBugOnSTack, 0);
1157  PTHREAD_JOIN(t, 0);
1158}
1159
1160TEST(AddressSanitizer, DISABLED_DemoUAFLowIn) {
1161  uaf_test<U1>(10, 0);
1162}
1163TEST(AddressSanitizer, DISABLED_DemoUAFLowLeft) {
1164  uaf_test<U1>(10, -2);
1165}
1166TEST(AddressSanitizer, DISABLED_DemoUAFLowRight) {
1167  uaf_test<U1>(10, 10);
1168}
1169
1170TEST(AddressSanitizer, DISABLED_DemoUAFHigh) {
1171  uaf_test<U1>(kLargeMalloc, 0);
1172}
1173
1174TEST(AddressSanitizer, DISABLED_DemoOOM) {
1175  size_t size = SANITIZER_WORDSIZE == 64 ? (size_t)(1ULL << 40) : (0xf0000000);
1176  printf("%p\n", malloc(size));
1177}
1178
1179TEST(AddressSanitizer, DISABLED_DemoDoubleFreeTest) {
1180  DoubleFree();
1181}
1182
1183TEST(AddressSanitizer, DISABLED_DemoNullDerefTest) {
1184  int *a = 0;
1185  Ident(a)[10] = 0;
1186}
1187
1188TEST(AddressSanitizer, DISABLED_DemoFunctionStaticTest) {
1189  static char a[100];
1190  static char b[100];
1191  static char c[100];
1192  Ident(a);
1193  Ident(b);
1194  Ident(c);
1195  Ident(a)[5] = 0;
1196  Ident(b)[105] = 0;
1197  Ident(a)[5] = 0;
1198}
1199
1200TEST(AddressSanitizer, DISABLED_DemoTooMuchMemoryTest) {
1201  const size_t kAllocSize = (1 << 28) - 1024;
1202  size_t total_size = 0;
1203  while (true) {
1204    char *x = (char*)malloc(kAllocSize);
1205    memset(x, 0, kAllocSize);
1206    total_size += kAllocSize;
1207    fprintf(stderr, "total: %ldM %p\n", (long)total_size >> 20, x);
1208  }
1209}
1210
1211// http://code.google.com/p/address-sanitizer/issues/detail?id=66
1212TEST(AddressSanitizer, BufferOverflowAfterManyFrees) {
1213  for (int i = 0; i < 1000000; i++) {
1214    delete [] (Ident(new char [8644]));
1215  }
1216  char *x = new char[8192];
1217  EXPECT_DEATH(x[Ident(8192)] = 0, "AddressSanitizer: heap-buffer-overflow");
1218  delete [] Ident(x);
1219}
1220
1221
1222// Test that instrumentation of stack allocations takes into account
1223// AllocSize of a type, and not its StoreSize (16 vs 10 bytes for long double).
1224// See http://llvm.org/bugs/show_bug.cgi?id=12047 for more details.
1225TEST(AddressSanitizer, LongDoubleNegativeTest) {
1226  long double a, b;
1227  static long double c;
1228  memcpy(Ident(&a), Ident(&b), sizeof(long double));
1229  memcpy(Ident(&c), Ident(&b), sizeof(long double));
1230}
1231