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