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