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