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