asan_test.cc revision b8a59a0e030d0aacf4df1fe8f7fb4e6f82bab654
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  int fill = 'o';
1317  char *s1 = MallocAndMemsetString(size, fill);
1318  char *s2 = MallocAndMemsetString(size, fill);
1319  s1[size - 1] = '\0';
1320  s2[size - 1] = '\0';
1321  // Normal StrCmp calls
1322  Ident(StrCmp(s1, s2));
1323  Ident(StrCmp(s1, s2 + size - 1));
1324  Ident(StrCmp(s1 + size - 1, s2 + size - 1));
1325  s1[size - 1] = 'z';
1326  s2[size - 1] = 'x';
1327  Ident(StrCmp(s1, s2));
1328  // One of arguments points to not allocated memory.
1329  EXPECT_DEATH(Ident(StrCmp)(s1 - 1, s2), LeftOOBReadMessage(1));
1330  EXPECT_DEATH(Ident(StrCmp)(s1, s2 - 1), LeftOOBReadMessage(1));
1331  EXPECT_DEATH(Ident(StrCmp)(s1 + size, s2), RightOOBReadMessage(0));
1332  EXPECT_DEATH(Ident(StrCmp)(s1, s2 + size), RightOOBReadMessage(0));
1333  // Hit unallocated memory and die.
1334  s1[size - 1] = fill;
1335  EXPECT_DEATH(Ident(StrCmp)(s1, s1), RightOOBReadMessage(0));
1336  EXPECT_DEATH(Ident(StrCmp)(s1 + size - 1, s2), RightOOBReadMessage(0));
1337  free(s1);
1338  free(s2);
1339}
1340
1341TEST(AddressSanitizer, StrCmpOOBTest) {
1342  RunStrCmpTest(&strcmp);
1343}
1344
1345TEST(AddressSanitizer, StrCaseCmpOOBTest) {
1346  RunStrCmpTest(&strcasecmp);
1347}
1348
1349typedef int(*PointerToStrNCmp)(const char*, const char*, size_t);
1350void RunStrNCmpTest(PointerToStrNCmp StrNCmp) {
1351  size_t size = Ident(100);
1352  char *s1 = MallocAndMemsetString(size);
1353  char *s2 = MallocAndMemsetString(size);
1354  s1[size - 1] = '\0';
1355  s2[size - 1] = '\0';
1356  // Normal StrNCmp calls
1357  Ident(StrNCmp(s1, s2, size + 2));
1358  s1[size - 1] = 'z';
1359  s2[size - 1] = 'x';
1360  Ident(StrNCmp(s1 + size - 2, s2 + size - 2, size));
1361  s2[size - 1] = 'z';
1362  Ident(StrNCmp(s1 - 1, s2 - 1, 0));
1363  Ident(StrNCmp(s1 + size - 1, s2 + size - 1, 1));
1364  // One of arguments points to not allocated memory.
1365  EXPECT_DEATH(Ident(StrNCmp)(s1 - 1, s2, 1), LeftOOBReadMessage(1));
1366  EXPECT_DEATH(Ident(StrNCmp)(s1, s2 - 1, 1), LeftOOBReadMessage(1));
1367  EXPECT_DEATH(Ident(StrNCmp)(s1 + size, s2, 1), RightOOBReadMessage(0));
1368  EXPECT_DEATH(Ident(StrNCmp)(s1, s2 + size, 1), RightOOBReadMessage(0));
1369  // Hit unallocated memory and die.
1370  EXPECT_DEATH(Ident(StrNCmp)(s1 + 1, s2 + 1, size), RightOOBReadMessage(0));
1371  EXPECT_DEATH(Ident(StrNCmp)(s1 + size - 1, s2, 2), RightOOBReadMessage(0));
1372  free(s1);
1373  free(s2);
1374}
1375
1376TEST(AddressSanitizer, StrNCmpOOBTest) {
1377  RunStrNCmpTest(&strncmp);
1378}
1379
1380TEST(AddressSanitizer, StrNCaseCmpOOBTest) {
1381  RunStrNCmpTest(&strncasecmp);
1382}
1383
1384TEST(AddressSanitizer, MemCmpOOBTest) {
1385  size_t size = Ident(100);
1386  char *s1 = MallocAndMemsetString(size);
1387  char *s2 = MallocAndMemsetString(size);
1388  // Normal memcmp calls.
1389  Ident(memcmp(s1, s2, size));
1390  Ident(memcmp(s1 + size - 1, s2 + size - 1, 1));
1391  Ident(memcmp(s1 - 1, s2 - 1, 0));
1392  // One of arguments points to not allocated memory.
1393  EXPECT_DEATH(Ident(memcmp)(s1 - 1, s2, 1), LeftOOBReadMessage(1));
1394  EXPECT_DEATH(Ident(memcmp)(s1, s2 - 1, 1), LeftOOBReadMessage(1));
1395  EXPECT_DEATH(Ident(memcmp)(s1 + size, s2, 1), RightOOBReadMessage(0));
1396  EXPECT_DEATH(Ident(memcmp)(s1, s2 + size, 1), RightOOBReadMessage(0));
1397  // Hit unallocated memory and die.
1398  EXPECT_DEATH(Ident(memcmp)(s1 + 1, s2 + 1, size), RightOOBReadMessage(0));
1399  EXPECT_DEATH(Ident(memcmp)(s1 + size - 1, s2, 2), RightOOBReadMessage(0));
1400  // Zero bytes are not terminators and don't prevent from OOB.
1401  s1[size - 1] = '\0';
1402  s2[size - 1] = '\0';
1403  EXPECT_DEATH(Ident(memcmp)(s1, s2, size + 1), RightOOBReadMessage(0));
1404  free(s1);
1405  free(s2);
1406}
1407
1408TEST(AddressSanitizer, StrCatOOBTest) {
1409  // strcat() reads strlen(to) bytes from |to| before concatenating.
1410  size_t to_size = Ident(100);
1411  char *to = MallocAndMemsetString(to_size);
1412  to[0] = '\0';
1413  size_t from_size = Ident(20);
1414  char *from = MallocAndMemsetString(from_size);
1415  from[from_size - 1] = '\0';
1416  // Normal strcat calls.
1417  strcat(to, from);
1418  strcat(to, from);
1419  strcat(to + from_size, from + from_size - 2);
1420  // Passing an invalid pointer is an error even when concatenating an empty
1421  // string.
1422  EXPECT_DEATH(strcat(to - 1, from + from_size - 1), LeftOOBAccessMessage(1));
1423  // One of arguments points to not allocated memory.
1424  EXPECT_DEATH(strcat(to - 1, from), LeftOOBAccessMessage(1));
1425  EXPECT_DEATH(strcat(to, from - 1), LeftOOBReadMessage(1));
1426  EXPECT_DEATH(strcat(to + to_size, from), RightOOBWriteMessage(0));
1427  EXPECT_DEATH(strcat(to, from + from_size), RightOOBReadMessage(0));
1428
1429  // "from" is not zero-terminated.
1430  from[from_size - 1] = 'z';
1431  EXPECT_DEATH(strcat(to, from), RightOOBReadMessage(0));
1432  from[from_size - 1] = '\0';
1433  // "to" is not zero-terminated.
1434  memset(to, 'z', to_size);
1435  EXPECT_DEATH(strcat(to, from), RightOOBWriteMessage(0));
1436  // "to" is too short to fit "from".
1437  to[to_size - from_size + 1] = '\0';
1438  EXPECT_DEATH(strcat(to, from), RightOOBWriteMessage(0));
1439  // length of "to" is just enough.
1440  strcat(to, from + 1);
1441
1442  free(to);
1443  free(from);
1444}
1445
1446TEST(AddressSanitizer, StrNCatOOBTest) {
1447  // strncat() reads strlen(to) bytes from |to| before concatenating.
1448  size_t to_size = Ident(100);
1449  char *to = MallocAndMemsetString(to_size);
1450  to[0] = '\0';
1451  size_t from_size = Ident(20);
1452  char *from = MallocAndMemsetString(from_size);
1453  // Normal strncat calls.
1454  strncat(to, from, 0);
1455  strncat(to, from, from_size);
1456  from[from_size - 1] = '\0';
1457  strncat(to, from, 2 * from_size);
1458  // Catenating empty string with an invalid string is still an error.
1459  EXPECT_DEATH(strncat(to - 1, from, 0), LeftOOBAccessMessage(1));
1460  strncat(to, from + from_size - 1, 10);
1461  // One of arguments points to not allocated memory.
1462  EXPECT_DEATH(strncat(to - 1, from, 2), LeftOOBAccessMessage(1));
1463  EXPECT_DEATH(strncat(to, from - 1, 2), LeftOOBReadMessage(1));
1464  EXPECT_DEATH(strncat(to + to_size, from, 2), RightOOBWriteMessage(0));
1465  EXPECT_DEATH(strncat(to, from + from_size, 2), RightOOBReadMessage(0));
1466
1467  memset(from, 'z', from_size);
1468  memset(to, 'z', to_size);
1469  to[0] = '\0';
1470  // "from" is too short.
1471  EXPECT_DEATH(strncat(to, from, from_size + 1), RightOOBReadMessage(0));
1472  // "to" is not zero-terminated.
1473  EXPECT_DEATH(strncat(to + 1, from, 1), RightOOBWriteMessage(0));
1474  // "to" is too short to fit "from".
1475  to[0] = 'z';
1476  to[to_size - from_size + 1] = '\0';
1477  EXPECT_DEATH(strncat(to, from, from_size - 1), RightOOBWriteMessage(0));
1478  // "to" is just enough.
1479  strncat(to, from, from_size - 2);
1480
1481  free(to);
1482  free(from);
1483}
1484
1485static string OverlapErrorMessage(const string &func) {
1486  return func + "-param-overlap";
1487}
1488
1489TEST(AddressSanitizer, StrArgsOverlapTest) {
1490  size_t size = Ident(100);
1491  char *str = Ident((char*)malloc(size));
1492
1493// Do not check memcpy() on OS X 10.7 and later, where it actually aliases
1494// memmove().
1495#if !defined(__APPLE__) || !defined(MAC_OS_X_VERSION_10_7) || \
1496    (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7)
1497  // Check "memcpy". Use Ident() to avoid inlining.
1498  memset(str, 'z', size);
1499  Ident(memcpy)(str + 1, str + 11, 10);
1500  Ident(memcpy)(str, str, 0);
1501  EXPECT_DEATH(Ident(memcpy)(str, str + 14, 15), OverlapErrorMessage("memcpy"));
1502  EXPECT_DEATH(Ident(memcpy)(str + 14, str, 15), OverlapErrorMessage("memcpy"));
1503#endif
1504
1505  // We do not treat memcpy with to==from as a bug.
1506  // See http://llvm.org/bugs/show_bug.cgi?id=11763.
1507  // EXPECT_DEATH(Ident(memcpy)(str + 20, str + 20, 1),
1508  //              OverlapErrorMessage("memcpy"));
1509
1510  // Check "strcpy".
1511  memset(str, 'z', size);
1512  str[9] = '\0';
1513  strcpy(str + 10, str);
1514  EXPECT_DEATH(strcpy(str + 9, str), OverlapErrorMessage("strcpy"));
1515  EXPECT_DEATH(strcpy(str, str + 4), OverlapErrorMessage("strcpy"));
1516  strcpy(str, str + 5);
1517
1518  // Check "strncpy".
1519  memset(str, 'z', size);
1520  strncpy(str, str + 10, 10);
1521  EXPECT_DEATH(strncpy(str, str + 9, 10), OverlapErrorMessage("strncpy"));
1522  EXPECT_DEATH(strncpy(str + 9, str, 10), OverlapErrorMessage("strncpy"));
1523  str[10] = '\0';
1524  strncpy(str + 11, str, 20);
1525  EXPECT_DEATH(strncpy(str + 10, str, 20), OverlapErrorMessage("strncpy"));
1526
1527  // Check "strcat".
1528  memset(str, 'z', size);
1529  str[10] = '\0';
1530  str[20] = '\0';
1531  strcat(str, str + 10);
1532  EXPECT_DEATH(strcat(str, str + 11), OverlapErrorMessage("strcat"));
1533  str[10] = '\0';
1534  strcat(str + 11, str);
1535  EXPECT_DEATH(strcat(str, str + 9), OverlapErrorMessage("strcat"));
1536  EXPECT_DEATH(strcat(str + 9, str), OverlapErrorMessage("strcat"));
1537  EXPECT_DEATH(strcat(str + 10, str), OverlapErrorMessage("strcat"));
1538
1539  // Check "strncat".
1540  memset(str, 'z', size);
1541  str[10] = '\0';
1542  strncat(str, str + 10, 10);  // from is empty
1543  EXPECT_DEATH(strncat(str, str + 11, 10), OverlapErrorMessage("strncat"));
1544  str[10] = '\0';
1545  str[20] = '\0';
1546  strncat(str + 5, str, 5);
1547  str[10] = '\0';
1548  EXPECT_DEATH(strncat(str + 5, str, 6), OverlapErrorMessage("strncat"));
1549  EXPECT_DEATH(strncat(str, str + 9, 10), OverlapErrorMessage("strncat"));
1550
1551  free(str);
1552}
1553
1554void CallAtoi(const char *nptr) {
1555  Ident(atoi(nptr));
1556}
1557void CallAtol(const char *nptr) {
1558  Ident(atol(nptr));
1559}
1560void CallAtoll(const char *nptr) {
1561  Ident(atoll(nptr));
1562}
1563typedef void(*PointerToCallAtoi)(const char*);
1564
1565void RunAtoiOOBTest(PointerToCallAtoi Atoi) {
1566  char *array = MallocAndMemsetString(10, '1');
1567  // Invalid pointer to the string.
1568  EXPECT_DEATH(Atoi(array + 11), RightOOBReadMessage(1));
1569  EXPECT_DEATH(Atoi(array - 1), LeftOOBReadMessage(1));
1570  // Die if a buffer doesn't have terminating NULL.
1571  EXPECT_DEATH(Atoi(array), RightOOBReadMessage(0));
1572  // Make last symbol a terminating NULL or other non-digit.
1573  array[9] = '\0';
1574  Atoi(array);
1575  array[9] = 'a';
1576  Atoi(array);
1577  Atoi(array + 9);
1578  // Sometimes we need to detect overflow if no digits are found.
1579  memset(array, ' ', 10);
1580  EXPECT_DEATH(Atoi(array), RightOOBReadMessage(0));
1581  array[9] = '-';
1582  EXPECT_DEATH(Atoi(array), RightOOBReadMessage(0));
1583  EXPECT_DEATH(Atoi(array + 9), RightOOBReadMessage(0));
1584  array[8] = '-';
1585  Atoi(array);
1586  free(array);
1587}
1588
1589TEST(AddressSanitizer, AtoiAndFriendsOOBTest) {
1590  RunAtoiOOBTest(&CallAtoi);
1591  RunAtoiOOBTest(&CallAtol);
1592  RunAtoiOOBTest(&CallAtoll);
1593}
1594
1595void CallStrtol(const char *nptr, char **endptr, int base) {
1596  Ident(strtol(nptr, endptr, base));
1597}
1598void CallStrtoll(const char *nptr, char **endptr, int base) {
1599  Ident(strtoll(nptr, endptr, base));
1600}
1601typedef void(*PointerToCallStrtol)(const char*, char**, int);
1602
1603void RunStrtolOOBTest(PointerToCallStrtol Strtol) {
1604  char *array = MallocAndMemsetString(3);
1605  char *endptr = NULL;
1606  array[0] = '1';
1607  array[1] = '2';
1608  array[2] = '3';
1609  // Invalid pointer to the string.
1610  EXPECT_DEATH(Strtol(array + 3, NULL, 0), RightOOBReadMessage(0));
1611  EXPECT_DEATH(Strtol(array - 1, NULL, 0), LeftOOBReadMessage(1));
1612  // Buffer overflow if there is no terminating null (depends on base).
1613  Strtol(array, &endptr, 3);
1614  EXPECT_EQ(array + 2, endptr);
1615  EXPECT_DEATH(Strtol(array, NULL, 0), RightOOBReadMessage(0));
1616  array[2] = 'z';
1617  Strtol(array, &endptr, 35);
1618  EXPECT_EQ(array + 2, endptr);
1619  EXPECT_DEATH(Strtol(array, NULL, 36), RightOOBReadMessage(0));
1620  // Add terminating zero to get rid of overflow.
1621  array[2] = '\0';
1622  Strtol(array, NULL, 36);
1623  // Don't check for overflow if base is invalid.
1624  Strtol(array - 1, NULL, -1);
1625  Strtol(array + 3, NULL, 1);
1626  // Sometimes we need to detect overflow if no digits are found.
1627  array[0] = array[1] = array[2] = ' ';
1628  EXPECT_DEATH(Strtol(array, NULL, 0), RightOOBReadMessage(0));
1629  array[2] = '+';
1630  EXPECT_DEATH(Strtol(array, NULL, 0), RightOOBReadMessage(0));
1631  array[2] = '-';
1632  EXPECT_DEATH(Strtol(array, NULL, 0), RightOOBReadMessage(0));
1633  array[1] = '+';
1634  Strtol(array, NULL, 0);
1635  array[1] = array[2] = 'z';
1636  Strtol(array, &endptr, 0);
1637  EXPECT_EQ(array, endptr);
1638  Strtol(array + 2, NULL, 0);
1639  EXPECT_EQ(array, endptr);
1640  free(array);
1641}
1642
1643TEST(AddressSanitizer, StrtollOOBTest) {
1644  RunStrtolOOBTest(&CallStrtoll);
1645}
1646TEST(AddressSanitizer, StrtolOOBTest) {
1647  RunStrtolOOBTest(&CallStrtol);
1648}
1649
1650// At the moment we instrument memcpy/memove/memset calls at compile time so we
1651// can't handle OOB error if these functions are called by pointer, see disabled
1652// MemIntrinsicCallByPointerTest below
1653typedef void*(*PointerToMemTransfer)(void*, const void*, size_t);
1654typedef void*(*PointerToMemSet)(void*, int, size_t);
1655
1656void CallMemSetByPointer(PointerToMemSet MemSet) {
1657  size_t size = Ident(100);
1658  char *array = Ident((char*)malloc(size));
1659  EXPECT_DEATH(MemSet(array, 0, 101), RightOOBWriteMessage(0));
1660  free(array);
1661}
1662
1663void CallMemTransferByPointer(PointerToMemTransfer MemTransfer) {
1664  size_t size = Ident(100);
1665  char *src = Ident((char*)malloc(size));
1666  char *dst = Ident((char*)malloc(size));
1667  EXPECT_DEATH(MemTransfer(dst, src, 101), RightOOBWriteMessage(0));
1668  free(src);
1669  free(dst);
1670}
1671
1672TEST(AddressSanitizer, DISABLED_MemIntrinsicCallByPointerTest) {
1673  CallMemSetByPointer(&memset);
1674  CallMemTransferByPointer(&memcpy);
1675  CallMemTransferByPointer(&memmove);
1676}
1677
1678#if defined(__linux__) && !defined(ANDROID) && !defined(__ANDROID__)
1679TEST(AddressSanitizer, pread) {
1680  char *x = new char[10];
1681  int fd = open("/proc/self/stat", O_RDONLY);
1682  ASSERT_GT(fd, 0);
1683  EXPECT_DEATH(pread(fd, x, 15, 0),
1684               ASAN_PCRE_DOTALL
1685               "AddressSanitizer: heap-buffer-overflow"
1686               ".* is located 0 bytes to the right of 10-byte region");
1687  close(fd);
1688  delete [] x;
1689}
1690
1691TEST(AddressSanitizer, pread64) {
1692  char *x = new char[10];
1693  int fd = open("/proc/self/stat", O_RDONLY);
1694  ASSERT_GT(fd, 0);
1695  EXPECT_DEATH(pread64(fd, x, 15, 0),
1696               ASAN_PCRE_DOTALL
1697               "AddressSanitizer: heap-buffer-overflow"
1698               ".* is located 0 bytes to the right of 10-byte region");
1699  close(fd);
1700  delete [] x;
1701}
1702
1703TEST(AddressSanitizer, read) {
1704  char *x = new char[10];
1705  int fd = open("/proc/self/stat", O_RDONLY);
1706  ASSERT_GT(fd, 0);
1707  EXPECT_DEATH(read(fd, x, 15),
1708               ASAN_PCRE_DOTALL
1709               "AddressSanitizer: heap-buffer-overflow"
1710               ".* is located 0 bytes to the right of 10-byte region");
1711  close(fd);
1712  delete [] x;
1713}
1714
1715#endif  // defined(__linux__) && !defined(ANDROID) && !defined(__ANDROID__)
1716
1717// This test case fails
1718// Clang optimizes memcpy/memset calls which lead to unaligned access
1719TEST(AddressSanitizer, DISABLED_MemIntrinsicUnalignedAccessTest) {
1720  int size = Ident(4096);
1721  char *s = Ident((char*)malloc(size));
1722  EXPECT_DEATH(memset(s + size - 1, 0, 2), RightOOBWriteMessage(0));
1723  free(s);
1724}
1725
1726// TODO(samsonov): Add a test with malloc(0)
1727// TODO(samsonov): Add tests for str* and mem* functions.
1728
1729NOINLINE static int LargeFunction(bool do_bad_access) {
1730  int *x = new int[100];
1731  x[0]++;
1732  x[1]++;
1733  x[2]++;
1734  x[3]++;
1735  x[4]++;
1736  x[5]++;
1737  x[6]++;
1738  x[7]++;
1739  x[8]++;
1740  x[9]++;
1741
1742  x[do_bad_access ? 100 : 0]++; int res = __LINE__;
1743
1744  x[10]++;
1745  x[11]++;
1746  x[12]++;
1747  x[13]++;
1748  x[14]++;
1749  x[15]++;
1750  x[16]++;
1751  x[17]++;
1752  x[18]++;
1753  x[19]++;
1754
1755  delete x;
1756  return res;
1757}
1758
1759// Test the we have correct debug info for the failing instruction.
1760// This test requires the in-process symbolizer to be enabled by default.
1761TEST(AddressSanitizer, DISABLED_LargeFunctionSymbolizeTest) {
1762  int failing_line = LargeFunction(false);
1763  char expected_warning[128];
1764  sprintf(expected_warning, "LargeFunction.*asan_test.*:%d", failing_line);
1765  EXPECT_DEATH(LargeFunction(true), expected_warning);
1766}
1767
1768// Check that we unwind and symbolize correctly.
1769TEST(AddressSanitizer, DISABLED_MallocFreeUnwindAndSymbolizeTest) {
1770  int *a = (int*)malloc_aaa(sizeof(int));
1771  *a = 1;
1772  free_aaa(a);
1773  EXPECT_DEATH(*a = 1, "free_ccc.*free_bbb.*free_aaa.*"
1774               "malloc_fff.*malloc_eee.*malloc_ddd");
1775}
1776
1777static bool TryToSetThreadName(const char *name) {
1778#if defined(__linux__) && defined(PR_SET_NAME)
1779  return 0 == prctl(PR_SET_NAME, (unsigned long)name, 0, 0, 0);
1780#else
1781  return false;
1782#endif
1783}
1784
1785void *ThreadedTestAlloc(void *a) {
1786  EXPECT_EQ(true, TryToSetThreadName("AllocThr"));
1787  int **p = (int**)a;
1788  *p = new int;
1789  return 0;
1790}
1791
1792void *ThreadedTestFree(void *a) {
1793  EXPECT_EQ(true, TryToSetThreadName("FreeThr"));
1794  int **p = (int**)a;
1795  delete *p;
1796  return 0;
1797}
1798
1799void *ThreadedTestUse(void *a) {
1800  EXPECT_EQ(true, TryToSetThreadName("UseThr"));
1801  int **p = (int**)a;
1802  **p = 1;
1803  return 0;
1804}
1805
1806void ThreadedTestSpawn() {
1807  pthread_t t;
1808  int *x;
1809  PTHREAD_CREATE(&t, 0, ThreadedTestAlloc, &x);
1810  PTHREAD_JOIN(t, 0);
1811  PTHREAD_CREATE(&t, 0, ThreadedTestFree, &x);
1812  PTHREAD_JOIN(t, 0);
1813  PTHREAD_CREATE(&t, 0, ThreadedTestUse, &x);
1814  PTHREAD_JOIN(t, 0);
1815}
1816
1817TEST(AddressSanitizer, ThreadedTest) {
1818  EXPECT_DEATH(ThreadedTestSpawn(),
1819               ASAN_PCRE_DOTALL
1820               "Thread T.*created"
1821               ".*Thread T.*created"
1822               ".*Thread T.*created");
1823}
1824
1825void *ThreadedTestFunc(void *unused) {
1826  // Check if prctl(PR_SET_NAME) is supported. Return if not.
1827  if (!TryToSetThreadName("TestFunc"))
1828    return 0;
1829  EXPECT_DEATH(ThreadedTestSpawn(),
1830               ASAN_PCRE_DOTALL
1831               "WRITE .*thread T. .UseThr."
1832               ".*freed by thread T. .FreeThr. here:"
1833               ".*previously allocated by thread T. .AllocThr. here:"
1834               ".*Thread T. .UseThr. created by T.*TestFunc"
1835               ".*Thread T. .FreeThr. created by T"
1836               ".*Thread T. .AllocThr. created by T"
1837               "");
1838  return 0;
1839}
1840
1841TEST(AddressSanitizer, ThreadNamesTest) {
1842  // Run ThreadedTestFunc in a separate thread because it tries to set a
1843  // thread name and we don't want to change the main thread's name.
1844  pthread_t t;
1845  PTHREAD_CREATE(&t, 0, ThreadedTestFunc, 0);
1846  PTHREAD_JOIN(t, 0);
1847}
1848
1849#if ASAN_NEEDS_SEGV
1850TEST(AddressSanitizer, ShadowGapTest) {
1851#if SANITIZER_WORDSIZE == 32
1852  char *addr = (char*)0x22000000;
1853#else
1854  char *addr = (char*)0x0000100000080000;
1855#endif
1856  EXPECT_DEATH(*addr = 1, "AddressSanitizer: SEGV on unknown");
1857}
1858#endif  // ASAN_NEEDS_SEGV
1859
1860extern "C" {
1861NOINLINE static void UseThenFreeThenUse() {
1862  char *x = Ident((char*)malloc(8));
1863  *x = 1;
1864  free_aaa(x);
1865  *x = 2;
1866}
1867}
1868
1869TEST(AddressSanitizer, UseThenFreeThenUseTest) {
1870  EXPECT_DEATH(UseThenFreeThenUse(), "freed by thread");
1871}
1872
1873TEST(AddressSanitizer, StrDupTest) {
1874  free(strdup(Ident("123")));
1875}
1876
1877// Currently we create and poison redzone at right of global variables.
1878char glob5[5];
1879static char static110[110];
1880const char ConstGlob[7] = {1, 2, 3, 4, 5, 6, 7};
1881static const char StaticConstGlob[3] = {9, 8, 7};
1882extern int GlobalsTest(int x);
1883
1884TEST(AddressSanitizer, GlobalTest) {
1885  static char func_static15[15];
1886
1887  static char fs1[10];
1888  static char fs2[10];
1889  static char fs3[10];
1890
1891  glob5[Ident(0)] = 0;
1892  glob5[Ident(1)] = 0;
1893  glob5[Ident(2)] = 0;
1894  glob5[Ident(3)] = 0;
1895  glob5[Ident(4)] = 0;
1896
1897  EXPECT_DEATH(glob5[Ident(5)] = 0,
1898               "0 bytes to the right of global variable.*glob5.* size 5");
1899  EXPECT_DEATH(glob5[Ident(5+6)] = 0,
1900               "6 bytes to the right of global variable.*glob5.* size 5");
1901  Ident(static110);  // avoid optimizations
1902  static110[Ident(0)] = 0;
1903  static110[Ident(109)] = 0;
1904  EXPECT_DEATH(static110[Ident(110)] = 0,
1905               "0 bytes to the right of global variable");
1906  EXPECT_DEATH(static110[Ident(110+7)] = 0,
1907               "7 bytes to the right of global variable");
1908
1909  Ident(func_static15);  // avoid optimizations
1910  func_static15[Ident(0)] = 0;
1911  EXPECT_DEATH(func_static15[Ident(15)] = 0,
1912               "0 bytes to the right of global variable");
1913  EXPECT_DEATH(func_static15[Ident(15 + 9)] = 0,
1914               "9 bytes to the right of global variable");
1915
1916  Ident(fs1);
1917  Ident(fs2);
1918  Ident(fs3);
1919
1920  // We don't create left redzones, so this is not 100% guaranteed to fail.
1921  // But most likely will.
1922  EXPECT_DEATH(fs2[Ident(-1)] = 0, "is located.*of global variable");
1923
1924  EXPECT_DEATH(Ident(Ident(ConstGlob)[8]),
1925               "is located 1 bytes to the right of .*ConstGlob");
1926  EXPECT_DEATH(Ident(Ident(StaticConstGlob)[5]),
1927               "is located 2 bytes to the right of .*StaticConstGlob");
1928
1929  // call stuff from another file.
1930  GlobalsTest(0);
1931}
1932
1933TEST(AddressSanitizer, GlobalStringConstTest) {
1934  static const char *zoo = "FOOBAR123";
1935  const char *p = Ident(zoo);
1936  EXPECT_DEATH(Ident(p[15]), "is ascii string 'FOOBAR123'");
1937}
1938
1939TEST(AddressSanitizer, FileNameInGlobalReportTest) {
1940  static char zoo[10];
1941  const char *p = Ident(zoo);
1942  // The file name should be present in the report.
1943  EXPECT_DEATH(Ident(p[15]), "zoo.*asan_test.");
1944}
1945
1946int *ReturnsPointerToALocalObject() {
1947  int a = 0;
1948  return Ident(&a);
1949}
1950
1951#if ASAN_UAR == 1
1952TEST(AddressSanitizer, LocalReferenceReturnTest) {
1953  int *(*f)() = Ident(ReturnsPointerToALocalObject);
1954  int *p = f();
1955  // Call 'f' a few more times, 'p' should still be poisoned.
1956  for (int i = 0; i < 32; i++)
1957    f();
1958  EXPECT_DEATH(*p = 1, "AddressSanitizer: stack-use-after-return");
1959  EXPECT_DEATH(*p = 1, "is located.*in frame .*ReturnsPointerToALocal");
1960}
1961#endif
1962
1963template <int kSize>
1964NOINLINE static void FuncWithStack() {
1965  char x[kSize];
1966  Ident(x)[0] = 0;
1967  Ident(x)[kSize-1] = 0;
1968}
1969
1970static void LotsOfStackReuse() {
1971  int LargeStack[10000];
1972  Ident(LargeStack)[0] = 0;
1973  for (int i = 0; i < 10000; i++) {
1974    FuncWithStack<128 * 1>();
1975    FuncWithStack<128 * 2>();
1976    FuncWithStack<128 * 4>();
1977    FuncWithStack<128 * 8>();
1978    FuncWithStack<128 * 16>();
1979    FuncWithStack<128 * 32>();
1980    FuncWithStack<128 * 64>();
1981    FuncWithStack<128 * 128>();
1982    FuncWithStack<128 * 256>();
1983    FuncWithStack<128 * 512>();
1984    Ident(LargeStack)[0] = 0;
1985  }
1986}
1987
1988TEST(AddressSanitizer, StressStackReuseTest) {
1989  LotsOfStackReuse();
1990}
1991
1992TEST(AddressSanitizer, ThreadedStressStackReuseTest) {
1993  const int kNumThreads = 20;
1994  pthread_t t[kNumThreads];
1995  for (int i = 0; i < kNumThreads; i++) {
1996    PTHREAD_CREATE(&t[i], 0, (void* (*)(void *x))LotsOfStackReuse, 0);
1997  }
1998  for (int i = 0; i < kNumThreads; i++) {
1999    PTHREAD_JOIN(t[i], 0);
2000  }
2001}
2002
2003static void *PthreadExit(void *a) {
2004  pthread_exit(0);
2005  return 0;
2006}
2007
2008TEST(AddressSanitizer, PthreadExitTest) {
2009  pthread_t t;
2010  for (int i = 0; i < 1000; i++) {
2011    PTHREAD_CREATE(&t, 0, PthreadExit, 0);
2012    PTHREAD_JOIN(t, 0);
2013  }
2014}
2015
2016#ifdef __EXCEPTIONS
2017NOINLINE static void StackReuseAndException() {
2018  int large_stack[1000];
2019  Ident(large_stack);
2020  ASAN_THROW(1);
2021}
2022
2023// TODO(kcc): support exceptions with use-after-return.
2024TEST(AddressSanitizer, DISABLED_StressStackReuseAndExceptionsTest) {
2025  for (int i = 0; i < 10000; i++) {
2026    try {
2027    StackReuseAndException();
2028    } catch(...) {
2029    }
2030  }
2031}
2032#endif
2033
2034TEST(AddressSanitizer, MlockTest) {
2035  EXPECT_EQ(0, mlockall(MCL_CURRENT));
2036  EXPECT_EQ(0, mlock((void*)0x12345, 0x5678));
2037  EXPECT_EQ(0, munlockall());
2038  EXPECT_EQ(0, munlock((void*)0x987, 0x654));
2039}
2040
2041struct LargeStruct {
2042  int foo[100];
2043};
2044
2045// Test for bug http://llvm.org/bugs/show_bug.cgi?id=11763.
2046// Struct copy should not cause asan warning even if lhs == rhs.
2047TEST(AddressSanitizer, LargeStructCopyTest) {
2048  LargeStruct a;
2049  *Ident(&a) = *Ident(&a);
2050}
2051
2052ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
2053static void NoAddressSafety() {
2054  char *foo = new char[10];
2055  Ident(foo)[10] = 0;
2056  delete [] foo;
2057}
2058
2059TEST(AddressSanitizer, AttributeNoAddressSafetyTest) {
2060  Ident(NoAddressSafety)();
2061}
2062
2063static string MismatchStr(const string &str) {
2064  return string("AddressSanitizer: alloc-dealloc-mismatch \\(") + str;
2065}
2066
2067// This test is disabled until we enable alloc_dealloc_mismatch by default.
2068// The feature is also tested by lit tests.
2069TEST(AddressSanitizer, DISABLED_AllocDeallocMismatch) {
2070  EXPECT_DEATH(free(Ident(new int)),
2071               MismatchStr("operator new vs free"));
2072  EXPECT_DEATH(free(Ident(new int[2])),
2073               MismatchStr("operator new \\[\\] vs free"));
2074  EXPECT_DEATH(delete (Ident(new int[2])),
2075               MismatchStr("operator new \\[\\] vs operator delete"));
2076  EXPECT_DEATH(delete (Ident((int*)malloc(2 * sizeof(int)))),
2077               MismatchStr("malloc vs operator delete"));
2078  EXPECT_DEATH(delete [] (Ident(new int)),
2079               MismatchStr("operator new vs operator delete \\[\\]"));
2080  EXPECT_DEATH(delete [] (Ident((int*)malloc(2 * sizeof(int)))),
2081               MismatchStr("malloc vs operator delete \\[\\]"));
2082}
2083
2084// ------------------ demo tests; run each one-by-one -------------
2085// e.g. --gtest_filter=*DemoOOBLeftHigh --gtest_also_run_disabled_tests
2086TEST(AddressSanitizer, DISABLED_DemoThreadedTest) {
2087  ThreadedTestSpawn();
2088}
2089
2090void *SimpleBugOnSTack(void *x = 0) {
2091  char a[20];
2092  Ident(a)[20] = 0;
2093  return 0;
2094}
2095
2096TEST(AddressSanitizer, DISABLED_DemoStackTest) {
2097  SimpleBugOnSTack();
2098}
2099
2100TEST(AddressSanitizer, DISABLED_DemoThreadStackTest) {
2101  pthread_t t;
2102  PTHREAD_CREATE(&t, 0, SimpleBugOnSTack, 0);
2103  PTHREAD_JOIN(t, 0);
2104}
2105
2106TEST(AddressSanitizer, DISABLED_DemoUAFLowIn) {
2107  uaf_test<U1>(10, 0);
2108}
2109TEST(AddressSanitizer, DISABLED_DemoUAFLowLeft) {
2110  uaf_test<U1>(10, -2);
2111}
2112TEST(AddressSanitizer, DISABLED_DemoUAFLowRight) {
2113  uaf_test<U1>(10, 10);
2114}
2115
2116TEST(AddressSanitizer, DISABLED_DemoUAFHigh) {
2117  uaf_test<U1>(kLargeMalloc, 0);
2118}
2119
2120TEST(AddressSanitizer, DISABLED_DemoOOBLeftLow) {
2121  oob_test<U1>(10, -1);
2122}
2123
2124TEST(AddressSanitizer, DISABLED_DemoOOBLeftHigh) {
2125  oob_test<U1>(kLargeMalloc, -1);
2126}
2127
2128TEST(AddressSanitizer, DISABLED_DemoOOBRightLow) {
2129  oob_test<U1>(10, 10);
2130}
2131
2132TEST(AddressSanitizer, DISABLED_DemoOOBRightHigh) {
2133  oob_test<U1>(kLargeMalloc, kLargeMalloc);
2134}
2135
2136TEST(AddressSanitizer, DISABLED_DemoOOM) {
2137  size_t size = SANITIZER_WORDSIZE == 64 ? (size_t)(1ULL << 40) : (0xf0000000);
2138  printf("%p\n", malloc(size));
2139}
2140
2141TEST(AddressSanitizer, DISABLED_DemoDoubleFreeTest) {
2142  DoubleFree();
2143}
2144
2145TEST(AddressSanitizer, DISABLED_DemoNullDerefTest) {
2146  int *a = 0;
2147  Ident(a)[10] = 0;
2148}
2149
2150TEST(AddressSanitizer, DISABLED_DemoFunctionStaticTest) {
2151  static char a[100];
2152  static char b[100];
2153  static char c[100];
2154  Ident(a);
2155  Ident(b);
2156  Ident(c);
2157  Ident(a)[5] = 0;
2158  Ident(b)[105] = 0;
2159  Ident(a)[5] = 0;
2160}
2161
2162TEST(AddressSanitizer, DISABLED_DemoTooMuchMemoryTest) {
2163  const size_t kAllocSize = (1 << 28) - 1024;
2164  size_t total_size = 0;
2165  while (true) {
2166    char *x = (char*)malloc(kAllocSize);
2167    memset(x, 0, kAllocSize);
2168    total_size += kAllocSize;
2169    fprintf(stderr, "total: %ldM %p\n", (long)total_size >> 20, x);
2170  }
2171}
2172
2173// http://code.google.com/p/address-sanitizer/issues/detail?id=66
2174TEST(AddressSanitizer, BufferOverflowAfterManyFrees) {
2175  for (int i = 0; i < 1000000; i++) {
2176    delete [] (Ident(new char [8644]));
2177  }
2178  char *x = new char[8192];
2179  EXPECT_DEATH(x[Ident(8192)] = 0, "AddressSanitizer: heap-buffer-overflow");
2180  delete [] Ident(x);
2181}
2182
2183#ifdef __APPLE__
2184#include "asan_mac_test.h"
2185TEST(AddressSanitizerMac, CFAllocatorDefaultDoubleFree) {
2186  EXPECT_DEATH(
2187      CFAllocatorDefaultDoubleFree(NULL),
2188      "attempting double-free");
2189}
2190
2191void CFAllocator_DoubleFreeOnPthread() {
2192  pthread_t child;
2193  PTHREAD_CREATE(&child, NULL, CFAllocatorDefaultDoubleFree, NULL);
2194  PTHREAD_JOIN(child, NULL);  // Shouldn't be reached.
2195}
2196
2197TEST(AddressSanitizerMac, CFAllocatorDefaultDoubleFree_ChildPhread) {
2198  EXPECT_DEATH(CFAllocator_DoubleFreeOnPthread(), "attempting double-free");
2199}
2200
2201namespace {
2202
2203void *GLOB;
2204
2205void *CFAllocatorAllocateToGlob(void *unused) {
2206  GLOB = CFAllocatorAllocate(NULL, 100, /*hint*/0);
2207  return NULL;
2208}
2209
2210void *CFAllocatorDeallocateFromGlob(void *unused) {
2211  char *p = (char*)GLOB;
2212  p[100] = 'A';  // ASan should report an error here.
2213  CFAllocatorDeallocate(NULL, GLOB);
2214  return NULL;
2215}
2216
2217void CFAllocator_PassMemoryToAnotherThread() {
2218  pthread_t th1, th2;
2219  PTHREAD_CREATE(&th1, NULL, CFAllocatorAllocateToGlob, NULL);
2220  PTHREAD_JOIN(th1, NULL);
2221  PTHREAD_CREATE(&th2, NULL, CFAllocatorDeallocateFromGlob, NULL);
2222  PTHREAD_JOIN(th2, NULL);
2223}
2224
2225TEST(AddressSanitizerMac, CFAllocator_PassMemoryToAnotherThread) {
2226  EXPECT_DEATH(CFAllocator_PassMemoryToAnotherThread(),
2227               "heap-buffer-overflow");
2228}
2229
2230}  // namespace
2231
2232// TODO(glider): figure out whether we still need these tests. Is it correct
2233// to intercept the non-default CFAllocators?
2234TEST(AddressSanitizerMac, DISABLED_CFAllocatorSystemDefaultDoubleFree) {
2235  EXPECT_DEATH(
2236      CFAllocatorSystemDefaultDoubleFree(),
2237      "attempting double-free");
2238}
2239
2240// We're intercepting malloc, so kCFAllocatorMalloc is routed to ASan.
2241TEST(AddressSanitizerMac, CFAllocatorMallocDoubleFree) {
2242  EXPECT_DEATH(CFAllocatorMallocDoubleFree(), "attempting double-free");
2243}
2244
2245TEST(AddressSanitizerMac, DISABLED_CFAllocatorMallocZoneDoubleFree) {
2246  EXPECT_DEATH(CFAllocatorMallocZoneDoubleFree(), "attempting double-free");
2247}
2248
2249// For libdispatch tests below we check that ASan got to the shadow byte
2250// legend, i.e. managed to print the thread stacks (this almost certainly
2251// means that the libdispatch task creation has been intercepted correctly).
2252TEST(AddressSanitizerMac, GCDDispatchAsync) {
2253  // Make sure the whole ASan report is printed, i.e. that we don't die
2254  // on a CHECK.
2255  EXPECT_DEATH(TestGCDDispatchAsync(), "Shadow byte legend");
2256}
2257
2258TEST(AddressSanitizerMac, GCDDispatchSync) {
2259  // Make sure the whole ASan report is printed, i.e. that we don't die
2260  // on a CHECK.
2261  EXPECT_DEATH(TestGCDDispatchSync(), "Shadow byte legend");
2262}
2263
2264
2265TEST(AddressSanitizerMac, GCDReuseWqthreadsAsync) {
2266  // Make sure the whole ASan report is printed, i.e. that we don't die
2267  // on a CHECK.
2268  EXPECT_DEATH(TestGCDReuseWqthreadsAsync(), "Shadow byte legend");
2269}
2270
2271TEST(AddressSanitizerMac, GCDReuseWqthreadsSync) {
2272  // Make sure the whole ASan report is printed, i.e. that we don't die
2273  // on a CHECK.
2274  EXPECT_DEATH(TestGCDReuseWqthreadsSync(), "Shadow byte legend");
2275}
2276
2277TEST(AddressSanitizerMac, GCDDispatchAfter) {
2278  // Make sure the whole ASan report is printed, i.e. that we don't die
2279  // on a CHECK.
2280  EXPECT_DEATH(TestGCDDispatchAfter(), "Shadow byte legend");
2281}
2282
2283TEST(AddressSanitizerMac, GCDSourceEvent) {
2284  // Make sure the whole ASan report is printed, i.e. that we don't die
2285  // on a CHECK.
2286  EXPECT_DEATH(TestGCDSourceEvent(), "Shadow byte legend");
2287}
2288
2289TEST(AddressSanitizerMac, GCDSourceCancel) {
2290  // Make sure the whole ASan report is printed, i.e. that we don't die
2291  // on a CHECK.
2292  EXPECT_DEATH(TestGCDSourceCancel(), "Shadow byte legend");
2293}
2294
2295TEST(AddressSanitizerMac, GCDGroupAsync) {
2296  // Make sure the whole ASan report is printed, i.e. that we don't die
2297  // on a CHECK.
2298  EXPECT_DEATH(TestGCDGroupAsync(), "Shadow byte legend");
2299}
2300
2301void *MallocIntrospectionLockWorker(void *_) {
2302  const int kNumPointers = 100;
2303  int i;
2304  void *pointers[kNumPointers];
2305  for (i = 0; i < kNumPointers; i++) {
2306    pointers[i] = malloc(i + 1);
2307  }
2308  for (i = 0; i < kNumPointers; i++) {
2309    free(pointers[i]);
2310  }
2311
2312  return NULL;
2313}
2314
2315void *MallocIntrospectionLockForker(void *_) {
2316  pid_t result = fork();
2317  if (result == -1) {
2318    perror("fork");
2319  }
2320  assert(result != -1);
2321  if (result == 0) {
2322    // Call malloc in the child process to make sure we won't deadlock.
2323    void *ptr = malloc(42);
2324    free(ptr);
2325    exit(0);
2326  } else {
2327    // Return in the parent process.
2328    return NULL;
2329  }
2330}
2331
2332TEST(AddressSanitizerMac, MallocIntrospectionLock) {
2333  // Incorrect implementation of force_lock and force_unlock in our malloc zone
2334  // will cause forked processes to deadlock.
2335  // TODO(glider): need to detect that none of the child processes deadlocked.
2336  const int kNumWorkers = 5, kNumIterations = 100;
2337  int i, iter;
2338  for (iter = 0; iter < kNumIterations; iter++) {
2339    pthread_t workers[kNumWorkers], forker;
2340    for (i = 0; i < kNumWorkers; i++) {
2341      PTHREAD_CREATE(&workers[i], 0, MallocIntrospectionLockWorker, 0);
2342    }
2343    PTHREAD_CREATE(&forker, 0, MallocIntrospectionLockForker, 0);
2344    for (i = 0; i < kNumWorkers; i++) {
2345      PTHREAD_JOIN(workers[i], 0);
2346    }
2347    PTHREAD_JOIN(forker, 0);
2348  }
2349}
2350
2351void *TSDAllocWorker(void *test_key) {
2352  if (test_key) {
2353    void *mem = malloc(10);
2354    pthread_setspecific(*(pthread_key_t*)test_key, mem);
2355  }
2356  return NULL;
2357}
2358
2359TEST(AddressSanitizerMac, DISABLED_TSDWorkqueueTest) {
2360  pthread_t th;
2361  pthread_key_t test_key;
2362  pthread_key_create(&test_key, CallFreeOnWorkqueue);
2363  PTHREAD_CREATE(&th, NULL, TSDAllocWorker, &test_key);
2364  PTHREAD_JOIN(th, NULL);
2365  pthread_key_delete(test_key);
2366}
2367
2368// Test that CFStringCreateCopy does not copy constant strings.
2369TEST(AddressSanitizerMac, CFStringCreateCopy) {
2370  CFStringRef str = CFSTR("Hello world!\n");
2371  CFStringRef str2 = CFStringCreateCopy(0, str);
2372  EXPECT_EQ(str, str2);
2373}
2374
2375TEST(AddressSanitizerMac, NSObjectOOB) {
2376  // Make sure that our allocators are used for NSObjects.
2377  EXPECT_DEATH(TestOOBNSObjects(), "heap-buffer-overflow");
2378}
2379
2380// Make sure that correct pointer is passed to free() when deallocating a
2381// NSURL object.
2382// See http://code.google.com/p/address-sanitizer/issues/detail?id=70.
2383TEST(AddressSanitizerMac, NSURLDeallocation) {
2384  TestNSURLDeallocation();
2385}
2386
2387// See http://code.google.com/p/address-sanitizer/issues/detail?id=109.
2388TEST(AddressSanitizerMac, Mstats) {
2389  malloc_statistics_t stats1, stats2;
2390  malloc_zone_statistics(/*all zones*/NULL, &stats1);
2391  const size_t kMallocSize = 100000;
2392  void *alloc = Ident(malloc(kMallocSize));
2393  malloc_zone_statistics(/*all zones*/NULL, &stats2);
2394  EXPECT_GT(stats2.blocks_in_use, stats1.blocks_in_use);
2395  EXPECT_GE(stats2.size_in_use - stats1.size_in_use, kMallocSize);
2396  free(alloc);
2397  // Even the default OSX allocator may not change the stats after free().
2398}
2399#endif  // __APPLE__
2400
2401// Test that instrumentation of stack allocations takes into account
2402// AllocSize of a type, and not its StoreSize (16 vs 10 bytes for long double).
2403// See http://llvm.org/bugs/show_bug.cgi?id=12047 for more details.
2404TEST(AddressSanitizer, LongDoubleNegativeTest) {
2405  long double a, b;
2406  static long double c;
2407  memcpy(Ident(&a), Ident(&b), sizeof(long double));
2408  memcpy(Ident(&c), Ident(&b), sizeof(long double));
2409}
2410