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