asan_test.cc revision 38db30686c5962f8b5c877e29c6669d72198d42b
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
173#if ASAN_HAS_BLACKLIST
174TEST(AddressSanitizer, IgnoreTest) {
175  int *x = Ident(new int);
176  delete Ident(x);
177  *x = 0;
178}
179#endif  // ASAN_HAS_BLACKLIST
180
181struct StructWithBitField {
182  int bf1:1;
183  int bf2:1;
184  int bf3:1;
185  int bf4:29;
186};
187
188TEST(AddressSanitizer, BitFieldPositiveTest) {
189  StructWithBitField *x = new StructWithBitField;
190  delete Ident(x);
191  EXPECT_DEATH(x->bf1 = 0, "use-after-free");
192  EXPECT_DEATH(x->bf2 = 0, "use-after-free");
193  EXPECT_DEATH(x->bf3 = 0, "use-after-free");
194  EXPECT_DEATH(x->bf4 = 0, "use-after-free");
195}
196
197struct StructWithBitFields_8_24 {
198  int a:8;
199  int b:24;
200};
201
202TEST(AddressSanitizer, BitFieldNegativeTest) {
203  StructWithBitFields_8_24 *x = Ident(new StructWithBitFields_8_24);
204  x->a = 0;
205  x->b = 0;
206  delete Ident(x);
207}
208
209TEST(AddressSanitizer, OutOfMemoryTest) {
210  size_t size = SANITIZER_WORDSIZE == 64 ? (size_t)(1ULL << 48) : (0xf0000000);
211  EXPECT_EQ(0, realloc(0, size));
212  EXPECT_EQ(0, realloc(0, ~Ident(0)));
213  EXPECT_EQ(0, malloc(size));
214  EXPECT_EQ(0, malloc(~Ident(0)));
215  EXPECT_EQ(0, calloc(1, size));
216  EXPECT_EQ(0, calloc(1, ~Ident(0)));
217}
218
219#if ASAN_NEEDS_SEGV
220namespace {
221
222const char kUnknownCrash[] = "AddressSanitizer: SEGV on unknown address";
223const char kOverriddenHandler[] = "ASan signal handler has been overridden\n";
224
225TEST(AddressSanitizer, WildAddressTest) {
226  char *c = (char*)0x123;
227  EXPECT_DEATH(*c = 0, kUnknownCrash);
228}
229
230void my_sigaction_sighandler(int, siginfo_t*, void*) {
231  fprintf(stderr, kOverriddenHandler);
232  exit(1);
233}
234
235void my_signal_sighandler(int signum) {
236  fprintf(stderr, kOverriddenHandler);
237  exit(1);
238}
239
240TEST(AddressSanitizer, SignalTest) {
241  struct sigaction sigact;
242  memset(&sigact, 0, sizeof(sigact));
243  sigact.sa_sigaction = my_sigaction_sighandler;
244  sigact.sa_flags = SA_SIGINFO;
245  // ASan should silently ignore sigaction()...
246  EXPECT_EQ(0, sigaction(SIGSEGV, &sigact, 0));
247#ifdef __APPLE__
248  EXPECT_EQ(0, sigaction(SIGBUS, &sigact, 0));
249#endif
250  char *c = (char*)0x123;
251  EXPECT_DEATH(*c = 0, kUnknownCrash);
252  // ... and signal().
253  EXPECT_EQ(0, signal(SIGSEGV, my_signal_sighandler));
254  EXPECT_DEATH(*c = 0, kUnknownCrash);
255}
256}  // namespace
257#endif
258
259static void MallocStress(size_t n) {
260  uint32_t seed = my_rand();
261  for (size_t iter = 0; iter < 10; iter++) {
262    vector<void *> vec;
263    for (size_t i = 0; i < n; i++) {
264      if ((i % 3) == 0) {
265        if (vec.empty()) continue;
266        size_t idx = my_rand_r(&seed) % vec.size();
267        void *ptr = vec[idx];
268        vec[idx] = vec.back();
269        vec.pop_back();
270        free_aaa(ptr);
271      } else {
272        size_t size = my_rand_r(&seed) % 1000 + 1;
273#ifndef __APPLE__
274        size_t alignment = 1 << (my_rand_r(&seed) % 7 + 3);
275        char *ptr = (char*)memalign_aaa(alignment, size);
276#else
277        char *ptr = (char*) malloc_aaa(size);
278#endif
279        vec.push_back(ptr);
280        ptr[0] = 0;
281        ptr[size-1] = 0;
282        ptr[size/2] = 0;
283      }
284    }
285    for (size_t i = 0; i < vec.size(); i++)
286      free_aaa(vec[i]);
287  }
288}
289
290TEST(AddressSanitizer, MallocStressTest) {
291  MallocStress((ASAN_LOW_MEMORY) ? 20000 : 200000);
292}
293
294static void TestLargeMalloc(size_t size) {
295  char buff[1024];
296  sprintf(buff, "is located 1 bytes to the left of %lu-byte", (long)size);
297  EXPECT_DEATH(Ident((char*)malloc(size))[-1] = 0, buff);
298}
299
300TEST(AddressSanitizer, LargeMallocTest) {
301  for (int i = 113; i < (1 << 28); i = i * 2 + 13) {
302    TestLargeMalloc(i);
303  }
304}
305
306#if ASAN_LOW_MEMORY != 1
307TEST(AddressSanitizer, HugeMallocTest) {
308#ifdef __APPLE__
309  // It was empirically found out that 1215 megabytes is the maximum amount of
310  // memory available to the process under AddressSanitizer on 32-bit Mac 10.6.
311  // 32-bit Mac 10.7 gives even less (< 1G).
312  // (the libSystem malloc() allows allocating up to 2300 megabytes without
313  // ASan).
314  size_t n_megs = SANITIZER_WORDSIZE == 32 ? 500 : 4100;
315#else
316  size_t n_megs = SANITIZER_WORDSIZE == 32 ? 2600 : 4100;
317#endif
318  TestLargeMalloc(n_megs << 20);
319}
320#endif
321
322#ifndef __APPLE__
323void MemalignRun(size_t align, size_t size, int idx) {
324  char *p = (char *)memalign(align, size);
325  Ident(p)[idx] = 0;
326  free(p);
327}
328
329TEST(AddressSanitizer, memalign) {
330  for (int align = 16; align <= (1 << 23); align *= 2) {
331    size_t size = align * 5;
332    EXPECT_DEATH(MemalignRun(align, size, -1),
333                 "is located 1 bytes to the left");
334    EXPECT_DEATH(MemalignRun(align, size, size + 1),
335                 "is located 1 bytes to the right");
336  }
337}
338#endif
339
340TEST(AddressSanitizer, ThreadedMallocStressTest) {
341  const int kNumThreads = 4;
342  const int kNumIterations = (ASAN_LOW_MEMORY) ? 10000 : 100000;
343  pthread_t t[kNumThreads];
344  for (int i = 0; i < kNumThreads; i++) {
345    PTHREAD_CREATE(&t[i], 0, (void* (*)(void *x))MallocStress,
346        (void*)kNumIterations);
347  }
348  for (int i = 0; i < kNumThreads; i++) {
349    PTHREAD_JOIN(t[i], 0);
350  }
351}
352
353void *ManyThreadsWorker(void *a) {
354  for (int iter = 0; iter < 100; iter++) {
355    for (size_t size = 100; size < 2000; size *= 2) {
356      free(Ident(malloc(size)));
357    }
358  }
359  return 0;
360}
361
362TEST(AddressSanitizer, ManyThreadsTest) {
363  const size_t kNumThreads =
364      (SANITIZER_WORDSIZE == 32 || ASAN_AVOID_EXPENSIVE_TESTS) ? 30 : 1000;
365  pthread_t t[kNumThreads];
366  for (size_t i = 0; i < kNumThreads; i++) {
367    PTHREAD_CREATE(&t[i], 0, ManyThreadsWorker, (void*)i);
368  }
369  for (size_t i = 0; i < kNumThreads; i++) {
370    PTHREAD_JOIN(t[i], 0);
371  }
372}
373
374TEST(AddressSanitizer, ReallocTest) {
375  const int kMinElem = 5;
376  int *ptr = (int*)malloc(sizeof(int) * kMinElem);
377  ptr[3] = 3;
378  for (int i = 0; i < 10000; i++) {
379    ptr = (int*)realloc(ptr,
380        (my_rand() % 1000 + kMinElem) * sizeof(int));
381    EXPECT_EQ(3, ptr[3]);
382  }
383}
384
385#ifndef __APPLE__
386static const char *kMallocUsableSizeErrorMsg =
387  "AddressSanitizer: attempting to call malloc_usable_size()";
388
389TEST(AddressSanitizer, MallocUsableSizeTest) {
390  const size_t kArraySize = 100;
391  char *array = Ident((char*)malloc(kArraySize));
392  int *int_ptr = Ident(new int);
393  EXPECT_EQ(0U, malloc_usable_size(NULL));
394  EXPECT_EQ(kArraySize, malloc_usable_size(array));
395  EXPECT_EQ(sizeof(int), malloc_usable_size(int_ptr));
396  EXPECT_DEATH(malloc_usable_size((void*)0x123), kMallocUsableSizeErrorMsg);
397  EXPECT_DEATH(malloc_usable_size(array + kArraySize / 2),
398               kMallocUsableSizeErrorMsg);
399  free(array);
400  EXPECT_DEATH(malloc_usable_size(array), kMallocUsableSizeErrorMsg);
401}
402#endif
403
404void WrongFree() {
405  int *x = (int*)malloc(100 * sizeof(int));
406  // Use the allocated memory, otherwise Clang will optimize it out.
407  Ident(x);
408  free(x + 1);
409}
410
411TEST(AddressSanitizer, WrongFreeTest) {
412  EXPECT_DEATH(WrongFree(),
413               "ERROR: AddressSanitizer: attempting free.*not malloc");
414}
415
416void DoubleFree() {
417  int *x = (int*)malloc(100 * sizeof(int));
418  fprintf(stderr, "DoubleFree: x=%p\n", x);
419  free(x);
420  free(x);
421  fprintf(stderr, "should have failed in the second free(%p)\n", x);
422  abort();
423}
424
425TEST(AddressSanitizer, DoubleFreeTest) {
426  EXPECT_DEATH(DoubleFree(), ASAN_PCRE_DOTALL
427               "ERROR: AddressSanitizer: attempting double-free"
428               ".*is located 0 bytes inside of 400-byte region"
429               ".*freed by thread T0 here"
430               ".*previously allocated by thread T0 here");
431}
432
433template<int kSize>
434NOINLINE void SizedStackTest() {
435  char a[kSize];
436  char  *A = Ident((char*)&a);
437  for (size_t i = 0; i < kSize; i++)
438    A[i] = i;
439  EXPECT_DEATH(A[-1] = 0, "");
440  EXPECT_DEATH(A[-20] = 0, "");
441  EXPECT_DEATH(A[-31] = 0, "");
442  EXPECT_DEATH(A[kSize] = 0, "");
443  EXPECT_DEATH(A[kSize + 1] = 0, "");
444  EXPECT_DEATH(A[kSize + 10] = 0, "");
445  EXPECT_DEATH(A[kSize + 31] = 0, "");
446}
447
448TEST(AddressSanitizer, SimpleStackTest) {
449  SizedStackTest<1>();
450  SizedStackTest<2>();
451  SizedStackTest<3>();
452  SizedStackTest<4>();
453  SizedStackTest<5>();
454  SizedStackTest<6>();
455  SizedStackTest<7>();
456  SizedStackTest<16>();
457  SizedStackTest<25>();
458  SizedStackTest<34>();
459  SizedStackTest<43>();
460  SizedStackTest<51>();
461  SizedStackTest<62>();
462  SizedStackTest<64>();
463  SizedStackTest<128>();
464}
465
466TEST(AddressSanitizer, ManyStackObjectsTest) {
467  char XXX[10];
468  char YYY[20];
469  char ZZZ[30];
470  Ident(XXX);
471  Ident(YYY);
472  EXPECT_DEATH(Ident(ZZZ)[-1] = 0, ASAN_PCRE_DOTALL "XXX.*YYY.*ZZZ");
473}
474
475NOINLINE static void Frame0(int frame, char *a, char *b, char *c) {
476  char d[4] = {0};
477  char *D = Ident(d);
478  switch (frame) {
479    case 3: a[5]++; break;
480    case 2: b[5]++; break;
481    case 1: c[5]++; break;
482    case 0: D[5]++; break;
483  }
484}
485NOINLINE static void Frame1(int frame, char *a, char *b) {
486  char c[4] = {0}; Frame0(frame, a, b, c);
487  break_optimization(0);
488}
489NOINLINE static void Frame2(int frame, char *a) {
490  char b[4] = {0}; Frame1(frame, a, b);
491  break_optimization(0);
492}
493NOINLINE static void Frame3(int frame) {
494  char a[4] = {0}; Frame2(frame, a);
495  break_optimization(0);
496}
497
498TEST(AddressSanitizer, GuiltyStackFrame0Test) {
499  EXPECT_DEATH(Frame3(0), "located .*in frame <.*Frame0");
500}
501TEST(AddressSanitizer, GuiltyStackFrame1Test) {
502  EXPECT_DEATH(Frame3(1), "located .*in frame <.*Frame1");
503}
504TEST(AddressSanitizer, GuiltyStackFrame2Test) {
505  EXPECT_DEATH(Frame3(2), "located .*in frame <.*Frame2");
506}
507TEST(AddressSanitizer, GuiltyStackFrame3Test) {
508  EXPECT_DEATH(Frame3(3), "located .*in frame <.*Frame3");
509}
510
511NOINLINE void LongJmpFunc1(jmp_buf buf) {
512  // create three red zones for these two stack objects.
513  int a;
514  int b;
515
516  int *A = Ident(&a);
517  int *B = Ident(&b);
518  *A = *B;
519  longjmp(buf, 1);
520}
521
522NOINLINE void BuiltinLongJmpFunc1(jmp_buf buf) {
523  // create three red zones for these two stack objects.
524  int a;
525  int b;
526
527  int *A = Ident(&a);
528  int *B = Ident(&b);
529  *A = *B;
530  __builtin_longjmp((void**)buf, 1);
531}
532
533NOINLINE void UnderscopeLongJmpFunc1(jmp_buf buf) {
534  // create three red zones for these two stack objects.
535  int a;
536  int b;
537
538  int *A = Ident(&a);
539  int *B = Ident(&b);
540  *A = *B;
541  _longjmp(buf, 1);
542}
543
544NOINLINE void SigLongJmpFunc1(sigjmp_buf buf) {
545  // create three red zones for these two stack objects.
546  int a;
547  int b;
548
549  int *A = Ident(&a);
550  int *B = Ident(&b);
551  *A = *B;
552  siglongjmp(buf, 1);
553}
554
555
556NOINLINE void TouchStackFunc() {
557  int a[100];  // long array will intersect with redzones from LongJmpFunc1.
558  int *A = Ident(a);
559  for (int i = 0; i < 100; i++)
560    A[i] = i*i;
561}
562
563// Test that we handle longjmp and do not report fals positives on stack.
564TEST(AddressSanitizer, LongJmpTest) {
565  static jmp_buf buf;
566  if (!setjmp(buf)) {
567    LongJmpFunc1(buf);
568  } else {
569    TouchStackFunc();
570  }
571}
572
573#if not defined(__ANDROID__)
574TEST(AddressSanitizer, BuiltinLongJmpTest) {
575  static jmp_buf buf;
576  if (!__builtin_setjmp((void**)buf)) {
577    BuiltinLongJmpFunc1(buf);
578  } else {
579    TouchStackFunc();
580  }
581}
582#endif  // not defined(__ANDROID__)
583
584TEST(AddressSanitizer, UnderscopeLongJmpTest) {
585  static jmp_buf buf;
586  if (!_setjmp(buf)) {
587    UnderscopeLongJmpFunc1(buf);
588  } else {
589    TouchStackFunc();
590  }
591}
592
593TEST(AddressSanitizer, SigLongJmpTest) {
594  static sigjmp_buf buf;
595  if (!sigsetjmp(buf, 1)) {
596    SigLongJmpFunc1(buf);
597  } else {
598    TouchStackFunc();
599  }
600}
601
602#ifdef __EXCEPTIONS
603NOINLINE void ThrowFunc() {
604  // create three red zones for these two stack objects.
605  int a;
606  int b;
607
608  int *A = Ident(&a);
609  int *B = Ident(&b);
610  *A = *B;
611  ASAN_THROW(1);
612}
613
614TEST(AddressSanitizer, CxxExceptionTest) {
615  if (ASAN_UAR) return;
616  // TODO(kcc): this test crashes on 32-bit for some reason...
617  if (SANITIZER_WORDSIZE == 32) return;
618  try {
619    ThrowFunc();
620  } catch(...) {}
621  TouchStackFunc();
622}
623#endif
624
625void *ThreadStackReuseFunc1(void *unused) {
626  // create three red zones for these two stack objects.
627  int a;
628  int b;
629
630  int *A = Ident(&a);
631  int *B = Ident(&b);
632  *A = *B;
633  pthread_exit(0);
634  return 0;
635}
636
637void *ThreadStackReuseFunc2(void *unused) {
638  TouchStackFunc();
639  return 0;
640}
641
642TEST(AddressSanitizer, ThreadStackReuseTest) {
643  pthread_t t;
644  PTHREAD_CREATE(&t, 0, ThreadStackReuseFunc1, 0);
645  PTHREAD_JOIN(t, 0);
646  PTHREAD_CREATE(&t, 0, ThreadStackReuseFunc2, 0);
647  PTHREAD_JOIN(t, 0);
648}
649
650#if defined(__i386__) || defined(__x86_64__)
651TEST(AddressSanitizer, Store128Test) {
652  char *a = Ident((char*)malloc(Ident(12)));
653  char *p = a;
654  if (((uintptr_t)a % 16) != 0)
655    p = a + 8;
656  assert(((uintptr_t)p % 16) == 0);
657  __m128i value_wide = _mm_set1_epi16(0x1234);
658  EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
659               "AddressSanitizer: heap-buffer-overflow");
660  EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
661               "WRITE of size 16");
662  EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
663               "located 0 bytes to the right of 12-byte");
664  free(a);
665}
666#endif
667
668static string RightOOBErrorMessage(int oob_distance, bool is_write) {
669  assert(oob_distance >= 0);
670  char expected_str[100];
671  sprintf(expected_str, ASAN_PCRE_DOTALL "%s.*located %d bytes to the right",
672          is_write ? "WRITE" : "READ", oob_distance);
673  return string(expected_str);
674}
675
676static string RightOOBWriteMessage(int oob_distance) {
677  return RightOOBErrorMessage(oob_distance, /*is_write*/true);
678}
679
680static string RightOOBReadMessage(int oob_distance) {
681  return RightOOBErrorMessage(oob_distance, /*is_write*/false);
682}
683
684static string LeftOOBErrorMessage(int oob_distance, bool is_write) {
685  assert(oob_distance > 0);
686  char expected_str[100];
687  sprintf(expected_str, ASAN_PCRE_DOTALL "%s.*located %d bytes to the left",
688          is_write ? "WRITE" : "READ", oob_distance);
689  return string(expected_str);
690}
691
692static string LeftOOBWriteMessage(int oob_distance) {
693  return LeftOOBErrorMessage(oob_distance, /*is_write*/true);
694}
695
696static string LeftOOBReadMessage(int oob_distance) {
697  return LeftOOBErrorMessage(oob_distance, /*is_write*/false);
698}
699
700static string LeftOOBAccessMessage(int oob_distance) {
701  assert(oob_distance > 0);
702  char expected_str[100];
703  sprintf(expected_str, "located %d bytes to the left", oob_distance);
704  return string(expected_str);
705}
706
707template<typename T>
708void MemSetOOBTestTemplate(size_t length) {
709  if (length == 0) return;
710  size_t size = Ident(sizeof(T) * length);
711  T *array = Ident((T*)malloc(size));
712  int element = Ident(42);
713  int zero = Ident(0);
714  void *(*MEMSET)(void *s, int c, size_t n) = Ident(memset);
715  // memset interval inside array
716  MEMSET(array, element, size);
717  MEMSET(array, element, size - 1);
718  MEMSET(array + length - 1, element, sizeof(T));
719  MEMSET(array, element, 1);
720
721  // memset 0 bytes
722  MEMSET(array - 10, element, zero);
723  MEMSET(array - 1, element, zero);
724  MEMSET(array, element, zero);
725  MEMSET(array + length, 0, zero);
726  MEMSET(array + length + 1, 0, zero);
727
728  // try to memset bytes to the right of array
729  EXPECT_DEATH(MEMSET(array, 0, size + 1),
730               RightOOBWriteMessage(0));
731  EXPECT_DEATH(MEMSET((char*)(array + length) - 1, element, 6),
732               RightOOBWriteMessage(0));
733  EXPECT_DEATH(MEMSET(array + 1, element, size + sizeof(T)),
734               RightOOBWriteMessage(0));
735  // whole interval is to the right
736  EXPECT_DEATH(MEMSET(array + length + 1, 0, 10),
737               RightOOBWriteMessage(sizeof(T)));
738
739  // try to memset bytes to the left of array
740  EXPECT_DEATH(MEMSET((char*)array - 1, element, size),
741               LeftOOBWriteMessage(1));
742  EXPECT_DEATH(MEMSET((char*)array - 5, 0, 6),
743               LeftOOBWriteMessage(5));
744  if (length >= 100) {
745    // Large OOB, we find it only if the redzone is large enough.
746    EXPECT_DEATH(memset(array - 5, element, size + 5 * sizeof(T)),
747                 LeftOOBWriteMessage(5 * sizeof(T)));
748  }
749  // whole interval is to the left
750  EXPECT_DEATH(MEMSET(array - 2, 0, sizeof(T)),
751               LeftOOBWriteMessage(2 * sizeof(T)));
752
753  // try to memset bytes both to the left & to the right
754  EXPECT_DEATH(MEMSET((char*)array - 2, element, size + 4),
755               LeftOOBWriteMessage(2));
756
757  free(array);
758}
759
760TEST(AddressSanitizer, MemSetOOBTest) {
761  MemSetOOBTestTemplate<char>(100);
762  MemSetOOBTestTemplate<int>(5);
763  MemSetOOBTestTemplate<double>(256);
764  // We can test arrays of structres/classes here, but what for?
765}
766
767// Try to allocate two arrays of 'size' bytes that are near each other.
768// Strictly speaking we are not guaranteed to find such two pointers,
769// but given the structure of asan's allocator we will.
770static bool AllocateTwoAdjacentArrays(char **x1, char **x2, size_t size) {
771  vector<char *> v;
772  bool res = false;
773  for (size_t i = 0; i < 1000U && !res; i++) {
774    v.push_back(new char[size]);
775    if (i == 0) continue;
776    sort(v.begin(), v.end());
777    for (size_t j = 1; j < v.size(); j++) {
778      assert(v[j] > v[j-1]);
779      if ((size_t)(v[j] - v[j-1]) < size * 2) {
780        *x2 = v[j];
781        *x1 = v[j-1];
782        res = true;
783        break;
784      }
785    }
786  }
787
788  for (size_t i = 0; i < v.size(); i++) {
789    if (res && v[i] == *x1) continue;
790    if (res && v[i] == *x2) continue;
791    delete [] v[i];
792  }
793  return res;
794}
795
796TEST(AddressSanitizer, LargeOOBInMemset) {
797  for (size_t size = 200; size < 100000; size += size / 2) {
798    char *x1, *x2;
799    if (!Ident(AllocateTwoAdjacentArrays)(&x1, &x2, size))
800      continue;
801    // fprintf(stderr, "  large oob memset: %p %p %zd\n", x1, x2, size);
802    // Do a memset on x1 with huge out-of-bound access that will end up in x2.
803    EXPECT_DEATH(Ident(memset)(x1, 0, size * 2),
804                 "is located 0 bytes to the right");
805    delete [] x1;
806    delete [] x2;
807    return;
808  }
809  assert(0 && "Did not find two adjacent malloc-ed pointers");
810}
811
812// Same test for memcpy and memmove functions
813template <typename T, class M>
814void MemTransferOOBTestTemplate(size_t length) {
815  if (length == 0) return;
816  size_t size = Ident(sizeof(T) * length);
817  T *src = Ident((T*)malloc(size));
818  T *dest = Ident((T*)malloc(size));
819  int zero = Ident(0);
820
821  // valid transfer of bytes between arrays
822  M::transfer(dest, src, size);
823  M::transfer(dest + 1, src, size - sizeof(T));
824  M::transfer(dest, src + length - 1, sizeof(T));
825  M::transfer(dest, src, 1);
826
827  // transfer zero bytes
828  M::transfer(dest - 1, src, 0);
829  M::transfer(dest + length, src, zero);
830  M::transfer(dest, src - 1, zero);
831  M::transfer(dest, src, zero);
832
833  // try to change mem to the right of dest
834  EXPECT_DEATH(M::transfer(dest + 1, src, size),
835               RightOOBWriteMessage(0));
836  EXPECT_DEATH(M::transfer((char*)(dest + length) - 1, src, 5),
837               RightOOBWriteMessage(0));
838
839  // try to change mem to the left of dest
840  EXPECT_DEATH(M::transfer(dest - 2, src, size),
841               LeftOOBWriteMessage(2 * sizeof(T)));
842  EXPECT_DEATH(M::transfer((char*)dest - 3, src, 4),
843               LeftOOBWriteMessage(3));
844
845  // try to access mem to the right of src
846  EXPECT_DEATH(M::transfer(dest, src + 2, size),
847               RightOOBReadMessage(0));
848  EXPECT_DEATH(M::transfer(dest, (char*)(src + length) - 3, 6),
849               RightOOBReadMessage(0));
850
851  // try to access mem to the left of src
852  EXPECT_DEATH(M::transfer(dest, src - 1, size),
853               LeftOOBReadMessage(sizeof(T)));
854  EXPECT_DEATH(M::transfer(dest, (char*)src - 6, 7),
855               LeftOOBReadMessage(6));
856
857  // Generally we don't need to test cases where both accessing src and writing
858  // to dest address to poisoned memory.
859
860  T *big_src = Ident((T*)malloc(size * 2));
861  T *big_dest = Ident((T*)malloc(size * 2));
862  // try to change mem to both sides of dest
863  EXPECT_DEATH(M::transfer(dest - 1, big_src, size * 2),
864               LeftOOBWriteMessage(sizeof(T)));
865  // try to access mem to both sides of src
866  EXPECT_DEATH(M::transfer(big_dest, src - 2, size * 2),
867               LeftOOBReadMessage(2 * sizeof(T)));
868
869  free(src);
870  free(dest);
871  free(big_src);
872  free(big_dest);
873}
874
875class MemCpyWrapper {
876 public:
877  static void* transfer(void *to, const void *from, size_t size) {
878    return Ident(memcpy)(to, from, size);
879  }
880};
881TEST(AddressSanitizer, MemCpyOOBTest) {
882  MemTransferOOBTestTemplate<char, MemCpyWrapper>(100);
883  MemTransferOOBTestTemplate<int, MemCpyWrapper>(1024);
884}
885
886class MemMoveWrapper {
887 public:
888  static void* transfer(void *to, const void *from, size_t size) {
889    return Ident(memmove)(to, from, size);
890  }
891};
892TEST(AddressSanitizer, MemMoveOOBTest) {
893  MemTransferOOBTestTemplate<char, MemMoveWrapper>(100);
894  MemTransferOOBTestTemplate<int, MemMoveWrapper>(1024);
895}
896
897// Tests for string functions
898
899// Used for string functions tests
900static char global_string[] = "global";
901static size_t global_string_length = 6;
902
903// Input to a test is a zero-terminated string str with given length
904// Accesses to the bytes to the left and to the right of str
905// are presumed to produce OOB errors
906void StrLenOOBTestTemplate(char *str, size_t length, bool is_global) {
907  // Normal strlen calls
908  EXPECT_EQ(strlen(str), length);
909  if (length > 0) {
910    EXPECT_EQ(length - 1, strlen(str + 1));
911    EXPECT_EQ(0U, strlen(str + length));
912  }
913  // Arg of strlen is not malloced, OOB access
914  if (!is_global) {
915    // We don't insert RedZones to the left of global variables
916    EXPECT_DEATH(Ident(strlen(str - 1)), LeftOOBReadMessage(1));
917    EXPECT_DEATH(Ident(strlen(str - 5)), LeftOOBReadMessage(5));
918  }
919  EXPECT_DEATH(Ident(strlen(str + length + 1)), RightOOBReadMessage(0));
920  // Overwrite terminator
921  str[length] = 'a';
922  // String is not zero-terminated, strlen will lead to OOB access
923  EXPECT_DEATH(Ident(strlen(str)), RightOOBReadMessage(0));
924  EXPECT_DEATH(Ident(strlen(str + length)), RightOOBReadMessage(0));
925  // Restore terminator
926  str[length] = 0;
927}
928TEST(AddressSanitizer, StrLenOOBTest) {
929  // Check heap-allocated string
930  size_t length = Ident(10);
931  char *heap_string = Ident((char*)malloc(length + 1));
932  char stack_string[10 + 1];
933  break_optimization(&stack_string);
934  for (size_t i = 0; i < length; i++) {
935    heap_string[i] = 'a';
936    stack_string[i] = 'b';
937  }
938  heap_string[length] = 0;
939  stack_string[length] = 0;
940  StrLenOOBTestTemplate(heap_string, length, false);
941  // TODO(samsonov): Fix expected messages in StrLenOOBTestTemplate to
942  //      make test for stack_string work. Or move it to output tests.
943  // StrLenOOBTestTemplate(stack_string, length, false);
944  StrLenOOBTestTemplate(global_string, global_string_length, true);
945  free(heap_string);
946}
947
948static inline char* MallocAndMemsetString(size_t size, char ch) {
949  char *s = Ident((char*)malloc(size));
950  memset(s, ch, size);
951  return s;
952}
953static inline char* MallocAndMemsetString(size_t size) {
954  return MallocAndMemsetString(size, 'z');
955}
956
957#ifndef __APPLE__
958TEST(AddressSanitizer, StrNLenOOBTest) {
959  size_t size = Ident(123);
960  char *str = MallocAndMemsetString(size);
961  // Normal strnlen calls.
962  Ident(strnlen(str - 1, 0));
963  Ident(strnlen(str, size));
964  Ident(strnlen(str + size - 1, 1));
965  str[size - 1] = '\0';
966  Ident(strnlen(str, 2 * size));
967  // Argument points to not allocated memory.
968  EXPECT_DEATH(Ident(strnlen(str - 1, 1)), LeftOOBReadMessage(1));
969  EXPECT_DEATH(Ident(strnlen(str + size, 1)), RightOOBReadMessage(0));
970  // Overwrite the terminating '\0' and hit unallocated memory.
971  str[size - 1] = 'z';
972  EXPECT_DEATH(Ident(strnlen(str, size + 1)), RightOOBReadMessage(0));
973  free(str);
974}
975#endif
976
977TEST(AddressSanitizer, StrDupOOBTest) {
978  size_t size = Ident(42);
979  char *str = MallocAndMemsetString(size);
980  char *new_str;
981  // Normal strdup calls.
982  str[size - 1] = '\0';
983  new_str = strdup(str);
984  free(new_str);
985  new_str = strdup(str + size - 1);
986  free(new_str);
987  // Argument points to not allocated memory.
988  EXPECT_DEATH(Ident(strdup(str - 1)), LeftOOBReadMessage(1));
989  EXPECT_DEATH(Ident(strdup(str + size)), RightOOBReadMessage(0));
990  // Overwrite the terminating '\0' and hit unallocated memory.
991  str[size - 1] = 'z';
992  EXPECT_DEATH(Ident(strdup(str)), RightOOBReadMessage(0));
993  free(str);
994}
995
996TEST(AddressSanitizer, StrCpyOOBTest) {
997  size_t to_size = Ident(30);
998  size_t from_size = Ident(6);  // less than to_size
999  char *to = Ident((char*)malloc(to_size));
1000  char *from = Ident((char*)malloc(from_size));
1001  // Normal strcpy calls.
1002  strcpy(from, "hello");
1003  strcpy(to, from);
1004  strcpy(to + to_size - from_size, from);
1005  // Length of "from" is too small.
1006  EXPECT_DEATH(Ident(strcpy(from, "hello2")), RightOOBWriteMessage(0));
1007  // "to" or "from" points to not allocated memory.
1008  EXPECT_DEATH(Ident(strcpy(to - 1, from)), LeftOOBWriteMessage(1));
1009  EXPECT_DEATH(Ident(strcpy(to, from - 1)), LeftOOBReadMessage(1));
1010  EXPECT_DEATH(Ident(strcpy(to, from + from_size)), RightOOBReadMessage(0));
1011  EXPECT_DEATH(Ident(strcpy(to + to_size, from)), RightOOBWriteMessage(0));
1012  // Overwrite the terminating '\0' character and hit unallocated memory.
1013  from[from_size - 1] = '!';
1014  EXPECT_DEATH(Ident(strcpy(to, from)), RightOOBReadMessage(0));
1015  free(to);
1016  free(from);
1017}
1018
1019TEST(AddressSanitizer, StrNCpyOOBTest) {
1020  size_t to_size = Ident(20);
1021  size_t from_size = Ident(6);  // less than to_size
1022  char *to = Ident((char*)malloc(to_size));
1023  // From is a zero-terminated string "hello\0" of length 6
1024  char *from = Ident((char*)malloc(from_size));
1025  strcpy(from, "hello");
1026  // copy 0 bytes
1027  strncpy(to, from, 0);
1028  strncpy(to - 1, from - 1, 0);
1029  // normal strncpy calls
1030  strncpy(to, from, from_size);
1031  strncpy(to, from, to_size);
1032  strncpy(to, from + from_size - 1, to_size);
1033  strncpy(to + to_size - 1, from, 1);
1034  // One of {to, from} points to not allocated memory
1035  EXPECT_DEATH(Ident(strncpy(to, from - 1, from_size)),
1036               LeftOOBReadMessage(1));
1037  EXPECT_DEATH(Ident(strncpy(to - 1, from, from_size)),
1038               LeftOOBWriteMessage(1));
1039  EXPECT_DEATH(Ident(strncpy(to, from + from_size, 1)),
1040               RightOOBReadMessage(0));
1041  EXPECT_DEATH(Ident(strncpy(to + to_size, from, 1)),
1042               RightOOBWriteMessage(0));
1043  // Length of "to" is too small
1044  EXPECT_DEATH(Ident(strncpy(to + to_size - from_size + 1, from, from_size)),
1045               RightOOBWriteMessage(0));
1046  EXPECT_DEATH(Ident(strncpy(to + 1, from, to_size)),
1047               RightOOBWriteMessage(0));
1048  // Overwrite terminator in from
1049  from[from_size - 1] = '!';
1050  // normal strncpy call
1051  strncpy(to, from, from_size);
1052  // Length of "from" is too small
1053  EXPECT_DEATH(Ident(strncpy(to, from, to_size)),
1054               RightOOBReadMessage(0));
1055  free(to);
1056  free(from);
1057}
1058
1059// Users may have different definitions of "strchr" and "index", so provide
1060// function pointer typedefs and overload RunStrChrTest implementation.
1061// We can't use macro for RunStrChrTest body here, as this macro would
1062// confuse EXPECT_DEATH gtest macro.
1063typedef char*(*PointerToStrChr1)(const char*, int);
1064typedef char*(*PointerToStrChr2)(char*, int);
1065
1066USED static void RunStrChrTest(PointerToStrChr1 StrChr) {
1067  size_t size = Ident(100);
1068  char *str = MallocAndMemsetString(size);
1069  str[10] = 'q';
1070  str[11] = '\0';
1071  EXPECT_EQ(str, StrChr(str, 'z'));
1072  EXPECT_EQ(str + 10, StrChr(str, 'q'));
1073  EXPECT_EQ(NULL, StrChr(str, 'a'));
1074  // StrChr argument points to not allocated memory.
1075  EXPECT_DEATH(Ident(StrChr(str - 1, 'z')), LeftOOBReadMessage(1));
1076  EXPECT_DEATH(Ident(StrChr(str + size, 'z')), RightOOBReadMessage(0));
1077  // Overwrite the terminator and hit not allocated memory.
1078  str[11] = 'z';
1079  EXPECT_DEATH(Ident(StrChr(str, 'a')), RightOOBReadMessage(0));
1080  free(str);
1081}
1082USED static void RunStrChrTest(PointerToStrChr2 StrChr) {
1083  size_t size = Ident(100);
1084  char *str = MallocAndMemsetString(size);
1085  str[10] = 'q';
1086  str[11] = '\0';
1087  EXPECT_EQ(str, StrChr(str, 'z'));
1088  EXPECT_EQ(str + 10, StrChr(str, 'q'));
1089  EXPECT_EQ(NULL, StrChr(str, 'a'));
1090  // StrChr argument points to not allocated memory.
1091  EXPECT_DEATH(Ident(StrChr(str - 1, 'z')), LeftOOBReadMessage(1));
1092  EXPECT_DEATH(Ident(StrChr(str + size, 'z')), RightOOBReadMessage(0));
1093  // Overwrite the terminator and hit not allocated memory.
1094  str[11] = 'z';
1095  EXPECT_DEATH(Ident(StrChr(str, 'a')), RightOOBReadMessage(0));
1096  free(str);
1097}
1098
1099TEST(AddressSanitizer, StrChrAndIndexOOBTest) {
1100  RunStrChrTest(&strchr);
1101  RunStrChrTest(&index);
1102}
1103
1104TEST(AddressSanitizer, StrCmpAndFriendsLogicTest) {
1105  // strcmp
1106  EXPECT_EQ(0, strcmp("", ""));
1107  EXPECT_EQ(0, strcmp("abcd", "abcd"));
1108  EXPECT_GT(0, strcmp("ab", "ac"));
1109  EXPECT_GT(0, strcmp("abc", "abcd"));
1110  EXPECT_LT(0, strcmp("acc", "abc"));
1111  EXPECT_LT(0, strcmp("abcd", "abc"));
1112
1113  // strncmp
1114  EXPECT_EQ(0, strncmp("a", "b", 0));
1115  EXPECT_EQ(0, strncmp("abcd", "abcd", 10));
1116  EXPECT_EQ(0, strncmp("abcd", "abcef", 3));
1117  EXPECT_GT(0, strncmp("abcde", "abcfa", 4));
1118  EXPECT_GT(0, strncmp("a", "b", 5));
1119  EXPECT_GT(0, strncmp("bc", "bcde", 4));
1120  EXPECT_LT(0, strncmp("xyz", "xyy", 10));
1121  EXPECT_LT(0, strncmp("baa", "aaa", 1));
1122  EXPECT_LT(0, strncmp("zyx", "", 2));
1123
1124  // strcasecmp
1125  EXPECT_EQ(0, strcasecmp("", ""));
1126  EXPECT_EQ(0, strcasecmp("zzz", "zzz"));
1127  EXPECT_EQ(0, strcasecmp("abCD", "ABcd"));
1128  EXPECT_GT(0, strcasecmp("aB", "Ac"));
1129  EXPECT_GT(0, strcasecmp("ABC", "ABCd"));
1130  EXPECT_LT(0, strcasecmp("acc", "abc"));
1131  EXPECT_LT(0, strcasecmp("ABCd", "abc"));
1132
1133  // strncasecmp
1134  EXPECT_EQ(0, strncasecmp("a", "b", 0));
1135  EXPECT_EQ(0, strncasecmp("abCD", "ABcd", 10));
1136  EXPECT_EQ(0, strncasecmp("abCd", "ABcef", 3));
1137  EXPECT_GT(0, strncasecmp("abcde", "ABCfa", 4));
1138  EXPECT_GT(0, strncasecmp("a", "B", 5));
1139  EXPECT_GT(0, strncasecmp("bc", "BCde", 4));
1140  EXPECT_LT(0, strncasecmp("xyz", "xyy", 10));
1141  EXPECT_LT(0, strncasecmp("Baa", "aaa", 1));
1142  EXPECT_LT(0, strncasecmp("zyx", "", 2));
1143
1144  // memcmp
1145  EXPECT_EQ(0, memcmp("a", "b", 0));
1146  EXPECT_EQ(0, memcmp("ab\0c", "ab\0c", 4));
1147  EXPECT_GT(0, memcmp("\0ab", "\0ac", 3));
1148  EXPECT_GT(0, memcmp("abb\0", "abba", 4));
1149  EXPECT_LT(0, memcmp("ab\0cd", "ab\0c\0", 5));
1150  EXPECT_LT(0, memcmp("zza", "zyx", 3));
1151}
1152
1153typedef int(*PointerToStrCmp)(const char*, const char*);
1154void RunStrCmpTest(PointerToStrCmp StrCmp) {
1155  size_t size = Ident(100);
1156  int fill = 'o';
1157  char *s1 = MallocAndMemsetString(size, fill);
1158  char *s2 = MallocAndMemsetString(size, fill);
1159  s1[size - 1] = '\0';
1160  s2[size - 1] = '\0';
1161  // Normal StrCmp calls
1162  Ident(StrCmp(s1, s2));
1163  Ident(StrCmp(s1, s2 + size - 1));
1164  Ident(StrCmp(s1 + size - 1, s2 + size - 1));
1165  s1[size - 1] = 'z';
1166  s2[size - 1] = 'x';
1167  Ident(StrCmp(s1, s2));
1168  // One of arguments points to not allocated memory.
1169  EXPECT_DEATH(Ident(StrCmp)(s1 - 1, s2), LeftOOBReadMessage(1));
1170  EXPECT_DEATH(Ident(StrCmp)(s1, s2 - 1), LeftOOBReadMessage(1));
1171  EXPECT_DEATH(Ident(StrCmp)(s1 + size, s2), RightOOBReadMessage(0));
1172  EXPECT_DEATH(Ident(StrCmp)(s1, s2 + size), RightOOBReadMessage(0));
1173  // Hit unallocated memory and die.
1174  s1[size - 1] = fill;
1175  EXPECT_DEATH(Ident(StrCmp)(s1, s1), RightOOBReadMessage(0));
1176  EXPECT_DEATH(Ident(StrCmp)(s1 + size - 1, s2), RightOOBReadMessage(0));
1177  free(s1);
1178  free(s2);
1179}
1180
1181TEST(AddressSanitizer, StrCmpOOBTest) {
1182  RunStrCmpTest(&strcmp);
1183}
1184
1185TEST(AddressSanitizer, StrCaseCmpOOBTest) {
1186  RunStrCmpTest(&strcasecmp);
1187}
1188
1189typedef int(*PointerToStrNCmp)(const char*, const char*, size_t);
1190void RunStrNCmpTest(PointerToStrNCmp StrNCmp) {
1191  size_t size = Ident(100);
1192  char *s1 = MallocAndMemsetString(size);
1193  char *s2 = MallocAndMemsetString(size);
1194  s1[size - 1] = '\0';
1195  s2[size - 1] = '\0';
1196  // Normal StrNCmp calls
1197  Ident(StrNCmp(s1, s2, size + 2));
1198  s1[size - 1] = 'z';
1199  s2[size - 1] = 'x';
1200  Ident(StrNCmp(s1 + size - 2, s2 + size - 2, size));
1201  s2[size - 1] = 'z';
1202  Ident(StrNCmp(s1 - 1, s2 - 1, 0));
1203  Ident(StrNCmp(s1 + size - 1, s2 + size - 1, 1));
1204  // One of arguments points to not allocated memory.
1205  EXPECT_DEATH(Ident(StrNCmp)(s1 - 1, s2, 1), LeftOOBReadMessage(1));
1206  EXPECT_DEATH(Ident(StrNCmp)(s1, s2 - 1, 1), LeftOOBReadMessage(1));
1207  EXPECT_DEATH(Ident(StrNCmp)(s1 + size, s2, 1), RightOOBReadMessage(0));
1208  EXPECT_DEATH(Ident(StrNCmp)(s1, s2 + size, 1), RightOOBReadMessage(0));
1209  // Hit unallocated memory and die.
1210  EXPECT_DEATH(Ident(StrNCmp)(s1 + 1, s2 + 1, size), RightOOBReadMessage(0));
1211  EXPECT_DEATH(Ident(StrNCmp)(s1 + size - 1, s2, 2), RightOOBReadMessage(0));
1212  free(s1);
1213  free(s2);
1214}
1215
1216TEST(AddressSanitizer, StrNCmpOOBTest) {
1217  RunStrNCmpTest(&strncmp);
1218}
1219
1220TEST(AddressSanitizer, StrNCaseCmpOOBTest) {
1221  RunStrNCmpTest(&strncasecmp);
1222}
1223
1224TEST(AddressSanitizer, MemCmpOOBTest) {
1225  size_t size = Ident(100);
1226  char *s1 = MallocAndMemsetString(size);
1227  char *s2 = MallocAndMemsetString(size);
1228  // Normal memcmp calls.
1229  Ident(memcmp(s1, s2, size));
1230  Ident(memcmp(s1 + size - 1, s2 + size - 1, 1));
1231  Ident(memcmp(s1 - 1, s2 - 1, 0));
1232  // One of arguments points to not allocated memory.
1233  EXPECT_DEATH(Ident(memcmp)(s1 - 1, s2, 1), LeftOOBReadMessage(1));
1234  EXPECT_DEATH(Ident(memcmp)(s1, s2 - 1, 1), LeftOOBReadMessage(1));
1235  EXPECT_DEATH(Ident(memcmp)(s1 + size, s2, 1), RightOOBReadMessage(0));
1236  EXPECT_DEATH(Ident(memcmp)(s1, s2 + size, 1), RightOOBReadMessage(0));
1237  // Hit unallocated memory and die.
1238  EXPECT_DEATH(Ident(memcmp)(s1 + 1, s2 + 1, size), RightOOBReadMessage(0));
1239  EXPECT_DEATH(Ident(memcmp)(s1 + size - 1, s2, 2), RightOOBReadMessage(0));
1240  // Zero bytes are not terminators and don't prevent from OOB.
1241  s1[size - 1] = '\0';
1242  s2[size - 1] = '\0';
1243  EXPECT_DEATH(Ident(memcmp)(s1, s2, size + 1), RightOOBReadMessage(0));
1244  free(s1);
1245  free(s2);
1246}
1247
1248TEST(AddressSanitizer, StrCatOOBTest) {
1249  // strcat() reads strlen(to) bytes from |to| before concatenating.
1250  size_t to_size = Ident(100);
1251  char *to = MallocAndMemsetString(to_size);
1252  to[0] = '\0';
1253  size_t from_size = Ident(20);
1254  char *from = MallocAndMemsetString(from_size);
1255  from[from_size - 1] = '\0';
1256  // Normal strcat calls.
1257  strcat(to, from);
1258  strcat(to, from);
1259  strcat(to + from_size, from + from_size - 2);
1260  // Passing an invalid pointer is an error even when concatenating an empty
1261  // string.
1262  EXPECT_DEATH(strcat(to - 1, from + from_size - 1), LeftOOBAccessMessage(1));
1263  // One of arguments points to not allocated memory.
1264  EXPECT_DEATH(strcat(to - 1, from), LeftOOBAccessMessage(1));
1265  EXPECT_DEATH(strcat(to, from - 1), LeftOOBReadMessage(1));
1266  EXPECT_DEATH(strcat(to + to_size, from), RightOOBWriteMessage(0));
1267  EXPECT_DEATH(strcat(to, from + from_size), RightOOBReadMessage(0));
1268
1269  // "from" is not zero-terminated.
1270  from[from_size - 1] = 'z';
1271  EXPECT_DEATH(strcat(to, from), RightOOBReadMessage(0));
1272  from[from_size - 1] = '\0';
1273  // "to" is not zero-terminated.
1274  memset(to, 'z', to_size);
1275  EXPECT_DEATH(strcat(to, from), RightOOBWriteMessage(0));
1276  // "to" is too short to fit "from".
1277  to[to_size - from_size + 1] = '\0';
1278  EXPECT_DEATH(strcat(to, from), RightOOBWriteMessage(0));
1279  // length of "to" is just enough.
1280  strcat(to, from + 1);
1281
1282  free(to);
1283  free(from);
1284}
1285
1286TEST(AddressSanitizer, StrNCatOOBTest) {
1287  // strncat() reads strlen(to) bytes from |to| before concatenating.
1288  size_t to_size = Ident(100);
1289  char *to = MallocAndMemsetString(to_size);
1290  to[0] = '\0';
1291  size_t from_size = Ident(20);
1292  char *from = MallocAndMemsetString(from_size);
1293  // Normal strncat calls.
1294  strncat(to, from, 0);
1295  strncat(to, from, from_size);
1296  from[from_size - 1] = '\0';
1297  strncat(to, from, 2 * from_size);
1298  // Catenating empty string with an invalid string is still an error.
1299  EXPECT_DEATH(strncat(to - 1, from, 0), LeftOOBAccessMessage(1));
1300  strncat(to, from + from_size - 1, 10);
1301  // One of arguments points to not allocated memory.
1302  EXPECT_DEATH(strncat(to - 1, from, 2), LeftOOBAccessMessage(1));
1303  EXPECT_DEATH(strncat(to, from - 1, 2), LeftOOBReadMessage(1));
1304  EXPECT_DEATH(strncat(to + to_size, from, 2), RightOOBWriteMessage(0));
1305  EXPECT_DEATH(strncat(to, from + from_size, 2), RightOOBReadMessage(0));
1306
1307  memset(from, 'z', from_size);
1308  memset(to, 'z', to_size);
1309  to[0] = '\0';
1310  // "from" is too short.
1311  EXPECT_DEATH(strncat(to, from, from_size + 1), RightOOBReadMessage(0));
1312  // "to" is not zero-terminated.
1313  EXPECT_DEATH(strncat(to + 1, from, 1), RightOOBWriteMessage(0));
1314  // "to" is too short to fit "from".
1315  to[0] = 'z';
1316  to[to_size - from_size + 1] = '\0';
1317  EXPECT_DEATH(strncat(to, from, from_size - 1), RightOOBWriteMessage(0));
1318  // "to" is just enough.
1319  strncat(to, from, from_size - 2);
1320
1321  free(to);
1322  free(from);
1323}
1324
1325static string OverlapErrorMessage(const string &func) {
1326  return func + "-param-overlap";
1327}
1328
1329TEST(AddressSanitizer, StrArgsOverlapTest) {
1330  size_t size = Ident(100);
1331  char *str = Ident((char*)malloc(size));
1332
1333// Do not check memcpy() on OS X 10.7 and later, where it actually aliases
1334// memmove().
1335#if !defined(__APPLE__) || !defined(MAC_OS_X_VERSION_10_7) || \
1336    (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7)
1337  // Check "memcpy". Use Ident() to avoid inlining.
1338  memset(str, 'z', size);
1339  Ident(memcpy)(str + 1, str + 11, 10);
1340  Ident(memcpy)(str, str, 0);
1341  EXPECT_DEATH(Ident(memcpy)(str, str + 14, 15), OverlapErrorMessage("memcpy"));
1342  EXPECT_DEATH(Ident(memcpy)(str + 14, str, 15), OverlapErrorMessage("memcpy"));
1343#endif
1344
1345  // We do not treat memcpy with to==from as a bug.
1346  // See http://llvm.org/bugs/show_bug.cgi?id=11763.
1347  // EXPECT_DEATH(Ident(memcpy)(str + 20, str + 20, 1),
1348  //              OverlapErrorMessage("memcpy"));
1349
1350  // Check "strcpy".
1351  memset(str, 'z', size);
1352  str[9] = '\0';
1353  strcpy(str + 10, str);
1354  EXPECT_DEATH(strcpy(str + 9, str), OverlapErrorMessage("strcpy"));
1355  EXPECT_DEATH(strcpy(str, str + 4), OverlapErrorMessage("strcpy"));
1356  strcpy(str, str + 5);
1357
1358  // Check "strncpy".
1359  memset(str, 'z', size);
1360  strncpy(str, str + 10, 10);
1361  EXPECT_DEATH(strncpy(str, str + 9, 10), OverlapErrorMessage("strncpy"));
1362  EXPECT_DEATH(strncpy(str + 9, str, 10), OverlapErrorMessage("strncpy"));
1363  str[10] = '\0';
1364  strncpy(str + 11, str, 20);
1365  EXPECT_DEATH(strncpy(str + 10, str, 20), OverlapErrorMessage("strncpy"));
1366
1367  // Check "strcat".
1368  memset(str, 'z', size);
1369  str[10] = '\0';
1370  str[20] = '\0';
1371  strcat(str, str + 10);
1372  EXPECT_DEATH(strcat(str, str + 11), OverlapErrorMessage("strcat"));
1373  str[10] = '\0';
1374  strcat(str + 11, str);
1375  EXPECT_DEATH(strcat(str, str + 9), OverlapErrorMessage("strcat"));
1376  EXPECT_DEATH(strcat(str + 9, str), OverlapErrorMessage("strcat"));
1377  EXPECT_DEATH(strcat(str + 10, str), OverlapErrorMessage("strcat"));
1378
1379  // Check "strncat".
1380  memset(str, 'z', size);
1381  str[10] = '\0';
1382  strncat(str, str + 10, 10);  // from is empty
1383  EXPECT_DEATH(strncat(str, str + 11, 10), OverlapErrorMessage("strncat"));
1384  str[10] = '\0';
1385  str[20] = '\0';
1386  strncat(str + 5, str, 5);
1387  str[10] = '\0';
1388  EXPECT_DEATH(strncat(str + 5, str, 6), OverlapErrorMessage("strncat"));
1389  EXPECT_DEATH(strncat(str, str + 9, 10), OverlapErrorMessage("strncat"));
1390
1391  free(str);
1392}
1393
1394void CallAtoi(const char *nptr) {
1395  Ident(atoi(nptr));
1396}
1397void CallAtol(const char *nptr) {
1398  Ident(atol(nptr));
1399}
1400void CallAtoll(const char *nptr) {
1401  Ident(atoll(nptr));
1402}
1403typedef void(*PointerToCallAtoi)(const char*);
1404
1405void RunAtoiOOBTest(PointerToCallAtoi Atoi) {
1406  char *array = MallocAndMemsetString(10, '1');
1407  // Invalid pointer to the string.
1408  EXPECT_DEATH(Atoi(array + 11), RightOOBReadMessage(1));
1409  EXPECT_DEATH(Atoi(array - 1), LeftOOBReadMessage(1));
1410  // Die if a buffer doesn't have terminating NULL.
1411  EXPECT_DEATH(Atoi(array), RightOOBReadMessage(0));
1412  // Make last symbol a terminating NULL or other non-digit.
1413  array[9] = '\0';
1414  Atoi(array);
1415  array[9] = 'a';
1416  Atoi(array);
1417  Atoi(array + 9);
1418  // Sometimes we need to detect overflow if no digits are found.
1419  memset(array, ' ', 10);
1420  EXPECT_DEATH(Atoi(array), RightOOBReadMessage(0));
1421  array[9] = '-';
1422  EXPECT_DEATH(Atoi(array), RightOOBReadMessage(0));
1423  EXPECT_DEATH(Atoi(array + 9), RightOOBReadMessage(0));
1424  array[8] = '-';
1425  Atoi(array);
1426  free(array);
1427}
1428
1429TEST(AddressSanitizer, AtoiAndFriendsOOBTest) {
1430  RunAtoiOOBTest(&CallAtoi);
1431  RunAtoiOOBTest(&CallAtol);
1432  RunAtoiOOBTest(&CallAtoll);
1433}
1434
1435void CallStrtol(const char *nptr, char **endptr, int base) {
1436  Ident(strtol(nptr, endptr, base));
1437}
1438void CallStrtoll(const char *nptr, char **endptr, int base) {
1439  Ident(strtoll(nptr, endptr, base));
1440}
1441typedef void(*PointerToCallStrtol)(const char*, char**, int);
1442
1443void RunStrtolOOBTest(PointerToCallStrtol Strtol) {
1444  char *array = MallocAndMemsetString(3);
1445  char *endptr = NULL;
1446  array[0] = '1';
1447  array[1] = '2';
1448  array[2] = '3';
1449  // Invalid pointer to the string.
1450  EXPECT_DEATH(Strtol(array + 3, NULL, 0), RightOOBReadMessage(0));
1451  EXPECT_DEATH(Strtol(array - 1, NULL, 0), LeftOOBReadMessage(1));
1452  // Buffer overflow if there is no terminating null (depends on base).
1453  Strtol(array, &endptr, 3);
1454  EXPECT_EQ(array + 2, endptr);
1455  EXPECT_DEATH(Strtol(array, NULL, 0), RightOOBReadMessage(0));
1456  array[2] = 'z';
1457  Strtol(array, &endptr, 35);
1458  EXPECT_EQ(array + 2, endptr);
1459  EXPECT_DEATH(Strtol(array, NULL, 36), RightOOBReadMessage(0));
1460  // Add terminating zero to get rid of overflow.
1461  array[2] = '\0';
1462  Strtol(array, NULL, 36);
1463  // Don't check for overflow if base is invalid.
1464  Strtol(array - 1, NULL, -1);
1465  Strtol(array + 3, NULL, 1);
1466  // Sometimes we need to detect overflow if no digits are found.
1467  array[0] = array[1] = array[2] = ' ';
1468  EXPECT_DEATH(Strtol(array, NULL, 0), RightOOBReadMessage(0));
1469  array[2] = '+';
1470  EXPECT_DEATH(Strtol(array, NULL, 0), RightOOBReadMessage(0));
1471  array[2] = '-';
1472  EXPECT_DEATH(Strtol(array, NULL, 0), RightOOBReadMessage(0));
1473  array[1] = '+';
1474  Strtol(array, NULL, 0);
1475  array[1] = array[2] = 'z';
1476  Strtol(array, &endptr, 0);
1477  EXPECT_EQ(array, endptr);
1478  Strtol(array + 2, NULL, 0);
1479  EXPECT_EQ(array, endptr);
1480  free(array);
1481}
1482
1483TEST(AddressSanitizer, StrtollOOBTest) {
1484  RunStrtolOOBTest(&CallStrtoll);
1485}
1486TEST(AddressSanitizer, StrtolOOBTest) {
1487  RunStrtolOOBTest(&CallStrtol);
1488}
1489
1490// At the moment we instrument memcpy/memove/memset calls at compile time so we
1491// can't handle OOB error if these functions are called by pointer, see disabled
1492// MemIntrinsicCallByPointerTest below
1493typedef void*(*PointerToMemTransfer)(void*, const void*, size_t);
1494typedef void*(*PointerToMemSet)(void*, int, size_t);
1495
1496void CallMemSetByPointer(PointerToMemSet MemSet) {
1497  size_t size = Ident(100);
1498  char *array = Ident((char*)malloc(size));
1499  EXPECT_DEATH(MemSet(array, 0, 101), RightOOBWriteMessage(0));
1500  free(array);
1501}
1502
1503void CallMemTransferByPointer(PointerToMemTransfer MemTransfer) {
1504  size_t size = Ident(100);
1505  char *src = Ident((char*)malloc(size));
1506  char *dst = Ident((char*)malloc(size));
1507  EXPECT_DEATH(MemTransfer(dst, src, 101), RightOOBWriteMessage(0));
1508  free(src);
1509  free(dst);
1510}
1511
1512TEST(AddressSanitizer, DISABLED_MemIntrinsicCallByPointerTest) {
1513  CallMemSetByPointer(&memset);
1514  CallMemTransferByPointer(&memcpy);
1515  CallMemTransferByPointer(&memmove);
1516}
1517
1518#if defined(__linux__) && !defined(ANDROID) && !defined(__ANDROID__)
1519#define READ_TEST(READ_N_BYTES)                                          \
1520  char *x = new char[10];                                                \
1521  int fd = open("/proc/self/stat", O_RDONLY);                            \
1522  ASSERT_GT(fd, 0);                                                      \
1523  EXPECT_DEATH(READ_N_BYTES,                                             \
1524               ASAN_PCRE_DOTALL                                          \
1525               "AddressSanitizer: heap-buffer-overflow"                  \
1526               ".* is located 0 bytes to the right of 10-byte region");  \
1527  close(fd);                                                             \
1528  delete [] x;                                                           \
1529
1530TEST(AddressSanitizer, pread) {
1531  READ_TEST(pread(fd, x, 15, 0));
1532}
1533
1534TEST(AddressSanitizer, pread64) {
1535  READ_TEST(pread64(fd, x, 15, 0));
1536}
1537
1538TEST(AddressSanitizer, read) {
1539  READ_TEST(read(fd, x, 15));
1540}
1541#endif  // defined(__linux__) && !defined(ANDROID) && !defined(__ANDROID__)
1542
1543// This test case fails
1544// Clang optimizes memcpy/memset calls which lead to unaligned access
1545TEST(AddressSanitizer, DISABLED_MemIntrinsicUnalignedAccessTest) {
1546  int size = Ident(4096);
1547  char *s = Ident((char*)malloc(size));
1548  EXPECT_DEATH(memset(s + size - 1, 0, 2), RightOOBWriteMessage(0));
1549  free(s);
1550}
1551
1552// TODO(samsonov): Add a test with malloc(0)
1553// TODO(samsonov): Add tests for str* and mem* functions.
1554
1555NOINLINE static int LargeFunction(bool do_bad_access) {
1556  int *x = new int[100];
1557  x[0]++;
1558  x[1]++;
1559  x[2]++;
1560  x[3]++;
1561  x[4]++;
1562  x[5]++;
1563  x[6]++;
1564  x[7]++;
1565  x[8]++;
1566  x[9]++;
1567
1568  x[do_bad_access ? 100 : 0]++; int res = __LINE__;
1569
1570  x[10]++;
1571  x[11]++;
1572  x[12]++;
1573  x[13]++;
1574  x[14]++;
1575  x[15]++;
1576  x[16]++;
1577  x[17]++;
1578  x[18]++;
1579  x[19]++;
1580
1581  delete x;
1582  return res;
1583}
1584
1585// Test the we have correct debug info for the failing instruction.
1586// This test requires the in-process symbolizer to be enabled by default.
1587TEST(AddressSanitizer, DISABLED_LargeFunctionSymbolizeTest) {
1588  int failing_line = LargeFunction(false);
1589  char expected_warning[128];
1590  sprintf(expected_warning, "LargeFunction.*asan_test.*:%d", failing_line);
1591  EXPECT_DEATH(LargeFunction(true), expected_warning);
1592}
1593
1594// Check that we unwind and symbolize correctly.
1595TEST(AddressSanitizer, DISABLED_MallocFreeUnwindAndSymbolizeTest) {
1596  int *a = (int*)malloc_aaa(sizeof(int));
1597  *a = 1;
1598  free_aaa(a);
1599  EXPECT_DEATH(*a = 1, "free_ccc.*free_bbb.*free_aaa.*"
1600               "malloc_fff.*malloc_eee.*malloc_ddd");
1601}
1602
1603static bool TryToSetThreadName(const char *name) {
1604#if defined(__linux__) && defined(PR_SET_NAME)
1605  return 0 == prctl(PR_SET_NAME, (unsigned long)name, 0, 0, 0);
1606#else
1607  return false;
1608#endif
1609}
1610
1611void *ThreadedTestAlloc(void *a) {
1612  EXPECT_EQ(true, TryToSetThreadName("AllocThr"));
1613  int **p = (int**)a;
1614  *p = new int;
1615  return 0;
1616}
1617
1618void *ThreadedTestFree(void *a) {
1619  EXPECT_EQ(true, TryToSetThreadName("FreeThr"));
1620  int **p = (int**)a;
1621  delete *p;
1622  return 0;
1623}
1624
1625void *ThreadedTestUse(void *a) {
1626  EXPECT_EQ(true, TryToSetThreadName("UseThr"));
1627  int **p = (int**)a;
1628  **p = 1;
1629  return 0;
1630}
1631
1632void ThreadedTestSpawn() {
1633  pthread_t t;
1634  int *x;
1635  PTHREAD_CREATE(&t, 0, ThreadedTestAlloc, &x);
1636  PTHREAD_JOIN(t, 0);
1637  PTHREAD_CREATE(&t, 0, ThreadedTestFree, &x);
1638  PTHREAD_JOIN(t, 0);
1639  PTHREAD_CREATE(&t, 0, ThreadedTestUse, &x);
1640  PTHREAD_JOIN(t, 0);
1641}
1642
1643TEST(AddressSanitizer, ThreadedTest) {
1644  EXPECT_DEATH(ThreadedTestSpawn(),
1645               ASAN_PCRE_DOTALL
1646               "Thread T.*created"
1647               ".*Thread T.*created"
1648               ".*Thread T.*created");
1649}
1650
1651void *ThreadedTestFunc(void *unused) {
1652  // Check if prctl(PR_SET_NAME) is supported. Return if not.
1653  if (!TryToSetThreadName("TestFunc"))
1654    return 0;
1655  EXPECT_DEATH(ThreadedTestSpawn(),
1656               ASAN_PCRE_DOTALL
1657               "WRITE .*thread T. .UseThr."
1658               ".*freed by thread T. .FreeThr. here:"
1659               ".*previously allocated by thread T. .AllocThr. here:"
1660               ".*Thread T. .UseThr. created by T.*TestFunc"
1661               ".*Thread T. .FreeThr. created by T"
1662               ".*Thread T. .AllocThr. created by T"
1663               "");
1664  return 0;
1665}
1666
1667TEST(AddressSanitizer, ThreadNamesTest) {
1668  // Run ThreadedTestFunc in a separate thread because it tries to set a
1669  // thread name and we don't want to change the main thread's name.
1670  pthread_t t;
1671  PTHREAD_CREATE(&t, 0, ThreadedTestFunc, 0);
1672  PTHREAD_JOIN(t, 0);
1673}
1674
1675#if ASAN_NEEDS_SEGV
1676TEST(AddressSanitizer, ShadowGapTest) {
1677#if SANITIZER_WORDSIZE == 32
1678  char *addr = (char*)0x22000000;
1679#else
1680  char *addr = (char*)0x0000100000080000;
1681#endif
1682  EXPECT_DEATH(*addr = 1, "AddressSanitizer: SEGV on unknown");
1683}
1684#endif  // ASAN_NEEDS_SEGV
1685
1686extern "C" {
1687NOINLINE static void UseThenFreeThenUse() {
1688  char *x = Ident((char*)malloc(8));
1689  *x = 1;
1690  free_aaa(x);
1691  *x = 2;
1692}
1693}
1694
1695TEST(AddressSanitizer, UseThenFreeThenUseTest) {
1696  EXPECT_DEATH(UseThenFreeThenUse(), "freed by thread");
1697}
1698
1699TEST(AddressSanitizer, StrDupTest) {
1700  free(strdup(Ident("123")));
1701}
1702
1703// Currently we create and poison redzone at right of global variables.
1704char glob5[5];
1705static char static110[110];
1706const char ConstGlob[7] = {1, 2, 3, 4, 5, 6, 7};
1707static const char StaticConstGlob[3] = {9, 8, 7};
1708extern int GlobalsTest(int x);
1709
1710TEST(AddressSanitizer, GlobalTest) {
1711  static char func_static15[15];
1712
1713  static char fs1[10];
1714  static char fs2[10];
1715  static char fs3[10];
1716
1717  glob5[Ident(0)] = 0;
1718  glob5[Ident(1)] = 0;
1719  glob5[Ident(2)] = 0;
1720  glob5[Ident(3)] = 0;
1721  glob5[Ident(4)] = 0;
1722
1723  EXPECT_DEATH(glob5[Ident(5)] = 0,
1724               "0 bytes to the right of global variable.*glob5.* size 5");
1725  EXPECT_DEATH(glob5[Ident(5+6)] = 0,
1726               "6 bytes to the right of global variable.*glob5.* size 5");
1727  Ident(static110);  // avoid optimizations
1728  static110[Ident(0)] = 0;
1729  static110[Ident(109)] = 0;
1730  EXPECT_DEATH(static110[Ident(110)] = 0,
1731               "0 bytes to the right of global variable");
1732  EXPECT_DEATH(static110[Ident(110+7)] = 0,
1733               "7 bytes to the right of global variable");
1734
1735  Ident(func_static15);  // avoid optimizations
1736  func_static15[Ident(0)] = 0;
1737  EXPECT_DEATH(func_static15[Ident(15)] = 0,
1738               "0 bytes to the right of global variable");
1739  EXPECT_DEATH(func_static15[Ident(15 + 9)] = 0,
1740               "9 bytes to the right of global variable");
1741
1742  Ident(fs1);
1743  Ident(fs2);
1744  Ident(fs3);
1745
1746  // We don't create left redzones, so this is not 100% guaranteed to fail.
1747  // But most likely will.
1748  EXPECT_DEATH(fs2[Ident(-1)] = 0, "is located.*of global variable");
1749
1750  EXPECT_DEATH(Ident(Ident(ConstGlob)[8]),
1751               "is located 1 bytes to the right of .*ConstGlob");
1752  EXPECT_DEATH(Ident(Ident(StaticConstGlob)[5]),
1753               "is located 2 bytes to the right of .*StaticConstGlob");
1754
1755  // call stuff from another file.
1756  GlobalsTest(0);
1757}
1758
1759TEST(AddressSanitizer, GlobalStringConstTest) {
1760  static const char *zoo = "FOOBAR123";
1761  const char *p = Ident(zoo);
1762  EXPECT_DEATH(Ident(p[15]), "is ascii string 'FOOBAR123'");
1763}
1764
1765TEST(AddressSanitizer, FileNameInGlobalReportTest) {
1766  static char zoo[10];
1767  const char *p = Ident(zoo);
1768  // The file name should be present in the report.
1769  EXPECT_DEATH(Ident(p[15]), "zoo.*asan_test.");
1770}
1771
1772int *ReturnsPointerToALocalObject() {
1773  int a = 0;
1774  return Ident(&a);
1775}
1776
1777#if ASAN_UAR == 1
1778TEST(AddressSanitizer, LocalReferenceReturnTest) {
1779  int *(*f)() = Ident(ReturnsPointerToALocalObject);
1780  int *p = f();
1781  // Call 'f' a few more times, 'p' should still be poisoned.
1782  for (int i = 0; i < 32; i++)
1783    f();
1784  EXPECT_DEATH(*p = 1, "AddressSanitizer: stack-use-after-return");
1785  EXPECT_DEATH(*p = 1, "is located.*in frame .*ReturnsPointerToALocal");
1786}
1787#endif
1788
1789template <int kSize>
1790NOINLINE static void FuncWithStack() {
1791  char x[kSize];
1792  Ident(x)[0] = 0;
1793  Ident(x)[kSize-1] = 0;
1794}
1795
1796static void LotsOfStackReuse() {
1797  int LargeStack[10000];
1798  Ident(LargeStack)[0] = 0;
1799  for (int i = 0; i < 10000; i++) {
1800    FuncWithStack<128 * 1>();
1801    FuncWithStack<128 * 2>();
1802    FuncWithStack<128 * 4>();
1803    FuncWithStack<128 * 8>();
1804    FuncWithStack<128 * 16>();
1805    FuncWithStack<128 * 32>();
1806    FuncWithStack<128 * 64>();
1807    FuncWithStack<128 * 128>();
1808    FuncWithStack<128 * 256>();
1809    FuncWithStack<128 * 512>();
1810    Ident(LargeStack)[0] = 0;
1811  }
1812}
1813
1814TEST(AddressSanitizer, StressStackReuseTest) {
1815  LotsOfStackReuse();
1816}
1817
1818TEST(AddressSanitizer, ThreadedStressStackReuseTest) {
1819  const int kNumThreads = 20;
1820  pthread_t t[kNumThreads];
1821  for (int i = 0; i < kNumThreads; i++) {
1822    PTHREAD_CREATE(&t[i], 0, (void* (*)(void *x))LotsOfStackReuse, 0);
1823  }
1824  for (int i = 0; i < kNumThreads; i++) {
1825    PTHREAD_JOIN(t[i], 0);
1826  }
1827}
1828
1829static void *PthreadExit(void *a) {
1830  pthread_exit(0);
1831  return 0;
1832}
1833
1834TEST(AddressSanitizer, PthreadExitTest) {
1835  pthread_t t;
1836  for (int i = 0; i < 1000; i++) {
1837    PTHREAD_CREATE(&t, 0, PthreadExit, 0);
1838    PTHREAD_JOIN(t, 0);
1839  }
1840}
1841
1842#ifdef __EXCEPTIONS
1843NOINLINE static void StackReuseAndException() {
1844  int large_stack[1000];
1845  Ident(large_stack);
1846  ASAN_THROW(1);
1847}
1848
1849// TODO(kcc): support exceptions with use-after-return.
1850TEST(AddressSanitizer, DISABLED_StressStackReuseAndExceptionsTest) {
1851  for (int i = 0; i < 10000; i++) {
1852    try {
1853    StackReuseAndException();
1854    } catch(...) {
1855    }
1856  }
1857}
1858#endif
1859
1860TEST(AddressSanitizer, MlockTest) {
1861  EXPECT_EQ(0, mlockall(MCL_CURRENT));
1862  EXPECT_EQ(0, mlock((void*)0x12345, 0x5678));
1863  EXPECT_EQ(0, munlockall());
1864  EXPECT_EQ(0, munlock((void*)0x987, 0x654));
1865}
1866
1867struct LargeStruct {
1868  int foo[100];
1869};
1870
1871// Test for bug http://llvm.org/bugs/show_bug.cgi?id=11763.
1872// Struct copy should not cause asan warning even if lhs == rhs.
1873TEST(AddressSanitizer, LargeStructCopyTest) {
1874  LargeStruct a;
1875  *Ident(&a) = *Ident(&a);
1876}
1877
1878ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
1879static void NoAddressSafety() {
1880  char *foo = new char[10];
1881  Ident(foo)[10] = 0;
1882  delete [] foo;
1883}
1884
1885TEST(AddressSanitizer, AttributeNoAddressSafetyTest) {
1886  Ident(NoAddressSafety)();
1887}
1888
1889// TODO(glider): Enable this test on Mac.
1890// It doesn't work on Android, as calls to new/delete go through malloc/free.
1891#if !defined(__APPLE__) && !defined(ANDROID) && !defined(__ANDROID__)
1892static string MismatchStr(const string &str) {
1893  return string("AddressSanitizer: alloc-dealloc-mismatch \\(") + str;
1894}
1895
1896TEST(AddressSanitizer, AllocDeallocMismatch) {
1897  EXPECT_DEATH(free(Ident(new int)),
1898               MismatchStr("operator new vs free"));
1899  EXPECT_DEATH(free(Ident(new int[2])),
1900               MismatchStr("operator new \\[\\] vs free"));
1901  EXPECT_DEATH(delete (Ident(new int[2])),
1902               MismatchStr("operator new \\[\\] vs operator delete"));
1903  EXPECT_DEATH(delete (Ident((int*)malloc(2 * sizeof(int)))),
1904               MismatchStr("malloc vs operator delete"));
1905  EXPECT_DEATH(delete [] (Ident(new int)),
1906               MismatchStr("operator new vs operator delete \\[\\]"));
1907  EXPECT_DEATH(delete [] (Ident((int*)malloc(2 * sizeof(int)))),
1908               MismatchStr("malloc vs operator delete \\[\\]"));
1909}
1910#endif
1911
1912// ------------------ demo tests; run each one-by-one -------------
1913// e.g. --gtest_filter=*DemoOOBLeftHigh --gtest_also_run_disabled_tests
1914TEST(AddressSanitizer, DISABLED_DemoThreadedTest) {
1915  ThreadedTestSpawn();
1916}
1917
1918void *SimpleBugOnSTack(void *x = 0) {
1919  char a[20];
1920  Ident(a)[20] = 0;
1921  return 0;
1922}
1923
1924TEST(AddressSanitizer, DISABLED_DemoStackTest) {
1925  SimpleBugOnSTack();
1926}
1927
1928TEST(AddressSanitizer, DISABLED_DemoThreadStackTest) {
1929  pthread_t t;
1930  PTHREAD_CREATE(&t, 0, SimpleBugOnSTack, 0);
1931  PTHREAD_JOIN(t, 0);
1932}
1933
1934TEST(AddressSanitizer, DISABLED_DemoUAFLowIn) {
1935  uaf_test<U1>(10, 0);
1936}
1937TEST(AddressSanitizer, DISABLED_DemoUAFLowLeft) {
1938  uaf_test<U1>(10, -2);
1939}
1940TEST(AddressSanitizer, DISABLED_DemoUAFLowRight) {
1941  uaf_test<U1>(10, 10);
1942}
1943
1944TEST(AddressSanitizer, DISABLED_DemoUAFHigh) {
1945  uaf_test<U1>(kLargeMalloc, 0);
1946}
1947
1948TEST(AddressSanitizer, DISABLED_DemoOOM) {
1949  size_t size = SANITIZER_WORDSIZE == 64 ? (size_t)(1ULL << 40) : (0xf0000000);
1950  printf("%p\n", malloc(size));
1951}
1952
1953TEST(AddressSanitizer, DISABLED_DemoDoubleFreeTest) {
1954  DoubleFree();
1955}
1956
1957TEST(AddressSanitizer, DISABLED_DemoNullDerefTest) {
1958  int *a = 0;
1959  Ident(a)[10] = 0;
1960}
1961
1962TEST(AddressSanitizer, DISABLED_DemoFunctionStaticTest) {
1963  static char a[100];
1964  static char b[100];
1965  static char c[100];
1966  Ident(a);
1967  Ident(b);
1968  Ident(c);
1969  Ident(a)[5] = 0;
1970  Ident(b)[105] = 0;
1971  Ident(a)[5] = 0;
1972}
1973
1974TEST(AddressSanitizer, DISABLED_DemoTooMuchMemoryTest) {
1975  const size_t kAllocSize = (1 << 28) - 1024;
1976  size_t total_size = 0;
1977  while (true) {
1978    char *x = (char*)malloc(kAllocSize);
1979    memset(x, 0, kAllocSize);
1980    total_size += kAllocSize;
1981    fprintf(stderr, "total: %ldM %p\n", (long)total_size >> 20, x);
1982  }
1983}
1984
1985// http://code.google.com/p/address-sanitizer/issues/detail?id=66
1986TEST(AddressSanitizer, BufferOverflowAfterManyFrees) {
1987  for (int i = 0; i < 1000000; i++) {
1988    delete [] (Ident(new char [8644]));
1989  }
1990  char *x = new char[8192];
1991  EXPECT_DEATH(x[Ident(8192)] = 0, "AddressSanitizer: heap-buffer-overflow");
1992  delete [] Ident(x);
1993}
1994
1995
1996// Test that instrumentation of stack allocations takes into account
1997// AllocSize of a type, and not its StoreSize (16 vs 10 bytes for long double).
1998// See http://llvm.org/bugs/show_bug.cgi?id=12047 for more details.
1999TEST(AddressSanitizer, LongDoubleNegativeTest) {
2000  long double a, b;
2001  static long double c;
2002  memcpy(Ident(&a), Ident(&b), sizeof(long double));
2003  memcpy(Ident(&c), Ident(&b), sizeof(long double));
2004}
2005