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