asan_test.cc revision 4dd8ba8238b1b698953628affe6e5b2edf3b3e3f
1//===-- asan_test.cc ------------*- C++ -*-===//
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__) or 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#endif  // __APPLE__
33
34#ifdef __APPLE__
35static bool APPLE = true;
36#else
37static bool APPLE = false;
38#endif
39
40#if ASAN_HAS_EXCEPTIONS
41# define ASAN_THROW(x) throw (x)
42#else
43# define ASAN_THROW(x)
44#endif
45
46#include <sys/mman.h>
47
48typedef uint8_t   U1;
49typedef uint16_t  U2;
50typedef uint32_t  U4;
51typedef uint64_t  U8;
52
53static const char *progname;
54static const int kPageSize = 4096;
55
56// Simple stand-alone pseudorandom number generator.
57// Current algorithm is ANSI C linear congruential PRNG.
58static inline uint32_t my_rand(uint32_t* state) {
59  return (*state = *state * 1103515245 + 12345) >> 16;
60}
61
62static uint32_t global_seed = 0;
63
64const size_t kLargeMalloc = 1 << 24;
65
66template<class T>
67__attribute__((noinline))
68void asan_write(T *a) {
69  *a = 0;
70}
71
72__attribute__((noinline))
73void asan_write_sized_aligned(uint8_t *p, size_t size) {
74  EXPECT_EQ(0, ((uintptr_t)p % size));
75  if      (size == 1) asan_write((uint8_t*)p);
76  else if (size == 2) asan_write((uint16_t*)p);
77  else if (size == 4) asan_write((uint32_t*)p);
78  else if (size == 8) asan_write((uint64_t*)p);
79}
80
81__attribute__((noinline)) void *malloc_fff(size_t size) {
82  void *res = malloc/**/(size); break_optimization(0); return res;}
83__attribute__((noinline)) void *malloc_eee(size_t size) {
84  void *res = malloc_fff(size); break_optimization(0); return res;}
85__attribute__((noinline)) void *malloc_ddd(size_t size) {
86  void *res = malloc_eee(size); break_optimization(0); return res;}
87__attribute__((noinline)) void *malloc_ccc(size_t size) {
88  void *res = malloc_ddd(size); break_optimization(0); return res;}
89__attribute__((noinline)) void *malloc_bbb(size_t size) {
90  void *res = malloc_ccc(size); break_optimization(0); return res;}
91__attribute__((noinline)) void *malloc_aaa(size_t size) {
92  void *res = malloc_bbb(size); break_optimization(0); return res;}
93
94#ifndef __APPLE__
95__attribute__((noinline)) void *memalign_fff(size_t alignment, size_t size) {
96  void *res = memalign/**/(alignment, size); break_optimization(0); return res;}
97__attribute__((noinline)) void *memalign_eee(size_t alignment, size_t size) {
98  void *res = memalign_fff(alignment, size); break_optimization(0); return res;}
99__attribute__((noinline)) void *memalign_ddd(size_t alignment, size_t size) {
100  void *res = memalign_eee(alignment, size); break_optimization(0); return res;}
101__attribute__((noinline)) void *memalign_ccc(size_t alignment, size_t size) {
102  void *res = memalign_ddd(alignment, size); break_optimization(0); return res;}
103__attribute__((noinline)) void *memalign_bbb(size_t alignment, size_t size) {
104  void *res = memalign_ccc(alignment, size); break_optimization(0); return res;}
105__attribute__((noinline)) void *memalign_aaa(size_t alignment, size_t size) {
106  void *res = memalign_bbb(alignment, size); break_optimization(0); return res;}
107#endif  // __APPLE__
108
109
110__attribute__((noinline))
111  void free_ccc(void *p) { free(p); break_optimization(0);}
112__attribute__((noinline))
113  void free_bbb(void *p) { free_ccc(p); break_optimization(0);}
114__attribute__((noinline))
115  void free_aaa(void *p) { free_bbb(p); break_optimization(0);}
116
117template<class T>
118__attribute__((noinline))
119void oob_test(int size, int off) {
120  char *p = (char*)malloc_aaa(size);
121  // fprintf(stderr, "writing %d byte(s) into [%p,%p) with offset %d\n",
122  //        sizeof(T), p, p + size, off);
123  asan_write((T*)(p + off));
124  free_aaa(p);
125}
126
127
128template<class T>
129__attribute__((noinline))
130void uaf_test(int size, int off) {
131  char *p = (char *)malloc_aaa(size);
132  free_aaa(p);
133  for (int i = 1; i < 100; i++)
134    free_aaa(malloc_aaa(i));
135  fprintf(stderr, "writing %ld byte(s) at %p with offset %d\n",
136          (long)sizeof(T), p, off);
137  asan_write((T*)(p + off));
138}
139
140TEST(AddressSanitizer, HasFeatureAddressSanitizerTest) {
141#if defined(__has_feature) && __has_feature(address_sanitizer)
142  bool asan = 1;
143#else
144  bool asan = 0;
145#endif
146  EXPECT_EQ(true, asan);
147}
148
149TEST(AddressSanitizer, SimpleDeathTest) {
150  EXPECT_DEATH(exit(1), "");
151}
152
153TEST(AddressSanitizer, VariousMallocsTest) {
154  // fprintf(stderr, "malloc:\n");
155  int *a = (int*)malloc(100 * sizeof(int));
156  a[50] = 0;
157  free(a);
158
159  // fprintf(stderr, "realloc:\n");
160  int *r = (int*)malloc(10);
161  r = (int*)realloc(r, 2000 * sizeof(int));
162  r[1000] = 0;
163  free(r);
164
165  // fprintf(stderr, "operator new []\n");
166  int *b = new int[100];
167  b[50] = 0;
168  delete [] b;
169
170  // fprintf(stderr, "operator new\n");
171  int *c = new int;
172  *c = 0;
173  delete c;
174
175#if !defined(__APPLE__) && !defined(ANDROID)
176  // fprintf(stderr, "posix_memalign\n");
177  int *pm;
178  int pm_res = posix_memalign((void**)&pm, kPageSize, kPageSize);
179  EXPECT_EQ(0, pm_res);
180  free(pm);
181#endif
182
183#if !defined(__APPLE__)
184  int *ma = (int*)memalign(kPageSize, kPageSize);
185  EXPECT_EQ(0, (uintptr_t)ma % kPageSize);
186  ma[123] = 0;
187  free(ma);
188#endif  // __APPLE__
189}
190
191TEST(AddressSanitizer, CallocTest) {
192  int *a = (int*)calloc(100, sizeof(int));
193  EXPECT_EQ(0, a[10]);
194  free(a);
195}
196
197TEST(AddressSanitizer, VallocTest) {
198  void *a = valloc(100);
199  EXPECT_EQ(0, (uintptr_t)a % kPageSize);
200  free(a);
201}
202
203#ifndef __APPLE__
204TEST(AddressSanitizer, PvallocTest) {
205  char *a = (char*)pvalloc(kPageSize + 100);
206  EXPECT_EQ(0, (uintptr_t)a % kPageSize);
207  a[kPageSize + 101] = 1;  // we should not report an error here.
208  free(a);
209
210  a = (char*)pvalloc(0);  // pvalloc(0) should allocate at least one page.
211  EXPECT_EQ(0, (uintptr_t)a % kPageSize);
212  a[101] = 1;  // we should not report an error here.
213  free(a);
214}
215#endif  // __APPLE__
216
217void NoOpSignalHandler(int unused) {
218  fprintf(stderr, "NoOpSignalHandler (should not happen). Aborting\n");
219  abort();
220}
221
222void NoOpSigaction(int, siginfo_t *siginfo, void *context) {
223  fprintf(stderr, "NoOpSigaction (should not happen). Aborting\n");
224  abort();
225}
226
227TEST(AddressSanitizer, SignalTest) {
228  signal(SIGSEGV, NoOpSignalHandler);
229  signal(SIGILL, NoOpSignalHandler);
230  // If asan did not intercept sigaction NoOpSigaction will fire.
231  char *x = Ident((char*)malloc(5));
232  EXPECT_DEATH(x[6]++, "is located 1 bytes to the right");
233  free(Ident(x));
234}
235
236TEST(AddressSanitizer, SigactionTest) {
237  {
238    struct sigaction sigact;
239    memset(&sigact, 0, sizeof(sigact));
240    sigact.sa_sigaction = NoOpSigaction;;
241    sigact.sa_flags = SA_SIGINFO;
242    sigaction(SIGSEGV, &sigact, 0);
243  }
244
245  {
246    struct sigaction sigact;
247    memset(&sigact, 0, sizeof(sigact));
248    sigact.sa_sigaction = NoOpSigaction;;
249    sigact.sa_flags = SA_SIGINFO;
250    sigaction(SIGILL, &sigact, 0);
251  }
252
253  // If asan did not intercept sigaction NoOpSigaction will fire.
254  char *x = Ident((char*)malloc(5));
255  EXPECT_DEATH(x[6]++, "is located 1 bytes to the right");
256  free(Ident(x));
257}
258
259void *TSDWorker(void *test_key) {
260  if (test_key) {
261    pthread_setspecific(*(pthread_key_t*)test_key, (void*)0xfeedface);
262  }
263  return NULL;
264}
265
266void TSDDestructor(void *tsd) {
267  // Spawning a thread will check that the current thread id is not -1.
268  pthread_t th;
269  pthread_create(&th, NULL, TSDWorker, NULL);
270  pthread_join(th, NULL);
271}
272
273// This tests triggers the thread-specific data destruction fiasco which occurs
274// if we don't manage the TSD destructors ourselves. We create a new pthread
275// key with a non-NULL destructor which is likely to be put after the destructor
276// of AsanThread in the list of destructors.
277// In this case the TSD for AsanThread will be destroyed before TSDDestructor
278// is called for the child thread, and a CHECK will fail when we call
279// pthread_create() to spawn the grandchild.
280TEST(AddressSanitizer, DISABLED_TSDTest) {
281  pthread_t th;
282  pthread_key_t test_key;
283  pthread_key_create(&test_key, TSDDestructor);
284  pthread_create(&th, NULL, TSDWorker, &test_key);
285  pthread_join(th, NULL);
286  pthread_key_delete(test_key);
287}
288
289template<class T>
290void OOBTest() {
291  char expected_str[100];
292  for (int size = sizeof(T); size < 20; size += 5) {
293    for (int i = -5; i < 0; i++) {
294      const char *str =
295          "is located.*%d byte.*to the left";
296      sprintf(expected_str, str, abs(i));
297      EXPECT_DEATH(oob_test<T>(size, i), expected_str);
298    }
299
300    for (int i = 0; i < size - sizeof(T) + 1; i++)
301      oob_test<T>(size, i);
302
303    for (int i = size - sizeof(T) + 1; i <= size + 3 * sizeof(T); i++) {
304      const char *str =
305          "is located.*%d byte.*to the right";
306      int off = i >= size ? (i - size) : 0;
307      // we don't catch unaligned partially OOB accesses.
308      if (i % sizeof(T)) continue;
309      sprintf(expected_str, str, off);
310      EXPECT_DEATH(oob_test<T>(size, i), expected_str);
311    }
312  }
313
314  EXPECT_DEATH(oob_test<T>(kLargeMalloc, -1),
315          "is located.*1 byte.*to the left");
316  EXPECT_DEATH(oob_test<T>(kLargeMalloc, kLargeMalloc),
317          "is located.*0 byte.*to the right");
318}
319
320// TODO(glider): the following tests are EXTREMELY slow on Darwin:
321//   AddressSanitizer.OOB_char (125503 ms)
322//   AddressSanitizer.OOB_int (126890 ms)
323//   AddressSanitizer.OOBRightTest (315605 ms)
324//   AddressSanitizer.SimpleStackTest (366559 ms)
325
326TEST(AddressSanitizer, OOB_char) {
327  OOBTest<U1>();
328}
329
330TEST(AddressSanitizer, OOB_int) {
331  OOBTest<U4>();
332}
333
334TEST(AddressSanitizer, OOBRightTest) {
335  for (size_t access_size = 1; access_size <= 8; access_size *= 2) {
336    for (size_t alloc_size = 1; alloc_size <= 8; alloc_size++) {
337      for (size_t offset = 0; offset <= 8; offset += access_size) {
338        void *p = malloc(alloc_size);
339        // allocated: [p, p + alloc_size)
340        // accessed:  [p + offset, p + offset + access_size)
341        uint8_t *addr = (uint8_t*)p + offset;
342        if (offset + access_size <= alloc_size) {
343          asan_write_sized_aligned(addr, access_size);
344        } else {
345          int outside_bytes = offset > alloc_size ? (offset - alloc_size) : 0;
346          const char *str =
347              "is located.%d *byte.*to the right";
348          char expected_str[100];
349          sprintf(expected_str, str, outside_bytes);
350          EXPECT_DEATH(asan_write_sized_aligned(addr, access_size),
351                       expected_str);
352        }
353        free(p);
354      }
355    }
356  }
357}
358
359TEST(AddressSanitizer, UAF_char) {
360  const char *uaf_string = "AddressSanitizer.*heap-use-after-free";
361  EXPECT_DEATH(uaf_test<U1>(1, 0), uaf_string);
362  EXPECT_DEATH(uaf_test<U1>(10, 0), uaf_string);
363  EXPECT_DEATH(uaf_test<U1>(10, 10), uaf_string);
364  EXPECT_DEATH(uaf_test<U1>(kLargeMalloc, 0), uaf_string);
365  EXPECT_DEATH(uaf_test<U1>(kLargeMalloc, kLargeMalloc / 2), uaf_string);
366}
367
368#if ASAN_HAS_BLACKLIST
369TEST(AddressSanitizer, IgnoreTest) {
370  int *x = Ident(new int);
371  delete Ident(x);
372  *x = 0;
373}
374#endif  // ASAN_HAS_BLACKLIST
375
376struct StructWithBitField {
377  int bf1:1;
378  int bf2:1;
379  int bf3:1;
380  int bf4:29;
381};
382
383TEST(AddressSanitizer, BitFieldPositiveTest) {
384  StructWithBitField *x = new StructWithBitField;
385  delete Ident(x);
386  EXPECT_DEATH(x->bf1 = 0, "use-after-free");
387  EXPECT_DEATH(x->bf2 = 0, "use-after-free");
388  EXPECT_DEATH(x->bf3 = 0, "use-after-free");
389  EXPECT_DEATH(x->bf4 = 0, "use-after-free");
390};
391
392struct StructWithBitFields_8_24 {
393  int a:8;
394  int b:24;
395};
396
397TEST(AddressSanitizer, BitFieldNegativeTest) {
398  StructWithBitFields_8_24 *x = Ident(new StructWithBitFields_8_24);
399  x->a = 0;
400  x->b = 0;
401  delete Ident(x);
402}
403
404TEST(AddressSanitizer, OutOfMemoryTest) {
405  size_t size = __WORDSIZE == 64 ? (size_t)(1ULL << 48) : (0xf0000000);
406  EXPECT_EQ(0, realloc(0, size));
407  EXPECT_EQ(0, realloc(0, ~Ident(0)));
408  EXPECT_EQ(0, malloc(size));
409  EXPECT_EQ(0, malloc(~Ident(0)));
410  EXPECT_EQ(0, calloc(1, size));
411  EXPECT_EQ(0, calloc(1, ~Ident(0)));
412}
413
414#if ASAN_NEEDS_SEGV
415TEST(AddressSanitizer, WildAddressTest) {
416  char *c = (char*)0x123;
417  EXPECT_DEATH(*c = 0, "AddressSanitizer crashed on unknown address");
418}
419#endif
420
421static void MallocStress(size_t n) {
422  uint32_t seed = my_rand(&global_seed);
423  for (size_t iter = 0; iter < 10; iter++) {
424    vector<void *> vec;
425    for (size_t i = 0; i < n; i++) {
426      if ((i % 3) == 0) {
427        if (vec.empty()) continue;
428        size_t idx = my_rand(&seed) % vec.size();
429        void *ptr = vec[idx];
430        vec[idx] = vec.back();
431        vec.pop_back();
432        free_aaa(ptr);
433      } else {
434        size_t size = my_rand(&seed) % 1000 + 1;
435#ifndef __APPLE__
436        size_t alignment = 1 << (my_rand(&seed) % 7 + 3);
437        char *ptr = (char*)memalign_aaa(alignment, size);
438#else
439        char *ptr = (char*) malloc_aaa(size);
440#endif
441        vec.push_back(ptr);
442        ptr[0] = 0;
443        ptr[size-1] = 0;
444        ptr[size/2] = 0;
445      }
446    }
447    for (size_t i = 0; i < vec.size(); i++)
448      free_aaa(vec[i]);
449  }
450}
451
452TEST(AddressSanitizer, MallocStressTest) {
453  MallocStress(200000);
454}
455
456static void TestLargeMalloc(size_t size) {
457  char buff[1024];
458  sprintf(buff, "is located 1 bytes to the left of %lu-byte", (long)size);
459  EXPECT_DEATH(Ident((char*)malloc(size))[-1] = 0, buff);
460}
461
462TEST(AddressSanitizer, LargeMallocTest) {
463  for (int i = 113; i < (1 << 28); i = i * 2 + 13) {
464    TestLargeMalloc(i);
465  }
466}
467
468TEST(AddressSanitizer, HugeMallocTest) {
469#ifdef __APPLE__
470  // It was empirically found out that 1215 megabytes is the maximum amount of
471  // memory available to the process under AddressSanitizer on Darwin.
472  // (the libSystem malloc() allows allocating up to 2300 megabytes without
473  // ASan).
474  size_t n_megs = __WORDSIZE == 32 ? 1200 : 4100;
475#else
476  size_t n_megs = __WORDSIZE == 32 ? 2600 : 4100;
477#endif
478  TestLargeMalloc(n_megs << 20);
479}
480
481TEST(AddressSanitizer, ThreadedMallocStressTest) {
482  const int kNumThreads = 4;
483  pthread_t t[kNumThreads];
484  for (int i = 0; i < kNumThreads; i++) {
485    pthread_create(&t[i], 0, (void* (*)(void *x))MallocStress, (void*)100000);
486  }
487  for (int i = 0; i < kNumThreads; i++) {
488    pthread_join(t[i], 0);
489  }
490}
491
492void *ManyThreadsWorker(void *a) {
493  for (int iter = 0; iter < 100; iter++) {
494    for (size_t size = 100; size < 2000; size *= 2) {
495      free(Ident(malloc(size)));
496    }
497  }
498  return 0;
499}
500
501TEST(AddressSanitizer, ManyThreadsTest) {
502  const size_t kNumThreads = __WORDSIZE == 32 ? 30 : 1000;
503  pthread_t t[kNumThreads];
504  for (size_t i = 0; i < kNumThreads; i++) {
505    pthread_create(&t[i], 0, (void* (*)(void *x))ManyThreadsWorker, (void*)i);
506  }
507  for (size_t i = 0; i < kNumThreads; i++) {
508    pthread_join(t[i], 0);
509  }
510}
511
512TEST(AddressSanitizer, ReallocTest) {
513  const int kMinElem = 5;
514  int *ptr = (int*)malloc(sizeof(int) * kMinElem);
515  ptr[3] = 3;
516  for (int i = 0; i < 10000; i++) {
517    ptr = (int*)realloc(ptr,
518        (my_rand(&global_seed) % 1000 + kMinElem) * sizeof(int));
519    EXPECT_EQ(3, ptr[3]);
520  }
521}
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(), "ERROR: AddressSanitizer attempting double-free");
546}
547
548template<int kSize>
549__attribute__((noinline))
550void SizedStackTest() {
551  char a[kSize];
552  char  *A = Ident((char*)&a);
553  for (size_t i = 0; i < kSize; i++)
554    A[i] = i;
555  EXPECT_DEATH(A[-1] = 0, "");
556  EXPECT_DEATH(A[-20] = 0, "");
557  EXPECT_DEATH(A[-31] = 0, "");
558  EXPECT_DEATH(A[kSize] = 0, "");
559  EXPECT_DEATH(A[kSize + 1] = 0, "");
560  EXPECT_DEATH(A[kSize + 10] = 0, "");
561  EXPECT_DEATH(A[kSize + 31] = 0, "");
562}
563
564TEST(AddressSanitizer, SimpleStackTest) {
565  SizedStackTest<1>();
566  SizedStackTest<2>();
567  SizedStackTest<3>();
568  SizedStackTest<4>();
569  SizedStackTest<5>();
570  SizedStackTest<6>();
571  SizedStackTest<7>();
572  SizedStackTest<16>();
573  SizedStackTest<25>();
574  SizedStackTest<34>();
575  SizedStackTest<43>();
576  SizedStackTest<51>();
577  SizedStackTest<62>();
578  SizedStackTest<64>();
579  SizedStackTest<128>();
580}
581
582TEST(AddressSanitizer, ManyStackObjectsTest) {
583  char XXX[10];
584  char YYY[20];
585  char ZZZ[30];
586  Ident(XXX);
587  Ident(YYY);
588  EXPECT_DEATH(Ident(ZZZ)[-1] = 0, ASAN_PCRE_DOTALL "XXX.*YYY.*ZZZ");
589}
590
591__attribute__((noinline))
592static void Frame0(int frame, char *a, char *b, char *c) {
593  char d[4] = {0};
594  char *D = Ident(d);
595  switch (frame) {
596    case 3: a[5]++; break;
597    case 2: b[5]++; break;
598    case 1: c[5]++; break;
599    case 0: D[5]++; break;
600  }
601}
602__attribute__((noinline)) static void Frame1(int frame, char *a, char *b) {
603  char c[4] = {0}; Frame0(frame, a, b, c);
604  break_optimization(0);
605}
606__attribute__((noinline)) static void Frame2(int frame, char *a) {
607  char b[4] = {0}; Frame1(frame, a, b);
608  break_optimization(0);
609}
610__attribute__((noinline)) static void Frame3(int frame) {
611  char a[4] = {0}; Frame2(frame, a);
612  break_optimization(0);
613}
614
615TEST(AddressSanitizer, GuiltyStackFrame0Test) {
616  EXPECT_DEATH(Frame3(0), "located .*in frame <.*Frame0");
617}
618TEST(AddressSanitizer, GuiltyStackFrame1Test) {
619  EXPECT_DEATH(Frame3(1), "located .*in frame <.*Frame1");
620}
621TEST(AddressSanitizer, GuiltyStackFrame2Test) {
622  EXPECT_DEATH(Frame3(2), "located .*in frame <.*Frame2");
623}
624TEST(AddressSanitizer, GuiltyStackFrame3Test) {
625  EXPECT_DEATH(Frame3(3), "located .*in frame <.*Frame3");
626}
627
628__attribute__((noinline))
629void LongJmpFunc1(jmp_buf buf) {
630  // create three red zones for these two stack objects.
631  int a;
632  int b;
633
634  int *A = Ident(&a);
635  int *B = Ident(&b);
636  *A = *B;
637  longjmp(buf, 1);
638}
639
640__attribute__((noinline))
641void 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
652__attribute__((noinline))
653void SigLongJmpFunc1(sigjmp_buf buf) {
654  // create three red zones for these two stack objects.
655  int a;
656  int b;
657
658  int *A = Ident(&a);
659  int *B = Ident(&b);
660  *A = *B;
661  siglongjmp(buf, 1);
662}
663
664
665__attribute__((noinline))
666void TouchStackFunc() {
667  int a[100];  // long array will intersect with redzones from LongJmpFunc1.
668  int *A = Ident(a);
669  for (int i = 0; i < 100; i++)
670    A[i] = i*i;
671}
672
673// Test that we handle longjmp and do not report fals positives on stack.
674TEST(AddressSanitizer, LongJmpTest) {
675  static jmp_buf buf;
676  if (!setjmp(buf)) {
677    LongJmpFunc1(buf);
678  } else {
679    TouchStackFunc();
680  }
681}
682
683TEST(AddressSanitizer, UnderscopeLongJmpTest) {
684  static jmp_buf buf;
685  if (!_setjmp(buf)) {
686    UnderscopeLongJmpFunc1(buf);
687  } else {
688    TouchStackFunc();
689  }
690}
691
692TEST(AddressSanitizer, SigLongJmpTest) {
693  static sigjmp_buf buf;
694  if (!sigsetjmp(buf, 1)) {
695    SigLongJmpFunc1(buf);
696  } else {
697    TouchStackFunc();
698  }
699}
700
701#ifdef __EXCEPTIONS
702__attribute__((noinline))
703void ThrowFunc() {
704  // create three red zones for these two stack objects.
705  int a;
706  int b;
707
708  int *A = Ident(&a);
709  int *B = Ident(&b);
710  *A = *B;
711  ASAN_THROW(1);
712}
713
714TEST(AddressSanitizer, CxxExceptionTest) {
715  if (ASAN_UAR) return;
716  // TODO(kcc): this test crashes on 32-bit for some reason...
717  if (__WORDSIZE == 32) return;
718  try {
719    ThrowFunc();
720  } catch(...) {}
721  TouchStackFunc();
722}
723#endif
724
725void *ThreadStackReuseFunc1(void *unused) {
726  // create three red zones for these two stack objects.
727  int a;
728  int b;
729
730  int *A = Ident(&a);
731  int *B = Ident(&b);
732  *A = *B;
733  pthread_exit(0);
734  return 0;
735}
736
737void *ThreadStackReuseFunc2(void *unused) {
738  TouchStackFunc();
739  return 0;
740}
741
742TEST(AddressSanitizer, ThreadStackReuseTest) {
743  pthread_t t;
744  pthread_create(&t, 0, ThreadStackReuseFunc1, 0);
745  pthread_join(t, 0);
746  pthread_create(&t, 0, ThreadStackReuseFunc2, 0);
747  pthread_join(t, 0);
748}
749
750#if defined(__i386__) or defined(__x86_64__)
751TEST(AddressSanitizer, Store128Test) {
752  char *a = Ident((char*)malloc(Ident(12)));
753  char *p = a;
754  if (((uintptr_t)a % 16) != 0)
755    p = a + 8;
756  assert(((uintptr_t)p % 16) == 0);
757  __m128i value_wide = _mm_set1_epi16(0x1234);
758  EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
759               "AddressSanitizer heap-buffer-overflow");
760  EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
761               "WRITE of size 16");
762  EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
763               "located 0 bytes to the right of 12-byte");
764  free(a);
765}
766#endif
767
768static string RightOOBErrorMessage(int oob_distance) {
769  assert(oob_distance >= 0);
770  char expected_str[100];
771  sprintf(expected_str, "located %d bytes to the right", oob_distance);
772  return string(expected_str);
773}
774
775static string LeftOOBErrorMessage(int oob_distance) {
776  assert(oob_distance > 0);
777  char expected_str[100];
778  sprintf(expected_str, "located %d bytes to the left", oob_distance);
779  return string(expected_str);
780}
781
782template<class T>
783void MemSetOOBTestTemplate(size_t length) {
784  if (length == 0) return;
785  size_t size = Ident(sizeof(T) * length);
786  T *array = Ident((T*)malloc(size));
787  int element = Ident(42);
788  int zero = Ident(0);
789  // memset interval inside array
790  memset(array, element, size);
791  memset(array, element, size - 1);
792  memset(array + length - 1, element, sizeof(T));
793  memset(array, element, 1);
794
795  // memset 0 bytes
796  memset(array - 10, element, zero);
797  memset(array - 1, element, zero);
798  memset(array, element, zero);
799  memset(array + length, 0, zero);
800  memset(array + length + 1, 0, zero);
801
802  // try to memset bytes to the right of array
803  EXPECT_DEATH(memset(array, 0, size + 1),
804               RightOOBErrorMessage(0));
805  EXPECT_DEATH(memset((char*)(array + length) - 1, element, 6),
806               RightOOBErrorMessage(4));
807  EXPECT_DEATH(memset(array + 1, element, size + sizeof(T)),
808               RightOOBErrorMessage(2 * sizeof(T) - 1));
809  // whole interval is to the right
810  EXPECT_DEATH(memset(array + length + 1, 0, 10),
811               RightOOBErrorMessage(sizeof(T)));
812
813  // try to memset bytes to the left of array
814  EXPECT_DEATH(memset((char*)array - 1, element, size),
815               LeftOOBErrorMessage(1));
816  EXPECT_DEATH(memset((char*)array - 5, 0, 6),
817               LeftOOBErrorMessage(5));
818  EXPECT_DEATH(memset(array - 5, element, size + 5 * sizeof(T)),
819               LeftOOBErrorMessage(5 * sizeof(T)));
820  // whole interval is to the left
821  EXPECT_DEATH(memset(array - 2, 0, sizeof(T)),
822               LeftOOBErrorMessage(2 * sizeof(T)));
823
824  // try to memset bytes both to the left & to the right
825  EXPECT_DEATH(memset((char*)array - 2, element, size + 4),
826               LeftOOBErrorMessage(2));
827
828  free(array);
829}
830
831TEST(AddressSanitizer, MemSetOOBTest) {
832  MemSetOOBTestTemplate<char>(100);
833  MemSetOOBTestTemplate<int>(5);
834  MemSetOOBTestTemplate<double>(256);
835  // We can test arrays of structres/classes here, but what for?
836}
837
838// Same test for memcpy and memmove functions
839template <class T, class M>
840void MemTransferOOBTestTemplate(size_t length) {
841  if (length == 0) return;
842  size_t size = Ident(sizeof(T) * length);
843  T *src = Ident((T*)malloc(size));
844  T *dest = Ident((T*)malloc(size));
845  int zero = Ident(0);
846
847  // valid transfer of bytes between arrays
848  M::transfer(dest, src, size);
849  M::transfer(dest + 1, src, size - sizeof(T));
850  M::transfer(dest, src + length - 1, sizeof(T));
851  M::transfer(dest, src, 1);
852
853  // transfer zero bytes
854  M::transfer(dest - 1, src, 0);
855  M::transfer(dest + length, src, zero);
856  M::transfer(dest, src - 1, zero);
857  M::transfer(dest, src, zero);
858
859  // try to change mem to the right of dest
860  EXPECT_DEATH(M::transfer(dest + 1, src, size),
861               RightOOBErrorMessage(sizeof(T) - 1));
862  EXPECT_DEATH(M::transfer((char*)(dest + length) - 1, src, 5),
863               RightOOBErrorMessage(3));
864
865  // try to change mem to the left of dest
866  EXPECT_DEATH(M::transfer(dest - 2, src, size),
867               LeftOOBErrorMessage(2 * sizeof(T)));
868  EXPECT_DEATH(M::transfer((char*)dest - 3, src, 4),
869               LeftOOBErrorMessage(3));
870
871  // try to access mem to the right of src
872  EXPECT_DEATH(M::transfer(dest, src + 2, size),
873               RightOOBErrorMessage(2 * sizeof(T) - 1));
874  EXPECT_DEATH(M::transfer(dest, (char*)(src + length) - 3, 6),
875               RightOOBErrorMessage(2));
876
877  // try to access mem to the left of src
878  EXPECT_DEATH(M::transfer(dest, src - 1, size),
879               LeftOOBErrorMessage(sizeof(T)));
880  EXPECT_DEATH(M::transfer(dest, (char*)src - 6, 7),
881               LeftOOBErrorMessage(6));
882
883  // Generally we don't need to test cases where both accessing src and writing
884  // to dest address to poisoned memory.
885
886  T *big_src = Ident((T*)malloc(size * 2));
887  T *big_dest = Ident((T*)malloc(size * 2));
888  // try to change mem to both sides of dest
889  EXPECT_DEATH(M::transfer(dest - 1, big_src, size * 2),
890               LeftOOBErrorMessage(sizeof(T)));
891  // try to access mem to both sides of src
892  EXPECT_DEATH(M::transfer(big_dest, src - 2, size * 2),
893               LeftOOBErrorMessage(2 * sizeof(T)));
894
895  free(src);
896  free(dest);
897  free(big_src);
898  free(big_dest);
899}
900
901class MemCpyWrapper {
902 public:
903  static void* transfer(void *to, const void *from, size_t size) {
904    return memcpy(to, from, size);
905  }
906};
907TEST(AddressSanitizer, MemCpyOOBTest) {
908  MemTransferOOBTestTemplate<char, MemCpyWrapper>(100);
909  MemTransferOOBTestTemplate<int, MemCpyWrapper>(1024);
910}
911
912class MemMoveWrapper {
913 public:
914  static void* transfer(void *to, const void *from, size_t size) {
915    return memmove(to, from, size);
916  }
917};
918TEST(AddressSanitizer, MemMoveOOBTest) {
919  MemTransferOOBTestTemplate<char, MemMoveWrapper>(100);
920  MemTransferOOBTestTemplate<int, MemMoveWrapper>(1024);
921}
922
923// Tests for string functions
924
925// Used for string functions tests
926static char global_string[] = "global";
927static size_t global_string_length = 6;
928
929// Input to a test is a zero-terminated string str with given length
930// Accesses to the bytes to the left and to the right of str
931// are presumed to produce OOB errors
932void StrLenOOBTestTemplate(char *str, size_t length, bool is_global) {
933  // Normal strlen calls
934  EXPECT_EQ(strlen(str), length);
935  if (length > 0) {
936    EXPECT_EQ(strlen(str + 1), length - 1);
937    EXPECT_EQ(strlen(str + length), 0);
938  }
939  // Arg of strlen is not malloced, OOB access
940  if (!is_global) {
941    // We don't insert RedZones to the left of global variables
942    EXPECT_DEATH(Ident(strlen(str - 1)), LeftOOBErrorMessage(1));
943    EXPECT_DEATH(Ident(strlen(str - 5)), LeftOOBErrorMessage(5));
944  }
945  EXPECT_DEATH(Ident(strlen(str + length + 1)), RightOOBErrorMessage(0));
946  // Overwrite terminator
947  str[length] = 'a';
948  // String is not zero-terminated, strlen will lead to OOB access
949  EXPECT_DEATH(Ident(strlen(str)), RightOOBErrorMessage(0));
950  EXPECT_DEATH(Ident(strlen(str + length)), RightOOBErrorMessage(0));
951  // Restore terminator
952  str[length] = 0;
953}
954TEST(AddressSanitizer, StrLenOOBTest) {
955  // Check heap-allocated string
956  size_t length = Ident(10);
957  char *heap_string = Ident((char*)malloc(length + 1));
958  char stack_string[10 + 1];
959  for (int i = 0; i < length; i++) {
960    heap_string[i] = 'a';
961    stack_string[i] = 'b';
962  }
963  heap_string[length] = 0;
964  stack_string[length] = 0;
965  StrLenOOBTestTemplate(heap_string, length, false);
966  // TODO(samsonov): Fix expected messages in StrLenOOBTestTemplate to
967  //      make test for stack_string work. Or move it to output tests.
968  // StrLenOOBTestTemplate(stack_string, length, false);
969  StrLenOOBTestTemplate(global_string, global_string_length, true);
970  free(heap_string);
971}
972
973static inline char* MallocAndMemsetString(size_t size) {
974  char *s = Ident((char*)malloc(size));
975  memset(s, 'z', size);
976  return s;
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  // Catenate empty string is not always an error.
1258  strcat(to - 1, from + from_size - 1);
1259  // One of arguments points to not allocated memory.
1260  EXPECT_DEATH(strcat(to - 1, from), LeftOOBErrorMessage(1));
1261  EXPECT_DEATH(strcat(to, from - 1), LeftOOBErrorMessage(1));
1262  EXPECT_DEATH(strcat(to + to_size, from), RightOOBErrorMessage(0));
1263  EXPECT_DEATH(strcat(to, from + from_size), RightOOBErrorMessage(0));
1264
1265  // "from" is not zero-terminated.
1266  from[from_size - 1] = 'z';
1267  EXPECT_DEATH(strcat(to, from), RightOOBErrorMessage(0));
1268  from[from_size - 1] = '\0';
1269  // "to" is not zero-terminated.
1270  memset(to, 'z', to_size);
1271  EXPECT_DEATH(strcat(to, from), RightOOBErrorMessage(0));
1272  // "to" is too short to fit "from".
1273  to[to_size - from_size + 1] = '\0';
1274  EXPECT_DEATH(strcat(to, from), RightOOBErrorMessage(0));
1275  // length of "to" is just enough.
1276  strcat(to, from + 1);
1277}
1278
1279static string OverlapErrorMessage(const string &func) {
1280  return func + "-param-overlap";
1281}
1282
1283TEST(AddressSanitizer, StrArgsOverlapTest) {
1284  size_t size = Ident(100);
1285  char *str = Ident((char*)malloc(size));
1286
1287  // Check "memcpy". Use Ident() to avoid inlining.
1288  memset(str, 'z', size);
1289  Ident(memcpy)(str + 1, str + 11, 10);
1290  Ident(memcpy)(str, str, 0);
1291  EXPECT_DEATH(Ident(memcpy)(str, str + 14, 15), OverlapErrorMessage("memcpy"));
1292  EXPECT_DEATH(Ident(memcpy)(str + 14, str, 15), OverlapErrorMessage("memcpy"));
1293  EXPECT_DEATH(Ident(memcpy)(str + 20, str + 20, 1),
1294               OverlapErrorMessage("memcpy"));
1295
1296  // Check "strcpy".
1297  memset(str, 'z', size);
1298  str[9] = '\0';
1299  strcpy(str + 10, str);
1300  EXPECT_DEATH(strcpy(str + 9, str), OverlapErrorMessage("strcpy"));
1301  EXPECT_DEATH(strcpy(str, str + 4), OverlapErrorMessage("strcpy"));
1302  strcpy(str, str + 5);
1303
1304  // Check "strncpy".
1305  memset(str, 'z', size);
1306  strncpy(str, str + 10, 10);
1307  EXPECT_DEATH(strncpy(str, str + 9, 10), OverlapErrorMessage("strncpy"));
1308  EXPECT_DEATH(strncpy(str + 9, str, 10), OverlapErrorMessage("strncpy"));
1309  str[10] = '\0';
1310  strncpy(str + 11, str, 20);
1311  EXPECT_DEATH(strncpy(str + 10, str, 20), OverlapErrorMessage("strncpy"));
1312
1313  // Check "strcat".
1314  memset(str, 'z', size);
1315  str[10] = '\0';
1316  str[20] = '\0';
1317  strcat(str, str + 10);
1318  strcat(str, str + 11);
1319  str[10] = '\0';
1320  strcat(str + 11, str);
1321  EXPECT_DEATH(strcat(str, str + 9), OverlapErrorMessage("strcat"));
1322  EXPECT_DEATH(strcat(str + 9, str), OverlapErrorMessage("strcat"));
1323  EXPECT_DEATH(strcat(str + 10, str), OverlapErrorMessage("strcat"));
1324
1325  free(str);
1326}
1327
1328// At the moment we instrument memcpy/memove/memset calls at compile time so we
1329// can't handle OOB error if these functions are called by pointer, see disabled
1330// MemIntrinsicCallByPointerTest below
1331typedef void*(*PointerToMemTransfer)(void*, const void*, size_t);
1332typedef void*(*PointerToMemSet)(void*, int, size_t);
1333
1334void CallMemSetByPointer(PointerToMemSet MemSet) {
1335  size_t size = Ident(100);
1336  char *array = Ident((char*)malloc(size));
1337  EXPECT_DEATH(MemSet(array, 0, 101), RightOOBErrorMessage(0));
1338  free(array);
1339}
1340
1341void CallMemTransferByPointer(PointerToMemTransfer MemTransfer) {
1342  size_t size = Ident(100);
1343  char *src = Ident((char*)malloc(size));
1344  char *dst = Ident((char*)malloc(size));
1345  EXPECT_DEATH(MemTransfer(dst, src, 101), RightOOBErrorMessage(0));
1346  free(src);
1347  free(dst);
1348}
1349
1350TEST(AddressSanitizer, DISABLED_MemIntrinsicCallByPointerTest) {
1351  CallMemSetByPointer(&memset);
1352  CallMemTransferByPointer(&memcpy);
1353  CallMemTransferByPointer(&memmove);
1354}
1355
1356// This test case fails
1357// Clang optimizes memcpy/memset calls which lead to unaligned access
1358TEST(AddressSanitizer, DISABLED_MemIntrinsicUnalignedAccessTest) {
1359  int size = Ident(4096);
1360  char *s = Ident((char*)malloc(size));
1361  EXPECT_DEATH(memset(s + size - 1, 0, 2), RightOOBErrorMessage(0));
1362  free(s);
1363}
1364
1365// TODO(samsonov): Add a test with malloc(0)
1366// TODO(samsonov): Add tests for str* and mem* functions.
1367
1368__attribute__((noinline))
1369static int LargeFunction(bool do_bad_access) {
1370  int *x = new int[100];
1371  x[0]++;
1372  x[1]++;
1373  x[2]++;
1374  x[3]++;
1375  x[4]++;
1376  x[5]++;
1377  x[6]++;
1378  x[7]++;
1379  x[8]++;
1380  x[9]++;
1381
1382  x[do_bad_access ? 100 : 0]++; int res = __LINE__;
1383
1384  x[10]++;
1385  x[11]++;
1386  x[12]++;
1387  x[13]++;
1388  x[14]++;
1389  x[15]++;
1390  x[16]++;
1391  x[17]++;
1392  x[18]++;
1393  x[19]++;
1394
1395  delete x;
1396  return res;
1397}
1398
1399// Test the we have correct debug info for the failing instruction.
1400// This test requires the in-process symbolizer to be enabled by default.
1401TEST(AddressSanitizer, DISABLED_LargeFunctionSymbolizeTest) {
1402  int failing_line = LargeFunction(false);
1403  char expected_warning[128];
1404  sprintf(expected_warning, "LargeFunction.*asan_test.cc:%d", failing_line);
1405  EXPECT_DEATH(LargeFunction(true), expected_warning);
1406}
1407
1408// Check that we unwind and symbolize correctly.
1409TEST(AddressSanitizer, DISABLED_MallocFreeUnwindAndSymbolizeTest) {
1410  int *a = (int*)malloc_aaa(sizeof(int));
1411  *a = 1;
1412  free_aaa(a);
1413  EXPECT_DEATH(*a = 1, "free_ccc.*free_bbb.*free_aaa.*"
1414               "malloc_fff.*malloc_eee.*malloc_ddd");
1415}
1416
1417void *ThreadedTestAlloc(void *a) {
1418  int **p = (int**)a;
1419  *p = new int;
1420  return 0;
1421}
1422
1423void *ThreadedTestFree(void *a) {
1424  int **p = (int**)a;
1425  delete *p;
1426  return 0;
1427}
1428
1429void *ThreadedTestUse(void *a) {
1430  int **p = (int**)a;
1431  **p = 1;
1432  return 0;
1433}
1434
1435void ThreadedTestSpawn() {
1436  pthread_t t;
1437  int *x;
1438  pthread_create(&t, 0, ThreadedTestAlloc, &x);
1439  pthread_join(t, 0);
1440  pthread_create(&t, 0, ThreadedTestFree, &x);
1441  pthread_join(t, 0);
1442  pthread_create(&t, 0, ThreadedTestUse, &x);
1443  pthread_join(t, 0);
1444}
1445
1446TEST(AddressSanitizer, ThreadedTest) {
1447  EXPECT_DEATH(ThreadedTestSpawn(),
1448               ASAN_PCRE_DOTALL
1449               "Thread T.*created"
1450               ".*Thread T.*created"
1451               ".*Thread T.*created");
1452}
1453
1454#if ASAN_NEEDS_SEGV
1455TEST(AddressSanitizer, ShadowGapTest) {
1456#if __WORDSIZE == 32
1457  char *addr = (char*)0x22000000;
1458#else
1459  char *addr = (char*)0x0000100000080000;
1460#endif
1461  EXPECT_DEATH(*addr = 1, "AddressSanitizer crashed on unknown");
1462}
1463#endif  // ASAN_NEEDS_SEGV
1464
1465extern "C" {
1466__attribute__((noinline))
1467static void UseThenFreeThenUse() {
1468  char *x = Ident((char*)malloc(8));
1469  *x = 1;
1470  free_aaa(x);
1471  *x = 2;
1472}
1473}
1474
1475TEST(AddressSanitizer, UseThenFreeThenUseTest) {
1476  EXPECT_DEATH(UseThenFreeThenUse(), "freed by thread");
1477}
1478
1479TEST(AddressSanitizer, StrDupTest) {
1480  free(strdup(Ident("123")));
1481}
1482
1483// Currently we create and poison redzone at right of global variables.
1484char glob5[5];
1485static char static110[110];
1486const char ConstGlob[7] = {1, 2, 3, 4, 5, 6, 7};
1487static const char StaticConstGlob[3] = {9, 8, 7};
1488extern int GlobalsTest(int x);
1489
1490TEST(AddressSanitizer, GlobalTest) {
1491  static char func_static15[15];
1492
1493  static char fs1[10];
1494  static char fs2[10];
1495  static char fs3[10];
1496
1497  glob5[Ident(0)] = 0;
1498  glob5[Ident(1)] = 0;
1499  glob5[Ident(2)] = 0;
1500  glob5[Ident(3)] = 0;
1501  glob5[Ident(4)] = 0;
1502
1503  EXPECT_DEATH(glob5[Ident(5)] = 0,
1504               "0 bytes to the right of global variable.*glob5.* size 5");
1505  EXPECT_DEATH(glob5[Ident(5+6)] = 0,
1506               "6 bytes to the right of global variable.*glob5.* size 5");
1507  Ident(static110);  // avoid optimizations
1508  static110[Ident(0)] = 0;
1509  static110[Ident(109)] = 0;
1510  EXPECT_DEATH(static110[Ident(110)] = 0,
1511               "0 bytes to the right of global variable");
1512  EXPECT_DEATH(static110[Ident(110+7)] = 0,
1513               "7 bytes to the right of global variable");
1514
1515  Ident(func_static15);  // avoid optimizations
1516  func_static15[Ident(0)] = 0;
1517  EXPECT_DEATH(func_static15[Ident(15)] = 0,
1518               "0 bytes to the right of global variable");
1519  EXPECT_DEATH(func_static15[Ident(15 + 9)] = 0,
1520               "9 bytes to the right of global variable");
1521
1522  Ident(fs1);
1523  Ident(fs2);
1524  Ident(fs3);
1525
1526  // We don't create left redzones, so this is not 100% guaranteed to fail.
1527  // But most likely will.
1528  EXPECT_DEATH(fs2[Ident(-1)] = 0, "is located.*of global variable");
1529
1530  EXPECT_DEATH(Ident(Ident(ConstGlob)[8]),
1531               "is located 1 bytes to the right of .*ConstGlob");
1532  EXPECT_DEATH(Ident(Ident(StaticConstGlob)[5]),
1533               "is located 2 bytes to the right of .*StaticConstGlob");
1534
1535  // call stuff from another file.
1536  GlobalsTest(0);
1537}
1538
1539TEST(AddressSanitizer, GlobalStringConstTest) {
1540  static const char *zoo = "FOOBAR123";
1541  const char *p = Ident(zoo);
1542  EXPECT_DEATH(Ident(p[15]), "is ascii string 'FOOBAR123'");
1543}
1544
1545TEST(AddressSanitizer, FileNameInGlobalReportTest) {
1546  static char zoo[10];
1547  const char *p = Ident(zoo);
1548  // The file name should be present in the report.
1549  EXPECT_DEATH(Ident(p[15]), "zoo.*asan_test.cc");
1550}
1551
1552int *ReturnsPointerToALocalObject() {
1553  int a = 0;
1554  return Ident(&a);
1555}
1556
1557#if ASAN_UAR == 1
1558TEST(AddressSanitizer, LocalReferenceReturnTest) {
1559  int *(*f)() = Ident(ReturnsPointerToALocalObject);
1560  int *p = f();
1561  // Call 'f' a few more times, 'p' should still be poisoned.
1562  for (int i = 0; i < 32; i++)
1563    f();
1564  EXPECT_DEATH(*p = 1, "AddressSanitizer stack-use-after-return");
1565  EXPECT_DEATH(*p = 1, "is located.*in frame .*ReturnsPointerToALocal");
1566}
1567#endif
1568
1569template <int kSize>
1570__attribute__((noinline))
1571static void FuncWithStack() {
1572  char x[kSize];
1573  Ident(x)[0] = 0;
1574  Ident(x)[kSize-1] = 0;
1575}
1576
1577static void LotsOfStackReuse() {
1578  int LargeStack[10000];
1579  Ident(LargeStack)[0] = 0;
1580  for (int i = 0; i < 10000; i++) {
1581    FuncWithStack<128 * 1>();
1582    FuncWithStack<128 * 2>();
1583    FuncWithStack<128 * 4>();
1584    FuncWithStack<128 * 8>();
1585    FuncWithStack<128 * 16>();
1586    FuncWithStack<128 * 32>();
1587    FuncWithStack<128 * 64>();
1588    FuncWithStack<128 * 128>();
1589    FuncWithStack<128 * 256>();
1590    FuncWithStack<128 * 512>();
1591    Ident(LargeStack)[0] = 0;
1592  }
1593}
1594
1595TEST(AddressSanitizer, StressStackReuseTest) {
1596  LotsOfStackReuse();
1597}
1598
1599TEST(AddressSanitizer, ThreadedStressStackReuseTest) {
1600  const int kNumThreads = 20;
1601  pthread_t t[kNumThreads];
1602  for (int i = 0; i < kNumThreads; i++) {
1603    pthread_create(&t[i], 0, (void* (*)(void *x))LotsOfStackReuse, 0);
1604  }
1605  for (int i = 0; i < kNumThreads; i++) {
1606    pthread_join(t[i], 0);
1607  }
1608}
1609
1610#ifdef __EXCEPTIONS
1611__attribute__((noinline))
1612static void StackReuseAndException() {
1613  int large_stack[1000];
1614  Ident(large_stack);
1615  ASAN_THROW(1);
1616}
1617
1618// TODO(kcc): support exceptions with use-after-return.
1619TEST(AddressSanitizer, DISABLED_StressStackReuseAndExceptionsTest) {
1620  for (int i = 0; i < 10000; i++) {
1621    try {
1622    StackReuseAndException();
1623    } catch(...) {
1624    }
1625  }
1626}
1627#endif
1628
1629TEST(AddressSanitizer, MlockTest) {
1630  EXPECT_EQ(0, mlockall(MCL_CURRENT));
1631  EXPECT_EQ(0, mlock((void*)0x12345, 0x5678));
1632  EXPECT_EQ(0, munlockall());
1633  EXPECT_EQ(0, munlock((void*)0x987, 0x654));
1634}
1635
1636// ------------------ demo tests; run each one-by-one -------------
1637// e.g. --gtest_filter=*DemoOOBLeftHigh --gtest_also_run_disabled_tests
1638TEST(AddressSanitizer, DISABLED_DemoThreadedTest) {
1639  ThreadedTestSpawn();
1640}
1641
1642void *SimpleBugOnSTack(void *x = 0) {
1643  char a[20];
1644  Ident(a)[20] = 0;
1645  return 0;
1646}
1647
1648TEST(AddressSanitizer, DISABLED_DemoStackTest) {
1649  SimpleBugOnSTack();
1650}
1651
1652TEST(AddressSanitizer, DISABLED_DemoThreadStackTest) {
1653  pthread_t t;
1654  pthread_create(&t, 0, SimpleBugOnSTack, 0);
1655  pthread_join(t, 0);
1656}
1657
1658TEST(AddressSanitizer, DISABLED_DemoUAFLowIn) {
1659  uaf_test<U1>(10, 0);
1660}
1661TEST(AddressSanitizer, DISABLED_DemoUAFLowLeft) {
1662  uaf_test<U1>(10, -2);
1663}
1664TEST(AddressSanitizer, DISABLED_DemoUAFLowRight) {
1665  uaf_test<U1>(10, 10);
1666}
1667
1668TEST(AddressSanitizer, DISABLED_DemoUAFHigh) {
1669  uaf_test<U1>(kLargeMalloc, 0);
1670}
1671
1672TEST(AddressSanitizer, DISABLED_DemoOOBLeftLow) {
1673  oob_test<U1>(10, -1);
1674}
1675
1676TEST(AddressSanitizer, DISABLED_DemoOOBLeftHigh) {
1677  oob_test<U1>(kLargeMalloc, -1);
1678}
1679
1680TEST(AddressSanitizer, DISABLED_DemoOOBRightLow) {
1681  oob_test<U1>(10, 10);
1682}
1683
1684TEST(AddressSanitizer, DISABLED_DemoOOBRightHigh) {
1685  oob_test<U1>(kLargeMalloc, kLargeMalloc);
1686}
1687
1688TEST(AddressSanitizer, DISABLED_DemoOOM) {
1689  size_t size = __WORDSIZE == 64 ? (size_t)(1ULL << 40) : (0xf0000000);
1690  printf("%p\n", malloc(size));
1691}
1692
1693TEST(AddressSanitizer, DISABLED_DemoDoubleFreeTest) {
1694  DoubleFree();
1695}
1696
1697TEST(AddressSanitizer, DISABLED_DemoNullDerefTest) {
1698  int *a = 0;
1699  Ident(a)[10] = 0;
1700}
1701
1702TEST(AddressSanitizer, DISABLED_DemoFunctionStaticTest) {
1703  static char a[100];
1704  static char b[100];
1705  static char c[100];
1706  Ident(a);
1707  Ident(b);
1708  Ident(c);
1709  Ident(a)[5] = 0;
1710  Ident(b)[105] = 0;
1711  Ident(a)[5] = 0;
1712}
1713
1714TEST(AddressSanitizer, DISABLED_DemoTooMuchMemoryTest) {
1715  const size_t kAllocSize = (1 << 28) - 1024;
1716  size_t total_size = 0;
1717  while (true) {
1718    char *x = (char*)malloc(kAllocSize);
1719    memset(x, 0, kAllocSize);
1720    total_size += kAllocSize;
1721    fprintf(stderr, "total: %ldM\n", (long)total_size >> 20);
1722  }
1723}
1724
1725#ifdef __APPLE__
1726#include "asan_mac_test.h"
1727// TODO(glider): figure out whether we still need these tests. Is it correct
1728// to intercept CFAllocator?
1729TEST(AddressSanitizerMac, DISABLED_CFAllocatorDefaultDoubleFree) {
1730  EXPECT_DEATH(
1731      CFAllocatorDefaultDoubleFree(),
1732      "attempting double-free");
1733}
1734
1735TEST(AddressSanitizerMac, DISABLED_CFAllocatorSystemDefaultDoubleFree) {
1736  EXPECT_DEATH(
1737      CFAllocatorSystemDefaultDoubleFree(),
1738      "attempting double-free");
1739}
1740
1741TEST(AddressSanitizerMac, DISABLED_CFAllocatorMallocDoubleFree) {
1742  EXPECT_DEATH(CFAllocatorMallocDoubleFree(), "attempting double-free");
1743}
1744
1745TEST(AddressSanitizerMac, DISABLED_CFAllocatorMallocZoneDoubleFree) {
1746  EXPECT_DEATH(CFAllocatorMallocZoneDoubleFree(), "attempting double-free");
1747}
1748
1749TEST(AddressSanitizerMac, GCDDispatchAsync) {
1750  // Make sure the whole ASan report is printed, i.e. that we don't die
1751  // on a CHECK.
1752  EXPECT_DEATH(TestGCDDispatchAsync(), "Shadow byte and word");
1753}
1754
1755TEST(AddressSanitizerMac, GCDDispatchSync) {
1756  // Make sure the whole ASan report is printed, i.e. that we don't die
1757  // on a CHECK.
1758  EXPECT_DEATH(TestGCDDispatchSync(), "Shadow byte and word");
1759}
1760
1761
1762TEST(AddressSanitizerMac, GCDReuseWqthreadsAsync) {
1763  // Make sure the whole ASan report is printed, i.e. that we don't die
1764  // on a CHECK.
1765  EXPECT_DEATH(TestGCDReuseWqthreadsAsync(), "Shadow byte and word");
1766}
1767
1768TEST(AddressSanitizerMac, GCDReuseWqthreadsSync) {
1769  // Make sure the whole ASan report is printed, i.e. that we don't die
1770  // on a CHECK.
1771  EXPECT_DEATH(TestGCDReuseWqthreadsSync(), "Shadow byte and word");
1772}
1773
1774TEST(AddressSanitizerMac, GCDDispatchAfter) {
1775  // Make sure the whole ASan report is printed, i.e. that we don't die
1776  // on a CHECK.
1777  EXPECT_DEATH(TestGCDDispatchAfter(), "Shadow byte and word");
1778}
1779
1780TEST(AddressSanitizerMac, GCDSourceEvent) {
1781  // Make sure the whole ASan report is printed, i.e. that we don't die
1782  // on a CHECK.
1783  EXPECT_DEATH(TestGCDSourceEvent(), "Shadow byte and word");
1784}
1785
1786TEST(AddressSanitizerMac, GCDSourceCancel) {
1787  // Make sure the whole ASan report is printed, i.e. that we don't die
1788  // on a CHECK.
1789  EXPECT_DEATH(TestGCDSourceCancel(), "Shadow byte and word");
1790}
1791
1792TEST(AddressSanitizerMac, GCDGroupAsync) {
1793  // Make sure the whole ASan report is printed, i.e. that we don't die
1794  // on a CHECK.
1795  EXPECT_DEATH(TestGCDGroupAsync(), "Shadow byte and word");
1796}
1797
1798void *MallocIntrospectionLockWorker(void *_) {
1799  const int kNumPointers = 100;
1800  int i;
1801  void *pointers[kNumPointers];
1802  for (i = 0; i < kNumPointers; i++) {
1803    pointers[i] = malloc(i + 1);
1804  }
1805  for (i = 0; i < kNumPointers; i++) {
1806    free(pointers[i]);
1807  }
1808
1809  return NULL;
1810}
1811
1812void *MallocIntrospectionLockForker(void *_) {
1813  pid_t result = fork();
1814  if (result == -1) {
1815    perror("fork");
1816  }
1817  assert(result != -1);
1818  if (result == 0) {
1819    // Call malloc in the child process to make sure we won't deadlock.
1820    void *ptr = malloc(42);
1821    free(ptr);
1822    exit(0);
1823  } else {
1824    // Return in the parent process.
1825    return NULL;
1826  }
1827}
1828
1829TEST(AddressSanitizerMac, MallocIntrospectionLock) {
1830  // Incorrect implementation of force_lock and force_unlock in our malloc zone
1831  // will cause forked processes to deadlock.
1832  // TODO(glider): need to detect that none of the child processes deadlocked.
1833  const int kNumWorkers = 5, kNumIterations = 100;
1834  int i, iter;
1835  for (iter = 0; iter < kNumIterations; iter++) {
1836    pthread_t workers[kNumWorkers], forker;
1837    for (i = 0; i < kNumWorkers; i++) {
1838      pthread_create(&workers[i], 0, MallocIntrospectionLockWorker, 0);
1839    }
1840    pthread_create(&forker, 0, MallocIntrospectionLockForker, 0);
1841    for (i = 0; i < kNumWorkers; i++) {
1842      pthread_join(workers[i], 0);
1843    }
1844    pthread_join(forker, 0);
1845  }
1846}
1847
1848void *TSDAllocWorker(void *test_key) {
1849  if (test_key) {
1850    void *mem = malloc(10);
1851    pthread_setspecific(*(pthread_key_t*)test_key, mem);
1852  }
1853  return NULL;
1854}
1855
1856TEST(AddressSanitizerMac, DISABLED_TSDWorkqueueTest) {
1857  pthread_t th;
1858  pthread_key_t test_key;
1859  pthread_key_create(&test_key, CallFreeOnWorkqueue);
1860  pthread_create(&th, NULL, TSDAllocWorker, &test_key);
1861  pthread_join(th, NULL);
1862  pthread_key_delete(test_key);
1863}
1864#endif  // __APPLE__
1865
1866int main(int argc, char **argv) {
1867  progname = argv[0];
1868  testing::GTEST_FLAG(death_test_style) = "threadsafe";
1869  testing::InitGoogleTest(&argc, argv);
1870  return RUN_ALL_TESTS();
1871}
1872