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