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