asan_test.cc revision 0f63831345e26b23d85a67e2dd96129f48eec477
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, CallocReturnsZeroMem) {
115  size_t sizes[] = {16, 1000, 10000, 100000, 2100000};
116  for (size_t s = 0; s < sizeof(sizes)/sizeof(sizes[0]); s++) {
117    size_t size = sizes[s];
118    for (size_t iter = 0; iter < 5; iter++) {
119      char *x = Ident((char*)calloc(1, size));
120      EXPECT_EQ(x[0], 0);
121      EXPECT_EQ(x[size - 1], 0);
122      EXPECT_EQ(x[size / 2], 0);
123      EXPECT_EQ(x[size / 3], 0);
124      EXPECT_EQ(x[size / 4], 0);
125      memset(x, 0x42, size);
126      free(Ident(x));
127      free(Ident(malloc(Ident(1 << 27))));  // Try to drain the quarantine.
128    }
129  }
130}
131
132TEST(AddressSanitizer, VallocTest) {
133  void *a = valloc(100);
134  EXPECT_EQ(0U, (uintptr_t)a % kPageSize);
135  free(a);
136}
137
138#ifndef __APPLE__
139TEST(AddressSanitizer, PvallocTest) {
140  char *a = (char*)pvalloc(kPageSize + 100);
141  EXPECT_EQ(0U, (uintptr_t)a % kPageSize);
142  a[kPageSize + 101] = 1;  // we should not report an error here.
143  free(a);
144
145  a = (char*)pvalloc(0);  // pvalloc(0) should allocate at least one page.
146  EXPECT_EQ(0U, (uintptr_t)a % kPageSize);
147  a[101] = 1;  // we should not report an error here.
148  free(a);
149}
150#endif  // __APPLE__
151
152void *TSDWorker(void *test_key) {
153  if (test_key) {
154    pthread_setspecific(*(pthread_key_t*)test_key, (void*)0xfeedface);
155  }
156  return NULL;
157}
158
159void TSDDestructor(void *tsd) {
160  // Spawning a thread will check that the current thread id is not -1.
161  pthread_t th;
162  PTHREAD_CREATE(&th, NULL, TSDWorker, NULL);
163  PTHREAD_JOIN(th, NULL);
164}
165
166// This tests triggers the thread-specific data destruction fiasco which occurs
167// if we don't manage the TSD destructors ourselves. We create a new pthread
168// key with a non-NULL destructor which is likely to be put after the destructor
169// of AsanThread in the list of destructors.
170// In this case the TSD for AsanThread will be destroyed before TSDDestructor
171// is called for the child thread, and a CHECK will fail when we call
172// pthread_create() to spawn the grandchild.
173TEST(AddressSanitizer, DISABLED_TSDTest) {
174  pthread_t th;
175  pthread_key_t test_key;
176  pthread_key_create(&test_key, TSDDestructor);
177  PTHREAD_CREATE(&th, NULL, TSDWorker, &test_key);
178  PTHREAD_JOIN(th, NULL);
179  pthread_key_delete(test_key);
180}
181
182TEST(AddressSanitizer, UAF_char) {
183  const char *uaf_string = "AddressSanitizer:.*heap-use-after-free";
184  EXPECT_DEATH(uaf_test<U1>(1, 0), uaf_string);
185  EXPECT_DEATH(uaf_test<U1>(10, 0), uaf_string);
186  EXPECT_DEATH(uaf_test<U1>(10, 10), uaf_string);
187  EXPECT_DEATH(uaf_test<U1>(kLargeMalloc, 0), uaf_string);
188  EXPECT_DEATH(uaf_test<U1>(kLargeMalloc, kLargeMalloc / 2), uaf_string);
189}
190
191TEST(AddressSanitizer, UAF_long_double) {
192  if (sizeof(long double) == sizeof(double)) return;
193  long double *p = Ident(new long double[10]);
194  EXPECT_DEATH(Ident(p)[12] = 0, "WRITE of size 1[06]");
195  EXPECT_DEATH(Ident(p)[0] = Ident(p)[12], "READ of size 1[06]");
196  delete [] Ident(p);
197}
198
199struct Packed5 {
200  int x;
201  char c;
202} __attribute__((packed));
203
204
205TEST(AddressSanitizer, UAF_Packed5) {
206  Packed5 *p = Ident(new Packed5[2]);
207  EXPECT_DEATH(p[0] = p[3], "READ of size 5");
208  EXPECT_DEATH(p[3] = p[0], "WRITE of size 5");
209  delete [] Ident(p);
210}
211
212#if ASAN_HAS_BLACKLIST
213TEST(AddressSanitizer, IgnoreTest) {
214  int *x = Ident(new int);
215  delete Ident(x);
216  *x = 0;
217}
218#endif  // ASAN_HAS_BLACKLIST
219
220struct StructWithBitField {
221  int bf1:1;
222  int bf2:1;
223  int bf3:1;
224  int bf4:29;
225};
226
227TEST(AddressSanitizer, BitFieldPositiveTest) {
228  StructWithBitField *x = new StructWithBitField;
229  delete Ident(x);
230  EXPECT_DEATH(x->bf1 = 0, "use-after-free");
231  EXPECT_DEATH(x->bf2 = 0, "use-after-free");
232  EXPECT_DEATH(x->bf3 = 0, "use-after-free");
233  EXPECT_DEATH(x->bf4 = 0, "use-after-free");
234}
235
236struct StructWithBitFields_8_24 {
237  int a:8;
238  int b:24;
239};
240
241TEST(AddressSanitizer, BitFieldNegativeTest) {
242  StructWithBitFields_8_24 *x = Ident(new StructWithBitFields_8_24);
243  x->a = 0;
244  x->b = 0;
245  delete Ident(x);
246}
247
248#if ASAN_NEEDS_SEGV
249namespace {
250
251const char kUnknownCrash[] = "AddressSanitizer: SEGV on unknown address";
252const char kOverriddenHandler[] = "ASan signal handler has been overridden\n";
253
254TEST(AddressSanitizer, WildAddressTest) {
255  char *c = (char*)0x123;
256  EXPECT_DEATH(*c = 0, kUnknownCrash);
257}
258
259void my_sigaction_sighandler(int, siginfo_t*, void*) {
260  fprintf(stderr, kOverriddenHandler);
261  exit(1);
262}
263
264void my_signal_sighandler(int signum) {
265  fprintf(stderr, kOverriddenHandler);
266  exit(1);
267}
268
269TEST(AddressSanitizer, SignalTest) {
270  struct sigaction sigact;
271  memset(&sigact, 0, sizeof(sigact));
272  sigact.sa_sigaction = my_sigaction_sighandler;
273  sigact.sa_flags = SA_SIGINFO;
274  // ASan should silently ignore sigaction()...
275  EXPECT_EQ(0, sigaction(SIGSEGV, &sigact, 0));
276#ifdef __APPLE__
277  EXPECT_EQ(0, sigaction(SIGBUS, &sigact, 0));
278#endif
279  char *c = (char*)0x123;
280  EXPECT_DEATH(*c = 0, kUnknownCrash);
281  // ... and signal().
282  EXPECT_EQ(0, signal(SIGSEGV, my_signal_sighandler));
283  EXPECT_DEATH(*c = 0, kUnknownCrash);
284}
285}  // namespace
286#endif
287
288static void TestLargeMalloc(size_t size) {
289  char buff[1024];
290  sprintf(buff, "is located 1 bytes to the left of %lu-byte", (long)size);
291  EXPECT_DEATH(Ident((char*)malloc(size))[-1] = 0, buff);
292}
293
294TEST(AddressSanitizer, LargeMallocTest) {
295  const int max_size = (SANITIZER_WORDSIZE == 32) ? 1 << 26 : 1 << 28;
296  for (int i = 113; i < max_size; i = i * 2 + 13) {
297    TestLargeMalloc(i);
298  }
299}
300
301TEST(AddressSanitizer, HugeMallocTest) {
302  if (SANITIZER_WORDSIZE != 64) return;
303  size_t n_megs = 4100;
304  TestLargeMalloc(n_megs << 20);
305}
306
307#ifndef __APPLE__
308void MemalignRun(size_t align, size_t size, int idx) {
309  char *p = (char *)memalign(align, size);
310  Ident(p)[idx] = 0;
311  free(p);
312}
313
314TEST(AddressSanitizer, memalign) {
315  for (int align = 16; align <= (1 << 23); align *= 2) {
316    size_t size = align * 5;
317    EXPECT_DEATH(MemalignRun(align, size, -1),
318                 "is located 1 bytes to the left");
319    EXPECT_DEATH(MemalignRun(align, size, size + 1),
320                 "is located 1 bytes to the right");
321  }
322}
323#endif
324
325void *ManyThreadsWorker(void *a) {
326  for (int iter = 0; iter < 100; iter++) {
327    for (size_t size = 100; size < 2000; size *= 2) {
328      free(Ident(malloc(size)));
329    }
330  }
331  return 0;
332}
333
334TEST(AddressSanitizer, ManyThreadsTest) {
335  const size_t kNumThreads =
336      (SANITIZER_WORDSIZE == 32 || ASAN_AVOID_EXPENSIVE_TESTS) ? 30 : 1000;
337  pthread_t t[kNumThreads];
338  for (size_t i = 0; i < kNumThreads; i++) {
339    PTHREAD_CREATE(&t[i], 0, ManyThreadsWorker, (void*)i);
340  }
341  for (size_t i = 0; i < kNumThreads; i++) {
342    PTHREAD_JOIN(t[i], 0);
343  }
344}
345
346TEST(AddressSanitizer, ReallocTest) {
347  const int kMinElem = 5;
348  int *ptr = (int*)malloc(sizeof(int) * kMinElem);
349  ptr[3] = 3;
350  for (int i = 0; i < 10000; i++) {
351    ptr = (int*)realloc(ptr,
352        (my_rand() % 1000 + kMinElem) * sizeof(int));
353    EXPECT_EQ(3, ptr[3]);
354  }
355  free(ptr);
356  // Realloc pointer returned by malloc(0).
357  int *ptr2 = Ident((int*)malloc(0));
358  ptr2 = Ident((int*)realloc(ptr2, sizeof(*ptr2)));
359  *ptr2 = 42;
360  EXPECT_EQ(42, *ptr2);
361  free(ptr2);
362}
363
364TEST(AddressSanitizer, ReallocFreedPointerTest) {
365  void *ptr = Ident(malloc(42));
366  ASSERT_TRUE(NULL != ptr);
367  free(ptr);
368  EXPECT_DEATH(ptr = realloc(ptr, 77), "attempting double-free");
369}
370
371TEST(AddressSanitizer, ReallocInvalidPointerTest) {
372  void *ptr = Ident(malloc(42));
373  EXPECT_DEATH(ptr = realloc((int*)ptr + 1, 77), "attempting free.*not malloc");
374  free(ptr);
375}
376
377TEST(AddressSanitizer, ZeroSizeMallocTest) {
378  // Test that malloc(0) and similar functions don't return NULL.
379  void *ptr = Ident(malloc(0));
380  EXPECT_TRUE(NULL != ptr);
381  free(ptr);
382#if !defined(__APPLE__) && !defined(ANDROID) && !defined(__ANDROID__)
383  int pm_res = posix_memalign(&ptr, 1<<20, 0);
384  EXPECT_EQ(0, pm_res);
385  EXPECT_TRUE(NULL != ptr);
386  free(ptr);
387#endif
388  int *int_ptr = new int[0];
389  int *int_ptr2 = new int[0];
390  EXPECT_TRUE(NULL != int_ptr);
391  EXPECT_TRUE(NULL != int_ptr2);
392  EXPECT_NE(int_ptr, int_ptr2);
393  delete[] int_ptr;
394  delete[] int_ptr2;
395}
396
397#ifndef __APPLE__
398static const char *kMallocUsableSizeErrorMsg =
399  "AddressSanitizer: attempting to call malloc_usable_size()";
400
401TEST(AddressSanitizer, MallocUsableSizeTest) {
402  const size_t kArraySize = 100;
403  char *array = Ident((char*)malloc(kArraySize));
404  int *int_ptr = Ident(new int);
405  EXPECT_EQ(0U, malloc_usable_size(NULL));
406  EXPECT_EQ(kArraySize, malloc_usable_size(array));
407  EXPECT_EQ(sizeof(int), malloc_usable_size(int_ptr));
408  EXPECT_DEATH(malloc_usable_size((void*)0x123), kMallocUsableSizeErrorMsg);
409  EXPECT_DEATH(malloc_usable_size(array + kArraySize / 2),
410               kMallocUsableSizeErrorMsg);
411  free(array);
412  EXPECT_DEATH(malloc_usable_size(array), kMallocUsableSizeErrorMsg);
413  delete int_ptr;
414}
415#endif
416
417void WrongFree() {
418  int *x = (int*)malloc(100 * sizeof(int));
419  // Use the allocated memory, otherwise Clang will optimize it out.
420  Ident(x);
421  free(x + 1);
422}
423
424TEST(AddressSanitizer, WrongFreeTest) {
425  EXPECT_DEATH(WrongFree(), ASAN_PCRE_DOTALL
426               "ERROR: AddressSanitizer: attempting free.*not malloc"
427               ".*is located 4 bytes inside of 400-byte region"
428               ".*allocated by thread");
429}
430
431void DoubleFree() {
432  int *x = (int*)malloc(100 * sizeof(int));
433  fprintf(stderr, "DoubleFree: x=%p\n", x);
434  free(x);
435  free(x);
436  fprintf(stderr, "should have failed in the second free(%p)\n", x);
437  abort();
438}
439
440TEST(AddressSanitizer, DoubleFreeTest) {
441  EXPECT_DEATH(DoubleFree(), ASAN_PCRE_DOTALL
442               "ERROR: AddressSanitizer: attempting double-free"
443               ".*is located 0 bytes inside of 400-byte region"
444               ".*freed by thread T0 here"
445               ".*previously allocated by thread T0 here");
446}
447
448template<int kSize>
449NOINLINE void SizedStackTest() {
450  char a[kSize];
451  char  *A = Ident((char*)&a);
452  for (size_t i = 0; i < kSize; i++)
453    A[i] = i;
454  EXPECT_DEATH(A[-1] = 0, "");
455  EXPECT_DEATH(A[-20] = 0, "");
456  EXPECT_DEATH(A[-31] = 0, "");
457  EXPECT_DEATH(A[kSize] = 0, "");
458  EXPECT_DEATH(A[kSize + 1] = 0, "");
459  EXPECT_DEATH(A[kSize + 10] = 0, "");
460  EXPECT_DEATH(A[kSize + 31] = 0, "");
461}
462
463TEST(AddressSanitizer, SimpleStackTest) {
464  SizedStackTest<1>();
465  SizedStackTest<2>();
466  SizedStackTest<3>();
467  SizedStackTest<4>();
468  SizedStackTest<5>();
469  SizedStackTest<6>();
470  SizedStackTest<7>();
471  SizedStackTest<16>();
472  SizedStackTest<25>();
473  SizedStackTest<34>();
474  SizedStackTest<43>();
475  SizedStackTest<51>();
476  SizedStackTest<62>();
477  SizedStackTest<64>();
478  SizedStackTest<128>();
479}
480
481TEST(AddressSanitizer, ManyStackObjectsTest) {
482  char XXX[10];
483  char YYY[20];
484  char ZZZ[30];
485  Ident(XXX);
486  Ident(YYY);
487  EXPECT_DEATH(Ident(ZZZ)[-1] = 0, ASAN_PCRE_DOTALL "XXX.*YYY.*ZZZ");
488}
489
490#if 0  // This test requires online symbolizer.
491// Moved to lit_tests/stack-oob-frames.cc.
492// Reenable here once we have online symbolizer by default.
493NOINLINE static void Frame0(int frame, char *a, char *b, char *c) {
494  char d[4] = {0};
495  char *D = Ident(d);
496  switch (frame) {
497    case 3: a[5]++; break;
498    case 2: b[5]++; break;
499    case 1: c[5]++; break;
500    case 0: D[5]++; break;
501  }
502}
503NOINLINE static void Frame1(int frame, char *a, char *b) {
504  char c[4] = {0}; Frame0(frame, a, b, c);
505  break_optimization(0);
506}
507NOINLINE static void Frame2(int frame, char *a) {
508  char b[4] = {0}; Frame1(frame, a, b);
509  break_optimization(0);
510}
511NOINLINE static void Frame3(int frame) {
512  char a[4] = {0}; Frame2(frame, a);
513  break_optimization(0);
514}
515
516TEST(AddressSanitizer, GuiltyStackFrame0Test) {
517  EXPECT_DEATH(Frame3(0), "located .*in frame <.*Frame0");
518}
519TEST(AddressSanitizer, GuiltyStackFrame1Test) {
520  EXPECT_DEATH(Frame3(1), "located .*in frame <.*Frame1");
521}
522TEST(AddressSanitizer, GuiltyStackFrame2Test) {
523  EXPECT_DEATH(Frame3(2), "located .*in frame <.*Frame2");
524}
525TEST(AddressSanitizer, GuiltyStackFrame3Test) {
526  EXPECT_DEATH(Frame3(3), "located .*in frame <.*Frame3");
527}
528#endif
529
530NOINLINE void LongJmpFunc1(jmp_buf buf) {
531  // create three red zones for these two stack objects.
532  int a;
533  int b;
534
535  int *A = Ident(&a);
536  int *B = Ident(&b);
537  *A = *B;
538  longjmp(buf, 1);
539}
540
541NOINLINE void BuiltinLongJmpFunc1(jmp_buf buf) {
542  // create three red zones for these two stack objects.
543  int a;
544  int b;
545
546  int *A = Ident(&a);
547  int *B = Ident(&b);
548  *A = *B;
549  __builtin_longjmp((void**)buf, 1);
550}
551
552NOINLINE void UnderscopeLongJmpFunc1(jmp_buf buf) {
553  // create three red zones for these two stack objects.
554  int a;
555  int b;
556
557  int *A = Ident(&a);
558  int *B = Ident(&b);
559  *A = *B;
560  _longjmp(buf, 1);
561}
562
563NOINLINE void SigLongJmpFunc1(sigjmp_buf buf) {
564  // create three red zones for these two stack objects.
565  int a;
566  int b;
567
568  int *A = Ident(&a);
569  int *B = Ident(&b);
570  *A = *B;
571  siglongjmp(buf, 1);
572}
573
574
575NOINLINE void TouchStackFunc() {
576  int a[100];  // long array will intersect with redzones from LongJmpFunc1.
577  int *A = Ident(a);
578  for (int i = 0; i < 100; i++)
579    A[i] = i*i;
580}
581
582// Test that we handle longjmp and do not report fals positives on stack.
583TEST(AddressSanitizer, LongJmpTest) {
584  static jmp_buf buf;
585  if (!setjmp(buf)) {
586    LongJmpFunc1(buf);
587  } else {
588    TouchStackFunc();
589  }
590}
591
592#if !defined(__ANDROID__) && \
593    !defined(__powerpc64__) && !defined(__powerpc__)
594// Does not work on Power:
595// https://code.google.com/p/address-sanitizer/issues/detail?id=185
596TEST(AddressSanitizer, BuiltinLongJmpTest) {
597  static jmp_buf buf;
598  if (!__builtin_setjmp((void**)buf)) {
599    BuiltinLongJmpFunc1(buf);
600  } else {
601    TouchStackFunc();
602  }
603}
604#endif  // not defined(__ANDROID__)
605
606TEST(AddressSanitizer, UnderscopeLongJmpTest) {
607  static jmp_buf buf;
608  if (!_setjmp(buf)) {
609    UnderscopeLongJmpFunc1(buf);
610  } else {
611    TouchStackFunc();
612  }
613}
614
615TEST(AddressSanitizer, SigLongJmpTest) {
616  static sigjmp_buf buf;
617  if (!sigsetjmp(buf, 1)) {
618    SigLongJmpFunc1(buf);
619  } else {
620    TouchStackFunc();
621  }
622}
623
624#ifdef __EXCEPTIONS
625NOINLINE void ThrowFunc() {
626  // create three red zones for these two stack objects.
627  int a;
628  int b;
629
630  int *A = Ident(&a);
631  int *B = Ident(&b);
632  *A = *B;
633  ASAN_THROW(1);
634}
635
636TEST(AddressSanitizer, CxxExceptionTest) {
637  if (ASAN_UAR) return;
638  // TODO(kcc): this test crashes on 32-bit for some reason...
639  if (SANITIZER_WORDSIZE == 32) return;
640  try {
641    ThrowFunc();
642  } catch(...) {}
643  TouchStackFunc();
644}
645#endif
646
647void *ThreadStackReuseFunc1(void *unused) {
648  // create three red zones for these two stack objects.
649  int a;
650  int b;
651
652  int *A = Ident(&a);
653  int *B = Ident(&b);
654  *A = *B;
655  pthread_exit(0);
656  return 0;
657}
658
659void *ThreadStackReuseFunc2(void *unused) {
660  TouchStackFunc();
661  return 0;
662}
663
664TEST(AddressSanitizer, ThreadStackReuseTest) {
665  pthread_t t;
666  PTHREAD_CREATE(&t, 0, ThreadStackReuseFunc1, 0);
667  PTHREAD_JOIN(t, 0);
668  PTHREAD_CREATE(&t, 0, ThreadStackReuseFunc2, 0);
669  PTHREAD_JOIN(t, 0);
670}
671
672#if defined(__i386__) || defined(__x86_64__)
673TEST(AddressSanitizer, Store128Test) {
674  char *a = Ident((char*)malloc(Ident(12)));
675  char *p = a;
676  if (((uintptr_t)a % 16) != 0)
677    p = a + 8;
678  assert(((uintptr_t)p % 16) == 0);
679  __m128i value_wide = _mm_set1_epi16(0x1234);
680  EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
681               "AddressSanitizer: heap-buffer-overflow");
682  EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
683               "WRITE of size 16");
684  EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
685               "located 0 bytes to the right of 12-byte");
686  free(a);
687}
688#endif
689
690string RightOOBErrorMessage(int oob_distance, bool is_write) {
691  assert(oob_distance >= 0);
692  char expected_str[100];
693  sprintf(expected_str, ASAN_PCRE_DOTALL
694          "buffer-overflow.*%s.*located %d bytes to the right",
695          is_write ? "WRITE" : "READ", oob_distance);
696  return string(expected_str);
697}
698
699string RightOOBWriteMessage(int oob_distance) {
700  return RightOOBErrorMessage(oob_distance, /*is_write*/true);
701}
702
703string RightOOBReadMessage(int oob_distance) {
704  return RightOOBErrorMessage(oob_distance, /*is_write*/false);
705}
706
707string LeftOOBErrorMessage(int oob_distance, bool is_write) {
708  assert(oob_distance > 0);
709  char expected_str[100];
710  sprintf(expected_str, ASAN_PCRE_DOTALL "%s.*located %d bytes to the left",
711          is_write ? "WRITE" : "READ", oob_distance);
712  return string(expected_str);
713}
714
715string LeftOOBWriteMessage(int oob_distance) {
716  return LeftOOBErrorMessage(oob_distance, /*is_write*/true);
717}
718
719string LeftOOBReadMessage(int oob_distance) {
720  return LeftOOBErrorMessage(oob_distance, /*is_write*/false);
721}
722
723string LeftOOBAccessMessage(int oob_distance) {
724  assert(oob_distance > 0);
725  char expected_str[100];
726  sprintf(expected_str, "located %d bytes to the left", oob_distance);
727  return string(expected_str);
728}
729
730char* MallocAndMemsetString(size_t size, char ch) {
731  char *s = Ident((char*)malloc(size));
732  memset(s, ch, size);
733  return s;
734}
735
736char* MallocAndMemsetString(size_t size) {
737  return MallocAndMemsetString(size, 'z');
738}
739
740#if defined(__linux__) && !defined(ANDROID) && !defined(__ANDROID__)
741#define READ_TEST(READ_N_BYTES)                                          \
742  char *x = new char[10];                                                \
743  int fd = open("/proc/self/stat", O_RDONLY);                            \
744  ASSERT_GT(fd, 0);                                                      \
745  EXPECT_DEATH(READ_N_BYTES,                                             \
746               ASAN_PCRE_DOTALL                                          \
747               "AddressSanitizer: heap-buffer-overflow"                  \
748               ".* is located 0 bytes to the right of 10-byte region");  \
749  close(fd);                                                             \
750  delete [] x;                                                           \
751
752TEST(AddressSanitizer, pread) {
753  READ_TEST(pread(fd, x, 15, 0));
754}
755
756TEST(AddressSanitizer, pread64) {
757  READ_TEST(pread64(fd, x, 15, 0));
758}
759
760TEST(AddressSanitizer, read) {
761  READ_TEST(read(fd, x, 15));
762}
763#endif  // defined(__linux__) && !defined(ANDROID) && !defined(__ANDROID__)
764
765// This test case fails
766// Clang optimizes memcpy/memset calls which lead to unaligned access
767TEST(AddressSanitizer, DISABLED_MemIntrinsicUnalignedAccessTest) {
768  int size = Ident(4096);
769  char *s = Ident((char*)malloc(size));
770  EXPECT_DEATH(memset(s + size - 1, 0, 2), RightOOBWriteMessage(0));
771  free(s);
772}
773
774// TODO(samsonov): Add a test with malloc(0)
775// TODO(samsonov): Add tests for str* and mem* functions.
776
777NOINLINE static int LargeFunction(bool do_bad_access) {
778  int *x = new int[100];
779  x[0]++;
780  x[1]++;
781  x[2]++;
782  x[3]++;
783  x[4]++;
784  x[5]++;
785  x[6]++;
786  x[7]++;
787  x[8]++;
788  x[9]++;
789
790  x[do_bad_access ? 100 : 0]++; int res = __LINE__;
791
792  x[10]++;
793  x[11]++;
794  x[12]++;
795  x[13]++;
796  x[14]++;
797  x[15]++;
798  x[16]++;
799  x[17]++;
800  x[18]++;
801  x[19]++;
802
803  delete x;
804  return res;
805}
806
807// Test the we have correct debug info for the failing instruction.
808// This test requires the in-process symbolizer to be enabled by default.
809TEST(AddressSanitizer, DISABLED_LargeFunctionSymbolizeTest) {
810  int failing_line = LargeFunction(false);
811  char expected_warning[128];
812  sprintf(expected_warning, "LargeFunction.*asan_test.*:%d", failing_line);
813  EXPECT_DEATH(LargeFunction(true), expected_warning);
814}
815
816// Check that we unwind and symbolize correctly.
817TEST(AddressSanitizer, DISABLED_MallocFreeUnwindAndSymbolizeTest) {
818  int *a = (int*)malloc_aaa(sizeof(int));
819  *a = 1;
820  free_aaa(a);
821  EXPECT_DEATH(*a = 1, "free_ccc.*free_bbb.*free_aaa.*"
822               "malloc_fff.*malloc_eee.*malloc_ddd");
823}
824
825static bool TryToSetThreadName(const char *name) {
826#if defined(__linux__) && defined(PR_SET_NAME)
827  return 0 == prctl(PR_SET_NAME, (unsigned long)name, 0, 0, 0);
828#else
829  return false;
830#endif
831}
832
833void *ThreadedTestAlloc(void *a) {
834  EXPECT_EQ(true, TryToSetThreadName("AllocThr"));
835  int **p = (int**)a;
836  *p = new int;
837  return 0;
838}
839
840void *ThreadedTestFree(void *a) {
841  EXPECT_EQ(true, TryToSetThreadName("FreeThr"));
842  int **p = (int**)a;
843  delete *p;
844  return 0;
845}
846
847void *ThreadedTestUse(void *a) {
848  EXPECT_EQ(true, TryToSetThreadName("UseThr"));
849  int **p = (int**)a;
850  **p = 1;
851  return 0;
852}
853
854void ThreadedTestSpawn() {
855  pthread_t t;
856  int *x;
857  PTHREAD_CREATE(&t, 0, ThreadedTestAlloc, &x);
858  PTHREAD_JOIN(t, 0);
859  PTHREAD_CREATE(&t, 0, ThreadedTestFree, &x);
860  PTHREAD_JOIN(t, 0);
861  PTHREAD_CREATE(&t, 0, ThreadedTestUse, &x);
862  PTHREAD_JOIN(t, 0);
863}
864
865TEST(AddressSanitizer, ThreadedTest) {
866  EXPECT_DEATH(ThreadedTestSpawn(),
867               ASAN_PCRE_DOTALL
868               "Thread T.*created"
869               ".*Thread T.*created"
870               ".*Thread T.*created");
871}
872
873void *ThreadedTestFunc(void *unused) {
874  // Check if prctl(PR_SET_NAME) is supported. Return if not.
875  if (!TryToSetThreadName("TestFunc"))
876    return 0;
877  EXPECT_DEATH(ThreadedTestSpawn(),
878               ASAN_PCRE_DOTALL
879               "WRITE .*thread T. .UseThr."
880               ".*freed by thread T. .FreeThr. here:"
881               ".*previously allocated by thread T. .AllocThr. here:"
882               ".*Thread T. .UseThr. created by T.*TestFunc"
883               ".*Thread T. .FreeThr. created by T"
884               ".*Thread T. .AllocThr. created by T"
885               "");
886  return 0;
887}
888
889TEST(AddressSanitizer, ThreadNamesTest) {
890  // Run ThreadedTestFunc in a separate thread because it tries to set a
891  // thread name and we don't want to change the main thread's name.
892  pthread_t t;
893  PTHREAD_CREATE(&t, 0, ThreadedTestFunc, 0);
894  PTHREAD_JOIN(t, 0);
895}
896
897#if ASAN_NEEDS_SEGV
898TEST(AddressSanitizer, ShadowGapTest) {
899#if SANITIZER_WORDSIZE == 32
900  char *addr = (char*)0x22000000;
901#else
902# if defined(__powerpc64__)
903  char *addr = (char*)0x024000800000;
904# else
905  char *addr = (char*)0x0000100000080000;
906# endif
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_SANITIZE_ADDRESS
1103static void NoSanitizeAddress() {
1104  char *foo = new char[10];
1105  Ident(foo)[10] = 0;
1106  delete [] foo;
1107}
1108
1109TEST(AddressSanitizer, AttributeNoSanitizeAddressTest) {
1110  Ident(NoSanitizeAddress)();
1111}
1112
1113// It doesn't work on Android, as calls to new/delete go through malloc/free.
1114// Neither it does on OS X, see
1115// https://code.google.com/p/address-sanitizer/issues/detail?id=131.
1116#if !defined(ANDROID) && !defined(__ANDROID__) && !defined(__APPLE__)
1117static string MismatchStr(const string &str) {
1118  return string("AddressSanitizer: alloc-dealloc-mismatch \\(") + str;
1119}
1120
1121TEST(AddressSanitizer, AllocDeallocMismatch) {
1122  EXPECT_DEATH(free(Ident(new int)),
1123               MismatchStr("operator new vs free"));
1124  EXPECT_DEATH(free(Ident(new int[2])),
1125               MismatchStr("operator new \\[\\] vs free"));
1126  EXPECT_DEATH(delete (Ident(new int[2])),
1127               MismatchStr("operator new \\[\\] vs operator delete"));
1128  EXPECT_DEATH(delete (Ident((int*)malloc(2 * sizeof(int)))),
1129               MismatchStr("malloc vs operator delete"));
1130  EXPECT_DEATH(delete [] (Ident(new int)),
1131               MismatchStr("operator new vs operator delete \\[\\]"));
1132  EXPECT_DEATH(delete [] (Ident((int*)malloc(2 * sizeof(int)))),
1133               MismatchStr("malloc vs operator delete \\[\\]"));
1134}
1135#endif
1136
1137// ------------------ demo tests; run each one-by-one -------------
1138// e.g. --gtest_filter=*DemoOOBLeftHigh --gtest_also_run_disabled_tests
1139TEST(AddressSanitizer, DISABLED_DemoThreadedTest) {
1140  ThreadedTestSpawn();
1141}
1142
1143void *SimpleBugOnSTack(void *x = 0) {
1144  char a[20];
1145  Ident(a)[20] = 0;
1146  return 0;
1147}
1148
1149TEST(AddressSanitizer, DISABLED_DemoStackTest) {
1150  SimpleBugOnSTack();
1151}
1152
1153TEST(AddressSanitizer, DISABLED_DemoThreadStackTest) {
1154  pthread_t t;
1155  PTHREAD_CREATE(&t, 0, SimpleBugOnSTack, 0);
1156  PTHREAD_JOIN(t, 0);
1157}
1158
1159TEST(AddressSanitizer, DISABLED_DemoUAFLowIn) {
1160  uaf_test<U1>(10, 0);
1161}
1162TEST(AddressSanitizer, DISABLED_DemoUAFLowLeft) {
1163  uaf_test<U1>(10, -2);
1164}
1165TEST(AddressSanitizer, DISABLED_DemoUAFLowRight) {
1166  uaf_test<U1>(10, 10);
1167}
1168
1169TEST(AddressSanitizer, DISABLED_DemoUAFHigh) {
1170  uaf_test<U1>(kLargeMalloc, 0);
1171}
1172
1173TEST(AddressSanitizer, DISABLED_DemoOOM) {
1174  size_t size = SANITIZER_WORDSIZE == 64 ? (size_t)(1ULL << 40) : (0xf0000000);
1175  printf("%p\n", malloc(size));
1176}
1177
1178TEST(AddressSanitizer, DISABLED_DemoDoubleFreeTest) {
1179  DoubleFree();
1180}
1181
1182TEST(AddressSanitizer, DISABLED_DemoNullDerefTest) {
1183  int *a = 0;
1184  Ident(a)[10] = 0;
1185}
1186
1187TEST(AddressSanitizer, DISABLED_DemoFunctionStaticTest) {
1188  static char a[100];
1189  static char b[100];
1190  static char c[100];
1191  Ident(a);
1192  Ident(b);
1193  Ident(c);
1194  Ident(a)[5] = 0;
1195  Ident(b)[105] = 0;
1196  Ident(a)[5] = 0;
1197}
1198
1199TEST(AddressSanitizer, DISABLED_DemoTooMuchMemoryTest) {
1200  const size_t kAllocSize = (1 << 28) - 1024;
1201  size_t total_size = 0;
1202  while (true) {
1203    char *x = (char*)malloc(kAllocSize);
1204    memset(x, 0, kAllocSize);
1205    total_size += kAllocSize;
1206    fprintf(stderr, "total: %ldM %p\n", (long)total_size >> 20, x);
1207  }
1208}
1209
1210// http://code.google.com/p/address-sanitizer/issues/detail?id=66
1211TEST(AddressSanitizer, BufferOverflowAfterManyFrees) {
1212  for (int i = 0; i < 1000000; i++) {
1213    delete [] (Ident(new char [8644]));
1214  }
1215  char *x = new char[8192];
1216  EXPECT_DEATH(x[Ident(8192)] = 0, "AddressSanitizer: heap-buffer-overflow");
1217  delete [] Ident(x);
1218}
1219
1220
1221// Test that instrumentation of stack allocations takes into account
1222// AllocSize of a type, and not its StoreSize (16 vs 10 bytes for long double).
1223// See http://llvm.org/bugs/show_bug.cgi?id=12047 for more details.
1224TEST(AddressSanitizer, LongDoubleNegativeTest) {
1225  long double a, b;
1226  static long double c;
1227  memcpy(Ident(&a), Ident(&b), sizeof(long double));
1228  memcpy(Ident(&c), Ident(&b), sizeof(long double));
1229}
1230
1231TEST(AddressSanitizer, pthread_getschedparam) {
1232  int policy;
1233  struct sched_param param;
1234  EXPECT_DEATH(
1235      pthread_getschedparam(pthread_self(), &policy, Ident(&param) + 2),
1236      "AddressSanitizer: stack-buffer-.*flow");
1237  EXPECT_DEATH(
1238      pthread_getschedparam(pthread_self(), Ident(&policy) - 1, &param),
1239      "AddressSanitizer: stack-buffer-.*flow");
1240  int res = pthread_getschedparam(pthread_self(), &policy, &param);
1241  ASSERT_EQ(0, res);
1242}
1243