asan_test.cc revision b37127085cbcc79f5f859bfab8e7204201c18287
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(__i686__) || defined(__x86_64__)
673#include <emmintrin.h>
674TEST(AddressSanitizer, Store128Test) {
675  char *a = Ident((char*)malloc(Ident(12)));
676  char *p = a;
677  if (((uintptr_t)a % 16) != 0)
678    p = a + 8;
679  assert(((uintptr_t)p % 16) == 0);
680  __m128i value_wide = _mm_set1_epi16(0x1234);
681  EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
682               "AddressSanitizer: heap-buffer-overflow");
683  EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
684               "WRITE of size 16");
685  EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
686               "located 0 bytes to the right of 12-byte");
687  free(a);
688}
689#endif
690
691string RightOOBErrorMessage(int oob_distance, bool is_write) {
692  assert(oob_distance >= 0);
693  char expected_str[100];
694  sprintf(expected_str, ASAN_PCRE_DOTALL
695          "buffer-overflow.*%s.*located %d bytes to the right",
696          is_write ? "WRITE" : "READ", oob_distance);
697  return string(expected_str);
698}
699
700string RightOOBWriteMessage(int oob_distance) {
701  return RightOOBErrorMessage(oob_distance, /*is_write*/true);
702}
703
704string RightOOBReadMessage(int oob_distance) {
705  return RightOOBErrorMessage(oob_distance, /*is_write*/false);
706}
707
708string LeftOOBErrorMessage(int oob_distance, bool is_write) {
709  assert(oob_distance > 0);
710  char expected_str[100];
711  sprintf(expected_str, ASAN_PCRE_DOTALL "%s.*located %d bytes to the left",
712          is_write ? "WRITE" : "READ", oob_distance);
713  return string(expected_str);
714}
715
716string LeftOOBWriteMessage(int oob_distance) {
717  return LeftOOBErrorMessage(oob_distance, /*is_write*/true);
718}
719
720string LeftOOBReadMessage(int oob_distance) {
721  return LeftOOBErrorMessage(oob_distance, /*is_write*/false);
722}
723
724string LeftOOBAccessMessage(int oob_distance) {
725  assert(oob_distance > 0);
726  char expected_str[100];
727  sprintf(expected_str, "located %d bytes to the left", oob_distance);
728  return string(expected_str);
729}
730
731char* MallocAndMemsetString(size_t size, char ch) {
732  char *s = Ident((char*)malloc(size));
733  memset(s, ch, size);
734  return s;
735}
736
737char* MallocAndMemsetString(size_t size) {
738  return MallocAndMemsetString(size, 'z');
739}
740
741#if defined(__linux__) && !defined(ANDROID) && !defined(__ANDROID__)
742#define READ_TEST(READ_N_BYTES)                                          \
743  char *x = new char[10];                                                \
744  int fd = open("/proc/self/stat", O_RDONLY);                            \
745  ASSERT_GT(fd, 0);                                                      \
746  EXPECT_DEATH(READ_N_BYTES,                                             \
747               ASAN_PCRE_DOTALL                                          \
748               "AddressSanitizer: heap-buffer-overflow"                  \
749               ".* is located 0 bytes to the right of 10-byte region");  \
750  close(fd);                                                             \
751  delete [] x;                                                           \
752
753TEST(AddressSanitizer, pread) {
754  READ_TEST(pread(fd, x, 15, 0));
755}
756
757TEST(AddressSanitizer, pread64) {
758  READ_TEST(pread64(fd, x, 15, 0));
759}
760
761TEST(AddressSanitizer, read) {
762  READ_TEST(read(fd, x, 15));
763}
764#endif  // defined(__linux__) && !defined(ANDROID) && !defined(__ANDROID__)
765
766// This test case fails
767// Clang optimizes memcpy/memset calls which lead to unaligned access
768TEST(AddressSanitizer, DISABLED_MemIntrinsicUnalignedAccessTest) {
769  int size = Ident(4096);
770  char *s = Ident((char*)malloc(size));
771  EXPECT_DEATH(memset(s + size - 1, 0, 2), RightOOBWriteMessage(0));
772  free(s);
773}
774
775// TODO(samsonov): Add a test with malloc(0)
776// TODO(samsonov): Add tests for str* and mem* functions.
777
778NOINLINE static int LargeFunction(bool do_bad_access) {
779  int *x = new int[100];
780  x[0]++;
781  x[1]++;
782  x[2]++;
783  x[3]++;
784  x[4]++;
785  x[5]++;
786  x[6]++;
787  x[7]++;
788  x[8]++;
789  x[9]++;
790
791  x[do_bad_access ? 100 : 0]++; int res = __LINE__;
792
793  x[10]++;
794  x[11]++;
795  x[12]++;
796  x[13]++;
797  x[14]++;
798  x[15]++;
799  x[16]++;
800  x[17]++;
801  x[18]++;
802  x[19]++;
803
804  delete x;
805  return res;
806}
807
808// Test the we have correct debug info for the failing instruction.
809// This test requires the in-process symbolizer to be enabled by default.
810TEST(AddressSanitizer, DISABLED_LargeFunctionSymbolizeTest) {
811  int failing_line = LargeFunction(false);
812  char expected_warning[128];
813  sprintf(expected_warning, "LargeFunction.*asan_test.*:%d", failing_line);
814  EXPECT_DEATH(LargeFunction(true), expected_warning);
815}
816
817// Check that we unwind and symbolize correctly.
818TEST(AddressSanitizer, DISABLED_MallocFreeUnwindAndSymbolizeTest) {
819  int *a = (int*)malloc_aaa(sizeof(int));
820  *a = 1;
821  free_aaa(a);
822  EXPECT_DEATH(*a = 1, "free_ccc.*free_bbb.*free_aaa.*"
823               "malloc_fff.*malloc_eee.*malloc_ddd");
824}
825
826static bool TryToSetThreadName(const char *name) {
827#if defined(__linux__) && defined(PR_SET_NAME)
828  return 0 == prctl(PR_SET_NAME, (unsigned long)name, 0, 0, 0);
829#else
830  return false;
831#endif
832}
833
834void *ThreadedTestAlloc(void *a) {
835  EXPECT_EQ(true, TryToSetThreadName("AllocThr"));
836  int **p = (int**)a;
837  *p = new int;
838  return 0;
839}
840
841void *ThreadedTestFree(void *a) {
842  EXPECT_EQ(true, TryToSetThreadName("FreeThr"));
843  int **p = (int**)a;
844  delete *p;
845  return 0;
846}
847
848void *ThreadedTestUse(void *a) {
849  EXPECT_EQ(true, TryToSetThreadName("UseThr"));
850  int **p = (int**)a;
851  **p = 1;
852  return 0;
853}
854
855void ThreadedTestSpawn() {
856  pthread_t t;
857  int *x;
858  PTHREAD_CREATE(&t, 0, ThreadedTestAlloc, &x);
859  PTHREAD_JOIN(t, 0);
860  PTHREAD_CREATE(&t, 0, ThreadedTestFree, &x);
861  PTHREAD_JOIN(t, 0);
862  PTHREAD_CREATE(&t, 0, ThreadedTestUse, &x);
863  PTHREAD_JOIN(t, 0);
864}
865
866TEST(AddressSanitizer, ThreadedTest) {
867  EXPECT_DEATH(ThreadedTestSpawn(),
868               ASAN_PCRE_DOTALL
869               "Thread T.*created"
870               ".*Thread T.*created"
871               ".*Thread T.*created");
872}
873
874void *ThreadedTestFunc(void *unused) {
875  // Check if prctl(PR_SET_NAME) is supported. Return if not.
876  if (!TryToSetThreadName("TestFunc"))
877    return 0;
878  EXPECT_DEATH(ThreadedTestSpawn(),
879               ASAN_PCRE_DOTALL
880               "WRITE .*thread T. .UseThr."
881               ".*freed by thread T. .FreeThr. here:"
882               ".*previously allocated by thread T. .AllocThr. here:"
883               ".*Thread T. .UseThr. created by T.*TestFunc"
884               ".*Thread T. .FreeThr. created by T"
885               ".*Thread T. .AllocThr. created by T"
886               "");
887  return 0;
888}
889
890TEST(AddressSanitizer, ThreadNamesTest) {
891  // Run ThreadedTestFunc in a separate thread because it tries to set a
892  // thread name and we don't want to change the main thread's name.
893  pthread_t t;
894  PTHREAD_CREATE(&t, 0, ThreadedTestFunc, 0);
895  PTHREAD_JOIN(t, 0);
896}
897
898#if ASAN_NEEDS_SEGV
899TEST(AddressSanitizer, ShadowGapTest) {
900#if SANITIZER_WORDSIZE == 32
901  char *addr = (char*)0x22000000;
902#else
903# if defined(__powerpc64__)
904  char *addr = (char*)0x024000800000;
905# else
906  char *addr = (char*)0x0000100000080000;
907# endif
908#endif
909  EXPECT_DEATH(*addr = 1, "AddressSanitizer: SEGV on unknown");
910}
911#endif  // ASAN_NEEDS_SEGV
912
913extern "C" {
914NOINLINE static void UseThenFreeThenUse() {
915  char *x = Ident((char*)malloc(8));
916  *x = 1;
917  free_aaa(x);
918  *x = 2;
919}
920}
921
922TEST(AddressSanitizer, UseThenFreeThenUseTest) {
923  EXPECT_DEATH(UseThenFreeThenUse(), "freed by thread");
924}
925
926TEST(AddressSanitizer, StrDupTest) {
927  free(strdup(Ident("123")));
928}
929
930// Currently we create and poison redzone at right of global variables.
931static char static110[110];
932const char ConstGlob[7] = {1, 2, 3, 4, 5, 6, 7};
933static const char StaticConstGlob[3] = {9, 8, 7};
934
935TEST(AddressSanitizer, GlobalTest) {
936  static char func_static15[15];
937
938  static char fs1[10];
939  static char fs2[10];
940  static char fs3[10];
941
942  glob5[Ident(0)] = 0;
943  glob5[Ident(1)] = 0;
944  glob5[Ident(2)] = 0;
945  glob5[Ident(3)] = 0;
946  glob5[Ident(4)] = 0;
947
948  EXPECT_DEATH(glob5[Ident(5)] = 0,
949               "0 bytes to the right of global variable.*glob5.* size 5");
950  EXPECT_DEATH(glob5[Ident(5+6)] = 0,
951               "6 bytes to the right of global variable.*glob5.* size 5");
952  Ident(static110);  // avoid optimizations
953  static110[Ident(0)] = 0;
954  static110[Ident(109)] = 0;
955  EXPECT_DEATH(static110[Ident(110)] = 0,
956               "0 bytes to the right of global variable");
957  EXPECT_DEATH(static110[Ident(110+7)] = 0,
958               "7 bytes to the right of global variable");
959
960  Ident(func_static15);  // avoid optimizations
961  func_static15[Ident(0)] = 0;
962  EXPECT_DEATH(func_static15[Ident(15)] = 0,
963               "0 bytes to the right of global variable");
964  EXPECT_DEATH(func_static15[Ident(15 + 9)] = 0,
965               "9 bytes to the right of global variable");
966
967  Ident(fs1);
968  Ident(fs2);
969  Ident(fs3);
970
971  // We don't create left redzones, so this is not 100% guaranteed to fail.
972  // But most likely will.
973  EXPECT_DEATH(fs2[Ident(-1)] = 0, "is located.*of global variable");
974
975  EXPECT_DEATH(Ident(Ident(ConstGlob)[8]),
976               "is located 1 bytes to the right of .*ConstGlob");
977  EXPECT_DEATH(Ident(Ident(StaticConstGlob)[5]),
978               "is located 2 bytes to the right of .*StaticConstGlob");
979
980  // call stuff from another file.
981  GlobalsTest(0);
982}
983
984TEST(AddressSanitizer, GlobalStringConstTest) {
985  static const char *zoo = "FOOBAR123";
986  const char *p = Ident(zoo);
987  EXPECT_DEATH(Ident(p[15]), "is ascii string 'FOOBAR123'");
988}
989
990TEST(AddressSanitizer, FileNameInGlobalReportTest) {
991  static char zoo[10];
992  const char *p = Ident(zoo);
993  // The file name should be present in the report.
994  EXPECT_DEATH(Ident(p[15]), "zoo.*asan_test.");
995}
996
997int *ReturnsPointerToALocalObject() {
998  int a = 0;
999  return Ident(&a);
1000}
1001
1002#if ASAN_UAR == 1
1003TEST(AddressSanitizer, LocalReferenceReturnTest) {
1004  int *(*f)() = Ident(ReturnsPointerToALocalObject);
1005  int *p = f();
1006  // Call 'f' a few more times, 'p' should still be poisoned.
1007  for (int i = 0; i < 32; i++)
1008    f();
1009  EXPECT_DEATH(*p = 1, "AddressSanitizer: stack-use-after-return");
1010  EXPECT_DEATH(*p = 1, "is located.*in frame .*ReturnsPointerToALocal");
1011}
1012#endif
1013
1014template <int kSize>
1015NOINLINE static void FuncWithStack() {
1016  char x[kSize];
1017  Ident(x)[0] = 0;
1018  Ident(x)[kSize-1] = 0;
1019}
1020
1021static void LotsOfStackReuse() {
1022  int LargeStack[10000];
1023  Ident(LargeStack)[0] = 0;
1024  for (int i = 0; i < 10000; i++) {
1025    FuncWithStack<128 * 1>();
1026    FuncWithStack<128 * 2>();
1027    FuncWithStack<128 * 4>();
1028    FuncWithStack<128 * 8>();
1029    FuncWithStack<128 * 16>();
1030    FuncWithStack<128 * 32>();
1031    FuncWithStack<128 * 64>();
1032    FuncWithStack<128 * 128>();
1033    FuncWithStack<128 * 256>();
1034    FuncWithStack<128 * 512>();
1035    Ident(LargeStack)[0] = 0;
1036  }
1037}
1038
1039TEST(AddressSanitizer, StressStackReuseTest) {
1040  LotsOfStackReuse();
1041}
1042
1043TEST(AddressSanitizer, ThreadedStressStackReuseTest) {
1044  const int kNumThreads = 20;
1045  pthread_t t[kNumThreads];
1046  for (int i = 0; i < kNumThreads; i++) {
1047    PTHREAD_CREATE(&t[i], 0, (void* (*)(void *x))LotsOfStackReuse, 0);
1048  }
1049  for (int i = 0; i < kNumThreads; i++) {
1050    PTHREAD_JOIN(t[i], 0);
1051  }
1052}
1053
1054static void *PthreadExit(void *a) {
1055  pthread_exit(0);
1056  return 0;
1057}
1058
1059TEST(AddressSanitizer, PthreadExitTest) {
1060  pthread_t t;
1061  for (int i = 0; i < 1000; i++) {
1062    PTHREAD_CREATE(&t, 0, PthreadExit, 0);
1063    PTHREAD_JOIN(t, 0);
1064  }
1065}
1066
1067#ifdef __EXCEPTIONS
1068NOINLINE static void StackReuseAndException() {
1069  int large_stack[1000];
1070  Ident(large_stack);
1071  ASAN_THROW(1);
1072}
1073
1074// TODO(kcc): support exceptions with use-after-return.
1075TEST(AddressSanitizer, DISABLED_StressStackReuseAndExceptionsTest) {
1076  for (int i = 0; i < 10000; i++) {
1077    try {
1078    StackReuseAndException();
1079    } catch(...) {
1080    }
1081  }
1082}
1083#endif
1084
1085TEST(AddressSanitizer, MlockTest) {
1086  EXPECT_EQ(0, mlockall(MCL_CURRENT));
1087  EXPECT_EQ(0, mlock((void*)0x12345, 0x5678));
1088  EXPECT_EQ(0, munlockall());
1089  EXPECT_EQ(0, munlock((void*)0x987, 0x654));
1090}
1091
1092struct LargeStruct {
1093  int foo[100];
1094};
1095
1096// Test for bug http://llvm.org/bugs/show_bug.cgi?id=11763.
1097// Struct copy should not cause asan warning even if lhs == rhs.
1098TEST(AddressSanitizer, LargeStructCopyTest) {
1099  LargeStruct a;
1100  *Ident(&a) = *Ident(&a);
1101}
1102
1103ATTRIBUTE_NO_SANITIZE_ADDRESS
1104static void NoSanitizeAddress() {
1105  char *foo = new char[10];
1106  Ident(foo)[10] = 0;
1107  delete [] foo;
1108}
1109
1110TEST(AddressSanitizer, AttributeNoSanitizeAddressTest) {
1111  Ident(NoSanitizeAddress)();
1112}
1113
1114// It doesn't work on Android, as calls to new/delete go through malloc/free.
1115// Neither it does on OS X, see
1116// https://code.google.com/p/address-sanitizer/issues/detail?id=131.
1117#if !defined(ANDROID) && !defined(__ANDROID__) && !defined(__APPLE__)
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
1232TEST(AddressSanitizer, pthread_getschedparam) {
1233  int policy;
1234  struct sched_param param;
1235  EXPECT_DEATH(
1236      pthread_getschedparam(pthread_self(), &policy, Ident(&param) + 2),
1237      "AddressSanitizer: stack-buffer-.*flow");
1238  EXPECT_DEATH(
1239      pthread_getschedparam(pthread_self(), Ident(&policy) - 1, &param),
1240      "AddressSanitizer: stack-buffer-.*flow");
1241  int res = pthread_getschedparam(pthread_self(), &policy, &param);
1242  ASSERT_EQ(0, res);
1243}
1244