asan_test.cc revision c3a5c173f228cbb15e332e6bbc17c76ebd55d7a8
15821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===-- asan_test.cc ------------------------------------------------------===//
25821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
35821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//                     The LLVM Compiler Infrastructure
45821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
55821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// This file is distributed under the University of Illinois Open Source
65821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// License. See LICENSE.TXT for details.
7a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)//
8a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)//===----------------------------------------------------------------------===//
95821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// This file is a part of AddressSanitizer, an address sanity checker.
117d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)//
121320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci//===----------------------------------------------------------------------===//
135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <stdio.h>
14a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include <signal.h>
155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <stdlib.h>
165821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <string.h>
175821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <strings.h>
185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <pthread.h>
195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <stdint.h>
205821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <setjmp.h>
215821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <assert.h>
225821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#if defined(__i386__) || defined(__x86_64__)
245821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <emmintrin.h>
255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#endif
265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "asan_test_utils.h"
285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#ifndef __APPLE__
305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <malloc.h>
315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#else
325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <malloc/malloc.h>
335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <AvailabilityMacros.h>  // For MAC_OS_X_VERSION_*
345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <CoreFoundation/CFString.h>
355821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#endif  // __APPLE__
36a36e5920737c6adbddd3e43b760e5de8431db6e0Torne (Richard Coles)
375821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#if ASAN_HAS_EXCEPTIONS
385821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)# define ASAN_THROW(x) throw (x)
395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#else
405821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)# define ASAN_THROW(x)
415821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#endif
425821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <sys/mman.h>
445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)typedef uint8_t   U1;
465821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)typedef uint16_t  U2;
475821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)typedef uint32_t  U4;
485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)typedef uint64_t  U8;
495821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
505821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static const int kPageSize = 4096;
515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// Simple stand-alone pseudorandom number generator.
535821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// Current algorithm is ANSI C linear congruential PRNG.
545821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static inline uint32_t my_rand(uint32_t* state) {
555821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  return (*state = *state * 1103515245 + 12345) >> 16;
565821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
575821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
585821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static uint32_t global_seed = 0;
595821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
605821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)const size_t kLargeMalloc = 1 << 24;
615821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
625821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)template<typename T>
635821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)NOINLINE void asan_write(T *a) {
645821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  *a = 0;
655821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
665821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
675821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)NOINLINE void asan_write_sized_aligned(uint8_t *p, size_t size) {
685821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  EXPECT_EQ(0U, ((uintptr_t)p % size));
695821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if      (size == 1) asan_write((uint8_t*)p);
705821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  else if (size == 2) asan_write((uint16_t*)p);
715821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  else if (size == 4) asan_write((uint32_t*)p);
725821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  else if (size == 8) asan_write((uint64_t*)p);
735821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
745821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
752a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)NOINLINE void *malloc_fff(size_t size) {
762a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  void *res = malloc/**/(size); break_optimization(0); return res;}
775821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)NOINLINE void *malloc_eee(size_t size) {
782a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  void *res = malloc_fff(size); break_optimization(0); return res;}
795821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)NOINLINE void *malloc_ddd(size_t size) {
801320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  void *res = malloc_eee(size); break_optimization(0); return res;}
815821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)NOINLINE void *malloc_ccc(size_t size) {
825821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  void *res = malloc_ddd(size); break_optimization(0); return res;}
835821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)NOINLINE void *malloc_bbb(size_t size) {
845821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  void *res = malloc_ccc(size); break_optimization(0); return res;}
855821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)NOINLINE void *malloc_aaa(size_t size) {
861320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  void *res = malloc_bbb(size); break_optimization(0); return res;}
871320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
881320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#ifndef __APPLE__
895821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)NOINLINE void *memalign_fff(size_t alignment, size_t size) {
905821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  void *res = memalign/**/(alignment, size); break_optimization(0); return res;}
915821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)NOINLINE void *memalign_eee(size_t alignment, size_t size) {
925821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  void *res = memalign_fff(alignment, size); break_optimization(0); return res;}
935821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)NOINLINE void *memalign_ddd(size_t alignment, size_t size) {
945821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  void *res = memalign_eee(alignment, size); break_optimization(0); return res;}
955821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)NOINLINE void *memalign_ccc(size_t alignment, size_t size) {
965821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  void *res = memalign_ddd(alignment, size); break_optimization(0); return res;}
975821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)NOINLINE void *memalign_bbb(size_t alignment, size_t size) {
985821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  void *res = memalign_ccc(alignment, size); break_optimization(0); return res;}
995821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)NOINLINE void *memalign_aaa(size_t alignment, size_t size) {
1005821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  void *res = memalign_bbb(alignment, size); break_optimization(0); return res;}
1015821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#endif  // __APPLE__
1025821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1035821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1045821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)NOINLINE void free_ccc(void *p) { free(p); break_optimization(0);}
1055821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)NOINLINE void free_bbb(void *p) { free_ccc(p); break_optimization(0);}
1065821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)NOINLINE void free_aaa(void *p) { free_bbb(p); break_optimization(0);}
1075821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1085821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)template<typename T>
1095821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)NOINLINE void oob_test(int size, int off) {
1105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  char *p = (char*)malloc_aaa(size);
1115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // fprintf(stderr, "writing %d byte(s) into [%p,%p) with offset %d\n",
1125821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  //        sizeof(T), p, p + size, off);
1135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  asan_write((T*)(p + off));
1145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  free_aaa(p);
1155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
1161320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
1171320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
1185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)template<typename T>
1195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)NOINLINE void uaf_test(int size, int off) {
1205821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  char *p = (char *)malloc_aaa(size);
1215821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  free_aaa(p);
1225821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  for (int i = 1; i < 100; i++)
123a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    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
691TEST(AddressSanitizer, BuiltinLongJmpTest) {
692  static jmp_buf buf;
693  if (!__builtin_setjmp((void**)buf)) {
694    BuiltinLongJmpFunc1(buf);
695  } else {
696    TouchStackFunc();
697  }
698}
699
700TEST(AddressSanitizer, UnderscopeLongJmpTest) {
701  static jmp_buf buf;
702  if (!_setjmp(buf)) {
703    UnderscopeLongJmpFunc1(buf);
704  } else {
705    TouchStackFunc();
706  }
707}
708
709TEST(AddressSanitizer, SigLongJmpTest) {
710  static sigjmp_buf buf;
711  if (!sigsetjmp(buf, 1)) {
712    SigLongJmpFunc1(buf);
713  } else {
714    TouchStackFunc();
715  }
716}
717
718#ifdef __EXCEPTIONS
719NOINLINE void ThrowFunc() {
720  // create three red zones for these two stack objects.
721  int a;
722  int b;
723
724  int *A = Ident(&a);
725  int *B = Ident(&b);
726  *A = *B;
727  ASAN_THROW(1);
728}
729
730TEST(AddressSanitizer, CxxExceptionTest) {
731  if (ASAN_UAR) return;
732  // TODO(kcc): this test crashes on 32-bit for some reason...
733  if (SANITIZER_WORDSIZE == 32) return;
734  try {
735    ThrowFunc();
736  } catch(...) {}
737  TouchStackFunc();
738}
739#endif
740
741void *ThreadStackReuseFunc1(void *unused) {
742  // create three red zones for these two stack objects.
743  int a;
744  int b;
745
746  int *A = Ident(&a);
747  int *B = Ident(&b);
748  *A = *B;
749  pthread_exit(0);
750  return 0;
751}
752
753void *ThreadStackReuseFunc2(void *unused) {
754  TouchStackFunc();
755  return 0;
756}
757
758TEST(AddressSanitizer, ThreadStackReuseTest) {
759  pthread_t t;
760  pthread_create(&t, 0, ThreadStackReuseFunc1, 0);
761  pthread_join(t, 0);
762  pthread_create(&t, 0, ThreadStackReuseFunc2, 0);
763  pthread_join(t, 0);
764}
765
766#if defined(__i386__) || defined(__x86_64__)
767TEST(AddressSanitizer, Store128Test) {
768  char *a = Ident((char*)malloc(Ident(12)));
769  char *p = a;
770  if (((uintptr_t)a % 16) != 0)
771    p = a + 8;
772  assert(((uintptr_t)p % 16) == 0);
773  __m128i value_wide = _mm_set1_epi16(0x1234);
774  EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
775               "AddressSanitizer: heap-buffer-overflow");
776  EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
777               "WRITE of size 16");
778  EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
779               "located 0 bytes to the right of 12-byte");
780  free(a);
781}
782#endif
783
784static string RightOOBErrorMessage(int oob_distance) {
785  assert(oob_distance >= 0);
786  char expected_str[100];
787  sprintf(expected_str, "located %d bytes to the right", oob_distance);
788  return string(expected_str);
789}
790
791static string LeftOOBErrorMessage(int oob_distance) {
792  assert(oob_distance > 0);
793  char expected_str[100];
794  sprintf(expected_str, "located %d bytes to the left", oob_distance);
795  return string(expected_str);
796}
797
798template<typename T>
799void MemSetOOBTestTemplate(size_t length) {
800  if (length == 0) return;
801  size_t size = Ident(sizeof(T) * length);
802  T *array = Ident((T*)malloc(size));
803  int element = Ident(42);
804  int zero = Ident(0);
805  // memset interval inside array
806  memset(array, element, size);
807  memset(array, element, size - 1);
808  memset(array + length - 1, element, sizeof(T));
809  memset(array, element, 1);
810
811  // memset 0 bytes
812  memset(array - 10, element, zero);
813  memset(array - 1, element, zero);
814  memset(array, element, zero);
815  memset(array + length, 0, zero);
816  memset(array + length + 1, 0, zero);
817
818  // try to memset bytes to the right of array
819  EXPECT_DEATH(memset(array, 0, size + 1),
820               RightOOBErrorMessage(0));
821  EXPECT_DEATH(memset((char*)(array + length) - 1, element, 6),
822               RightOOBErrorMessage(4));
823  EXPECT_DEATH(memset(array + 1, element, size + sizeof(T)),
824               RightOOBErrorMessage(2 * sizeof(T) - 1));
825  // whole interval is to the right
826  EXPECT_DEATH(memset(array + length + 1, 0, 10),
827               RightOOBErrorMessage(sizeof(T)));
828
829  // try to memset bytes to the left of array
830  EXPECT_DEATH(memset((char*)array - 1, element, size),
831               LeftOOBErrorMessage(1));
832  EXPECT_DEATH(memset((char*)array - 5, 0, 6),
833               LeftOOBErrorMessage(5));
834  EXPECT_DEATH(memset(array - 5, element, size + 5 * sizeof(T)),
835               LeftOOBErrorMessage(5 * sizeof(T)));
836  // whole interval is to the left
837  EXPECT_DEATH(memset(array - 2, 0, sizeof(T)),
838               LeftOOBErrorMessage(2 * sizeof(T)));
839
840  // try to memset bytes both to the left & to the right
841  EXPECT_DEATH(memset((char*)array - 2, element, size + 4),
842               LeftOOBErrorMessage(2));
843
844  free(array);
845}
846
847TEST(AddressSanitizer, MemSetOOBTest) {
848  MemSetOOBTestTemplate<char>(100);
849  MemSetOOBTestTemplate<int>(5);
850  MemSetOOBTestTemplate<double>(256);
851  // We can test arrays of structres/classes here, but what for?
852}
853
854// Same test for memcpy and memmove functions
855template <typename T, class M>
856void MemTransferOOBTestTemplate(size_t length) {
857  if (length == 0) return;
858  size_t size = Ident(sizeof(T) * length);
859  T *src = Ident((T*)malloc(size));
860  T *dest = Ident((T*)malloc(size));
861  int zero = Ident(0);
862
863  // valid transfer of bytes between arrays
864  M::transfer(dest, src, size);
865  M::transfer(dest + 1, src, size - sizeof(T));
866  M::transfer(dest, src + length - 1, sizeof(T));
867  M::transfer(dest, src, 1);
868
869  // transfer zero bytes
870  M::transfer(dest - 1, src, 0);
871  M::transfer(dest + length, src, zero);
872  M::transfer(dest, src - 1, zero);
873  M::transfer(dest, src, zero);
874
875  // try to change mem to the right of dest
876  EXPECT_DEATH(M::transfer(dest + 1, src, size),
877               RightOOBErrorMessage(sizeof(T) - 1));
878  EXPECT_DEATH(M::transfer((char*)(dest + length) - 1, src, 5),
879               RightOOBErrorMessage(3));
880
881  // try to change mem to the left of dest
882  EXPECT_DEATH(M::transfer(dest - 2, src, size),
883               LeftOOBErrorMessage(2 * sizeof(T)));
884  EXPECT_DEATH(M::transfer((char*)dest - 3, src, 4),
885               LeftOOBErrorMessage(3));
886
887  // try to access mem to the right of src
888  EXPECT_DEATH(M::transfer(dest, src + 2, size),
889               RightOOBErrorMessage(2 * sizeof(T) - 1));
890  EXPECT_DEATH(M::transfer(dest, (char*)(src + length) - 3, 6),
891               RightOOBErrorMessage(2));
892
893  // try to access mem to the left of src
894  EXPECT_DEATH(M::transfer(dest, src - 1, size),
895               LeftOOBErrorMessage(sizeof(T)));
896  EXPECT_DEATH(M::transfer(dest, (char*)src - 6, 7),
897               LeftOOBErrorMessage(6));
898
899  // Generally we don't need to test cases where both accessing src and writing
900  // to dest address to poisoned memory.
901
902  T *big_src = Ident((T*)malloc(size * 2));
903  T *big_dest = Ident((T*)malloc(size * 2));
904  // try to change mem to both sides of dest
905  EXPECT_DEATH(M::transfer(dest - 1, big_src, size * 2),
906               LeftOOBErrorMessage(sizeof(T)));
907  // try to access mem to both sides of src
908  EXPECT_DEATH(M::transfer(big_dest, src - 2, size * 2),
909               LeftOOBErrorMessage(2 * sizeof(T)));
910
911  free(src);
912  free(dest);
913  free(big_src);
914  free(big_dest);
915}
916
917class MemCpyWrapper {
918 public:
919  static void* transfer(void *to, const void *from, size_t size) {
920    return memcpy(to, from, size);
921  }
922};
923TEST(AddressSanitizer, MemCpyOOBTest) {
924  MemTransferOOBTestTemplate<char, MemCpyWrapper>(100);
925  MemTransferOOBTestTemplate<int, MemCpyWrapper>(1024);
926}
927
928class MemMoveWrapper {
929 public:
930  static void* transfer(void *to, const void *from, size_t size) {
931    return memmove(to, from, size);
932  }
933};
934TEST(AddressSanitizer, MemMoveOOBTest) {
935  MemTransferOOBTestTemplate<char, MemMoveWrapper>(100);
936  MemTransferOOBTestTemplate<int, MemMoveWrapper>(1024);
937}
938
939// Tests for string functions
940
941// Used for string functions tests
942static char global_string[] = "global";
943static size_t global_string_length = 6;
944
945// Input to a test is a zero-terminated string str with given length
946// Accesses to the bytes to the left and to the right of str
947// are presumed to produce OOB errors
948void StrLenOOBTestTemplate(char *str, size_t length, bool is_global) {
949  // Normal strlen calls
950  EXPECT_EQ(strlen(str), length);
951  if (length > 0) {
952    EXPECT_EQ(length - 1, strlen(str + 1));
953    EXPECT_EQ(0U, strlen(str + length));
954  }
955  // Arg of strlen is not malloced, OOB access
956  if (!is_global) {
957    // We don't insert RedZones to the left of global variables
958    EXPECT_DEATH(Ident(strlen(str - 1)), LeftOOBErrorMessage(1));
959    EXPECT_DEATH(Ident(strlen(str - 5)), LeftOOBErrorMessage(5));
960  }
961  EXPECT_DEATH(Ident(strlen(str + length + 1)), RightOOBErrorMessage(0));
962  // Overwrite terminator
963  str[length] = 'a';
964  // String is not zero-terminated, strlen will lead to OOB access
965  EXPECT_DEATH(Ident(strlen(str)), RightOOBErrorMessage(0));
966  EXPECT_DEATH(Ident(strlen(str + length)), RightOOBErrorMessage(0));
967  // Restore terminator
968  str[length] = 0;
969}
970TEST(AddressSanitizer, StrLenOOBTest) {
971  // Check heap-allocated string
972  size_t length = Ident(10);
973  char *heap_string = Ident((char*)malloc(length + 1));
974  char stack_string[10 + 1];
975  for (size_t i = 0; i < length; i++) {
976    heap_string[i] = 'a';
977    stack_string[i] = 'b';
978  }
979  heap_string[length] = 0;
980  stack_string[length] = 0;
981  StrLenOOBTestTemplate(heap_string, length, false);
982  // TODO(samsonov): Fix expected messages in StrLenOOBTestTemplate to
983  //      make test for stack_string work. Or move it to output tests.
984  // StrLenOOBTestTemplate(stack_string, length, false);
985  StrLenOOBTestTemplate(global_string, global_string_length, true);
986  free(heap_string);
987}
988
989static inline char* MallocAndMemsetString(size_t size, char ch) {
990  char *s = Ident((char*)malloc(size));
991  memset(s, ch, size);
992  return s;
993}
994static inline char* MallocAndMemsetString(size_t size) {
995  return MallocAndMemsetString(size, 'z');
996}
997
998#ifndef __APPLE__
999TEST(AddressSanitizer, StrNLenOOBTest) {
1000  size_t size = Ident(123);
1001  char *str = MallocAndMemsetString(size);
1002  // Normal strnlen calls.
1003  Ident(strnlen(str - 1, 0));
1004  Ident(strnlen(str, size));
1005  Ident(strnlen(str + size - 1, 1));
1006  str[size - 1] = '\0';
1007  Ident(strnlen(str, 2 * size));
1008  // Argument points to not allocated memory.
1009  EXPECT_DEATH(Ident(strnlen(str - 1, 1)), LeftOOBErrorMessage(1));
1010  EXPECT_DEATH(Ident(strnlen(str + size, 1)), RightOOBErrorMessage(0));
1011  // Overwrite the terminating '\0' and hit unallocated memory.
1012  str[size - 1] = 'z';
1013  EXPECT_DEATH(Ident(strnlen(str, size + 1)), RightOOBErrorMessage(0));
1014  free(str);
1015}
1016#endif
1017
1018TEST(AddressSanitizer, StrDupOOBTest) {
1019  size_t size = Ident(42);
1020  char *str = MallocAndMemsetString(size);
1021  char *new_str;
1022  // Normal strdup calls.
1023  str[size - 1] = '\0';
1024  new_str = strdup(str);
1025  free(new_str);
1026  new_str = strdup(str + size - 1);
1027  free(new_str);
1028  // Argument points to not allocated memory.
1029  EXPECT_DEATH(Ident(strdup(str - 1)), LeftOOBErrorMessage(1));
1030  EXPECT_DEATH(Ident(strdup(str + size)), RightOOBErrorMessage(0));
1031  // Overwrite the terminating '\0' and hit unallocated memory.
1032  str[size - 1] = 'z';
1033  EXPECT_DEATH(Ident(strdup(str)), RightOOBErrorMessage(0));
1034  free(str);
1035}
1036
1037TEST(AddressSanitizer, StrCpyOOBTest) {
1038  size_t to_size = Ident(30);
1039  size_t from_size = Ident(6);  // less than to_size
1040  char *to = Ident((char*)malloc(to_size));
1041  char *from = Ident((char*)malloc(from_size));
1042  // Normal strcpy calls.
1043  strcpy(from, "hello");
1044  strcpy(to, from);
1045  strcpy(to + to_size - from_size, from);
1046  // Length of "from" is too small.
1047  EXPECT_DEATH(Ident(strcpy(from, "hello2")), RightOOBErrorMessage(0));
1048  // "to" or "from" points to not allocated memory.
1049  EXPECT_DEATH(Ident(strcpy(to - 1, from)), LeftOOBErrorMessage(1));
1050  EXPECT_DEATH(Ident(strcpy(to, from - 1)), LeftOOBErrorMessage(1));
1051  EXPECT_DEATH(Ident(strcpy(to, from + from_size)), RightOOBErrorMessage(0));
1052  EXPECT_DEATH(Ident(strcpy(to + to_size, from)), RightOOBErrorMessage(0));
1053  // Overwrite the terminating '\0' character and hit unallocated memory.
1054  from[from_size - 1] = '!';
1055  EXPECT_DEATH(Ident(strcpy(to, from)), RightOOBErrorMessage(0));
1056  free(to);
1057  free(from);
1058}
1059
1060TEST(AddressSanitizer, StrNCpyOOBTest) {
1061  size_t to_size = Ident(20);
1062  size_t from_size = Ident(6);  // less than to_size
1063  char *to = Ident((char*)malloc(to_size));
1064  // From is a zero-terminated string "hello\0" of length 6
1065  char *from = Ident((char*)malloc(from_size));
1066  strcpy(from, "hello");
1067  // copy 0 bytes
1068  strncpy(to, from, 0);
1069  strncpy(to - 1, from - 1, 0);
1070  // normal strncpy calls
1071  strncpy(to, from, from_size);
1072  strncpy(to, from, to_size);
1073  strncpy(to, from + from_size - 1, to_size);
1074  strncpy(to + to_size - 1, from, 1);
1075  // One of {to, from} points to not allocated memory
1076  EXPECT_DEATH(Ident(strncpy(to, from - 1, from_size)),
1077               LeftOOBErrorMessage(1));
1078  EXPECT_DEATH(Ident(strncpy(to - 1, from, from_size)),
1079               LeftOOBErrorMessage(1));
1080  EXPECT_DEATH(Ident(strncpy(to, from + from_size, 1)),
1081               RightOOBErrorMessage(0));
1082  EXPECT_DEATH(Ident(strncpy(to + to_size, from, 1)),
1083               RightOOBErrorMessage(0));
1084  // Length of "to" is too small
1085  EXPECT_DEATH(Ident(strncpy(to + to_size - from_size + 1, from, from_size)),
1086               RightOOBErrorMessage(0));
1087  EXPECT_DEATH(Ident(strncpy(to + 1, from, to_size)),
1088               RightOOBErrorMessage(0));
1089  // Overwrite terminator in from
1090  from[from_size - 1] = '!';
1091  // normal strncpy call
1092  strncpy(to, from, from_size);
1093  // Length of "from" is too small
1094  EXPECT_DEATH(Ident(strncpy(to, from, to_size)),
1095               RightOOBErrorMessage(0));
1096  free(to);
1097  free(from);
1098}
1099
1100// Users may have different definitions of "strchr" and "index", so provide
1101// function pointer typedefs and overload RunStrChrTest implementation.
1102// We can't use macro for RunStrChrTest body here, as this macro would
1103// confuse EXPECT_DEATH gtest macro.
1104typedef char*(*PointerToStrChr1)(const char*, int);
1105typedef char*(*PointerToStrChr2)(char*, int);
1106
1107USED static void RunStrChrTest(PointerToStrChr1 StrChr) {
1108  size_t size = Ident(100);
1109  char *str = MallocAndMemsetString(size);
1110  str[10] = 'q';
1111  str[11] = '\0';
1112  EXPECT_EQ(str, StrChr(str, 'z'));
1113  EXPECT_EQ(str + 10, StrChr(str, 'q'));
1114  EXPECT_EQ(NULL, StrChr(str, 'a'));
1115  // StrChr argument points to not allocated memory.
1116  EXPECT_DEATH(Ident(StrChr(str - 1, 'z')), LeftOOBErrorMessage(1));
1117  EXPECT_DEATH(Ident(StrChr(str + size, 'z')), RightOOBErrorMessage(0));
1118  // Overwrite the terminator and hit not allocated memory.
1119  str[11] = 'z';
1120  EXPECT_DEATH(Ident(StrChr(str, 'a')), RightOOBErrorMessage(0));
1121  free(str);
1122}
1123USED static void RunStrChrTest(PointerToStrChr2 StrChr) {
1124  size_t size = Ident(100);
1125  char *str = MallocAndMemsetString(size);
1126  str[10] = 'q';
1127  str[11] = '\0';
1128  EXPECT_EQ(str, StrChr(str, 'z'));
1129  EXPECT_EQ(str + 10, StrChr(str, 'q'));
1130  EXPECT_EQ(NULL, StrChr(str, 'a'));
1131  // StrChr argument points to not allocated memory.
1132  EXPECT_DEATH(Ident(StrChr(str - 1, 'z')), LeftOOBErrorMessage(1));
1133  EXPECT_DEATH(Ident(StrChr(str + size, 'z')), RightOOBErrorMessage(0));
1134  // Overwrite the terminator and hit not allocated memory.
1135  str[11] = 'z';
1136  EXPECT_DEATH(Ident(StrChr(str, 'a')), RightOOBErrorMessage(0));
1137  free(str);
1138}
1139
1140TEST(AddressSanitizer, StrChrAndIndexOOBTest) {
1141  RunStrChrTest(&strchr);
1142  RunStrChrTest(&index);
1143}
1144
1145TEST(AddressSanitizer, StrCmpAndFriendsLogicTest) {
1146  // strcmp
1147  EXPECT_EQ(0, strcmp("", ""));
1148  EXPECT_EQ(0, strcmp("abcd", "abcd"));
1149  EXPECT_GT(0, strcmp("ab", "ac"));
1150  EXPECT_GT(0, strcmp("abc", "abcd"));
1151  EXPECT_LT(0, strcmp("acc", "abc"));
1152  EXPECT_LT(0, strcmp("abcd", "abc"));
1153
1154  // strncmp
1155  EXPECT_EQ(0, strncmp("a", "b", 0));
1156  EXPECT_EQ(0, strncmp("abcd", "abcd", 10));
1157  EXPECT_EQ(0, strncmp("abcd", "abcef", 3));
1158  EXPECT_GT(0, strncmp("abcde", "abcfa", 4));
1159  EXPECT_GT(0, strncmp("a", "b", 5));
1160  EXPECT_GT(0, strncmp("bc", "bcde", 4));
1161  EXPECT_LT(0, strncmp("xyz", "xyy", 10));
1162  EXPECT_LT(0, strncmp("baa", "aaa", 1));
1163  EXPECT_LT(0, strncmp("zyx", "", 2));
1164
1165  // strcasecmp
1166  EXPECT_EQ(0, strcasecmp("", ""));
1167  EXPECT_EQ(0, strcasecmp("zzz", "zzz"));
1168  EXPECT_EQ(0, strcasecmp("abCD", "ABcd"));
1169  EXPECT_GT(0, strcasecmp("aB", "Ac"));
1170  EXPECT_GT(0, strcasecmp("ABC", "ABCd"));
1171  EXPECT_LT(0, strcasecmp("acc", "abc"));
1172  EXPECT_LT(0, strcasecmp("ABCd", "abc"));
1173
1174  // strncasecmp
1175  EXPECT_EQ(0, strncasecmp("a", "b", 0));
1176  EXPECT_EQ(0, strncasecmp("abCD", "ABcd", 10));
1177  EXPECT_EQ(0, strncasecmp("abCd", "ABcef", 3));
1178  EXPECT_GT(0, strncasecmp("abcde", "ABCfa", 4));
1179  EXPECT_GT(0, strncasecmp("a", "B", 5));
1180  EXPECT_GT(0, strncasecmp("bc", "BCde", 4));
1181  EXPECT_LT(0, strncasecmp("xyz", "xyy", 10));
1182  EXPECT_LT(0, strncasecmp("Baa", "aaa", 1));
1183  EXPECT_LT(0, strncasecmp("zyx", "", 2));
1184
1185  // memcmp
1186  EXPECT_EQ(0, memcmp("a", "b", 0));
1187  EXPECT_EQ(0, memcmp("ab\0c", "ab\0c", 4));
1188  EXPECT_GT(0, memcmp("\0ab", "\0ac", 3));
1189  EXPECT_GT(0, memcmp("abb\0", "abba", 4));
1190  EXPECT_LT(0, memcmp("ab\0cd", "ab\0c\0", 5));
1191  EXPECT_LT(0, memcmp("zza", "zyx", 3));
1192}
1193
1194typedef int(*PointerToStrCmp)(const char*, const char*);
1195void RunStrCmpTest(PointerToStrCmp StrCmp) {
1196  size_t size = Ident(100);
1197  char *s1 = MallocAndMemsetString(size);
1198  char *s2 = MallocAndMemsetString(size);
1199  s1[size - 1] = '\0';
1200  s2[size - 1] = '\0';
1201  // Normal StrCmp calls
1202  Ident(StrCmp(s1, s2));
1203  Ident(StrCmp(s1, s2 + size - 1));
1204  Ident(StrCmp(s1 + size - 1, s2 + size - 1));
1205  s1[size - 1] = 'z';
1206  s2[size - 1] = 'x';
1207  Ident(StrCmp(s1, s2));
1208  // One of arguments points to not allocated memory.
1209  EXPECT_DEATH(Ident(StrCmp)(s1 - 1, s2), LeftOOBErrorMessage(1));
1210  EXPECT_DEATH(Ident(StrCmp)(s1, s2 - 1), LeftOOBErrorMessage(1));
1211  EXPECT_DEATH(Ident(StrCmp)(s1 + size, s2), RightOOBErrorMessage(0));
1212  EXPECT_DEATH(Ident(StrCmp)(s1, s2 + size), RightOOBErrorMessage(0));
1213  // Hit unallocated memory and die.
1214  s2[size - 1] = 'z';
1215  EXPECT_DEATH(Ident(StrCmp)(s1, s1), RightOOBErrorMessage(0));
1216  EXPECT_DEATH(Ident(StrCmp)(s1 + size - 1, s2), RightOOBErrorMessage(0));
1217  free(s1);
1218  free(s2);
1219}
1220
1221TEST(AddressSanitizer, StrCmpOOBTest) {
1222  RunStrCmpTest(&strcmp);
1223}
1224
1225TEST(AddressSanitizer, StrCaseCmpOOBTest) {
1226  RunStrCmpTest(&strcasecmp);
1227}
1228
1229typedef int(*PointerToStrNCmp)(const char*, const char*, size_t);
1230void RunStrNCmpTest(PointerToStrNCmp StrNCmp) {
1231  size_t size = Ident(100);
1232  char *s1 = MallocAndMemsetString(size);
1233  char *s2 = MallocAndMemsetString(size);
1234  s1[size - 1] = '\0';
1235  s2[size - 1] = '\0';
1236  // Normal StrNCmp calls
1237  Ident(StrNCmp(s1, s2, size + 2));
1238  s1[size - 1] = 'z';
1239  s2[size - 1] = 'x';
1240  Ident(StrNCmp(s1 + size - 2, s2 + size - 2, size));
1241  s2[size - 1] = 'z';
1242  Ident(StrNCmp(s1 - 1, s2 - 1, 0));
1243  Ident(StrNCmp(s1 + size - 1, s2 + size - 1, 1));
1244  // One of arguments points to not allocated memory.
1245  EXPECT_DEATH(Ident(StrNCmp)(s1 - 1, s2, 1), LeftOOBErrorMessage(1));
1246  EXPECT_DEATH(Ident(StrNCmp)(s1, s2 - 1, 1), LeftOOBErrorMessage(1));
1247  EXPECT_DEATH(Ident(StrNCmp)(s1 + size, s2, 1), RightOOBErrorMessage(0));
1248  EXPECT_DEATH(Ident(StrNCmp)(s1, s2 + size, 1), RightOOBErrorMessage(0));
1249  // Hit unallocated memory and die.
1250  EXPECT_DEATH(Ident(StrNCmp)(s1 + 1, s2 + 1, size), RightOOBErrorMessage(0));
1251  EXPECT_DEATH(Ident(StrNCmp)(s1 + size - 1, s2, 2), RightOOBErrorMessage(0));
1252  free(s1);
1253  free(s2);
1254}
1255
1256TEST(AddressSanitizer, StrNCmpOOBTest) {
1257  RunStrNCmpTest(&strncmp);
1258}
1259
1260TEST(AddressSanitizer, StrNCaseCmpOOBTest) {
1261  RunStrNCmpTest(&strncasecmp);
1262}
1263
1264TEST(AddressSanitizer, MemCmpOOBTest) {
1265  size_t size = Ident(100);
1266  char *s1 = MallocAndMemsetString(size);
1267  char *s2 = MallocAndMemsetString(size);
1268  // Normal memcmp calls.
1269  Ident(memcmp(s1, s2, size));
1270  Ident(memcmp(s1 + size - 1, s2 + size - 1, 1));
1271  Ident(memcmp(s1 - 1, s2 - 1, 0));
1272  // One of arguments points to not allocated memory.
1273  EXPECT_DEATH(Ident(memcmp)(s1 - 1, s2, 1), LeftOOBErrorMessage(1));
1274  EXPECT_DEATH(Ident(memcmp)(s1, s2 - 1, 1), LeftOOBErrorMessage(1));
1275  EXPECT_DEATH(Ident(memcmp)(s1 + size, s2, 1), RightOOBErrorMessage(0));
1276  EXPECT_DEATH(Ident(memcmp)(s1, s2 + size, 1), RightOOBErrorMessage(0));
1277  // Hit unallocated memory and die.
1278  EXPECT_DEATH(Ident(memcmp)(s1 + 1, s2 + 1, size), RightOOBErrorMessage(0));
1279  EXPECT_DEATH(Ident(memcmp)(s1 + size - 1, s2, 2), RightOOBErrorMessage(0));
1280  // Zero bytes are not terminators and don't prevent from OOB.
1281  s1[size - 1] = '\0';
1282  s2[size - 1] = '\0';
1283  EXPECT_DEATH(Ident(memcmp)(s1, s2, size + 1), RightOOBErrorMessage(0));
1284  free(s1);
1285  free(s2);
1286}
1287
1288TEST(AddressSanitizer, StrCatOOBTest) {
1289  size_t to_size = Ident(100);
1290  char *to = MallocAndMemsetString(to_size);
1291  to[0] = '\0';
1292  size_t from_size = Ident(20);
1293  char *from = MallocAndMemsetString(from_size);
1294  from[from_size - 1] = '\0';
1295  // Normal strcat calls.
1296  strcat(to, from);
1297  strcat(to, from);
1298  strcat(to + from_size, from + from_size - 2);
1299  // Passing an invalid pointer is an error even when concatenating an empty
1300  // string.
1301  EXPECT_DEATH(strcat(to - 1, from + from_size - 1), LeftOOBErrorMessage(1));
1302  // One of arguments points to not allocated memory.
1303  EXPECT_DEATH(strcat(to - 1, from), LeftOOBErrorMessage(1));
1304  EXPECT_DEATH(strcat(to, from - 1), LeftOOBErrorMessage(1));
1305  EXPECT_DEATH(strcat(to + to_size, from), RightOOBErrorMessage(0));
1306  EXPECT_DEATH(strcat(to, from + from_size), RightOOBErrorMessage(0));
1307
1308  // "from" is not zero-terminated.
1309  from[from_size - 1] = 'z';
1310  EXPECT_DEATH(strcat(to, from), RightOOBErrorMessage(0));
1311  from[from_size - 1] = '\0';
1312  // "to" is not zero-terminated.
1313  memset(to, 'z', to_size);
1314  EXPECT_DEATH(strcat(to, from), RightOOBErrorMessage(0));
1315  // "to" is too short to fit "from".
1316  to[to_size - from_size + 1] = '\0';
1317  EXPECT_DEATH(strcat(to, from), RightOOBErrorMessage(0));
1318  // length of "to" is just enough.
1319  strcat(to, from + 1);
1320
1321  free(to);
1322  free(from);
1323}
1324
1325TEST(AddressSanitizer, StrNCatOOBTest) {
1326  size_t to_size = Ident(100);
1327  char *to = MallocAndMemsetString(to_size);
1328  to[0] = '\0';
1329  size_t from_size = Ident(20);
1330  char *from = MallocAndMemsetString(from_size);
1331  // Normal strncat calls.
1332  strncat(to, from, 0);
1333  strncat(to, from, from_size);
1334  from[from_size - 1] = '\0';
1335  strncat(to, from, 2 * from_size);
1336  // Catenating empty string with an invalid string is still an error.
1337  EXPECT_DEATH(strncat(to - 1, from, 0), LeftOOBErrorMessage(1));
1338  strncat(to, from + from_size - 1, 10);
1339  // One of arguments points to not allocated memory.
1340  EXPECT_DEATH(strncat(to - 1, from, 2), LeftOOBErrorMessage(1));
1341  EXPECT_DEATH(strncat(to, from - 1, 2), LeftOOBErrorMessage(1));
1342  EXPECT_DEATH(strncat(to + to_size, from, 2), RightOOBErrorMessage(0));
1343  EXPECT_DEATH(strncat(to, from + from_size, 2), RightOOBErrorMessage(0));
1344
1345  memset(from, 'z', from_size);
1346  memset(to, 'z', to_size);
1347  to[0] = '\0';
1348  // "from" is too short.
1349  EXPECT_DEATH(strncat(to, from, from_size + 1), RightOOBErrorMessage(0));
1350  // "to" is not zero-terminated.
1351  EXPECT_DEATH(strncat(to + 1, from, 1), RightOOBErrorMessage(0));
1352  // "to" is too short to fit "from".
1353  to[0] = 'z';
1354  to[to_size - from_size + 1] = '\0';
1355  EXPECT_DEATH(strncat(to, from, from_size - 1), RightOOBErrorMessage(0));
1356  // "to" is just enough.
1357  strncat(to, from, from_size - 2);
1358
1359  free(to);
1360  free(from);
1361}
1362
1363static string OverlapErrorMessage(const string &func) {
1364  return func + "-param-overlap";
1365}
1366
1367TEST(AddressSanitizer, StrArgsOverlapTest) {
1368  size_t size = Ident(100);
1369  char *str = Ident((char*)malloc(size));
1370
1371// Do not check memcpy() on OS X 10.7 and later, where it actually aliases
1372// memmove().
1373#if !defined(__APPLE__) || !defined(MAC_OS_X_VERSION_10_7) || \
1374    (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7)
1375  // Check "memcpy". Use Ident() to avoid inlining.
1376  memset(str, 'z', size);
1377  Ident(memcpy)(str + 1, str + 11, 10);
1378  Ident(memcpy)(str, str, 0);
1379  EXPECT_DEATH(Ident(memcpy)(str, str + 14, 15), OverlapErrorMessage("memcpy"));
1380  EXPECT_DEATH(Ident(memcpy)(str + 14, str, 15), OverlapErrorMessage("memcpy"));
1381#endif
1382
1383  // We do not treat memcpy with to==from as a bug.
1384  // See http://llvm.org/bugs/show_bug.cgi?id=11763.
1385  // EXPECT_DEATH(Ident(memcpy)(str + 20, str + 20, 1),
1386  //              OverlapErrorMessage("memcpy"));
1387
1388  // Check "strcpy".
1389  memset(str, 'z', size);
1390  str[9] = '\0';
1391  strcpy(str + 10, str);
1392  EXPECT_DEATH(strcpy(str + 9, str), OverlapErrorMessage("strcpy"));
1393  EXPECT_DEATH(strcpy(str, str + 4), OverlapErrorMessage("strcpy"));
1394  strcpy(str, str + 5);
1395
1396  // Check "strncpy".
1397  memset(str, 'z', size);
1398  strncpy(str, str + 10, 10);
1399  EXPECT_DEATH(strncpy(str, str + 9, 10), OverlapErrorMessage("strncpy"));
1400  EXPECT_DEATH(strncpy(str + 9, str, 10), OverlapErrorMessage("strncpy"));
1401  str[10] = '\0';
1402  strncpy(str + 11, str, 20);
1403  EXPECT_DEATH(strncpy(str + 10, str, 20), OverlapErrorMessage("strncpy"));
1404
1405  // Check "strcat".
1406  memset(str, 'z', size);
1407  str[10] = '\0';
1408  str[20] = '\0';
1409  strcat(str, str + 10);
1410  EXPECT_DEATH(strcat(str, str + 11), OverlapErrorMessage("strcat"));
1411  str[10] = '\0';
1412  strcat(str + 11, str);
1413  EXPECT_DEATH(strcat(str, str + 9), OverlapErrorMessage("strcat"));
1414  EXPECT_DEATH(strcat(str + 9, str), OverlapErrorMessage("strcat"));
1415  EXPECT_DEATH(strcat(str + 10, str), OverlapErrorMessage("strcat"));
1416
1417  // Check "strncat".
1418  memset(str, 'z', size);
1419  str[10] = '\0';
1420  strncat(str, str + 10, 10);  // from is empty
1421  EXPECT_DEATH(strncat(str, str + 11, 10), OverlapErrorMessage("strncat"));
1422  str[10] = '\0';
1423  str[20] = '\0';
1424  strncat(str + 5, str, 5);
1425  str[10] = '\0';
1426  EXPECT_DEATH(strncat(str + 5, str, 6), OverlapErrorMessage("strncat"));
1427  EXPECT_DEATH(strncat(str, str + 9, 10), OverlapErrorMessage("strncat"));
1428
1429  free(str);
1430}
1431
1432void CallAtoi(const char *nptr) {
1433  Ident(atoi(nptr));
1434}
1435void CallAtol(const char *nptr) {
1436  Ident(atol(nptr));
1437}
1438void CallAtoll(const char *nptr) {
1439  Ident(atoll(nptr));
1440}
1441typedef void(*PointerToCallAtoi)(const char*);
1442
1443void RunAtoiOOBTest(PointerToCallAtoi Atoi) {
1444  char *array = MallocAndMemsetString(10, '1');
1445  // Invalid pointer to the string.
1446  EXPECT_DEATH(Atoi(array + 11), RightOOBErrorMessage(1));
1447  EXPECT_DEATH(Atoi(array - 1), LeftOOBErrorMessage(1));
1448  // Die if a buffer doesn't have terminating NULL.
1449  EXPECT_DEATH(Atoi(array), RightOOBErrorMessage(0));
1450  // Make last symbol a terminating NULL or other non-digit.
1451  array[9] = '\0';
1452  Atoi(array);
1453  array[9] = 'a';
1454  Atoi(array);
1455  Atoi(array + 9);
1456  // Sometimes we need to detect overflow if no digits are found.
1457  memset(array, ' ', 10);
1458  EXPECT_DEATH(Atoi(array), RightOOBErrorMessage(0));
1459  array[9] = '-';
1460  EXPECT_DEATH(Atoi(array), RightOOBErrorMessage(0));
1461  EXPECT_DEATH(Atoi(array + 9), RightOOBErrorMessage(0));
1462  array[8] = '-';
1463  Atoi(array);
1464  delete array;
1465}
1466
1467TEST(AddressSanitizer, AtoiAndFriendsOOBTest) {
1468  RunAtoiOOBTest(&CallAtoi);
1469  RunAtoiOOBTest(&CallAtol);
1470  RunAtoiOOBTest(&CallAtoll);
1471}
1472
1473void CallStrtol(const char *nptr, char **endptr, int base) {
1474  Ident(strtol(nptr, endptr, base));
1475}
1476void CallStrtoll(const char *nptr, char **endptr, int base) {
1477  Ident(strtoll(nptr, endptr, base));
1478}
1479typedef void(*PointerToCallStrtol)(const char*, char**, int);
1480
1481void RunStrtolOOBTest(PointerToCallStrtol Strtol) {
1482  char *array = MallocAndMemsetString(3);
1483  char *endptr = NULL;
1484  array[0] = '1';
1485  array[1] = '2';
1486  array[2] = '3';
1487  // Invalid pointer to the string.
1488  EXPECT_DEATH(Strtol(array + 3, NULL, 0), RightOOBErrorMessage(0));
1489  EXPECT_DEATH(Strtol(array - 1, NULL, 0), LeftOOBErrorMessage(1));
1490  // Buffer overflow if there is no terminating null (depends on base).
1491  Strtol(array, &endptr, 3);
1492  EXPECT_EQ(array + 2, endptr);
1493  EXPECT_DEATH(Strtol(array, NULL, 0), RightOOBErrorMessage(0));
1494  array[2] = 'z';
1495  Strtol(array, &endptr, 35);
1496  EXPECT_EQ(array + 2, endptr);
1497  EXPECT_DEATH(Strtol(array, NULL, 36), RightOOBErrorMessage(0));
1498  // Add terminating zero to get rid of overflow.
1499  array[2] = '\0';
1500  Strtol(array, NULL, 36);
1501  // Don't check for overflow if base is invalid.
1502  Strtol(array - 1, NULL, -1);
1503  Strtol(array + 3, NULL, 1);
1504  // Sometimes we need to detect overflow if no digits are found.
1505  array[0] = array[1] = array[2] = ' ';
1506  EXPECT_DEATH(Strtol(array, NULL, 0), RightOOBErrorMessage(0));
1507  array[2] = '+';
1508  EXPECT_DEATH(Strtol(array, NULL, 0), RightOOBErrorMessage(0));
1509  array[2] = '-';
1510  EXPECT_DEATH(Strtol(array, NULL, 0), RightOOBErrorMessage(0));
1511  array[1] = '+';
1512  Strtol(array, NULL, 0);
1513  array[1] = array[2] = 'z';
1514  Strtol(array, &endptr, 0);
1515  EXPECT_EQ(array, endptr);
1516  Strtol(array + 2, NULL, 0);
1517  EXPECT_EQ(array, endptr);
1518  delete array;
1519}
1520
1521TEST(AddressSanitizer, StrtollOOBTest) {
1522  RunStrtolOOBTest(&CallStrtoll);
1523}
1524TEST(AddressSanitizer, StrtolOOBTest) {
1525  RunStrtolOOBTest(&CallStrtol);
1526}
1527
1528// At the moment we instrument memcpy/memove/memset calls at compile time so we
1529// can't handle OOB error if these functions are called by pointer, see disabled
1530// MemIntrinsicCallByPointerTest below
1531typedef void*(*PointerToMemTransfer)(void*, const void*, size_t);
1532typedef void*(*PointerToMemSet)(void*, int, size_t);
1533
1534void CallMemSetByPointer(PointerToMemSet MemSet) {
1535  size_t size = Ident(100);
1536  char *array = Ident((char*)malloc(size));
1537  EXPECT_DEATH(MemSet(array, 0, 101), RightOOBErrorMessage(0));
1538  free(array);
1539}
1540
1541void CallMemTransferByPointer(PointerToMemTransfer MemTransfer) {
1542  size_t size = Ident(100);
1543  char *src = Ident((char*)malloc(size));
1544  char *dst = Ident((char*)malloc(size));
1545  EXPECT_DEATH(MemTransfer(dst, src, 101), RightOOBErrorMessage(0));
1546  free(src);
1547  free(dst);
1548}
1549
1550TEST(AddressSanitizer, DISABLED_MemIntrinsicCallByPointerTest) {
1551  CallMemSetByPointer(&memset);
1552  CallMemTransferByPointer(&memcpy);
1553  CallMemTransferByPointer(&memmove);
1554}
1555
1556// This test case fails
1557// Clang optimizes memcpy/memset calls which lead to unaligned access
1558TEST(AddressSanitizer, DISABLED_MemIntrinsicUnalignedAccessTest) {
1559  int size = Ident(4096);
1560  char *s = Ident((char*)malloc(size));
1561  EXPECT_DEATH(memset(s + size - 1, 0, 2), RightOOBErrorMessage(0));
1562  free(s);
1563}
1564
1565// TODO(samsonov): Add a test with malloc(0)
1566// TODO(samsonov): Add tests for str* and mem* functions.
1567
1568NOINLINE static int LargeFunction(bool do_bad_access) {
1569  int *x = new int[100];
1570  x[0]++;
1571  x[1]++;
1572  x[2]++;
1573  x[3]++;
1574  x[4]++;
1575  x[5]++;
1576  x[6]++;
1577  x[7]++;
1578  x[8]++;
1579  x[9]++;
1580
1581  x[do_bad_access ? 100 : 0]++; int res = __LINE__;
1582
1583  x[10]++;
1584  x[11]++;
1585  x[12]++;
1586  x[13]++;
1587  x[14]++;
1588  x[15]++;
1589  x[16]++;
1590  x[17]++;
1591  x[18]++;
1592  x[19]++;
1593
1594  delete x;
1595  return res;
1596}
1597
1598// Test the we have correct debug info for the failing instruction.
1599// This test requires the in-process symbolizer to be enabled by default.
1600TEST(AddressSanitizer, DISABLED_LargeFunctionSymbolizeTest) {
1601  int failing_line = LargeFunction(false);
1602  char expected_warning[128];
1603  sprintf(expected_warning, "LargeFunction.*asan_test.cc:%d", failing_line);
1604  EXPECT_DEATH(LargeFunction(true), expected_warning);
1605}
1606
1607// Check that we unwind and symbolize correctly.
1608TEST(AddressSanitizer, DISABLED_MallocFreeUnwindAndSymbolizeTest) {
1609  int *a = (int*)malloc_aaa(sizeof(int));
1610  *a = 1;
1611  free_aaa(a);
1612  EXPECT_DEATH(*a = 1, "free_ccc.*free_bbb.*free_aaa.*"
1613               "malloc_fff.*malloc_eee.*malloc_ddd");
1614}
1615
1616void *ThreadedTestAlloc(void *a) {
1617  int **p = (int**)a;
1618  *p = new int;
1619  return 0;
1620}
1621
1622void *ThreadedTestFree(void *a) {
1623  int **p = (int**)a;
1624  delete *p;
1625  return 0;
1626}
1627
1628void *ThreadedTestUse(void *a) {
1629  int **p = (int**)a;
1630  **p = 1;
1631  return 0;
1632}
1633
1634void ThreadedTestSpawn() {
1635  pthread_t t;
1636  int *x;
1637  pthread_create(&t, 0, ThreadedTestAlloc, &x);
1638  pthread_join(t, 0);
1639  pthread_create(&t, 0, ThreadedTestFree, &x);
1640  pthread_join(t, 0);
1641  pthread_create(&t, 0, ThreadedTestUse, &x);
1642  pthread_join(t, 0);
1643}
1644
1645TEST(AddressSanitizer, ThreadedTest) {
1646  EXPECT_DEATH(ThreadedTestSpawn(),
1647               ASAN_PCRE_DOTALL
1648               "Thread T.*created"
1649               ".*Thread T.*created"
1650               ".*Thread T.*created");
1651}
1652
1653#if ASAN_NEEDS_SEGV
1654TEST(AddressSanitizer, ShadowGapTest) {
1655#if SANITIZER_WORDSIZE == 32
1656  char *addr = (char*)0x22000000;
1657#else
1658  char *addr = (char*)0x0000100000080000;
1659#endif
1660  EXPECT_DEATH(*addr = 1, "AddressSanitizer: SEGV on unknown");
1661}
1662#endif  // ASAN_NEEDS_SEGV
1663
1664extern "C" {
1665NOINLINE static void UseThenFreeThenUse() {
1666  char *x = Ident((char*)malloc(8));
1667  *x = 1;
1668  free_aaa(x);
1669  *x = 2;
1670}
1671}
1672
1673TEST(AddressSanitizer, UseThenFreeThenUseTest) {
1674  EXPECT_DEATH(UseThenFreeThenUse(), "freed by thread");
1675}
1676
1677TEST(AddressSanitizer, StrDupTest) {
1678  free(strdup(Ident("123")));
1679}
1680
1681// Currently we create and poison redzone at right of global variables.
1682char glob5[5];
1683static char static110[110];
1684const char ConstGlob[7] = {1, 2, 3, 4, 5, 6, 7};
1685static const char StaticConstGlob[3] = {9, 8, 7};
1686extern int GlobalsTest(int x);
1687
1688TEST(AddressSanitizer, GlobalTest) {
1689  static char func_static15[15];
1690
1691  static char fs1[10];
1692  static char fs2[10];
1693  static char fs3[10];
1694
1695  glob5[Ident(0)] = 0;
1696  glob5[Ident(1)] = 0;
1697  glob5[Ident(2)] = 0;
1698  glob5[Ident(3)] = 0;
1699  glob5[Ident(4)] = 0;
1700
1701  EXPECT_DEATH(glob5[Ident(5)] = 0,
1702               "0 bytes to the right of global variable.*glob5.* size 5");
1703  EXPECT_DEATH(glob5[Ident(5+6)] = 0,
1704               "6 bytes to the right of global variable.*glob5.* size 5");
1705  Ident(static110);  // avoid optimizations
1706  static110[Ident(0)] = 0;
1707  static110[Ident(109)] = 0;
1708  EXPECT_DEATH(static110[Ident(110)] = 0,
1709               "0 bytes to the right of global variable");
1710  EXPECT_DEATH(static110[Ident(110+7)] = 0,
1711               "7 bytes to the right of global variable");
1712
1713  Ident(func_static15);  // avoid optimizations
1714  func_static15[Ident(0)] = 0;
1715  EXPECT_DEATH(func_static15[Ident(15)] = 0,
1716               "0 bytes to the right of global variable");
1717  EXPECT_DEATH(func_static15[Ident(15 + 9)] = 0,
1718               "9 bytes to the right of global variable");
1719
1720  Ident(fs1);
1721  Ident(fs2);
1722  Ident(fs3);
1723
1724  // We don't create left redzones, so this is not 100% guaranteed to fail.
1725  // But most likely will.
1726  EXPECT_DEATH(fs2[Ident(-1)] = 0, "is located.*of global variable");
1727
1728  EXPECT_DEATH(Ident(Ident(ConstGlob)[8]),
1729               "is located 1 bytes to the right of .*ConstGlob");
1730  EXPECT_DEATH(Ident(Ident(StaticConstGlob)[5]),
1731               "is located 2 bytes to the right of .*StaticConstGlob");
1732
1733  // call stuff from another file.
1734  GlobalsTest(0);
1735}
1736
1737TEST(AddressSanitizer, GlobalStringConstTest) {
1738  static const char *zoo = "FOOBAR123";
1739  const char *p = Ident(zoo);
1740  EXPECT_DEATH(Ident(p[15]), "is ascii string 'FOOBAR123'");
1741}
1742
1743TEST(AddressSanitizer, FileNameInGlobalReportTest) {
1744  static char zoo[10];
1745  const char *p = Ident(zoo);
1746  // The file name should be present in the report.
1747  EXPECT_DEATH(Ident(p[15]), "zoo.*asan_test.cc");
1748}
1749
1750int *ReturnsPointerToALocalObject() {
1751  int a = 0;
1752  return Ident(&a);
1753}
1754
1755#if ASAN_UAR == 1
1756TEST(AddressSanitizer, LocalReferenceReturnTest) {
1757  int *(*f)() = Ident(ReturnsPointerToALocalObject);
1758  int *p = f();
1759  // Call 'f' a few more times, 'p' should still be poisoned.
1760  for (int i = 0; i < 32; i++)
1761    f();
1762  EXPECT_DEATH(*p = 1, "AddressSanitizer: stack-use-after-return");
1763  EXPECT_DEATH(*p = 1, "is located.*in frame .*ReturnsPointerToALocal");
1764}
1765#endif
1766
1767template <int kSize>
1768NOINLINE static void FuncWithStack() {
1769  char x[kSize];
1770  Ident(x)[0] = 0;
1771  Ident(x)[kSize-1] = 0;
1772}
1773
1774static void LotsOfStackReuse() {
1775  int LargeStack[10000];
1776  Ident(LargeStack)[0] = 0;
1777  for (int i = 0; i < 10000; i++) {
1778    FuncWithStack<128 * 1>();
1779    FuncWithStack<128 * 2>();
1780    FuncWithStack<128 * 4>();
1781    FuncWithStack<128 * 8>();
1782    FuncWithStack<128 * 16>();
1783    FuncWithStack<128 * 32>();
1784    FuncWithStack<128 * 64>();
1785    FuncWithStack<128 * 128>();
1786    FuncWithStack<128 * 256>();
1787    FuncWithStack<128 * 512>();
1788    Ident(LargeStack)[0] = 0;
1789  }
1790}
1791
1792TEST(AddressSanitizer, StressStackReuseTest) {
1793  LotsOfStackReuse();
1794}
1795
1796TEST(AddressSanitizer, ThreadedStressStackReuseTest) {
1797  const int kNumThreads = 20;
1798  pthread_t t[kNumThreads];
1799  for (int i = 0; i < kNumThreads; i++) {
1800    pthread_create(&t[i], 0, (void* (*)(void *x))LotsOfStackReuse, 0);
1801  }
1802  for (int i = 0; i < kNumThreads; i++) {
1803    pthread_join(t[i], 0);
1804  }
1805}
1806
1807static void *PthreadExit(void *a) {
1808  pthread_exit(0);
1809  return 0;
1810}
1811
1812TEST(AddressSanitizer, PthreadExitTest) {
1813  pthread_t t;
1814  for (int i = 0; i < 1000; i++) {
1815    pthread_create(&t, 0, PthreadExit, 0);
1816    pthread_join(t, 0);
1817  }
1818}
1819
1820#ifdef __EXCEPTIONS
1821NOINLINE static void StackReuseAndException() {
1822  int large_stack[1000];
1823  Ident(large_stack);
1824  ASAN_THROW(1);
1825}
1826
1827// TODO(kcc): support exceptions with use-after-return.
1828TEST(AddressSanitizer, DISABLED_StressStackReuseAndExceptionsTest) {
1829  for (int i = 0; i < 10000; i++) {
1830    try {
1831    StackReuseAndException();
1832    } catch(...) {
1833    }
1834  }
1835}
1836#endif
1837
1838TEST(AddressSanitizer, MlockTest) {
1839  EXPECT_EQ(0, mlockall(MCL_CURRENT));
1840  EXPECT_EQ(0, mlock((void*)0x12345, 0x5678));
1841  EXPECT_EQ(0, munlockall());
1842  EXPECT_EQ(0, munlock((void*)0x987, 0x654));
1843}
1844
1845struct LargeStruct {
1846  int foo[100];
1847};
1848
1849// Test for bug http://llvm.org/bugs/show_bug.cgi?id=11763.
1850// Struct copy should not cause asan warning even if lhs == rhs.
1851TEST(AddressSanitizer, LargeStructCopyTest) {
1852  LargeStruct a;
1853  *Ident(&a) = *Ident(&a);
1854}
1855
1856ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
1857static void NoAddressSafety() {
1858  char *foo = new char[10];
1859  Ident(foo)[10] = 0;
1860  delete [] foo;
1861}
1862
1863TEST(AddressSanitizer, AttributeNoAddressSafetyTest) {
1864  Ident(NoAddressSafety)();
1865}
1866
1867// ------------------ demo tests; run each one-by-one -------------
1868// e.g. --gtest_filter=*DemoOOBLeftHigh --gtest_also_run_disabled_tests
1869TEST(AddressSanitizer, DISABLED_DemoThreadedTest) {
1870  ThreadedTestSpawn();
1871}
1872
1873void *SimpleBugOnSTack(void *x = 0) {
1874  char a[20];
1875  Ident(a)[20] = 0;
1876  return 0;
1877}
1878
1879TEST(AddressSanitizer, DISABLED_DemoStackTest) {
1880  SimpleBugOnSTack();
1881}
1882
1883TEST(AddressSanitizer, DISABLED_DemoThreadStackTest) {
1884  pthread_t t;
1885  pthread_create(&t, 0, SimpleBugOnSTack, 0);
1886  pthread_join(t, 0);
1887}
1888
1889TEST(AddressSanitizer, DISABLED_DemoUAFLowIn) {
1890  uaf_test<U1>(10, 0);
1891}
1892TEST(AddressSanitizer, DISABLED_DemoUAFLowLeft) {
1893  uaf_test<U1>(10, -2);
1894}
1895TEST(AddressSanitizer, DISABLED_DemoUAFLowRight) {
1896  uaf_test<U1>(10, 10);
1897}
1898
1899TEST(AddressSanitizer, DISABLED_DemoUAFHigh) {
1900  uaf_test<U1>(kLargeMalloc, 0);
1901}
1902
1903TEST(AddressSanitizer, DISABLED_DemoOOBLeftLow) {
1904  oob_test<U1>(10, -1);
1905}
1906
1907TEST(AddressSanitizer, DISABLED_DemoOOBLeftHigh) {
1908  oob_test<U1>(kLargeMalloc, -1);
1909}
1910
1911TEST(AddressSanitizer, DISABLED_DemoOOBRightLow) {
1912  oob_test<U1>(10, 10);
1913}
1914
1915TEST(AddressSanitizer, DISABLED_DemoOOBRightHigh) {
1916  oob_test<U1>(kLargeMalloc, kLargeMalloc);
1917}
1918
1919TEST(AddressSanitizer, DISABLED_DemoOOM) {
1920  size_t size = SANITIZER_WORDSIZE == 64 ? (size_t)(1ULL << 40) : (0xf0000000);
1921  printf("%p\n", malloc(size));
1922}
1923
1924TEST(AddressSanitizer, DISABLED_DemoDoubleFreeTest) {
1925  DoubleFree();
1926}
1927
1928TEST(AddressSanitizer, DISABLED_DemoNullDerefTest) {
1929  int *a = 0;
1930  Ident(a)[10] = 0;
1931}
1932
1933TEST(AddressSanitizer, DISABLED_DemoFunctionStaticTest) {
1934  static char a[100];
1935  static char b[100];
1936  static char c[100];
1937  Ident(a);
1938  Ident(b);
1939  Ident(c);
1940  Ident(a)[5] = 0;
1941  Ident(b)[105] = 0;
1942  Ident(a)[5] = 0;
1943}
1944
1945TEST(AddressSanitizer, DISABLED_DemoTooMuchMemoryTest) {
1946  const size_t kAllocSize = (1 << 28) - 1024;
1947  size_t total_size = 0;
1948  while (true) {
1949    char *x = (char*)malloc(kAllocSize);
1950    memset(x, 0, kAllocSize);
1951    total_size += kAllocSize;
1952    fprintf(stderr, "total: %ldM %p\n", (long)total_size >> 20, x);
1953  }
1954}
1955
1956// http://code.google.com/p/address-sanitizer/issues/detail?id=66
1957TEST(AddressSanitizer, BufferOverflowAfterManyFrees) {
1958  for (int i = 0; i < 1000000; i++) {
1959    delete [] (Ident(new char [8644]));
1960  }
1961  char *x = new char[8192];
1962  EXPECT_DEATH(x[Ident(8192)] = 0, "AddressSanitizer: heap-buffer-overflow");
1963  delete [] Ident(x);
1964}
1965
1966#ifdef __APPLE__
1967#include "asan_mac_test.h"
1968TEST(AddressSanitizerMac, CFAllocatorDefaultDoubleFree) {
1969  EXPECT_DEATH(
1970      CFAllocatorDefaultDoubleFree(NULL),
1971      "attempting double-free");
1972}
1973
1974void CFAllocator_DoubleFreeOnPthread() {
1975  pthread_t child;
1976  pthread_create(&child, NULL, CFAllocatorDefaultDoubleFree, NULL);
1977  pthread_join(child, NULL);  // Shouldn't be reached.
1978}
1979
1980TEST(AddressSanitizerMac, CFAllocatorDefaultDoubleFree_ChildPhread) {
1981  EXPECT_DEATH(CFAllocator_DoubleFreeOnPthread(), "attempting double-free");
1982}
1983
1984namespace {
1985
1986void *GLOB;
1987
1988void *CFAllocatorAllocateToGlob(void *unused) {
1989  GLOB = CFAllocatorAllocate(NULL, 100, /*hint*/0);
1990  return NULL;
1991}
1992
1993void *CFAllocatorDeallocateFromGlob(void *unused) {
1994  char *p = (char*)GLOB;
1995  p[100] = 'A';  // ASan should report an error here.
1996  CFAllocatorDeallocate(NULL, GLOB);
1997  return NULL;
1998}
1999
2000void CFAllocator_PassMemoryToAnotherThread() {
2001  pthread_t th1, th2;
2002  pthread_create(&th1, NULL, CFAllocatorAllocateToGlob, NULL);
2003  pthread_join(th1, NULL);
2004  pthread_create(&th2, NULL, CFAllocatorDeallocateFromGlob, NULL);
2005  pthread_join(th2, NULL);
2006}
2007
2008TEST(AddressSanitizerMac, CFAllocator_PassMemoryToAnotherThread) {
2009  EXPECT_DEATH(CFAllocator_PassMemoryToAnotherThread(),
2010               "heap-buffer-overflow");
2011}
2012
2013}  // namespace
2014
2015// TODO(glider): figure out whether we still need these tests. Is it correct
2016// to intercept the non-default CFAllocators?
2017TEST(AddressSanitizerMac, DISABLED_CFAllocatorSystemDefaultDoubleFree) {
2018  EXPECT_DEATH(
2019      CFAllocatorSystemDefaultDoubleFree(),
2020      "attempting double-free");
2021}
2022
2023// We're intercepting malloc, so kCFAllocatorMalloc is routed to ASan.
2024TEST(AddressSanitizerMac, CFAllocatorMallocDoubleFree) {
2025  EXPECT_DEATH(CFAllocatorMallocDoubleFree(), "attempting double-free");
2026}
2027
2028TEST(AddressSanitizerMac, DISABLED_CFAllocatorMallocZoneDoubleFree) {
2029  EXPECT_DEATH(CFAllocatorMallocZoneDoubleFree(), "attempting double-free");
2030}
2031
2032TEST(AddressSanitizerMac, GCDDispatchAsync) {
2033  // Make sure the whole ASan report is printed, i.e. that we don't die
2034  // on a CHECK.
2035  EXPECT_DEATH(TestGCDDispatchAsync(), "Shadow byte and word");
2036}
2037
2038TEST(AddressSanitizerMac, GCDDispatchSync) {
2039  // Make sure the whole ASan report is printed, i.e. that we don't die
2040  // on a CHECK.
2041  EXPECT_DEATH(TestGCDDispatchSync(), "Shadow byte and word");
2042}
2043
2044
2045TEST(AddressSanitizerMac, GCDReuseWqthreadsAsync) {
2046  // Make sure the whole ASan report is printed, i.e. that we don't die
2047  // on a CHECK.
2048  EXPECT_DEATH(TestGCDReuseWqthreadsAsync(), "Shadow byte and word");
2049}
2050
2051TEST(AddressSanitizerMac, GCDReuseWqthreadsSync) {
2052  // Make sure the whole ASan report is printed, i.e. that we don't die
2053  // on a CHECK.
2054  EXPECT_DEATH(TestGCDReuseWqthreadsSync(), "Shadow byte and word");
2055}
2056
2057TEST(AddressSanitizerMac, GCDDispatchAfter) {
2058  // Make sure the whole ASan report is printed, i.e. that we don't die
2059  // on a CHECK.
2060  EXPECT_DEATH(TestGCDDispatchAfter(), "Shadow byte and word");
2061}
2062
2063TEST(AddressSanitizerMac, GCDSourceEvent) {
2064  // Make sure the whole ASan report is printed, i.e. that we don't die
2065  // on a CHECK.
2066  EXPECT_DEATH(TestGCDSourceEvent(), "Shadow byte and word");
2067}
2068
2069TEST(AddressSanitizerMac, GCDSourceCancel) {
2070  // Make sure the whole ASan report is printed, i.e. that we don't die
2071  // on a CHECK.
2072  EXPECT_DEATH(TestGCDSourceCancel(), "Shadow byte and word");
2073}
2074
2075TEST(AddressSanitizerMac, GCDGroupAsync) {
2076  // Make sure the whole ASan report is printed, i.e. that we don't die
2077  // on a CHECK.
2078  EXPECT_DEATH(TestGCDGroupAsync(), "Shadow byte and word");
2079}
2080
2081void *MallocIntrospectionLockWorker(void *_) {
2082  const int kNumPointers = 100;
2083  int i;
2084  void *pointers[kNumPointers];
2085  for (i = 0; i < kNumPointers; i++) {
2086    pointers[i] = malloc(i + 1);
2087  }
2088  for (i = 0; i < kNumPointers; i++) {
2089    free(pointers[i]);
2090  }
2091
2092  return NULL;
2093}
2094
2095void *MallocIntrospectionLockForker(void *_) {
2096  pid_t result = fork();
2097  if (result == -1) {
2098    perror("fork");
2099  }
2100  assert(result != -1);
2101  if (result == 0) {
2102    // Call malloc in the child process to make sure we won't deadlock.
2103    void *ptr = malloc(42);
2104    free(ptr);
2105    exit(0);
2106  } else {
2107    // Return in the parent process.
2108    return NULL;
2109  }
2110}
2111
2112TEST(AddressSanitizerMac, MallocIntrospectionLock) {
2113  // Incorrect implementation of force_lock and force_unlock in our malloc zone
2114  // will cause forked processes to deadlock.
2115  // TODO(glider): need to detect that none of the child processes deadlocked.
2116  const int kNumWorkers = 5, kNumIterations = 100;
2117  int i, iter;
2118  for (iter = 0; iter < kNumIterations; iter++) {
2119    pthread_t workers[kNumWorkers], forker;
2120    for (i = 0; i < kNumWorkers; i++) {
2121      pthread_create(&workers[i], 0, MallocIntrospectionLockWorker, 0);
2122    }
2123    pthread_create(&forker, 0, MallocIntrospectionLockForker, 0);
2124    for (i = 0; i < kNumWorkers; i++) {
2125      pthread_join(workers[i], 0);
2126    }
2127    pthread_join(forker, 0);
2128  }
2129}
2130
2131void *TSDAllocWorker(void *test_key) {
2132  if (test_key) {
2133    void *mem = malloc(10);
2134    pthread_setspecific(*(pthread_key_t*)test_key, mem);
2135  }
2136  return NULL;
2137}
2138
2139TEST(AddressSanitizerMac, DISABLED_TSDWorkqueueTest) {
2140  pthread_t th;
2141  pthread_key_t test_key;
2142  pthread_key_create(&test_key, CallFreeOnWorkqueue);
2143  pthread_create(&th, NULL, TSDAllocWorker, &test_key);
2144  pthread_join(th, NULL);
2145  pthread_key_delete(test_key);
2146}
2147
2148// Test that CFStringCreateCopy does not copy constant strings.
2149TEST(AddressSanitizerMac, CFStringCreateCopy) {
2150  CFStringRef str = CFSTR("Hello world!\n");
2151  CFStringRef str2 = CFStringCreateCopy(0, str);
2152  EXPECT_EQ(str, str2);
2153}
2154
2155TEST(AddressSanitizerMac, NSObjectOOB) {
2156  // Make sure that our allocators are used for NSObjects.
2157  EXPECT_DEATH(TestOOBNSObjects(), "heap-buffer-overflow");
2158}
2159
2160// Make sure that correct pointer is passed to free() when deallocating a
2161// NSURL object.
2162// See http://code.google.com/p/address-sanitizer/issues/detail?id=70.
2163TEST(AddressSanitizerMac, NSURLDeallocation) {
2164  TestNSURLDeallocation();
2165}
2166
2167// See http://code.google.com/p/address-sanitizer/issues/detail?id=109.
2168TEST(AddressSanitizerMac, Mstats) {
2169  malloc_statistics_t stats1, stats2;
2170  malloc_zone_statistics(/*all zones*/NULL, &stats1);
2171  const int kMallocSize = 100000;
2172  void *alloc = Ident(malloc(kMallocSize));
2173  malloc_zone_statistics(/*all zones*/NULL, &stats2);
2174  EXPECT_GT(stats2.blocks_in_use, stats1.blocks_in_use);
2175  EXPECT_GE(stats2.size_in_use - stats1.size_in_use, kMallocSize);
2176  free(alloc);
2177  // Even the default OSX allocator may not change the stats after free().
2178}
2179#endif  // __APPLE__
2180
2181// Test that instrumentation of stack allocations takes into account
2182// AllocSize of a type, and not its StoreSize (16 vs 10 bytes for long double).
2183// See http://llvm.org/bugs/show_bug.cgi?id=12047 for more details.
2184TEST(AddressSanitizer, LongDoubleNegativeTest) {
2185  long double a, b;
2186  static long double c;
2187  memcpy(Ident(&a), Ident(&b), sizeof(long double));
2188  memcpy(Ident(&c), Ident(&b), sizeof(long double));
2189}
2190