asan_test.cc revision 2dcf44991a8ec1ca7c8051eb27c5ff158530bdc3
1f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org//===-- asan_test.cc ------------*- C++ -*-===//
2f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org//
3f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org//                     The LLVM Compiler Infrastructure
4f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org//
5f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org// This file is distributed under the University of Illinois Open Source
6f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org// License. See LICENSE.TXT for details.
7f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org//
8f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org//===----------------------------------------------------------------------===//
9f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org//
10f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org// This file is a part of AddressSanitizer, an address sanity checker.
11f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org//
12f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org//===----------------------------------------------------------------------===//
13f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include <stdio.h>
14f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include <signal.h>
15f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include <stdlib.h>
16f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include <string.h>
17f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include <strings.h>
18f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include <pthread.h>
19f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include <stdint.h>
20f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include <setjmp.h>
21f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include <assert.h>
22f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
23f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#if defined(__i386__) || defined(__x86_64__)
24f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include <emmintrin.h>
25f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#endif
26f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
27f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "asan_test_config.h"
28f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "asan_test_utils.h"
29f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
30f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#ifndef __APPLE__
31f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include <malloc.h>
32f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#else
33f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include <AvailabilityMacros.h>  // For MAC_OS_X_VERSION_*
34f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include <CoreFoundation/CFString.h>
35f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#endif  // __APPLE__
36f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
37f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#ifdef __APPLE__
38f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgstatic bool APPLE = true;
39f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#else
40f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgstatic bool APPLE = false;
41f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#endif
42f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
43f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#if ASAN_HAS_EXCEPTIONS
44f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org# define ASAN_THROW(x) throw (x)
45f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#else
46f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org# define ASAN_THROW(x)
47f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#endif
48f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
49f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include <sys/mman.h>
50f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
51f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgtypedef uint8_t   U1;
52f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgtypedef uint16_t  U2;
53f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgtypedef uint32_t  U4;
54f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgtypedef uint64_t  U8;
55f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
56f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgstatic const char *progname;
57f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgstatic const int kPageSize = 4096;
58f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
59f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org// Simple stand-alone pseudorandom number generator.
60f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org// Current algorithm is ANSI C linear congruential PRNG.
61f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgstatic inline uint32_t my_rand(uint32_t* state) {
62f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  return (*state = *state * 1103515245 + 12345) >> 16;
63f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org}
64f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
65f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgstatic uint32_t global_seed = 0;
66f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
67f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgconst size_t kLargeMalloc = 1 << 24;
68f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
69f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgtemplate<typename T>
70f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgNOINLINE void asan_write(T *a) {
71f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  *a = 0;
72f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org}
73f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
74f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgNOINLINE void asan_write_sized_aligned(uint8_t *p, size_t size) {
75f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  EXPECT_EQ(0, ((uintptr_t)p % size));
76f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  if      (size == 1) asan_write((uint8_t*)p);
77f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  else if (size == 2) asan_write((uint16_t*)p);
78f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  else if (size == 4) asan_write((uint32_t*)p);
79f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  else if (size == 8) asan_write((uint64_t*)p);
80f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org}
81f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
82f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgNOINLINE void *malloc_fff(size_t size) {
83f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  void *res = malloc/**/(size); break_optimization(0); return res;}
84f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgNOINLINE void *malloc_eee(size_t size) {
85f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  void *res = malloc_fff(size); break_optimization(0); return res;}
86f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgNOINLINE void *malloc_ddd(size_t size) {
87f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  void *res = malloc_eee(size); break_optimization(0); return res;}
88f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgNOINLINE void *malloc_ccc(size_t size) {
89f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  void *res = malloc_ddd(size); break_optimization(0); return res;}
90f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgNOINLINE void *malloc_bbb(size_t size) {
91f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  void *res = malloc_ccc(size); break_optimization(0); return res;}
92f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgNOINLINE void *malloc_aaa(size_t size) {
93f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  void *res = malloc_bbb(size); break_optimization(0); return res;}
94f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
95f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#ifndef __APPLE__
96f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgNOINLINE void *memalign_fff(size_t alignment, size_t size) {
97f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  void *res = memalign/**/(alignment, size); break_optimization(0); return res;}
98f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgNOINLINE void *memalign_eee(size_t alignment, size_t size) {
99f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  void *res = memalign_fff(alignment, size); break_optimization(0); return res;}
100f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgNOINLINE void *memalign_ddd(size_t alignment, size_t size) {
101f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  void *res = memalign_eee(alignment, size); break_optimization(0); return res;}
102f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgNOINLINE void *memalign_ccc(size_t alignment, size_t size) {
103f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  void *res = memalign_ddd(alignment, size); break_optimization(0); return res;}
104f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgNOINLINE void *memalign_bbb(size_t alignment, size_t size) {
105f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  void *res = memalign_ccc(alignment, size); break_optimization(0); return res;}
106f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgNOINLINE void *memalign_aaa(size_t alignment, size_t size) {
107f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  void *res = memalign_bbb(alignment, size); break_optimization(0); return res;}
108f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#endif  // __APPLE__
109f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
110f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
111f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgNOINLINE void free_ccc(void *p) { free(p); break_optimization(0);}
112f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgNOINLINE void free_bbb(void *p) { free_ccc(p); break_optimization(0);}
113f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgNOINLINE void free_aaa(void *p) { free_bbb(p); break_optimization(0);}
114f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
115f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgtemplate<typename T>
116f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgNOINLINE void oob_test(int size, int off) {
117f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  char *p = (char*)malloc_aaa(size);
118f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  // fprintf(stderr, "writing %d byte(s) into [%p,%p) with offset %d\n",
119f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  //        sizeof(T), p, p + size, off);
120f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  asan_write((T*)(p + off));
121f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  free_aaa(p);
122f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org}
123f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
124f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
125f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgtemplate<typename T>
126f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgNOINLINE void uaf_test(int size, int off) {
127f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  char *p = (char *)malloc_aaa(size);
128f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  free_aaa(p);
129f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  for (int i = 1; i < 100; i++)
130f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org    free_aaa(malloc_aaa(i));
131f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  fprintf(stderr, "writing %ld byte(s) at %p with offset %d\n",
132f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org          (long)sizeof(T), p, off);
133f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  asan_write((T*)(p + off));
134f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org}
135f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
136f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgTEST(AddressSanitizer, HasFeatureAddressSanitizerTest) {
137f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#if defined(__has_feature) && __has_feature(address_sanitizer)
138f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  bool asan = 1;
139f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#else
140f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  bool asan = 0;
141f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#endif
142f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  EXPECT_EQ(true, asan);
143f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org}
144f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
145f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgTEST(AddressSanitizer, SimpleDeathTest) {
146f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  EXPECT_DEATH(exit(1), "");
147f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org}
148f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
149f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgTEST(AddressSanitizer, VariousMallocsTest) {
150f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  // fprintf(stderr, "malloc:\n");
151f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  int *a = (int*)malloc(100 * sizeof(int));
152f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  a[50] = 0;
153f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  free(a);
154f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
155f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  // fprintf(stderr, "realloc:\n");
156f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  int *r = (int*)malloc(10);
157f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  r = (int*)realloc(r, 2000 * sizeof(int));
158f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  r[1000] = 0;
159f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  free(r);
160f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
161f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  // fprintf(stderr, "operator new []\n");
162f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  int *b = new int[100];
163f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  b[50] = 0;
164f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  delete [] b;
165f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
166f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  // fprintf(stderr, "operator new\n");
167f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  int *c = new int;
168f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  *c = 0;
169f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  delete c;
170f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
171f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#if !defined(__APPLE__) && !defined(ANDROID)
172f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  // fprintf(stderr, "posix_memalign\n");
173f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  int *pm;
174f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  int pm_res = posix_memalign((void**)&pm, kPageSize, kPageSize);
175f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  EXPECT_EQ(0, pm_res);
176f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  free(pm);
177f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#endif
178f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
179f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#if !defined(__APPLE__)
180f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  int *ma = (int*)memalign(kPageSize, kPageSize);
181f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  EXPECT_EQ(0, (uintptr_t)ma % kPageSize);
182f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  ma[123] = 0;
183f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  free(ma);
184f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#endif  // __APPLE__
185f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org}
186f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
187f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgTEST(AddressSanitizer, CallocTest) {
188f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  int *a = (int*)calloc(100, sizeof(int));
189f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  EXPECT_EQ(0, a[10]);
190f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  free(a);
191f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org}
192f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
193f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgTEST(AddressSanitizer, VallocTest) {
194f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  void *a = valloc(100);
195f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  EXPECT_EQ(0, (uintptr_t)a % kPageSize);
196f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  free(a);
197f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org}
198
199#ifndef __APPLE__
200TEST(AddressSanitizer, PvallocTest) {
201  char *a = (char*)pvalloc(kPageSize + 100);
202  EXPECT_EQ(0, (uintptr_t)a % kPageSize);
203  a[kPageSize + 101] = 1;  // we should not report an error here.
204  free(a);
205
206  a = (char*)pvalloc(0);  // pvalloc(0) should allocate at least one page.
207  EXPECT_EQ(0, (uintptr_t)a % kPageSize);
208  a[101] = 1;  // we should not report an error here.
209  free(a);
210}
211#endif  // __APPLE__
212
213void NoOpSignalHandler(int unused) {
214  fprintf(stderr, "NoOpSignalHandler (should not happen). Aborting\n");
215  abort();
216}
217
218void NoOpSigaction(int, siginfo_t *siginfo, void *context) {
219  fprintf(stderr, "NoOpSigaction (should not happen). Aborting\n");
220  abort();
221}
222
223TEST(AddressSanitizer, SignalTest) {
224  signal(SIGSEGV, NoOpSignalHandler);
225  signal(SIGILL, NoOpSignalHandler);
226  // If asan did not intercept sigaction NoOpSigaction will fire.
227  char *x = Ident((char*)malloc(5));
228  EXPECT_DEATH(x[6]++, "is located 1 bytes to the right");
229  free(Ident(x));
230}
231
232TEST(AddressSanitizer, SigactionTest) {
233  {
234    struct sigaction sigact;
235    memset(&sigact, 0, sizeof(sigact));
236    sigact.sa_sigaction = NoOpSigaction;;
237    sigact.sa_flags = SA_SIGINFO;
238    sigaction(SIGSEGV, &sigact, 0);
239  }
240
241  {
242    struct sigaction sigact;
243    memset(&sigact, 0, sizeof(sigact));
244    sigact.sa_sigaction = NoOpSigaction;;
245    sigact.sa_flags = SA_SIGINFO;
246    sigaction(SIGILL, &sigact, 0);
247  }
248
249  // If asan did not intercept sigaction NoOpSigaction will fire.
250  char *x = Ident((char*)malloc(5));
251  EXPECT_DEATH(x[6]++, "is located 1 bytes to the right");
252  free(Ident(x));
253}
254
255void *TSDWorker(void *test_key) {
256  if (test_key) {
257    pthread_setspecific(*(pthread_key_t*)test_key, (void*)0xfeedface);
258  }
259  return NULL;
260}
261
262void TSDDestructor(void *tsd) {
263  // Spawning a thread will check that the current thread id is not -1.
264  pthread_t th;
265  pthread_create(&th, NULL, TSDWorker, NULL);
266  pthread_join(th, NULL);
267}
268
269// This tests triggers the thread-specific data destruction fiasco which occurs
270// if we don't manage the TSD destructors ourselves. We create a new pthread
271// key with a non-NULL destructor which is likely to be put after the destructor
272// of AsanThread in the list of destructors.
273// In this case the TSD for AsanThread will be destroyed before TSDDestructor
274// is called for the child thread, and a CHECK will fail when we call
275// pthread_create() to spawn the grandchild.
276TEST(AddressSanitizer, DISABLED_TSDTest) {
277  pthread_t th;
278  pthread_key_t test_key;
279  pthread_key_create(&test_key, TSDDestructor);
280  pthread_create(&th, NULL, TSDWorker, &test_key);
281  pthread_join(th, NULL);
282  pthread_key_delete(test_key);
283}
284
285template<typename T>
286void OOBTest() {
287  char expected_str[100];
288  for (int size = sizeof(T); size < 20; size += 5) {
289    for (int i = -5; i < 0; i++) {
290      const char *str =
291          "is located.*%d byte.*to the left";
292      sprintf(expected_str, str, abs(i));
293      EXPECT_DEATH(oob_test<T>(size, i), expected_str);
294    }
295
296    for (int i = 0; i < size - sizeof(T) + 1; i++)
297      oob_test<T>(size, i);
298
299    for (int i = size - sizeof(T) + 1; i <= size + 3 * sizeof(T); i++) {
300      const char *str =
301          "is located.*%d byte.*to the right";
302      int off = i >= size ? (i - size) : 0;
303      // we don't catch unaligned partially OOB accesses.
304      if (i % sizeof(T)) continue;
305      sprintf(expected_str, str, off);
306      EXPECT_DEATH(oob_test<T>(size, i), expected_str);
307    }
308  }
309
310  EXPECT_DEATH(oob_test<T>(kLargeMalloc, -1),
311          "is located.*1 byte.*to the left");
312  EXPECT_DEATH(oob_test<T>(kLargeMalloc, kLargeMalloc),
313          "is located.*0 byte.*to the right");
314}
315
316// TODO(glider): the following tests are EXTREMELY slow on Darwin:
317//   AddressSanitizer.OOB_char (125503 ms)
318//   AddressSanitizer.OOB_int (126890 ms)
319//   AddressSanitizer.OOBRightTest (315605 ms)
320//   AddressSanitizer.SimpleStackTest (366559 ms)
321
322TEST(AddressSanitizer, OOB_char) {
323  OOBTest<U1>();
324}
325
326TEST(AddressSanitizer, OOB_int) {
327  OOBTest<U4>();
328}
329
330TEST(AddressSanitizer, OOBRightTest) {
331  for (size_t access_size = 1; access_size <= 8; access_size *= 2) {
332    for (size_t alloc_size = 1; alloc_size <= 8; alloc_size++) {
333      for (size_t offset = 0; offset <= 8; offset += access_size) {
334        void *p = malloc(alloc_size);
335        // allocated: [p, p + alloc_size)
336        // accessed:  [p + offset, p + offset + access_size)
337        uint8_t *addr = (uint8_t*)p + offset;
338        if (offset + access_size <= alloc_size) {
339          asan_write_sized_aligned(addr, access_size);
340        } else {
341          int outside_bytes = offset > alloc_size ? (offset - alloc_size) : 0;
342          const char *str =
343              "is located.%d *byte.*to the right";
344          char expected_str[100];
345          sprintf(expected_str, str, outside_bytes);
346          EXPECT_DEATH(asan_write_sized_aligned(addr, access_size),
347                       expected_str);
348        }
349        free(p);
350      }
351    }
352  }
353}
354
355TEST(AddressSanitizer, UAF_char) {
356  const char *uaf_string = "AddressSanitizer.*heap-use-after-free";
357  EXPECT_DEATH(uaf_test<U1>(1, 0), uaf_string);
358  EXPECT_DEATH(uaf_test<U1>(10, 0), uaf_string);
359  EXPECT_DEATH(uaf_test<U1>(10, 10), uaf_string);
360  EXPECT_DEATH(uaf_test<U1>(kLargeMalloc, 0), uaf_string);
361  EXPECT_DEATH(uaf_test<U1>(kLargeMalloc, kLargeMalloc / 2), uaf_string);
362}
363
364#if ASAN_HAS_BLACKLIST
365TEST(AddressSanitizer, IgnoreTest) {
366  int *x = Ident(new int);
367  delete Ident(x);
368  *x = 0;
369}
370#endif  // ASAN_HAS_BLACKLIST
371
372struct StructWithBitField {
373  int bf1:1;
374  int bf2:1;
375  int bf3:1;
376  int bf4:29;
377};
378
379TEST(AddressSanitizer, BitFieldPositiveTest) {
380  StructWithBitField *x = new StructWithBitField;
381  delete Ident(x);
382  EXPECT_DEATH(x->bf1 = 0, "use-after-free");
383  EXPECT_DEATH(x->bf2 = 0, "use-after-free");
384  EXPECT_DEATH(x->bf3 = 0, "use-after-free");
385  EXPECT_DEATH(x->bf4 = 0, "use-after-free");
386};
387
388struct StructWithBitFields_8_24 {
389  int a:8;
390  int b:24;
391};
392
393TEST(AddressSanitizer, BitFieldNegativeTest) {
394  StructWithBitFields_8_24 *x = Ident(new StructWithBitFields_8_24);
395  x->a = 0;
396  x->b = 0;
397  delete Ident(x);
398}
399
400TEST(AddressSanitizer, OutOfMemoryTest) {
401  size_t size = __WORDSIZE == 64 ? (size_t)(1ULL << 48) : (0xf0000000);
402  EXPECT_EQ(0, realloc(0, size));
403  EXPECT_EQ(0, realloc(0, ~Ident(0)));
404  EXPECT_EQ(0, malloc(size));
405  EXPECT_EQ(0, malloc(~Ident(0)));
406  EXPECT_EQ(0, calloc(1, size));
407  EXPECT_EQ(0, calloc(1, ~Ident(0)));
408}
409
410#if ASAN_NEEDS_SEGV
411TEST(AddressSanitizer, WildAddressTest) {
412  char *c = (char*)0x123;
413  EXPECT_DEATH(*c = 0, "AddressSanitizer crashed on unknown address");
414}
415#endif
416
417static void MallocStress(size_t n) {
418  uint32_t seed = my_rand(&global_seed);
419  for (size_t iter = 0; iter < 10; iter++) {
420    vector<void *> vec;
421    for (size_t i = 0; i < n; i++) {
422      if ((i % 3) == 0) {
423        if (vec.empty()) continue;
424        size_t idx = my_rand(&seed) % vec.size();
425        void *ptr = vec[idx];
426        vec[idx] = vec.back();
427        vec.pop_back();
428        free_aaa(ptr);
429      } else {
430        size_t size = my_rand(&seed) % 1000 + 1;
431#ifndef __APPLE__
432        size_t alignment = 1 << (my_rand(&seed) % 7 + 3);
433        char *ptr = (char*)memalign_aaa(alignment, size);
434#else
435        char *ptr = (char*) malloc_aaa(size);
436#endif
437        vec.push_back(ptr);
438        ptr[0] = 0;
439        ptr[size-1] = 0;
440        ptr[size/2] = 0;
441      }
442    }
443    for (size_t i = 0; i < vec.size(); i++)
444      free_aaa(vec[i]);
445  }
446}
447
448TEST(AddressSanitizer, MallocStressTest) {
449  MallocStress((ASAN_LOW_MEMORY) ? 20000 : 200000);
450}
451
452static void TestLargeMalloc(size_t size) {
453  char buff[1024];
454  sprintf(buff, "is located 1 bytes to the left of %lu-byte", (long)size);
455  EXPECT_DEATH(Ident((char*)malloc(size))[-1] = 0, buff);
456}
457
458TEST(AddressSanitizer, LargeMallocTest) {
459  for (int i = 113; i < (1 << 28); i = i * 2 + 13) {
460    TestLargeMalloc(i);
461  }
462}
463
464#if ASAN_LOW_MEMORY != 1
465TEST(AddressSanitizer, HugeMallocTest) {
466#ifdef __APPLE__
467  // It was empirically found out that 1215 megabytes is the maximum amount of
468  // memory available to the process under AddressSanitizer on Darwin.
469  // (the libSystem malloc() allows allocating up to 2300 megabytes without
470  // ASan).
471  size_t n_megs = __WORDSIZE == 32 ? 1200 : 4100;
472#else
473  size_t n_megs = __WORDSIZE == 32 ? 2600 : 4100;
474#endif
475  TestLargeMalloc(n_megs << 20);
476}
477#endif
478
479TEST(AddressSanitizer, ThreadedMallocStressTest) {
480  const int kNumThreads = 4;
481  const int kNumIterations = (ASAN_LOW_MEMORY) ? 10000 : 100000;
482  pthread_t t[kNumThreads];
483  for (int i = 0; i < kNumThreads; i++) {
484    pthread_create(&t[i], 0, (void* (*)(void *x))MallocStress,
485        (void*)kNumIterations);
486  }
487  for (int i = 0; i < kNumThreads; i++) {
488    pthread_join(t[i], 0);
489  }
490}
491
492void *ManyThreadsWorker(void *a) {
493  for (int iter = 0; iter < 100; iter++) {
494    for (size_t size = 100; size < 2000; size *= 2) {
495      free(Ident(malloc(size)));
496    }
497  }
498  return 0;
499}
500
501TEST(AddressSanitizer, ManyThreadsTest) {
502  const size_t kNumThreads = __WORDSIZE == 32 ? 30 : 1000;
503  pthread_t t[kNumThreads];
504  for (size_t i = 0; i < kNumThreads; i++) {
505    pthread_create(&t[i], 0, (void* (*)(void *x))ManyThreadsWorker, (void*)i);
506  }
507  for (size_t i = 0; i < kNumThreads; i++) {
508    pthread_join(t[i], 0);
509  }
510}
511
512TEST(AddressSanitizer, ReallocTest) {
513  const int kMinElem = 5;
514  int *ptr = (int*)malloc(sizeof(int) * kMinElem);
515  ptr[3] = 3;
516  for (int i = 0; i < 10000; i++) {
517    ptr = (int*)realloc(ptr,
518        (my_rand(&global_seed) % 1000 + kMinElem) * sizeof(int));
519    EXPECT_EQ(3, ptr[3]);
520  }
521}
522
523#ifndef __APPLE__
524static const char *kMallocUsableSizeErrorMsg =
525  "AddressSanitizer attempting to call malloc_usable_size()";
526
527TEST(AddressSanitizer, MallocUsableSizeTest) {
528  const size_t kArraySize = 100;
529  char *array = Ident((char*)malloc(kArraySize));
530  int *int_ptr = Ident(new int);
531  EXPECT_EQ(0, malloc_usable_size(NULL));
532  EXPECT_EQ(kArraySize, malloc_usable_size(array));
533  EXPECT_EQ(sizeof(int), malloc_usable_size(int_ptr));
534  EXPECT_DEATH(malloc_usable_size((void*)0x123), kMallocUsableSizeErrorMsg);
535  EXPECT_DEATH(malloc_usable_size(array + kArraySize / 2),
536               kMallocUsableSizeErrorMsg);
537  free(array);
538  EXPECT_DEATH(malloc_usable_size(array), kMallocUsableSizeErrorMsg);
539}
540#endif
541
542void WrongFree() {
543  int *x = (int*)malloc(100 * sizeof(int));
544  // Use the allocated memory, otherwise Clang will optimize it out.
545  Ident(x);
546  free(x + 1);
547}
548
549TEST(AddressSanitizer, WrongFreeTest) {
550  EXPECT_DEATH(WrongFree(),
551               "ERROR: AddressSanitizer attempting free.*not malloc");
552}
553
554void DoubleFree() {
555  int *x = (int*)malloc(100 * sizeof(int));
556  fprintf(stderr, "DoubleFree: x=%p\n", x);
557  free(x);
558  free(x);
559  fprintf(stderr, "should have failed in the second free(%p)\n", x);
560  abort();
561}
562
563TEST(AddressSanitizer, DoubleFreeTest) {
564  EXPECT_DEATH(DoubleFree(), ASAN_PCRE_DOTALL
565               "ERROR: AddressSanitizer attempting double-free"
566               ".*is located 0 bytes inside of 400-byte region"
567               ".*freed by thread T0 here"
568               ".*previously allocated by thread T0 here");
569}
570
571template<int kSize>
572NOINLINE void SizedStackTest() {
573  char a[kSize];
574  char  *A = Ident((char*)&a);
575  for (size_t i = 0; i < kSize; i++)
576    A[i] = i;
577  EXPECT_DEATH(A[-1] = 0, "");
578  EXPECT_DEATH(A[-20] = 0, "");
579  EXPECT_DEATH(A[-31] = 0, "");
580  EXPECT_DEATH(A[kSize] = 0, "");
581  EXPECT_DEATH(A[kSize + 1] = 0, "");
582  EXPECT_DEATH(A[kSize + 10] = 0, "");
583  EXPECT_DEATH(A[kSize + 31] = 0, "");
584}
585
586TEST(AddressSanitizer, SimpleStackTest) {
587  SizedStackTest<1>();
588  SizedStackTest<2>();
589  SizedStackTest<3>();
590  SizedStackTest<4>();
591  SizedStackTest<5>();
592  SizedStackTest<6>();
593  SizedStackTest<7>();
594  SizedStackTest<16>();
595  SizedStackTest<25>();
596  SizedStackTest<34>();
597  SizedStackTest<43>();
598  SizedStackTest<51>();
599  SizedStackTest<62>();
600  SizedStackTest<64>();
601  SizedStackTest<128>();
602}
603
604TEST(AddressSanitizer, ManyStackObjectsTest) {
605  char XXX[10];
606  char YYY[20];
607  char ZZZ[30];
608  Ident(XXX);
609  Ident(YYY);
610  EXPECT_DEATH(Ident(ZZZ)[-1] = 0, ASAN_PCRE_DOTALL "XXX.*YYY.*ZZZ");
611}
612
613NOINLINE static void Frame0(int frame, char *a, char *b, char *c) {
614  char d[4] = {0};
615  char *D = Ident(d);
616  switch (frame) {
617    case 3: a[5]++; break;
618    case 2: b[5]++; break;
619    case 1: c[5]++; break;
620    case 0: D[5]++; break;
621  }
622}
623NOINLINE static void Frame1(int frame, char *a, char *b) {
624  char c[4] = {0}; Frame0(frame, a, b, c);
625  break_optimization(0);
626}
627NOINLINE static void Frame2(int frame, char *a) {
628  char b[4] = {0}; Frame1(frame, a, b);
629  break_optimization(0);
630}
631NOINLINE static void Frame3(int frame) {
632  char a[4] = {0}; Frame2(frame, a);
633  break_optimization(0);
634}
635
636TEST(AddressSanitizer, GuiltyStackFrame0Test) {
637  EXPECT_DEATH(Frame3(0), "located .*in frame <.*Frame0");
638}
639TEST(AddressSanitizer, GuiltyStackFrame1Test) {
640  EXPECT_DEATH(Frame3(1), "located .*in frame <.*Frame1");
641}
642TEST(AddressSanitizer, GuiltyStackFrame2Test) {
643  EXPECT_DEATH(Frame3(2), "located .*in frame <.*Frame2");
644}
645TEST(AddressSanitizer, GuiltyStackFrame3Test) {
646  EXPECT_DEATH(Frame3(3), "located .*in frame <.*Frame3");
647}
648
649NOINLINE void LongJmpFunc1(jmp_buf buf) {
650  // create three red zones for these two stack objects.
651  int a;
652  int b;
653
654  int *A = Ident(&a);
655  int *B = Ident(&b);
656  *A = *B;
657  longjmp(buf, 1);
658}
659
660NOINLINE void UnderscopeLongJmpFunc1(jmp_buf buf) {
661  // create three red zones for these two stack objects.
662  int a;
663  int b;
664
665  int *A = Ident(&a);
666  int *B = Ident(&b);
667  *A = *B;
668  _longjmp(buf, 1);
669}
670
671NOINLINE void SigLongJmpFunc1(sigjmp_buf buf) {
672  // create three red zones for these two stack objects.
673  int a;
674  int b;
675
676  int *A = Ident(&a);
677  int *B = Ident(&b);
678  *A = *B;
679  siglongjmp(buf, 1);
680}
681
682
683NOINLINE void TouchStackFunc() {
684  int a[100];  // long array will intersect with redzones from LongJmpFunc1.
685  int *A = Ident(a);
686  for (int i = 0; i < 100; i++)
687    A[i] = i*i;
688}
689
690// Test that we handle longjmp and do not report fals positives on stack.
691TEST(AddressSanitizer, LongJmpTest) {
692  static jmp_buf buf;
693  if (!setjmp(buf)) {
694    LongJmpFunc1(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 (__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(strlen(str + 1), length - 1);
953    EXPECT_EQ(strlen(str + length), 0);
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 (int 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
1100typedef char*(*PointerToStrChr)(const char*, int);
1101void RunStrChrTest(PointerToStrChr StrChr) {
1102  size_t size = Ident(100);
1103  char *str = MallocAndMemsetString(size);
1104  str[10] = 'q';
1105  str[11] = '\0';
1106  EXPECT_EQ(str, StrChr(str, 'z'));
1107  EXPECT_EQ(str + 10, StrChr(str, 'q'));
1108  EXPECT_EQ(NULL, StrChr(str, 'a'));
1109  // StrChr argument points to not allocated memory.
1110  EXPECT_DEATH(Ident(StrChr(str - 1, 'z')), LeftOOBErrorMessage(1));
1111  EXPECT_DEATH(Ident(StrChr(str + size, 'z')), RightOOBErrorMessage(0));
1112  // Overwrite the terminator and hit not allocated memory.
1113  str[11] = 'z';
1114  EXPECT_DEATH(Ident(StrChr(str, 'a')), RightOOBErrorMessage(0));
1115  free(str);
1116}
1117TEST(AddressSanitizer, StrChrAndIndexOOBTest) {
1118  RunStrChrTest(&strchr);
1119  RunStrChrTest(&index);
1120}
1121
1122TEST(AddressSanitizer, StrCmpAndFriendsLogicTest) {
1123  // strcmp
1124  EXPECT_EQ(0, strcmp("", ""));
1125  EXPECT_EQ(0, strcmp("abcd", "abcd"));
1126  EXPECT_GT(0, strcmp("ab", "ac"));
1127  EXPECT_GT(0, strcmp("abc", "abcd"));
1128  EXPECT_LT(0, strcmp("acc", "abc"));
1129  EXPECT_LT(0, strcmp("abcd", "abc"));
1130
1131  // strncmp
1132  EXPECT_EQ(0, strncmp("a", "b", 0));
1133  EXPECT_EQ(0, strncmp("abcd", "abcd", 10));
1134  EXPECT_EQ(0, strncmp("abcd", "abcef", 3));
1135  EXPECT_GT(0, strncmp("abcde", "abcfa", 4));
1136  EXPECT_GT(0, strncmp("a", "b", 5));
1137  EXPECT_GT(0, strncmp("bc", "bcde", 4));
1138  EXPECT_LT(0, strncmp("xyz", "xyy", 10));
1139  EXPECT_LT(0, strncmp("baa", "aaa", 1));
1140  EXPECT_LT(0, strncmp("zyx", "", 2));
1141
1142  // strcasecmp
1143  EXPECT_EQ(0, strcasecmp("", ""));
1144  EXPECT_EQ(0, strcasecmp("zzz", "zzz"));
1145  EXPECT_EQ(0, strcasecmp("abCD", "ABcd"));
1146  EXPECT_GT(0, strcasecmp("aB", "Ac"));
1147  EXPECT_GT(0, strcasecmp("ABC", "ABCd"));
1148  EXPECT_LT(0, strcasecmp("acc", "abc"));
1149  EXPECT_LT(0, strcasecmp("ABCd", "abc"));
1150
1151  // strncasecmp
1152  EXPECT_EQ(0, strncasecmp("a", "b", 0));
1153  EXPECT_EQ(0, strncasecmp("abCD", "ABcd", 10));
1154  EXPECT_EQ(0, strncasecmp("abCd", "ABcef", 3));
1155  EXPECT_GT(0, strncasecmp("abcde", "ABCfa", 4));
1156  EXPECT_GT(0, strncasecmp("a", "B", 5));
1157  EXPECT_GT(0, strncasecmp("bc", "BCde", 4));
1158  EXPECT_LT(0, strncasecmp("xyz", "xyy", 10));
1159  EXPECT_LT(0, strncasecmp("Baa", "aaa", 1));
1160  EXPECT_LT(0, strncasecmp("zyx", "", 2));
1161
1162  // memcmp
1163  EXPECT_EQ(0, memcmp("a", "b", 0));
1164  EXPECT_EQ(0, memcmp("ab\0c", "ab\0c", 4));
1165  EXPECT_GT(0, memcmp("\0ab", "\0ac", 3));
1166  EXPECT_GT(0, memcmp("abb\0", "abba", 4));
1167  EXPECT_LT(0, memcmp("ab\0cd", "ab\0c\0", 5));
1168  EXPECT_LT(0, memcmp("zza", "zyx", 3));
1169}
1170
1171typedef int(*PointerToStrCmp)(const char*, const char*);
1172void RunStrCmpTest(PointerToStrCmp StrCmp) {
1173  size_t size = Ident(100);
1174  char *s1 = MallocAndMemsetString(size);
1175  char *s2 = MallocAndMemsetString(size);
1176  s1[size - 1] = '\0';
1177  s2[size - 1] = '\0';
1178  // Normal StrCmp calls
1179  Ident(StrCmp(s1, s2));
1180  Ident(StrCmp(s1, s2 + size - 1));
1181  Ident(StrCmp(s1 + size - 1, s2 + size - 1));
1182  s1[size - 1] = 'z';
1183  s2[size - 1] = 'x';
1184  Ident(StrCmp(s1, s2));
1185  // One of arguments points to not allocated memory.
1186  EXPECT_DEATH(Ident(StrCmp)(s1 - 1, s2), LeftOOBErrorMessage(1));
1187  EXPECT_DEATH(Ident(StrCmp)(s1, s2 - 1), LeftOOBErrorMessage(1));
1188  EXPECT_DEATH(Ident(StrCmp)(s1 + size, s2), RightOOBErrorMessage(0));
1189  EXPECT_DEATH(Ident(StrCmp)(s1, s2 + size), RightOOBErrorMessage(0));
1190  // Hit unallocated memory and die.
1191  s2[size - 1] = 'z';
1192  EXPECT_DEATH(Ident(StrCmp)(s1, s1), RightOOBErrorMessage(0));
1193  EXPECT_DEATH(Ident(StrCmp)(s1 + size - 1, s2), RightOOBErrorMessage(0));
1194  free(s1);
1195  free(s2);
1196}
1197
1198TEST(AddressSanitizer, StrCmpOOBTest) {
1199  RunStrCmpTest(&strcmp);
1200}
1201
1202TEST(AddressSanitizer, StrCaseCmpOOBTest) {
1203  RunStrCmpTest(&strcasecmp);
1204}
1205
1206typedef int(*PointerToStrNCmp)(const char*, const char*, size_t);
1207void RunStrNCmpTest(PointerToStrNCmp StrNCmp) {
1208  size_t size = Ident(100);
1209  char *s1 = MallocAndMemsetString(size);
1210  char *s2 = MallocAndMemsetString(size);
1211  s1[size - 1] = '\0';
1212  s2[size - 1] = '\0';
1213  // Normal StrNCmp calls
1214  Ident(StrNCmp(s1, s2, size + 2));
1215  s1[size - 1] = 'z';
1216  s2[size - 1] = 'x';
1217  Ident(StrNCmp(s1 + size - 2, s2 + size - 2, size));
1218  s2[size - 1] = 'z';
1219  Ident(StrNCmp(s1 - 1, s2 - 1, 0));
1220  Ident(StrNCmp(s1 + size - 1, s2 + size - 1, 1));
1221  // One of arguments points to not allocated memory.
1222  EXPECT_DEATH(Ident(StrNCmp)(s1 - 1, s2, 1), LeftOOBErrorMessage(1));
1223  EXPECT_DEATH(Ident(StrNCmp)(s1, s2 - 1, 1), LeftOOBErrorMessage(1));
1224  EXPECT_DEATH(Ident(StrNCmp)(s1 + size, s2, 1), RightOOBErrorMessage(0));
1225  EXPECT_DEATH(Ident(StrNCmp)(s1, s2 + size, 1), RightOOBErrorMessage(0));
1226  // Hit unallocated memory and die.
1227  EXPECT_DEATH(Ident(StrNCmp)(s1 + 1, s2 + 1, size), RightOOBErrorMessage(0));
1228  EXPECT_DEATH(Ident(StrNCmp)(s1 + size - 1, s2, 2), RightOOBErrorMessage(0));
1229  free(s1);
1230  free(s2);
1231}
1232
1233TEST(AddressSanitizer, StrNCmpOOBTest) {
1234  RunStrNCmpTest(&strncmp);
1235}
1236
1237TEST(AddressSanitizer, StrNCaseCmpOOBTest) {
1238  RunStrNCmpTest(&strncasecmp);
1239}
1240
1241TEST(AddressSanitizer, MemCmpOOBTest) {
1242  size_t size = Ident(100);
1243  char *s1 = MallocAndMemsetString(size);
1244  char *s2 = MallocAndMemsetString(size);
1245  // Normal memcmp calls.
1246  Ident(memcmp(s1, s2, size));
1247  Ident(memcmp(s1 + size - 1, s2 + size - 1, 1));
1248  Ident(memcmp(s1 - 1, s2 - 1, 0));
1249  // One of arguments points to not allocated memory.
1250  EXPECT_DEATH(Ident(memcmp)(s1 - 1, s2, 1), LeftOOBErrorMessage(1));
1251  EXPECT_DEATH(Ident(memcmp)(s1, s2 - 1, 1), LeftOOBErrorMessage(1));
1252  EXPECT_DEATH(Ident(memcmp)(s1 + size, s2, 1), RightOOBErrorMessage(0));
1253  EXPECT_DEATH(Ident(memcmp)(s1, s2 + size, 1), RightOOBErrorMessage(0));
1254  // Hit unallocated memory and die.
1255  EXPECT_DEATH(Ident(memcmp)(s1 + 1, s2 + 1, size), RightOOBErrorMessage(0));
1256  EXPECT_DEATH(Ident(memcmp)(s1 + size - 1, s2, 2), RightOOBErrorMessage(0));
1257  // Zero bytes are not terminators and don't prevent from OOB.
1258  s1[size - 1] = '\0';
1259  s2[size - 1] = '\0';
1260  EXPECT_DEATH(Ident(memcmp)(s1, s2, size + 1), RightOOBErrorMessage(0));
1261  free(s1);
1262  free(s2);
1263}
1264
1265TEST(AddressSanitizer, StrCatOOBTest) {
1266  size_t to_size = Ident(100);
1267  char *to = MallocAndMemsetString(to_size);
1268  to[0] = '\0';
1269  size_t from_size = Ident(20);
1270  char *from = MallocAndMemsetString(from_size);
1271  from[from_size - 1] = '\0';
1272  // Normal strcat calls.
1273  strcat(to, from);
1274  strcat(to, from);
1275  strcat(to + from_size, from + from_size - 2);
1276  // Catenate empty string is not always an error.
1277  strcat(to - 1, from + from_size - 1);
1278  // One of arguments points to not allocated memory.
1279  EXPECT_DEATH(strcat(to - 1, from), LeftOOBErrorMessage(1));
1280  EXPECT_DEATH(strcat(to, from - 1), LeftOOBErrorMessage(1));
1281  EXPECT_DEATH(strcat(to + to_size, from), RightOOBErrorMessage(0));
1282  EXPECT_DEATH(strcat(to, from + from_size), RightOOBErrorMessage(0));
1283
1284  // "from" is not zero-terminated.
1285  from[from_size - 1] = 'z';
1286  EXPECT_DEATH(strcat(to, from), RightOOBErrorMessage(0));
1287  from[from_size - 1] = '\0';
1288  // "to" is not zero-terminated.
1289  memset(to, 'z', to_size);
1290  EXPECT_DEATH(strcat(to, from), RightOOBErrorMessage(0));
1291  // "to" is too short to fit "from".
1292  to[to_size - from_size + 1] = '\0';
1293  EXPECT_DEATH(strcat(to, from), RightOOBErrorMessage(0));
1294  // length of "to" is just enough.
1295  strcat(to, from + 1);
1296}
1297
1298static string OverlapErrorMessage(const string &func) {
1299  return func + "-param-overlap";
1300}
1301
1302TEST(AddressSanitizer, StrArgsOverlapTest) {
1303  size_t size = Ident(100);
1304  char *str = Ident((char*)malloc(size));
1305
1306// Do not check memcpy() on OS X 10.7 and later, where it actually aliases
1307// memmove().
1308#if !defined(__APPLE__) || !defined(MAC_OS_X_VERSION_10_7) || \
1309    (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7)
1310  // Check "memcpy". Use Ident() to avoid inlining.
1311  memset(str, 'z', size);
1312  Ident(memcpy)(str + 1, str + 11, 10);
1313  Ident(memcpy)(str, str, 0);
1314  EXPECT_DEATH(Ident(memcpy)(str, str + 14, 15), OverlapErrorMessage("memcpy"));
1315  EXPECT_DEATH(Ident(memcpy)(str + 14, str, 15), OverlapErrorMessage("memcpy"));
1316#endif
1317
1318  // We do not treat memcpy with to==from as a bug.
1319  // See http://llvm.org/bugs/show_bug.cgi?id=11763.
1320  // EXPECT_DEATH(Ident(memcpy)(str + 20, str + 20, 1),
1321  //              OverlapErrorMessage("memcpy"));
1322
1323  // Check "strcpy".
1324  memset(str, 'z', size);
1325  str[9] = '\0';
1326  strcpy(str + 10, str);
1327  EXPECT_DEATH(strcpy(str + 9, str), OverlapErrorMessage("strcpy"));
1328  EXPECT_DEATH(strcpy(str, str + 4), OverlapErrorMessage("strcpy"));
1329  strcpy(str, str + 5);
1330
1331  // Check "strncpy".
1332  memset(str, 'z', size);
1333  strncpy(str, str + 10, 10);
1334  EXPECT_DEATH(strncpy(str, str + 9, 10), OverlapErrorMessage("strncpy"));
1335  EXPECT_DEATH(strncpy(str + 9, str, 10), OverlapErrorMessage("strncpy"));
1336  str[10] = '\0';
1337  strncpy(str + 11, str, 20);
1338  EXPECT_DEATH(strncpy(str + 10, str, 20), OverlapErrorMessage("strncpy"));
1339
1340  // Check "strcat".
1341  memset(str, 'z', size);
1342  str[10] = '\0';
1343  str[20] = '\0';
1344  strcat(str, str + 10);
1345  strcat(str, str + 11);
1346  str[10] = '\0';
1347  strcat(str + 11, str);
1348  EXPECT_DEATH(strcat(str, str + 9), OverlapErrorMessage("strcat"));
1349  EXPECT_DEATH(strcat(str + 9, str), OverlapErrorMessage("strcat"));
1350  EXPECT_DEATH(strcat(str + 10, str), OverlapErrorMessage("strcat"));
1351
1352  free(str);
1353}
1354
1355void CallAtoi(const char *nptr) {
1356  Ident(atoi(nptr));
1357}
1358void CallAtol(const char *nptr) {
1359  Ident(atol(nptr));
1360}
1361void CallAtoll(const char *nptr) {
1362  Ident(atoll(nptr));
1363}
1364typedef void(*PointerToCallAtoi)(const char*);
1365
1366void RunAtoiOOBTest(PointerToCallAtoi Atoi) {
1367  char *array = MallocAndMemsetString(10, '1');
1368  // Invalid pointer to the string.
1369  EXPECT_DEATH(Atoi(array + 11), RightOOBErrorMessage(1));
1370  EXPECT_DEATH(Atoi(array - 1), LeftOOBErrorMessage(1));
1371  // Die if a buffer doesn't have terminating NULL.
1372  EXPECT_DEATH(Atoi(array), RightOOBErrorMessage(0));
1373  // Make last symbol a terminating NULL or other non-digit.
1374  array[9] = '\0';
1375  Atoi(array);
1376  array[9] = 'a';
1377  Atoi(array);
1378  Atoi(array + 9);
1379  // Sometimes we need to detect overflow if no digits are found.
1380  memset(array, ' ', 10);
1381  EXPECT_DEATH(Atoi(array), RightOOBErrorMessage(0));
1382  array[9] = '-';
1383  EXPECT_DEATH(Atoi(array), RightOOBErrorMessage(0));
1384  EXPECT_DEATH(Atoi(array + 9), RightOOBErrorMessage(0));
1385  array[8] = '-';
1386  Atoi(array);
1387  delete array;
1388}
1389
1390TEST(AddressSanitizer, AtoiAndFriendsOOBTest) {
1391  RunAtoiOOBTest(&CallAtoi);
1392  RunAtoiOOBTest(&CallAtol);
1393  RunAtoiOOBTest(&CallAtoll);
1394}
1395
1396void CallStrtol(const char *nptr, char **endptr, int base) {
1397  Ident(strtol(nptr, endptr, base));
1398}
1399void CallStrtoll(const char *nptr, char **endptr, int base) {
1400  Ident(strtoll(nptr, endptr, base));
1401}
1402typedef void(*PointerToCallStrtol)(const char*, char**, int);
1403
1404void RunStrtolOOBTest(PointerToCallStrtol Strtol) {
1405  char *array = MallocAndMemsetString(3);
1406  char *endptr = NULL;
1407  array[0] = '1';
1408  array[1] = '2';
1409  array[2] = '3';
1410  // Invalid pointer to the string.
1411  EXPECT_DEATH(Strtol(array + 3, NULL, 0), RightOOBErrorMessage(0));
1412  EXPECT_DEATH(Strtol(array - 1, NULL, 0), LeftOOBErrorMessage(1));
1413  // Buffer overflow if there is no terminating null (depends on base).
1414  Strtol(array, &endptr, 3);
1415  EXPECT_EQ(array + 2, endptr);
1416  EXPECT_DEATH(Strtol(array, NULL, 0), RightOOBErrorMessage(0));
1417  array[2] = 'z';
1418  Strtol(array, &endptr, 35);
1419  EXPECT_EQ(array + 2, endptr);
1420  EXPECT_DEATH(Strtol(array, NULL, 36), RightOOBErrorMessage(0));
1421  // Add terminating zero to get rid of overflow.
1422  array[2] = '\0';
1423  Strtol(array, NULL, 36);
1424  // Don't check for overflow if base is invalid.
1425  Strtol(array - 1, NULL, -1);
1426  Strtol(array + 3, NULL, 1);
1427  // Sometimes we need to detect overflow if no digits are found.
1428  array[0] = array[1] = array[2] = ' ';
1429  EXPECT_DEATH(Strtol(array, NULL, 0), RightOOBErrorMessage(0));
1430  array[2] = '+';
1431  EXPECT_DEATH(Strtol(array, NULL, 0), RightOOBErrorMessage(0));
1432  array[2] = '-';
1433  EXPECT_DEATH(Strtol(array, NULL, 0), RightOOBErrorMessage(0));
1434  array[1] = '+';
1435  Strtol(array, NULL, 0);
1436  array[1] = array[2] = 'z';
1437  Strtol(array, &endptr, 0);
1438  EXPECT_EQ(array, endptr);
1439  Strtol(array + 2, NULL, 0);
1440  EXPECT_EQ(array, endptr);
1441  delete array;
1442}
1443
1444TEST(AddressSanitizer, StrtollOOBTest) {
1445  RunStrtolOOBTest(&CallStrtoll);
1446}
1447TEST(AddressSanitizer, StrtolOOBTest) {
1448  RunStrtolOOBTest(&CallStrtol);
1449}
1450
1451// At the moment we instrument memcpy/memove/memset calls at compile time so we
1452// can't handle OOB error if these functions are called by pointer, see disabled
1453// MemIntrinsicCallByPointerTest below
1454typedef void*(*PointerToMemTransfer)(void*, const void*, size_t);
1455typedef void*(*PointerToMemSet)(void*, int, size_t);
1456
1457void CallMemSetByPointer(PointerToMemSet MemSet) {
1458  size_t size = Ident(100);
1459  char *array = Ident((char*)malloc(size));
1460  EXPECT_DEATH(MemSet(array, 0, 101), RightOOBErrorMessage(0));
1461  free(array);
1462}
1463
1464void CallMemTransferByPointer(PointerToMemTransfer MemTransfer) {
1465  size_t size = Ident(100);
1466  char *src = Ident((char*)malloc(size));
1467  char *dst = Ident((char*)malloc(size));
1468  EXPECT_DEATH(MemTransfer(dst, src, 101), RightOOBErrorMessage(0));
1469  free(src);
1470  free(dst);
1471}
1472
1473TEST(AddressSanitizer, DISABLED_MemIntrinsicCallByPointerTest) {
1474  CallMemSetByPointer(&memset);
1475  CallMemTransferByPointer(&memcpy);
1476  CallMemTransferByPointer(&memmove);
1477}
1478
1479// This test case fails
1480// Clang optimizes memcpy/memset calls which lead to unaligned access
1481TEST(AddressSanitizer, DISABLED_MemIntrinsicUnalignedAccessTest) {
1482  int size = Ident(4096);
1483  char *s = Ident((char*)malloc(size));
1484  EXPECT_DEATH(memset(s + size - 1, 0, 2), RightOOBErrorMessage(0));
1485  free(s);
1486}
1487
1488// TODO(samsonov): Add a test with malloc(0)
1489// TODO(samsonov): Add tests for str* and mem* functions.
1490
1491NOINLINE static int LargeFunction(bool do_bad_access) {
1492  int *x = new int[100];
1493  x[0]++;
1494  x[1]++;
1495  x[2]++;
1496  x[3]++;
1497  x[4]++;
1498  x[5]++;
1499  x[6]++;
1500  x[7]++;
1501  x[8]++;
1502  x[9]++;
1503
1504  x[do_bad_access ? 100 : 0]++; int res = __LINE__;
1505
1506  x[10]++;
1507  x[11]++;
1508  x[12]++;
1509  x[13]++;
1510  x[14]++;
1511  x[15]++;
1512  x[16]++;
1513  x[17]++;
1514  x[18]++;
1515  x[19]++;
1516
1517  delete x;
1518  return res;
1519}
1520
1521// Test the we have correct debug info for the failing instruction.
1522// This test requires the in-process symbolizer to be enabled by default.
1523TEST(AddressSanitizer, DISABLED_LargeFunctionSymbolizeTest) {
1524  int failing_line = LargeFunction(false);
1525  char expected_warning[128];
1526  sprintf(expected_warning, "LargeFunction.*asan_test.cc:%d", failing_line);
1527  EXPECT_DEATH(LargeFunction(true), expected_warning);
1528}
1529
1530// Check that we unwind and symbolize correctly.
1531TEST(AddressSanitizer, DISABLED_MallocFreeUnwindAndSymbolizeTest) {
1532  int *a = (int*)malloc_aaa(sizeof(int));
1533  *a = 1;
1534  free_aaa(a);
1535  EXPECT_DEATH(*a = 1, "free_ccc.*free_bbb.*free_aaa.*"
1536               "malloc_fff.*malloc_eee.*malloc_ddd");
1537}
1538
1539void *ThreadedTestAlloc(void *a) {
1540  int **p = (int**)a;
1541  *p = new int;
1542  return 0;
1543}
1544
1545void *ThreadedTestFree(void *a) {
1546  int **p = (int**)a;
1547  delete *p;
1548  return 0;
1549}
1550
1551void *ThreadedTestUse(void *a) {
1552  int **p = (int**)a;
1553  **p = 1;
1554  return 0;
1555}
1556
1557void ThreadedTestSpawn() {
1558  pthread_t t;
1559  int *x;
1560  pthread_create(&t, 0, ThreadedTestAlloc, &x);
1561  pthread_join(t, 0);
1562  pthread_create(&t, 0, ThreadedTestFree, &x);
1563  pthread_join(t, 0);
1564  pthread_create(&t, 0, ThreadedTestUse, &x);
1565  pthread_join(t, 0);
1566}
1567
1568TEST(AddressSanitizer, ThreadedTest) {
1569  EXPECT_DEATH(ThreadedTestSpawn(),
1570               ASAN_PCRE_DOTALL
1571               "Thread T.*created"
1572               ".*Thread T.*created"
1573               ".*Thread T.*created");
1574}
1575
1576#if ASAN_NEEDS_SEGV
1577TEST(AddressSanitizer, ShadowGapTest) {
1578#if __WORDSIZE == 32
1579  char *addr = (char*)0x22000000;
1580#else
1581  char *addr = (char*)0x0000100000080000;
1582#endif
1583  EXPECT_DEATH(*addr = 1, "AddressSanitizer crashed on unknown");
1584}
1585#endif  // ASAN_NEEDS_SEGV
1586
1587extern "C" {
1588NOINLINE static void UseThenFreeThenUse() {
1589  char *x = Ident((char*)malloc(8));
1590  *x = 1;
1591  free_aaa(x);
1592  *x = 2;
1593}
1594}
1595
1596TEST(AddressSanitizer, UseThenFreeThenUseTest) {
1597  EXPECT_DEATH(UseThenFreeThenUse(), "freed by thread");
1598}
1599
1600TEST(AddressSanitizer, StrDupTest) {
1601  free(strdup(Ident("123")));
1602}
1603
1604// Currently we create and poison redzone at right of global variables.
1605char glob5[5];
1606static char static110[110];
1607const char ConstGlob[7] = {1, 2, 3, 4, 5, 6, 7};
1608static const char StaticConstGlob[3] = {9, 8, 7};
1609extern int GlobalsTest(int x);
1610
1611TEST(AddressSanitizer, GlobalTest) {
1612  static char func_static15[15];
1613
1614  static char fs1[10];
1615  static char fs2[10];
1616  static char fs3[10];
1617
1618  glob5[Ident(0)] = 0;
1619  glob5[Ident(1)] = 0;
1620  glob5[Ident(2)] = 0;
1621  glob5[Ident(3)] = 0;
1622  glob5[Ident(4)] = 0;
1623
1624  EXPECT_DEATH(glob5[Ident(5)] = 0,
1625               "0 bytes to the right of global variable.*glob5.* size 5");
1626  EXPECT_DEATH(glob5[Ident(5+6)] = 0,
1627               "6 bytes to the right of global variable.*glob5.* size 5");
1628  Ident(static110);  // avoid optimizations
1629  static110[Ident(0)] = 0;
1630  static110[Ident(109)] = 0;
1631  EXPECT_DEATH(static110[Ident(110)] = 0,
1632               "0 bytes to the right of global variable");
1633  EXPECT_DEATH(static110[Ident(110+7)] = 0,
1634               "7 bytes to the right of global variable");
1635
1636  Ident(func_static15);  // avoid optimizations
1637  func_static15[Ident(0)] = 0;
1638  EXPECT_DEATH(func_static15[Ident(15)] = 0,
1639               "0 bytes to the right of global variable");
1640  EXPECT_DEATH(func_static15[Ident(15 + 9)] = 0,
1641               "9 bytes to the right of global variable");
1642
1643  Ident(fs1);
1644  Ident(fs2);
1645  Ident(fs3);
1646
1647  // We don't create left redzones, so this is not 100% guaranteed to fail.
1648  // But most likely will.
1649  EXPECT_DEATH(fs2[Ident(-1)] = 0, "is located.*of global variable");
1650
1651  EXPECT_DEATH(Ident(Ident(ConstGlob)[8]),
1652               "is located 1 bytes to the right of .*ConstGlob");
1653  EXPECT_DEATH(Ident(Ident(StaticConstGlob)[5]),
1654               "is located 2 bytes to the right of .*StaticConstGlob");
1655
1656  // call stuff from another file.
1657  GlobalsTest(0);
1658}
1659
1660TEST(AddressSanitizer, GlobalStringConstTest) {
1661  static const char *zoo = "FOOBAR123";
1662  const char *p = Ident(zoo);
1663  EXPECT_DEATH(Ident(p[15]), "is ascii string 'FOOBAR123'");
1664}
1665
1666TEST(AddressSanitizer, FileNameInGlobalReportTest) {
1667  static char zoo[10];
1668  const char *p = Ident(zoo);
1669  // The file name should be present in the report.
1670  EXPECT_DEATH(Ident(p[15]), "zoo.*asan_test.cc");
1671}
1672
1673int *ReturnsPointerToALocalObject() {
1674  int a = 0;
1675  return Ident(&a);
1676}
1677
1678#if ASAN_UAR == 1
1679TEST(AddressSanitizer, LocalReferenceReturnTest) {
1680  int *(*f)() = Ident(ReturnsPointerToALocalObject);
1681  int *p = f();
1682  // Call 'f' a few more times, 'p' should still be poisoned.
1683  for (int i = 0; i < 32; i++)
1684    f();
1685  EXPECT_DEATH(*p = 1, "AddressSanitizer stack-use-after-return");
1686  EXPECT_DEATH(*p = 1, "is located.*in frame .*ReturnsPointerToALocal");
1687}
1688#endif
1689
1690template <int kSize>
1691NOINLINE static void FuncWithStack() {
1692  char x[kSize];
1693  Ident(x)[0] = 0;
1694  Ident(x)[kSize-1] = 0;
1695}
1696
1697static void LotsOfStackReuse() {
1698  int LargeStack[10000];
1699  Ident(LargeStack)[0] = 0;
1700  for (int i = 0; i < 10000; i++) {
1701    FuncWithStack<128 * 1>();
1702    FuncWithStack<128 * 2>();
1703    FuncWithStack<128 * 4>();
1704    FuncWithStack<128 * 8>();
1705    FuncWithStack<128 * 16>();
1706    FuncWithStack<128 * 32>();
1707    FuncWithStack<128 * 64>();
1708    FuncWithStack<128 * 128>();
1709    FuncWithStack<128 * 256>();
1710    FuncWithStack<128 * 512>();
1711    Ident(LargeStack)[0] = 0;
1712  }
1713}
1714
1715TEST(AddressSanitizer, StressStackReuseTest) {
1716  LotsOfStackReuse();
1717}
1718
1719TEST(AddressSanitizer, ThreadedStressStackReuseTest) {
1720  const int kNumThreads = 20;
1721  pthread_t t[kNumThreads];
1722  for (int i = 0; i < kNumThreads; i++) {
1723    pthread_create(&t[i], 0, (void* (*)(void *x))LotsOfStackReuse, 0);
1724  }
1725  for (int i = 0; i < kNumThreads; i++) {
1726    pthread_join(t[i], 0);
1727  }
1728}
1729
1730static void *PthreadExit(void *a) {
1731  pthread_exit(0);
1732  return 0;
1733}
1734
1735TEST(AddressSanitizer, PthreadExitTest) {
1736  pthread_t t;
1737  for (int i = 0; i < 1000; i++) {
1738    pthread_create(&t, 0, PthreadExit, 0);
1739    pthread_join(t, 0);
1740  }
1741}
1742
1743#ifdef __EXCEPTIONS
1744NOINLINE static void StackReuseAndException() {
1745  int large_stack[1000];
1746  Ident(large_stack);
1747  ASAN_THROW(1);
1748}
1749
1750// TODO(kcc): support exceptions with use-after-return.
1751TEST(AddressSanitizer, DISABLED_StressStackReuseAndExceptionsTest) {
1752  for (int i = 0; i < 10000; i++) {
1753    try {
1754    StackReuseAndException();
1755    } catch(...) {
1756    }
1757  }
1758}
1759#endif
1760
1761TEST(AddressSanitizer, MlockTest) {
1762  EXPECT_EQ(0, mlockall(MCL_CURRENT));
1763  EXPECT_EQ(0, mlock((void*)0x12345, 0x5678));
1764  EXPECT_EQ(0, munlockall());
1765  EXPECT_EQ(0, munlock((void*)0x987, 0x654));
1766}
1767
1768struct LargeStruct {
1769  int foo[100];
1770};
1771
1772// Test for bug http://llvm.org/bugs/show_bug.cgi?id=11763.
1773// Struct copy should not cause asan warning even if lhs == rhs.
1774TEST(AddressSanitizer, LargeStructCopyTest) {
1775  LargeStruct a;
1776  *Ident(&a) = *Ident(&a);
1777}
1778
1779__attribute__((no_address_safety_analysis))
1780static void NoAddressSafety() {
1781  char *foo = new char[10];
1782  Ident(foo)[10] = 0;
1783  delete [] foo;
1784}
1785
1786TEST(AddressSanitizer, AttributeNoAddressSafetyTest) {
1787  Ident(NoAddressSafety)();
1788}
1789
1790// ------------------ demo tests; run each one-by-one -------------
1791// e.g. --gtest_filter=*DemoOOBLeftHigh --gtest_also_run_disabled_tests
1792TEST(AddressSanitizer, DISABLED_DemoThreadedTest) {
1793  ThreadedTestSpawn();
1794}
1795
1796void *SimpleBugOnSTack(void *x = 0) {
1797  char a[20];
1798  Ident(a)[20] = 0;
1799  return 0;
1800}
1801
1802TEST(AddressSanitizer, DISABLED_DemoStackTest) {
1803  SimpleBugOnSTack();
1804}
1805
1806TEST(AddressSanitizer, DISABLED_DemoThreadStackTest) {
1807  pthread_t t;
1808  pthread_create(&t, 0, SimpleBugOnSTack, 0);
1809  pthread_join(t, 0);
1810}
1811
1812TEST(AddressSanitizer, DISABLED_DemoUAFLowIn) {
1813  uaf_test<U1>(10, 0);
1814}
1815TEST(AddressSanitizer, DISABLED_DemoUAFLowLeft) {
1816  uaf_test<U1>(10, -2);
1817}
1818TEST(AddressSanitizer, DISABLED_DemoUAFLowRight) {
1819  uaf_test<U1>(10, 10);
1820}
1821
1822TEST(AddressSanitizer, DISABLED_DemoUAFHigh) {
1823  uaf_test<U1>(kLargeMalloc, 0);
1824}
1825
1826TEST(AddressSanitizer, DISABLED_DemoOOBLeftLow) {
1827  oob_test<U1>(10, -1);
1828}
1829
1830TEST(AddressSanitizer, DISABLED_DemoOOBLeftHigh) {
1831  oob_test<U1>(kLargeMalloc, -1);
1832}
1833
1834TEST(AddressSanitizer, DISABLED_DemoOOBRightLow) {
1835  oob_test<U1>(10, 10);
1836}
1837
1838TEST(AddressSanitizer, DISABLED_DemoOOBRightHigh) {
1839  oob_test<U1>(kLargeMalloc, kLargeMalloc);
1840}
1841
1842TEST(AddressSanitizer, DISABLED_DemoOOM) {
1843  size_t size = __WORDSIZE == 64 ? (size_t)(1ULL << 40) : (0xf0000000);
1844  printf("%p\n", malloc(size));
1845}
1846
1847TEST(AddressSanitizer, DISABLED_DemoDoubleFreeTest) {
1848  DoubleFree();
1849}
1850
1851TEST(AddressSanitizer, DISABLED_DemoNullDerefTest) {
1852  int *a = 0;
1853  Ident(a)[10] = 0;
1854}
1855
1856TEST(AddressSanitizer, DISABLED_DemoFunctionStaticTest) {
1857  static char a[100];
1858  static char b[100];
1859  static char c[100];
1860  Ident(a);
1861  Ident(b);
1862  Ident(c);
1863  Ident(a)[5] = 0;
1864  Ident(b)[105] = 0;
1865  Ident(a)[5] = 0;
1866}
1867
1868TEST(AddressSanitizer, DISABLED_DemoTooMuchMemoryTest) {
1869  const size_t kAllocSize = (1 << 28) - 1024;
1870  size_t total_size = 0;
1871  while (true) {
1872    char *x = (char*)malloc(kAllocSize);
1873    memset(x, 0, kAllocSize);
1874    total_size += kAllocSize;
1875    fprintf(stderr, "total: %ldM\n", (long)total_size >> 20);
1876  }
1877}
1878
1879#ifdef __APPLE__
1880#include "asan_mac_test.h"
1881// TODO(glider): figure out whether we still need these tests. Is it correct
1882// to intercept CFAllocator?
1883TEST(AddressSanitizerMac, DISABLED_CFAllocatorDefaultDoubleFree) {
1884  EXPECT_DEATH(
1885      CFAllocatorDefaultDoubleFree(),
1886      "attempting double-free");
1887}
1888
1889TEST(AddressSanitizerMac, DISABLED_CFAllocatorSystemDefaultDoubleFree) {
1890  EXPECT_DEATH(
1891      CFAllocatorSystemDefaultDoubleFree(),
1892      "attempting double-free");
1893}
1894
1895TEST(AddressSanitizerMac, DISABLED_CFAllocatorMallocDoubleFree) {
1896  EXPECT_DEATH(CFAllocatorMallocDoubleFree(), "attempting double-free");
1897}
1898
1899TEST(AddressSanitizerMac, DISABLED_CFAllocatorMallocZoneDoubleFree) {
1900  EXPECT_DEATH(CFAllocatorMallocZoneDoubleFree(), "attempting double-free");
1901}
1902
1903TEST(AddressSanitizerMac, GCDDispatchAsync) {
1904  // Make sure the whole ASan report is printed, i.e. that we don't die
1905  // on a CHECK.
1906  EXPECT_DEATH(TestGCDDispatchAsync(), "Shadow byte and word");
1907}
1908
1909TEST(AddressSanitizerMac, GCDDispatchSync) {
1910  // Make sure the whole ASan report is printed, i.e. that we don't die
1911  // on a CHECK.
1912  EXPECT_DEATH(TestGCDDispatchSync(), "Shadow byte and word");
1913}
1914
1915
1916TEST(AddressSanitizerMac, GCDReuseWqthreadsAsync) {
1917  // Make sure the whole ASan report is printed, i.e. that we don't die
1918  // on a CHECK.
1919  EXPECT_DEATH(TestGCDReuseWqthreadsAsync(), "Shadow byte and word");
1920}
1921
1922TEST(AddressSanitizerMac, GCDReuseWqthreadsSync) {
1923  // Make sure the whole ASan report is printed, i.e. that we don't die
1924  // on a CHECK.
1925  EXPECT_DEATH(TestGCDReuseWqthreadsSync(), "Shadow byte and word");
1926}
1927
1928TEST(AddressSanitizerMac, GCDDispatchAfter) {
1929  // Make sure the whole ASan report is printed, i.e. that we don't die
1930  // on a CHECK.
1931  EXPECT_DEATH(TestGCDDispatchAfter(), "Shadow byte and word");
1932}
1933
1934TEST(AddressSanitizerMac, GCDSourceEvent) {
1935  // Make sure the whole ASan report is printed, i.e. that we don't die
1936  // on a CHECK.
1937  EXPECT_DEATH(TestGCDSourceEvent(), "Shadow byte and word");
1938}
1939
1940TEST(AddressSanitizerMac, GCDSourceCancel) {
1941  // Make sure the whole ASan report is printed, i.e. that we don't die
1942  // on a CHECK.
1943  EXPECT_DEATH(TestGCDSourceCancel(), "Shadow byte and word");
1944}
1945
1946TEST(AddressSanitizerMac, GCDGroupAsync) {
1947  // Make sure the whole ASan report is printed, i.e. that we don't die
1948  // on a CHECK.
1949  EXPECT_DEATH(TestGCDGroupAsync(), "Shadow byte and word");
1950}
1951
1952void *MallocIntrospectionLockWorker(void *_) {
1953  const int kNumPointers = 100;
1954  int i;
1955  void *pointers[kNumPointers];
1956  for (i = 0; i < kNumPointers; i++) {
1957    pointers[i] = malloc(i + 1);
1958  }
1959  for (i = 0; i < kNumPointers; i++) {
1960    free(pointers[i]);
1961  }
1962
1963  return NULL;
1964}
1965
1966void *MallocIntrospectionLockForker(void *_) {
1967  pid_t result = fork();
1968  if (result == -1) {
1969    perror("fork");
1970  }
1971  assert(result != -1);
1972  if (result == 0) {
1973    // Call malloc in the child process to make sure we won't deadlock.
1974    void *ptr = malloc(42);
1975    free(ptr);
1976    exit(0);
1977  } else {
1978    // Return in the parent process.
1979    return NULL;
1980  }
1981}
1982
1983TEST(AddressSanitizerMac, MallocIntrospectionLock) {
1984  // Incorrect implementation of force_lock and force_unlock in our malloc zone
1985  // will cause forked processes to deadlock.
1986  // TODO(glider): need to detect that none of the child processes deadlocked.
1987  const int kNumWorkers = 5, kNumIterations = 100;
1988  int i, iter;
1989  for (iter = 0; iter < kNumIterations; iter++) {
1990    pthread_t workers[kNumWorkers], forker;
1991    for (i = 0; i < kNumWorkers; i++) {
1992      pthread_create(&workers[i], 0, MallocIntrospectionLockWorker, 0);
1993    }
1994    pthread_create(&forker, 0, MallocIntrospectionLockForker, 0);
1995    for (i = 0; i < kNumWorkers; i++) {
1996      pthread_join(workers[i], 0);
1997    }
1998    pthread_join(forker, 0);
1999  }
2000}
2001
2002void *TSDAllocWorker(void *test_key) {
2003  if (test_key) {
2004    void *mem = malloc(10);
2005    pthread_setspecific(*(pthread_key_t*)test_key, mem);
2006  }
2007  return NULL;
2008}
2009
2010TEST(AddressSanitizerMac, DISABLED_TSDWorkqueueTest) {
2011  pthread_t th;
2012  pthread_key_t test_key;
2013  pthread_key_create(&test_key, CallFreeOnWorkqueue);
2014  pthread_create(&th, NULL, TSDAllocWorker, &test_key);
2015  pthread_join(th, NULL);
2016  pthread_key_delete(test_key);
2017}
2018
2019// Test that CFStringCreateCopy does not copy constant strings.
2020TEST(AddressSanitizerMac, CFStringCreateCopy) {
2021  CFStringRef str = CFSTR("Hello world!\n");
2022  CFStringRef str2 = CFStringCreateCopy(0, str);
2023  EXPECT_EQ(str, str2);
2024}
2025
2026TEST(AddressSanitizerMac, NSObjectOOB) {
2027  // Make sure that our allocators are used for NSObjects.
2028  EXPECT_DEATH(TestOOBNSObjects(), "heap-buffer-overflow");
2029}
2030#endif  // __APPLE__
2031
2032// Test that instrumentation of stack allocations takes into account
2033// AllocSize of a type, and not its StoreSize (16 vs 10 bytes for long double).
2034// See http://llvm.org/bugs/show_bug.cgi?id=12047 for more details.
2035TEST(AddressSanitizer, LongDoubleNegativeTest) {
2036  long double a, b;
2037  static long double c;
2038  memcpy(Ident(&a), Ident(&b), sizeof(long double));
2039  memcpy(Ident(&c), Ident(&b), sizeof(long double));
2040};
2041
2042int main(int argc, char **argv) {
2043  progname = argv[0];
2044  testing::GTEST_FLAG(death_test_style) = "threadsafe";
2045  testing::InitGoogleTest(&argc, argv);
2046  return RUN_ALL_TESTS();
2047}
2048