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