asan_test.cc revision f4e8fc675ab52d0b3022847764a70ed7f03817bd
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  free(to);
1257  free(from);
1258}
1259
1260TEST(AddressSanitizer, StrNCatOOBTest) {
1261  size_t to_size = Ident(100);
1262  char *to = MallocAndMemsetString(to_size);
1263  to[0] = '\0';
1264  size_t from_size = Ident(20);
1265  char *from = MallocAndMemsetString(from_size);
1266  // Normal strncat calls.
1267  strncat(to, from, 0);
1268  strncat(to, from, from_size);
1269  from[from_size - 1] = '\0';
1270  strncat(to, from, 2 * from_size);
1271  // Catenating empty string is not an error.
1272  strncat(to - 1, from, 0);
1273  strncat(to, from + from_size - 1, 10);
1274  // One of arguments points to not allocated memory.
1275  EXPECT_DEATH(strncat(to - 1, from, 2), LeftOOBErrorMessage(1));
1276  EXPECT_DEATH(strncat(to, from - 1, 2), LeftOOBErrorMessage(1));
1277  EXPECT_DEATH(strncat(to + to_size, from, 2), RightOOBErrorMessage(0));
1278  EXPECT_DEATH(strncat(to, from + from_size, 2), RightOOBErrorMessage(0));
1279
1280  memset(from, 'z', from_size);
1281  memset(to, 'z', to_size);
1282  to[0] = '\0';
1283  // "from" is too short.
1284  EXPECT_DEATH(strncat(to, from, from_size + 1), RightOOBErrorMessage(0));
1285  // "to" is not zero-terminated.
1286  EXPECT_DEATH(strncat(to + 1, from, 1), RightOOBErrorMessage(0));
1287  // "to" is too short to fit "from".
1288  to[0] = 'z';
1289  to[to_size - from_size + 1] = '\0';
1290  EXPECT_DEATH(strncat(to, from, from_size - 1), RightOOBErrorMessage(0));
1291  // "to" is just enough.
1292  strncat(to, from, from_size - 2);
1293
1294  free(to);
1295  free(from);
1296}
1297
1298static string OverlapErrorMessage(const string &func) {
1299  return func + "-param-overlap";
1300}
1301
1302TEST(AddressSanitizer, StrArgsOverlapTest) {
1303  size_t size = Ident(100);
1304  char *str = Ident((char*)malloc(size));
1305
1306// Do not check memcpy() on OS X 10.7 and later, where it actually aliases
1307// memmove().
1308#if !defined(__APPLE__) || !defined(MAC_OS_X_VERSION_10_7) || \
1309    (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7)
1310  // Check "memcpy". Use Ident() to avoid inlining.
1311  memset(str, 'z', size);
1312  Ident(memcpy)(str + 1, str + 11, 10);
1313  Ident(memcpy)(str, str, 0);
1314  EXPECT_DEATH(Ident(memcpy)(str, str + 14, 15), OverlapErrorMessage("memcpy"));
1315  EXPECT_DEATH(Ident(memcpy)(str + 14, str, 15), OverlapErrorMessage("memcpy"));
1316#endif
1317
1318  // We do not treat memcpy with to==from as a bug.
1319  // See http://llvm.org/bugs/show_bug.cgi?id=11763.
1320  // EXPECT_DEATH(Ident(memcpy)(str + 20, str + 20, 1),
1321  //              OverlapErrorMessage("memcpy"));
1322
1323  // Check "strcpy".
1324  memset(str, 'z', size);
1325  str[9] = '\0';
1326  strcpy(str + 10, str);
1327  EXPECT_DEATH(strcpy(str + 9, str), OverlapErrorMessage("strcpy"));
1328  EXPECT_DEATH(strcpy(str, str + 4), OverlapErrorMessage("strcpy"));
1329  strcpy(str, str + 5);
1330
1331  // Check "strncpy".
1332  memset(str, 'z', size);
1333  strncpy(str, str + 10, 10);
1334  EXPECT_DEATH(strncpy(str, str + 9, 10), OverlapErrorMessage("strncpy"));
1335  EXPECT_DEATH(strncpy(str + 9, str, 10), OverlapErrorMessage("strncpy"));
1336  str[10] = '\0';
1337  strncpy(str + 11, str, 20);
1338  EXPECT_DEATH(strncpy(str + 10, str, 20), OverlapErrorMessage("strncpy"));
1339
1340  // Check "strcat".
1341  memset(str, 'z', size);
1342  str[10] = '\0';
1343  str[20] = '\0';
1344  strcat(str, str + 10);
1345  strcat(str, str + 11);
1346  str[10] = '\0';
1347  strcat(str + 11, str);
1348  EXPECT_DEATH(strcat(str, str + 9), OverlapErrorMessage("strcat"));
1349  EXPECT_DEATH(strcat(str + 9, str), OverlapErrorMessage("strcat"));
1350  EXPECT_DEATH(strcat(str + 10, str), OverlapErrorMessage("strcat"));
1351
1352  // Check "strncat".
1353  memset(str, 'z', size);
1354  str[10] = '\0';
1355  strncat(str, str + 10, 10);  // from is empty
1356  strncat(str, str + 11, 10);
1357  str[10] = '\0';
1358  str[20] = '\0';
1359  strncat(str + 5, str, 5);
1360  str[10] = '\0';
1361  EXPECT_DEATH(strncat(str + 5, str, 6), OverlapErrorMessage("strncat"));
1362  EXPECT_DEATH(strncat(str, str + 9, 10), OverlapErrorMessage("strncat"));
1363
1364  free(str);
1365}
1366
1367void CallAtoi(const char *nptr) {
1368  Ident(atoi(nptr));
1369}
1370void CallAtol(const char *nptr) {
1371  Ident(atol(nptr));
1372}
1373void CallAtoll(const char *nptr) {
1374  Ident(atoll(nptr));
1375}
1376typedef void(*PointerToCallAtoi)(const char*);
1377
1378void RunAtoiOOBTest(PointerToCallAtoi Atoi) {
1379  char *array = MallocAndMemsetString(10, '1');
1380  // Invalid pointer to the string.
1381  EXPECT_DEATH(Atoi(array + 11), RightOOBErrorMessage(1));
1382  EXPECT_DEATH(Atoi(array - 1), LeftOOBErrorMessage(1));
1383  // Die if a buffer doesn't have terminating NULL.
1384  EXPECT_DEATH(Atoi(array), RightOOBErrorMessage(0));
1385  // Make last symbol a terminating NULL or other non-digit.
1386  array[9] = '\0';
1387  Atoi(array);
1388  array[9] = 'a';
1389  Atoi(array);
1390  Atoi(array + 9);
1391  // Sometimes we need to detect overflow if no digits are found.
1392  memset(array, ' ', 10);
1393  EXPECT_DEATH(Atoi(array), RightOOBErrorMessage(0));
1394  array[9] = '-';
1395  EXPECT_DEATH(Atoi(array), RightOOBErrorMessage(0));
1396  EXPECT_DEATH(Atoi(array + 9), RightOOBErrorMessage(0));
1397  array[8] = '-';
1398  Atoi(array);
1399  delete array;
1400}
1401
1402TEST(AddressSanitizer, AtoiAndFriendsOOBTest) {
1403  RunAtoiOOBTest(&CallAtoi);
1404  RunAtoiOOBTest(&CallAtol);
1405  RunAtoiOOBTest(&CallAtoll);
1406}
1407
1408void CallStrtol(const char *nptr, char **endptr, int base) {
1409  Ident(strtol(nptr, endptr, base));
1410}
1411void CallStrtoll(const char *nptr, char **endptr, int base) {
1412  Ident(strtoll(nptr, endptr, base));
1413}
1414typedef void(*PointerToCallStrtol)(const char*, char**, int);
1415
1416void RunStrtolOOBTest(PointerToCallStrtol Strtol) {
1417  char *array = MallocAndMemsetString(3);
1418  char *endptr = NULL;
1419  array[0] = '1';
1420  array[1] = '2';
1421  array[2] = '3';
1422  // Invalid pointer to the string.
1423  EXPECT_DEATH(Strtol(array + 3, NULL, 0), RightOOBErrorMessage(0));
1424  EXPECT_DEATH(Strtol(array - 1, NULL, 0), LeftOOBErrorMessage(1));
1425  // Buffer overflow if there is no terminating null (depends on base).
1426  Strtol(array, &endptr, 3);
1427  EXPECT_EQ(array + 2, endptr);
1428  EXPECT_DEATH(Strtol(array, NULL, 0), RightOOBErrorMessage(0));
1429  array[2] = 'z';
1430  Strtol(array, &endptr, 35);
1431  EXPECT_EQ(array + 2, endptr);
1432  EXPECT_DEATH(Strtol(array, NULL, 36), RightOOBErrorMessage(0));
1433  // Add terminating zero to get rid of overflow.
1434  array[2] = '\0';
1435  Strtol(array, NULL, 36);
1436  // Don't check for overflow if base is invalid.
1437  Strtol(array - 1, NULL, -1);
1438  Strtol(array + 3, NULL, 1);
1439  // Sometimes we need to detect overflow if no digits are found.
1440  array[0] = array[1] = array[2] = ' ';
1441  EXPECT_DEATH(Strtol(array, NULL, 0), RightOOBErrorMessage(0));
1442  array[2] = '+';
1443  EXPECT_DEATH(Strtol(array, NULL, 0), RightOOBErrorMessage(0));
1444  array[2] = '-';
1445  EXPECT_DEATH(Strtol(array, NULL, 0), RightOOBErrorMessage(0));
1446  array[1] = '+';
1447  Strtol(array, NULL, 0);
1448  array[1] = array[2] = 'z';
1449  Strtol(array, &endptr, 0);
1450  EXPECT_EQ(array, endptr);
1451  Strtol(array + 2, NULL, 0);
1452  EXPECT_EQ(array, endptr);
1453  delete array;
1454}
1455
1456TEST(AddressSanitizer, StrtollOOBTest) {
1457  RunStrtolOOBTest(&CallStrtoll);
1458}
1459TEST(AddressSanitizer, StrtolOOBTest) {
1460  RunStrtolOOBTest(&CallStrtol);
1461}
1462
1463// At the moment we instrument memcpy/memove/memset calls at compile time so we
1464// can't handle OOB error if these functions are called by pointer, see disabled
1465// MemIntrinsicCallByPointerTest below
1466typedef void*(*PointerToMemTransfer)(void*, const void*, size_t);
1467typedef void*(*PointerToMemSet)(void*, int, size_t);
1468
1469void CallMemSetByPointer(PointerToMemSet MemSet) {
1470  size_t size = Ident(100);
1471  char *array = Ident((char*)malloc(size));
1472  EXPECT_DEATH(MemSet(array, 0, 101), RightOOBErrorMessage(0));
1473  free(array);
1474}
1475
1476void CallMemTransferByPointer(PointerToMemTransfer MemTransfer) {
1477  size_t size = Ident(100);
1478  char *src = Ident((char*)malloc(size));
1479  char *dst = Ident((char*)malloc(size));
1480  EXPECT_DEATH(MemTransfer(dst, src, 101), RightOOBErrorMessage(0));
1481  free(src);
1482  free(dst);
1483}
1484
1485TEST(AddressSanitizer, DISABLED_MemIntrinsicCallByPointerTest) {
1486  CallMemSetByPointer(&memset);
1487  CallMemTransferByPointer(&memcpy);
1488  CallMemTransferByPointer(&memmove);
1489}
1490
1491// This test case fails
1492// Clang optimizes memcpy/memset calls which lead to unaligned access
1493TEST(AddressSanitizer, DISABLED_MemIntrinsicUnalignedAccessTest) {
1494  int size = Ident(4096);
1495  char *s = Ident((char*)malloc(size));
1496  EXPECT_DEATH(memset(s + size - 1, 0, 2), RightOOBErrorMessage(0));
1497  free(s);
1498}
1499
1500// TODO(samsonov): Add a test with malloc(0)
1501// TODO(samsonov): Add tests for str* and mem* functions.
1502
1503NOINLINE static int LargeFunction(bool do_bad_access) {
1504  int *x = new int[100];
1505  x[0]++;
1506  x[1]++;
1507  x[2]++;
1508  x[3]++;
1509  x[4]++;
1510  x[5]++;
1511  x[6]++;
1512  x[7]++;
1513  x[8]++;
1514  x[9]++;
1515
1516  x[do_bad_access ? 100 : 0]++; int res = __LINE__;
1517
1518  x[10]++;
1519  x[11]++;
1520  x[12]++;
1521  x[13]++;
1522  x[14]++;
1523  x[15]++;
1524  x[16]++;
1525  x[17]++;
1526  x[18]++;
1527  x[19]++;
1528
1529  delete x;
1530  return res;
1531}
1532
1533// Test the we have correct debug info for the failing instruction.
1534// This test requires the in-process symbolizer to be enabled by default.
1535TEST(AddressSanitizer, DISABLED_LargeFunctionSymbolizeTest) {
1536  int failing_line = LargeFunction(false);
1537  char expected_warning[128];
1538  sprintf(expected_warning, "LargeFunction.*asan_test.cc:%d", failing_line);
1539  EXPECT_DEATH(LargeFunction(true), expected_warning);
1540}
1541
1542// Check that we unwind and symbolize correctly.
1543TEST(AddressSanitizer, DISABLED_MallocFreeUnwindAndSymbolizeTest) {
1544  int *a = (int*)malloc_aaa(sizeof(int));
1545  *a = 1;
1546  free_aaa(a);
1547  EXPECT_DEATH(*a = 1, "free_ccc.*free_bbb.*free_aaa.*"
1548               "malloc_fff.*malloc_eee.*malloc_ddd");
1549}
1550
1551void *ThreadedTestAlloc(void *a) {
1552  int **p = (int**)a;
1553  *p = new int;
1554  return 0;
1555}
1556
1557void *ThreadedTestFree(void *a) {
1558  int **p = (int**)a;
1559  delete *p;
1560  return 0;
1561}
1562
1563void *ThreadedTestUse(void *a) {
1564  int **p = (int**)a;
1565  **p = 1;
1566  return 0;
1567}
1568
1569void ThreadedTestSpawn() {
1570  pthread_t t;
1571  int *x;
1572  pthread_create(&t, 0, ThreadedTestAlloc, &x);
1573  pthread_join(t, 0);
1574  pthread_create(&t, 0, ThreadedTestFree, &x);
1575  pthread_join(t, 0);
1576  pthread_create(&t, 0, ThreadedTestUse, &x);
1577  pthread_join(t, 0);
1578}
1579
1580TEST(AddressSanitizer, ThreadedTest) {
1581  EXPECT_DEATH(ThreadedTestSpawn(),
1582               ASAN_PCRE_DOTALL
1583               "Thread T.*created"
1584               ".*Thread T.*created"
1585               ".*Thread T.*created");
1586}
1587
1588#if ASAN_NEEDS_SEGV
1589TEST(AddressSanitizer, ShadowGapTest) {
1590#if __WORDSIZE == 32
1591  char *addr = (char*)0x22000000;
1592#else
1593  char *addr = (char*)0x0000100000080000;
1594#endif
1595  EXPECT_DEATH(*addr = 1, "AddressSanitizer crashed on unknown");
1596}
1597#endif  // ASAN_NEEDS_SEGV
1598
1599extern "C" {
1600NOINLINE static void UseThenFreeThenUse() {
1601  char *x = Ident((char*)malloc(8));
1602  *x = 1;
1603  free_aaa(x);
1604  *x = 2;
1605}
1606}
1607
1608TEST(AddressSanitizer, UseThenFreeThenUseTest) {
1609  EXPECT_DEATH(UseThenFreeThenUse(), "freed by thread");
1610}
1611
1612TEST(AddressSanitizer, StrDupTest) {
1613  free(strdup(Ident("123")));
1614}
1615
1616// Currently we create and poison redzone at right of global variables.
1617char glob5[5];
1618static char static110[110];
1619const char ConstGlob[7] = {1, 2, 3, 4, 5, 6, 7};
1620static const char StaticConstGlob[3] = {9, 8, 7};
1621extern int GlobalsTest(int x);
1622
1623TEST(AddressSanitizer, GlobalTest) {
1624  static char func_static15[15];
1625
1626  static char fs1[10];
1627  static char fs2[10];
1628  static char fs3[10];
1629
1630  glob5[Ident(0)] = 0;
1631  glob5[Ident(1)] = 0;
1632  glob5[Ident(2)] = 0;
1633  glob5[Ident(3)] = 0;
1634  glob5[Ident(4)] = 0;
1635
1636  EXPECT_DEATH(glob5[Ident(5)] = 0,
1637               "0 bytes to the right of global variable.*glob5.* size 5");
1638  EXPECT_DEATH(glob5[Ident(5+6)] = 0,
1639               "6 bytes to the right of global variable.*glob5.* size 5");
1640  Ident(static110);  // avoid optimizations
1641  static110[Ident(0)] = 0;
1642  static110[Ident(109)] = 0;
1643  EXPECT_DEATH(static110[Ident(110)] = 0,
1644               "0 bytes to the right of global variable");
1645  EXPECT_DEATH(static110[Ident(110+7)] = 0,
1646               "7 bytes to the right of global variable");
1647
1648  Ident(func_static15);  // avoid optimizations
1649  func_static15[Ident(0)] = 0;
1650  EXPECT_DEATH(func_static15[Ident(15)] = 0,
1651               "0 bytes to the right of global variable");
1652  EXPECT_DEATH(func_static15[Ident(15 + 9)] = 0,
1653               "9 bytes to the right of global variable");
1654
1655  Ident(fs1);
1656  Ident(fs2);
1657  Ident(fs3);
1658
1659  // We don't create left redzones, so this is not 100% guaranteed to fail.
1660  // But most likely will.
1661  EXPECT_DEATH(fs2[Ident(-1)] = 0, "is located.*of global variable");
1662
1663  EXPECT_DEATH(Ident(Ident(ConstGlob)[8]),
1664               "is located 1 bytes to the right of .*ConstGlob");
1665  EXPECT_DEATH(Ident(Ident(StaticConstGlob)[5]),
1666               "is located 2 bytes to the right of .*StaticConstGlob");
1667
1668  // call stuff from another file.
1669  GlobalsTest(0);
1670}
1671
1672TEST(AddressSanitizer, GlobalStringConstTest) {
1673  static const char *zoo = "FOOBAR123";
1674  const char *p = Ident(zoo);
1675  EXPECT_DEATH(Ident(p[15]), "is ascii string 'FOOBAR123'");
1676}
1677
1678TEST(AddressSanitizer, FileNameInGlobalReportTest) {
1679  static char zoo[10];
1680  const char *p = Ident(zoo);
1681  // The file name should be present in the report.
1682  EXPECT_DEATH(Ident(p[15]), "zoo.*asan_test.cc");
1683}
1684
1685int *ReturnsPointerToALocalObject() {
1686  int a = 0;
1687  return Ident(&a);
1688}
1689
1690#if ASAN_UAR == 1
1691TEST(AddressSanitizer, LocalReferenceReturnTest) {
1692  int *(*f)() = Ident(ReturnsPointerToALocalObject);
1693  int *p = f();
1694  // Call 'f' a few more times, 'p' should still be poisoned.
1695  for (int i = 0; i < 32; i++)
1696    f();
1697  EXPECT_DEATH(*p = 1, "AddressSanitizer stack-use-after-return");
1698  EXPECT_DEATH(*p = 1, "is located.*in frame .*ReturnsPointerToALocal");
1699}
1700#endif
1701
1702template <int kSize>
1703NOINLINE static void FuncWithStack() {
1704  char x[kSize];
1705  Ident(x)[0] = 0;
1706  Ident(x)[kSize-1] = 0;
1707}
1708
1709static void LotsOfStackReuse() {
1710  int LargeStack[10000];
1711  Ident(LargeStack)[0] = 0;
1712  for (int i = 0; i < 10000; i++) {
1713    FuncWithStack<128 * 1>();
1714    FuncWithStack<128 * 2>();
1715    FuncWithStack<128 * 4>();
1716    FuncWithStack<128 * 8>();
1717    FuncWithStack<128 * 16>();
1718    FuncWithStack<128 * 32>();
1719    FuncWithStack<128 * 64>();
1720    FuncWithStack<128 * 128>();
1721    FuncWithStack<128 * 256>();
1722    FuncWithStack<128 * 512>();
1723    Ident(LargeStack)[0] = 0;
1724  }
1725}
1726
1727TEST(AddressSanitizer, StressStackReuseTest) {
1728  LotsOfStackReuse();
1729}
1730
1731TEST(AddressSanitizer, ThreadedStressStackReuseTest) {
1732  const int kNumThreads = 20;
1733  pthread_t t[kNumThreads];
1734  for (int i = 0; i < kNumThreads; i++) {
1735    pthread_create(&t[i], 0, (void* (*)(void *x))LotsOfStackReuse, 0);
1736  }
1737  for (int i = 0; i < kNumThreads; i++) {
1738    pthread_join(t[i], 0);
1739  }
1740}
1741
1742static void *PthreadExit(void *a) {
1743  pthread_exit(0);
1744  return 0;
1745}
1746
1747TEST(AddressSanitizer, PthreadExitTest) {
1748  pthread_t t;
1749  for (int i = 0; i < 1000; i++) {
1750    pthread_create(&t, 0, PthreadExit, 0);
1751    pthread_join(t, 0);
1752  }
1753}
1754
1755#ifdef __EXCEPTIONS
1756NOINLINE static void StackReuseAndException() {
1757  int large_stack[1000];
1758  Ident(large_stack);
1759  ASAN_THROW(1);
1760}
1761
1762// TODO(kcc): support exceptions with use-after-return.
1763TEST(AddressSanitizer, DISABLED_StressStackReuseAndExceptionsTest) {
1764  for (int i = 0; i < 10000; i++) {
1765    try {
1766    StackReuseAndException();
1767    } catch(...) {
1768    }
1769  }
1770}
1771#endif
1772
1773TEST(AddressSanitizer, MlockTest) {
1774  EXPECT_EQ(0, mlockall(MCL_CURRENT));
1775  EXPECT_EQ(0, mlock((void*)0x12345, 0x5678));
1776  EXPECT_EQ(0, munlockall());
1777  EXPECT_EQ(0, munlock((void*)0x987, 0x654));
1778}
1779
1780struct LargeStruct {
1781  int foo[100];
1782};
1783
1784// Test for bug http://llvm.org/bugs/show_bug.cgi?id=11763.
1785// Struct copy should not cause asan warning even if lhs == rhs.
1786TEST(AddressSanitizer, LargeStructCopyTest) {
1787  LargeStruct a;
1788  *Ident(&a) = *Ident(&a);
1789}
1790
1791__attribute__((no_address_safety_analysis))
1792static void NoAddressSafety() {
1793  char *foo = new char[10];
1794  Ident(foo)[10] = 0;
1795  delete [] foo;
1796}
1797
1798TEST(AddressSanitizer, AttributeNoAddressSafetyTest) {
1799  Ident(NoAddressSafety)();
1800}
1801
1802// ------------------ demo tests; run each one-by-one -------------
1803// e.g. --gtest_filter=*DemoOOBLeftHigh --gtest_also_run_disabled_tests
1804TEST(AddressSanitizer, DISABLED_DemoThreadedTest) {
1805  ThreadedTestSpawn();
1806}
1807
1808void *SimpleBugOnSTack(void *x = 0) {
1809  char a[20];
1810  Ident(a)[20] = 0;
1811  return 0;
1812}
1813
1814TEST(AddressSanitizer, DISABLED_DemoStackTest) {
1815  SimpleBugOnSTack();
1816}
1817
1818TEST(AddressSanitizer, DISABLED_DemoThreadStackTest) {
1819  pthread_t t;
1820  pthread_create(&t, 0, SimpleBugOnSTack, 0);
1821  pthread_join(t, 0);
1822}
1823
1824TEST(AddressSanitizer, DISABLED_DemoUAFLowIn) {
1825  uaf_test<U1>(10, 0);
1826}
1827TEST(AddressSanitizer, DISABLED_DemoUAFLowLeft) {
1828  uaf_test<U1>(10, -2);
1829}
1830TEST(AddressSanitizer, DISABLED_DemoUAFLowRight) {
1831  uaf_test<U1>(10, 10);
1832}
1833
1834TEST(AddressSanitizer, DISABLED_DemoUAFHigh) {
1835  uaf_test<U1>(kLargeMalloc, 0);
1836}
1837
1838TEST(AddressSanitizer, DISABLED_DemoOOBLeftLow) {
1839  oob_test<U1>(10, -1);
1840}
1841
1842TEST(AddressSanitizer, DISABLED_DemoOOBLeftHigh) {
1843  oob_test<U1>(kLargeMalloc, -1);
1844}
1845
1846TEST(AddressSanitizer, DISABLED_DemoOOBRightLow) {
1847  oob_test<U1>(10, 10);
1848}
1849
1850TEST(AddressSanitizer, DISABLED_DemoOOBRightHigh) {
1851  oob_test<U1>(kLargeMalloc, kLargeMalloc);
1852}
1853
1854TEST(AddressSanitizer, DISABLED_DemoOOM) {
1855  size_t size = __WORDSIZE == 64 ? (size_t)(1ULL << 40) : (0xf0000000);
1856  printf("%p\n", malloc(size));
1857}
1858
1859TEST(AddressSanitizer, DISABLED_DemoDoubleFreeTest) {
1860  DoubleFree();
1861}
1862
1863TEST(AddressSanitizer, DISABLED_DemoNullDerefTest) {
1864  int *a = 0;
1865  Ident(a)[10] = 0;
1866}
1867
1868TEST(AddressSanitizer, DISABLED_DemoFunctionStaticTest) {
1869  static char a[100];
1870  static char b[100];
1871  static char c[100];
1872  Ident(a);
1873  Ident(b);
1874  Ident(c);
1875  Ident(a)[5] = 0;
1876  Ident(b)[105] = 0;
1877  Ident(a)[5] = 0;
1878}
1879
1880TEST(AddressSanitizer, DISABLED_DemoTooMuchMemoryTest) {
1881  const size_t kAllocSize = (1 << 28) - 1024;
1882  size_t total_size = 0;
1883  while (true) {
1884    char *x = (char*)malloc(kAllocSize);
1885    memset(x, 0, kAllocSize);
1886    total_size += kAllocSize;
1887    fprintf(stderr, "total: %ldM\n", (long)total_size >> 20);
1888  }
1889}
1890
1891// http://code.google.com/p/address-sanitizer/issues/detail?id=66
1892TEST(AddressSanitizer, BufferOverflowAfterManyFrees) {
1893  for (int i = 0; i < 1000000; i++) {
1894    delete [] (Ident(new char [8644]));
1895  }
1896  char *x = new char[8192];
1897  EXPECT_DEATH(x[Ident(8192)] = 0, "AddressSanitizer heap-buffer-overflow");
1898  delete [] Ident(x);
1899}
1900
1901#ifdef __APPLE__
1902#include "asan_mac_test.h"
1903TEST(AddressSanitizerMac, CFAllocatorDefaultDoubleFree) {
1904  EXPECT_DEATH(
1905      CFAllocatorDefaultDoubleFree(NULL),
1906      "attempting double-free");
1907}
1908
1909void CFAllocator_DoubleFreeOnPthread() {
1910  pthread_t child;
1911  pthread_create(&child, NULL, CFAllocatorDefaultDoubleFree, NULL);
1912  pthread_join(child, NULL);  // Shouldn't be reached.
1913}
1914
1915TEST(AddressSanitizerMac, DISABLED_CFAllocatorDefaultDoubleFree_ChildPhread) {
1916  EXPECT_DEATH(CFAllocator_DoubleFreeOnPthread(), "attempting double-free");
1917}
1918
1919// TODO(glider): figure out whether we still need these tests. Is it correct
1920// to intercept the non-default CFAllocators?
1921TEST(AddressSanitizerMac, DISABLED_CFAllocatorSystemDefaultDoubleFree) {
1922  EXPECT_DEATH(
1923      CFAllocatorSystemDefaultDoubleFree(),
1924      "attempting double-free");
1925}
1926
1927// We're intercepting malloc, so kCFAllocatorMalloc is routed to ASan.
1928TEST(AddressSanitizerMac, CFAllocatorMallocDoubleFree) {
1929  EXPECT_DEATH(CFAllocatorMallocDoubleFree(), "attempting double-free");
1930}
1931
1932TEST(AddressSanitizerMac, DISABLED_CFAllocatorMallocZoneDoubleFree) {
1933  EXPECT_DEATH(CFAllocatorMallocZoneDoubleFree(), "attempting double-free");
1934}
1935
1936TEST(AddressSanitizerMac, GCDDispatchAsync) {
1937  // Make sure the whole ASan report is printed, i.e. that we don't die
1938  // on a CHECK.
1939  EXPECT_DEATH(TestGCDDispatchAsync(), "Shadow byte and word");
1940}
1941
1942TEST(AddressSanitizerMac, GCDDispatchSync) {
1943  // Make sure the whole ASan report is printed, i.e. that we don't die
1944  // on a CHECK.
1945  EXPECT_DEATH(TestGCDDispatchSync(), "Shadow byte and word");
1946}
1947
1948
1949TEST(AddressSanitizerMac, GCDReuseWqthreadsAsync) {
1950  // Make sure the whole ASan report is printed, i.e. that we don't die
1951  // on a CHECK.
1952  EXPECT_DEATH(TestGCDReuseWqthreadsAsync(), "Shadow byte and word");
1953}
1954
1955TEST(AddressSanitizerMac, GCDReuseWqthreadsSync) {
1956  // Make sure the whole ASan report is printed, i.e. that we don't die
1957  // on a CHECK.
1958  EXPECT_DEATH(TestGCDReuseWqthreadsSync(), "Shadow byte and word");
1959}
1960
1961TEST(AddressSanitizerMac, GCDDispatchAfter) {
1962  // Make sure the whole ASan report is printed, i.e. that we don't die
1963  // on a CHECK.
1964  EXPECT_DEATH(TestGCDDispatchAfter(), "Shadow byte and word");
1965}
1966
1967TEST(AddressSanitizerMac, GCDSourceEvent) {
1968  // Make sure the whole ASan report is printed, i.e. that we don't die
1969  // on a CHECK.
1970  EXPECT_DEATH(TestGCDSourceEvent(), "Shadow byte and word");
1971}
1972
1973TEST(AddressSanitizerMac, GCDSourceCancel) {
1974  // Make sure the whole ASan report is printed, i.e. that we don't die
1975  // on a CHECK.
1976  EXPECT_DEATH(TestGCDSourceCancel(), "Shadow byte and word");
1977}
1978
1979TEST(AddressSanitizerMac, GCDGroupAsync) {
1980  // Make sure the whole ASan report is printed, i.e. that we don't die
1981  // on a CHECK.
1982  EXPECT_DEATH(TestGCDGroupAsync(), "Shadow byte and word");
1983}
1984
1985void *MallocIntrospectionLockWorker(void *_) {
1986  const int kNumPointers = 100;
1987  int i;
1988  void *pointers[kNumPointers];
1989  for (i = 0; i < kNumPointers; i++) {
1990    pointers[i] = malloc(i + 1);
1991  }
1992  for (i = 0; i < kNumPointers; i++) {
1993    free(pointers[i]);
1994  }
1995
1996  return NULL;
1997}
1998
1999void *MallocIntrospectionLockForker(void *_) {
2000  pid_t result = fork();
2001  if (result == -1) {
2002    perror("fork");
2003  }
2004  assert(result != -1);
2005  if (result == 0) {
2006    // Call malloc in the child process to make sure we won't deadlock.
2007    void *ptr = malloc(42);
2008    free(ptr);
2009    exit(0);
2010  } else {
2011    // Return in the parent process.
2012    return NULL;
2013  }
2014}
2015
2016TEST(AddressSanitizerMac, MallocIntrospectionLock) {
2017  // Incorrect implementation of force_lock and force_unlock in our malloc zone
2018  // will cause forked processes to deadlock.
2019  // TODO(glider): need to detect that none of the child processes deadlocked.
2020  const int kNumWorkers = 5, kNumIterations = 100;
2021  int i, iter;
2022  for (iter = 0; iter < kNumIterations; iter++) {
2023    pthread_t workers[kNumWorkers], forker;
2024    for (i = 0; i < kNumWorkers; i++) {
2025      pthread_create(&workers[i], 0, MallocIntrospectionLockWorker, 0);
2026    }
2027    pthread_create(&forker, 0, MallocIntrospectionLockForker, 0);
2028    for (i = 0; i < kNumWorkers; i++) {
2029      pthread_join(workers[i], 0);
2030    }
2031    pthread_join(forker, 0);
2032  }
2033}
2034
2035void *TSDAllocWorker(void *test_key) {
2036  if (test_key) {
2037    void *mem = malloc(10);
2038    pthread_setspecific(*(pthread_key_t*)test_key, mem);
2039  }
2040  return NULL;
2041}
2042
2043TEST(AddressSanitizerMac, DISABLED_TSDWorkqueueTest) {
2044  pthread_t th;
2045  pthread_key_t test_key;
2046  pthread_key_create(&test_key, CallFreeOnWorkqueue);
2047  pthread_create(&th, NULL, TSDAllocWorker, &test_key);
2048  pthread_join(th, NULL);
2049  pthread_key_delete(test_key);
2050}
2051
2052// Test that CFStringCreateCopy does not copy constant strings.
2053TEST(AddressSanitizerMac, CFStringCreateCopy) {
2054  CFStringRef str = CFSTR("Hello world!\n");
2055  CFStringRef str2 = CFStringCreateCopy(0, str);
2056  EXPECT_EQ(str, str2);
2057}
2058
2059TEST(AddressSanitizerMac, NSObjectOOB) {
2060  // Make sure that our allocators are used for NSObjects.
2061  EXPECT_DEATH(TestOOBNSObjects(), "heap-buffer-overflow");
2062}
2063
2064// Make sure that correct pointer is passed to free() when deallocating a
2065// NSURL object.
2066// See http://code.google.com/p/address-sanitizer/issues/detail?id=70.
2067TEST(AddressSanitizerMac, NSURLDeallocation) {
2068  TestNSURLDeallocation();
2069}
2070#endif  // __APPLE__
2071
2072// Test that instrumentation of stack allocations takes into account
2073// AllocSize of a type, and not its StoreSize (16 vs 10 bytes for long double).
2074// See http://llvm.org/bugs/show_bug.cgi?id=12047 for more details.
2075TEST(AddressSanitizer, LongDoubleNegativeTest) {
2076  long double a, b;
2077  static long double c;
2078  memcpy(Ident(&a), Ident(&b), sizeof(long double));
2079  memcpy(Ident(&c), Ident(&b), sizeof(long double));
2080};
2081
2082int main(int argc, char **argv) {
2083  progname = argv[0];
2084  testing::GTEST_FLAG(death_test_style) = "threadsafe";
2085  testing::InitGoogleTest(&argc, argv);
2086  return RUN_ALL_TESTS();
2087}
2088