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