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