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