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