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