asan_rtl.cc revision f2981f3bfdc7900784d446d2dde96d99fbcad756
1a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)//===-- asan_rtl.cc ---------------------------------------------*- C++ -*-===//
2a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)//
3a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)//                     The LLVM Compiler Infrastructure
4a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)//
5a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)// This file is distributed under the University of Illinois Open Source
6a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)// License. See LICENSE.TXT for details.
7a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)//
8a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)//===----------------------------------------------------------------------===//
9e5d81f57cb97b3b6b7fccc9c5610d21eb81db09dBen Murdoch//
10a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)// This file is a part of AddressSanitizer, an address sanity checker.
11f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)//
12a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)// Main file of the ASan run-time library.
13a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)//===----------------------------------------------------------------------===//
14a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "asan_allocator.h"
15a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "asan_interceptors.h"
16a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "asan_interface.h"
17a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "asan_internal.h"
18a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "asan_lock.h"
19a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "asan_mapping.h"
20a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "asan_stack.h"
21a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "asan_stats.h"
22a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "asan_thread.h"
23a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "asan_thread_registry.h"
24a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
25a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)namespace __asan {
26a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
27a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)// -------------------------- Flags ------------------------- {{{1
28a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)static const size_t kMallocContextSize = 30;
29a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)static int    FLAG_atexit;
30a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
31a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)size_t FLAG_redzone;  // power of two, >= 32
32a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)size_t FLAG_quarantine_size;
33c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdochint    FLAG_demangle;
34c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdochbool   FLAG_symbolize;
35a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)int    FLAG_v;
36a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)int    FLAG_debug;
37a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)bool   FLAG_poison_shadow;
38a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)int    FLAG_report_globals;
39a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)size_t FLAG_malloc_context_size = kMallocContextSize;
40a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)uintptr_t FLAG_large_malloc;
41a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)bool   FLAG_handle_segv;
42a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)bool   FLAG_use_sigaltstack;
43a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)bool   FLAG_replace_str;
44a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)bool   FLAG_replace_intrin;
45a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)bool   FLAG_replace_cfallocator;  // Used on Mac only.
46a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)size_t FLAG_max_malloc_fill_size = 0;
47a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)bool   FLAG_use_fake_stack;
48a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)bool   FLAG_abort_on_error;
49a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)int    FLAG_exitcode = ASAN_DEFAULT_FAILURE_EXITCODE;
50a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)bool   FLAG_allow_user_poisoning;
51e5d81f57cb97b3b6b7fccc9c5610d21eb81db09dBen Murdochint    FLAG_sleep_before_dying;
52e5d81f57cb97b3b6b7fccc9c5610d21eb81db09dBen Murdochbool   FLAG_unmap_shadow_on_exit;
53f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)bool   FLAG_disable_core;
54e5d81f57cb97b3b6b7fccc9c5610d21eb81db09dBen Murdochbool   FLAG_check_malloc_usable_size;
55e5d81f57cb97b3b6b7fccc9c5610d21eb81db09dBen Murdoch
56a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)// -------------------------- Globals --------------------- {{{1
571320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucciint asan_inited;
581320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccibool asan_init_is_running;
591320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccistatic void (*death_callback)(void);
601320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccistatic void (*error_report_callback)(const char*);
61a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)char *error_message_buffer = NULL;
62a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)size_t error_message_buffer_pos = 0;
63a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)size_t error_message_buffer_size = 0;
64a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
65f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)// -------------------------- Misc ---------------- {{{1
66a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)void ShowStatsAndAbort() {
67a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  __asan_print_accumulated_stats();
68a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  AsanDie();
69f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)}
70a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
71a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)static void PrintBytes(const char *before, uintptr_t *a) {
72a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  uint8_t *bytes = (uint8_t*)a;
73a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  size_t byte_num = (__WORDSIZE) / 8;
74a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Printf("%s%p:", before, (void*)a);
75a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  for (size_t i = 0; i < byte_num; i++) {
76a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    Printf(" %x%x", bytes[i] >> 4, bytes[i] & 15);
77a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  }
78a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Printf("\n");
79a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)}
80a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
81a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)size_t ReadFileToBuffer(const char *file_name, char **buff,
82a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)                         size_t *buff_size, size_t max_len) {
83a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  const size_t kMinFileLen = kPageSize;
84a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  size_t read_len = 0;
85a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  *buff = 0;
86a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  *buff_size = 0;
87a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  // The files we usually open are not seekable, so try different buffer sizes.
88a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  for (size_t size = kMinFileLen; size <= max_len; size *= 2) {
89a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    int fd = AsanOpenReadonly(file_name);
90a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    if (fd < 0) return 0;
91a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    AsanUnmapOrDie(*buff, *buff_size);
92a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    *buff = (char*)AsanMmapSomewhereOrDie(size, __FUNCTION__);
93a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    *buff_size = size;
94a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    // Read up to one page at a time.
95a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    read_len = 0;
96a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    bool reached_eof = false;
97a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    while (read_len + kPageSize <= size) {
98a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)      size_t just_read = AsanRead(fd, *buff + read_len, kPageSize);
99a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)      if (just_read == 0) {
100a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)        reached_eof = true;
101a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)        break;
102a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)      }
103a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)      read_len += just_read;
104a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    }
105a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    AsanClose(fd);
106a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    if (reached_eof)  // We've read the whole file.
107a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)      break;
108a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  }
109a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  return read_len;
110a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)}
111a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
112f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)void AsanDie() {
113f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)  static int num_calls = 0;
114f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)  if (AtomicInc(&num_calls) > 1) {
115e5d81f57cb97b3b6b7fccc9c5610d21eb81db09dBen Murdoch    // Don't die twice - run a busy loop.
116e5d81f57cb97b3b6b7fccc9c5610d21eb81db09dBen Murdoch    while (1) { }
117e5d81f57cb97b3b6b7fccc9c5610d21eb81db09dBen Murdoch  }
118a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  if (FLAG_sleep_before_dying) {
119    Report("Sleeping for %d second(s)\n", FLAG_sleep_before_dying);
120    SleepForSeconds(FLAG_sleep_before_dying);
121  }
122  if (FLAG_unmap_shadow_on_exit)
123    AsanUnmapOrDie((void*)kLowShadowBeg, kHighShadowEnd - kLowShadowBeg);
124  if (death_callback)
125    death_callback();
126  if (FLAG_abort_on_error)
127    Abort();
128  Exit(FLAG_exitcode);
129}
130
131// ---------------------- mmap -------------------- {{{1
132void OutOfMemoryMessageAndDie(const char *mem_type, size_t size) {
133  Report("ERROR: AddressSanitizer failed to allocate "
134         "0x%zx (%zd) bytes of %s\n",
135         size, size, mem_type);
136  PRINT_CURRENT_STACK();
137  ShowStatsAndAbort();
138}
139
140// Reserve memory range [beg, end].
141static void ReserveShadowMemoryRange(uintptr_t beg, uintptr_t end) {
142  CHECK((beg % kPageSize) == 0);
143  CHECK(((end + 1) % kPageSize) == 0);
144  size_t size = end - beg + 1;
145  void *res = AsanMmapFixedNoReserve(beg, size);
146  CHECK(res == (void*)beg && "ReserveShadowMemoryRange failed");
147}
148
149// ---------------------- LowLevelAllocator ------------- {{{1
150void *LowLevelAllocator::Allocate(size_t size) {
151  CHECK((size & (size - 1)) == 0 && "size must be a power of two");
152  if (allocated_end_ - allocated_current_ < size) {
153    size_t size_to_allocate = Max(size, kPageSize);
154    allocated_current_ =
155        (char*)AsanMmapSomewhereOrDie(size_to_allocate, __FUNCTION__);
156    allocated_end_ = allocated_current_ + size_to_allocate;
157    PoisonShadow((uintptr_t)allocated_current_, size_to_allocate,
158                 kAsanInternalHeapMagic);
159  }
160  CHECK(allocated_end_ - allocated_current_ >= size);
161  void *res = allocated_current_;
162  allocated_current_ += size;
163  return res;
164}
165
166// ---------------------- DescribeAddress -------------------- {{{1
167static bool DescribeStackAddress(uintptr_t addr, uintptr_t access_size) {
168  AsanThread *t = asanThreadRegistry().FindThreadByStackAddress(addr);
169  if (!t) return false;
170  const intptr_t kBufSize = 4095;
171  char buf[kBufSize];
172  uintptr_t offset = 0;
173  const char *frame_descr = t->GetFrameNameByAddr(addr, &offset);
174  // This string is created by the compiler and has the following form:
175  // "FunctioName n alloc_1 alloc_2 ... alloc_n"
176  // where alloc_i looks like "offset size len ObjectName ".
177  CHECK(frame_descr);
178  // Report the function name and the offset.
179  const char *name_end = internal_strchr(frame_descr, ' ');
180  CHECK(name_end);
181  buf[0] = 0;
182  internal_strncat(buf, frame_descr,
183                   Min(kBufSize,
184                       static_cast<intptr_t>(name_end - frame_descr)));
185  Printf("Address %p is located at offset %zu "
186         "in frame <%s> of T%d's stack:\n",
187         addr, offset, buf, t->tid());
188  // Report the number of stack objects.
189  char *p;
190  size_t n_objects = internal_simple_strtoll(name_end, &p, 10);
191  CHECK(n_objects > 0);
192  Printf("  This frame has %zu object(s):\n", n_objects);
193  // Report all objects in this frame.
194  for (size_t i = 0; i < n_objects; i++) {
195    size_t beg, size;
196    intptr_t len;
197    beg  = internal_simple_strtoll(p, &p, 10);
198    size = internal_simple_strtoll(p, &p, 10);
199    len  = internal_simple_strtoll(p, &p, 10);
200    if (beg <= 0 || size <= 0 || len < 0 || *p != ' ') {
201      Printf("AddressSanitizer can't parse the stack frame descriptor: |%s|\n",
202             frame_descr);
203      break;
204    }
205    p++;
206    buf[0] = 0;
207    internal_strncat(buf, p, Min(kBufSize, len));
208    p += len;
209    Printf("    [%zu, %zu) '%s'\n", beg, beg + size, buf);
210  }
211  Printf("HINT: this may be a false positive if your program uses "
212         "some custom stack unwind mechanism\n"
213         "      (longjmp and C++ exceptions *are* supported)\n");
214  t->summary()->Announce();
215  return true;
216}
217
218static NOINLINE void DescribeAddress(uintptr_t addr, uintptr_t access_size) {
219  // Check if this is a global.
220  if (DescribeAddrIfGlobal(addr))
221    return;
222
223  if (DescribeStackAddress(addr, access_size))
224    return;
225
226  // finally, check if this is a heap.
227  DescribeHeapAddress(addr, access_size);
228}
229
230// -------------------------- Run-time entry ------------------- {{{1
231// exported functions
232#define ASAN_REPORT_ERROR(type, is_write, size)                     \
233extern "C" NOINLINE ASAN_INTERFACE_ATTRIBUTE                        \
234void __asan_report_ ## type ## size(uintptr_t addr);                \
235void __asan_report_ ## type ## size(uintptr_t addr) {               \
236  GET_CALLER_PC_BP_SP;                                              \
237  __asan_report_error(pc, bp, sp, addr, is_write, size);            \
238}
239
240ASAN_REPORT_ERROR(load, false, 1)
241ASAN_REPORT_ERROR(load, false, 2)
242ASAN_REPORT_ERROR(load, false, 4)
243ASAN_REPORT_ERROR(load, false, 8)
244ASAN_REPORT_ERROR(load, false, 16)
245ASAN_REPORT_ERROR(store, true, 1)
246ASAN_REPORT_ERROR(store, true, 2)
247ASAN_REPORT_ERROR(store, true, 4)
248ASAN_REPORT_ERROR(store, true, 8)
249ASAN_REPORT_ERROR(store, true, 16)
250
251// Force the linker to keep the symbols for various ASan interface functions.
252// We want to keep those in the executable in order to let the instrumented
253// dynamic libraries access the symbol even if it is not used by the executable
254// itself. This should help if the build system is removing dead code at link
255// time.
256static NOINLINE void force_interface_symbols() {
257  volatile int fake_condition = 0;  // prevent dead condition elimination.
258  if (fake_condition) {
259    __asan_report_load1(0);
260    __asan_report_load2(0);
261    __asan_report_load4(0);
262    __asan_report_load8(0);
263    __asan_report_load16(0);
264    __asan_report_store1(0);
265    __asan_report_store2(0);
266    __asan_report_store4(0);
267    __asan_report_store8(0);
268    __asan_report_store16(0);
269    __asan_register_global(0, 0, NULL);
270    __asan_register_globals(NULL, 0);
271    __asan_unregister_globals(NULL, 0);
272    __asan_set_death_callback(NULL);
273    __asan_set_error_report_callback(NULL);
274    __asan_handle_no_return();
275  }
276}
277
278// -------------------------- Init ------------------- {{{1
279static int64_t IntFlagValue(const char *flags, const char *flag,
280                            int64_t default_val) {
281  if (!flags) return default_val;
282  const char *str = internal_strstr(flags, flag);
283  if (!str) return default_val;
284  return internal_atoll(str + internal_strlen(flag));
285}
286
287static void asan_atexit() {
288  Printf("AddressSanitizer exit stats:\n");
289  __asan_print_accumulated_stats();
290}
291
292void CheckFailed(const char *cond, const char *file, int line) {
293  Report("CHECK failed: %s at %s:%d\n", cond, file, line);
294  PRINT_CURRENT_STACK();
295  ShowStatsAndAbort();
296}
297
298}  // namespace __asan
299
300// ---------------------- Interface ---------------- {{{1
301using namespace __asan;  // NOLINT
302
303int __asan_set_error_exit_code(int exit_code) {
304  int old = FLAG_exitcode;
305  FLAG_exitcode = exit_code;
306  return old;
307}
308
309void NOINLINE __asan_handle_no_return() {
310  int local_stack;
311  AsanThread *curr_thread = asanThreadRegistry().GetCurrent();
312  CHECK(curr_thread);
313  uintptr_t top = curr_thread->stack_top();
314  uintptr_t bottom = ((uintptr_t)&local_stack - kPageSize) & ~(kPageSize-1);
315  PoisonShadow(bottom, top - bottom, 0);
316}
317
318void NOINLINE __asan_set_death_callback(void (*callback)(void)) {
319  death_callback = callback;
320}
321
322void NOINLINE __asan_set_error_report_callback(void (*callback)(const char*)) {
323  error_report_callback = callback;
324  if (callback) {
325    error_message_buffer_size = 1 << 16;
326    error_message_buffer =
327        (char*)AsanMmapSomewhereOrDie(error_message_buffer_size, __FUNCTION__);
328    error_message_buffer_pos = 0;
329  }
330}
331
332void __asan_report_error(uintptr_t pc, uintptr_t bp, uintptr_t sp,
333                         uintptr_t addr, bool is_write, size_t access_size) {
334  // Do not print more than one report, otherwise they will mix up.
335  static int num_calls = 0;
336  if (AtomicInc(&num_calls) > 1) return;
337
338  Printf("=================================================================\n");
339  const char *bug_descr = "unknown-crash";
340  if (AddrIsInMem(addr)) {
341    uint8_t *shadow_addr = (uint8_t*)MemToShadow(addr);
342    // If we are accessing 16 bytes, look at the second shadow byte.
343    if (*shadow_addr == 0 && access_size > SHADOW_GRANULARITY)
344      shadow_addr++;
345    // If we are in the partial right redzone, look at the next shadow byte.
346    if (*shadow_addr > 0 && *shadow_addr < 128)
347      shadow_addr++;
348    switch (*shadow_addr) {
349      case kAsanHeapLeftRedzoneMagic:
350      case kAsanHeapRightRedzoneMagic:
351        bug_descr = "heap-buffer-overflow";
352        break;
353      case kAsanHeapFreeMagic:
354        bug_descr = "heap-use-after-free";
355        break;
356      case kAsanStackLeftRedzoneMagic:
357        bug_descr = "stack-buffer-underflow";
358        break;
359      case kAsanStackMidRedzoneMagic:
360      case kAsanStackRightRedzoneMagic:
361      case kAsanStackPartialRedzoneMagic:
362        bug_descr = "stack-buffer-overflow";
363        break;
364      case kAsanStackAfterReturnMagic:
365        bug_descr = "stack-use-after-return";
366        break;
367      case kAsanUserPoisonedMemoryMagic:
368        bug_descr = "use-after-poison";
369        break;
370      case kAsanGlobalRedzoneMagic:
371        bug_descr = "global-buffer-overflow";
372        break;
373    }
374  }
375
376  AsanThread *curr_thread = asanThreadRegistry().GetCurrent();
377  int curr_tid = asanThreadRegistry().GetCurrentTidOrMinusOne();
378
379  if (curr_thread) {
380    // We started reporting an error message. Stop using the fake stack
381    // in case we will call an instrumented function from a symbolizer.
382    curr_thread->fake_stack().StopUsingFakeStack();
383  }
384
385  Report("ERROR: AddressSanitizer %s on address "
386         "%p at pc 0x%zx bp 0x%zx sp 0x%zx\n",
387         bug_descr, addr, pc, bp, sp);
388
389  Printf("%s of size %zu at %p thread T%d\n",
390         access_size ? (is_write ? "WRITE" : "READ") : "ACCESS",
391         access_size, addr, curr_tid);
392
393  if (FLAG_debug) {
394    PrintBytes("PC: ", (uintptr_t*)pc);
395  }
396
397  GET_STACK_TRACE_WITH_PC_AND_BP(kStackTraceMax, pc, bp);
398  stack.PrintStack();
399
400  CHECK(AddrIsInMem(addr));
401
402  DescribeAddress(addr, access_size);
403
404  uintptr_t shadow_addr = MemToShadow(addr);
405  Report("ABORTING\n");
406  __asan_print_accumulated_stats();
407  Printf("Shadow byte and word:\n");
408  Printf("  %p: %x\n", shadow_addr, *(unsigned char*)shadow_addr);
409  uintptr_t aligned_shadow = shadow_addr & ~(kWordSize - 1);
410  PrintBytes("  ", (uintptr_t*)(aligned_shadow));
411  Printf("More shadow bytes:\n");
412  PrintBytes("  ", (uintptr_t*)(aligned_shadow-4*kWordSize));
413  PrintBytes("  ", (uintptr_t*)(aligned_shadow-3*kWordSize));
414  PrintBytes("  ", (uintptr_t*)(aligned_shadow-2*kWordSize));
415  PrintBytes("  ", (uintptr_t*)(aligned_shadow-1*kWordSize));
416  PrintBytes("=>", (uintptr_t*)(aligned_shadow+0*kWordSize));
417  PrintBytes("  ", (uintptr_t*)(aligned_shadow+1*kWordSize));
418  PrintBytes("  ", (uintptr_t*)(aligned_shadow+2*kWordSize));
419  PrintBytes("  ", (uintptr_t*)(aligned_shadow+3*kWordSize));
420  PrintBytes("  ", (uintptr_t*)(aligned_shadow+4*kWordSize));
421  if (error_report_callback) {
422    error_report_callback(error_message_buffer);
423  }
424  AsanDie();
425}
426
427static void ParseAsanOptions(const char *options) {
428  FLAG_malloc_context_size =
429      IntFlagValue(options, "malloc_context_size=", kMallocContextSize);
430  CHECK(FLAG_malloc_context_size <= kMallocContextSize);
431
432  FLAG_max_malloc_fill_size =
433      IntFlagValue(options, "max_malloc_fill_size=", 0);
434
435  FLAG_v = IntFlagValue(options, "verbosity=", 0);
436
437  FLAG_redzone = IntFlagValue(options, "redzone=",
438      (ASAN_LOW_MEMORY) ? 64 : 128);
439  CHECK(FLAG_redzone >= 32);
440  CHECK((FLAG_redzone & (FLAG_redzone - 1)) == 0);
441
442  FLAG_atexit = IntFlagValue(options, "atexit=", 0);
443  FLAG_poison_shadow = IntFlagValue(options, "poison_shadow=", 1);
444  FLAG_report_globals = IntFlagValue(options, "report_globals=", 1);
445  FLAG_handle_segv = IntFlagValue(options, "handle_segv=", ASAN_NEEDS_SEGV);
446  FLAG_use_sigaltstack = IntFlagValue(options, "use_sigaltstack=", 0);
447  FLAG_symbolize = IntFlagValue(options, "symbolize=", 1);
448  FLAG_demangle = IntFlagValue(options, "demangle=", 1);
449  FLAG_debug = IntFlagValue(options, "debug=", 0);
450  FLAG_replace_cfallocator = IntFlagValue(options, "replace_cfallocator=", 1);
451  FLAG_replace_str = IntFlagValue(options, "replace_str=", 1);
452  FLAG_replace_intrin = IntFlagValue(options, "replace_intrin=", 1);
453  FLAG_use_fake_stack = IntFlagValue(options, "use_fake_stack=", 1);
454  FLAG_exitcode = IntFlagValue(options, "exitcode=",
455                               ASAN_DEFAULT_FAILURE_EXITCODE);
456  FLAG_allow_user_poisoning = IntFlagValue(options,
457                                           "allow_user_poisoning=", 1);
458  FLAG_sleep_before_dying = IntFlagValue(options, "sleep_before_dying=", 0);
459  FLAG_abort_on_error = IntFlagValue(options, "abort_on_error=", 0);
460  FLAG_unmap_shadow_on_exit = IntFlagValue(options, "unmap_shadow_on_exit=", 0);
461  // By default, disable core dumper on 64-bit --
462  // it makes little sense to dump 16T+ core.
463  FLAG_disable_core = IntFlagValue(options, "disable_core=", __WORDSIZE == 64);
464
465  // Allow the users to work around the bug in Nvidia drivers prior to 295.*.
466  FLAG_check_malloc_usable_size =
467      IntFlagValue(options, "check_malloc_usable_size=", 1);
468
469  FLAG_quarantine_size = IntFlagValue(options, "quarantine_size=",
470      (ASAN_LOW_MEMORY) ? 1UL << 24 : 1UL << 28);
471}
472
473void __asan_init() {
474  if (asan_inited) return;
475  asan_init_is_running = true;
476
477  // Make sure we are not statically linked.
478  AsanDoesNotSupportStaticLinkage();
479
480  // flags
481  const char *options = AsanGetEnv("ASAN_OPTIONS");
482  ParseAsanOptions(options);
483
484  if (FLAG_v) {
485    Report("Parsed ASAN_OPTIONS: %s\n", options);
486  }
487
488  if (FLAG_atexit) {
489    Atexit(asan_atexit);
490  }
491
492  // interceptors
493  InitializeAsanInterceptors();
494
495  ReplaceSystemMalloc();
496  ReplaceOperatorsNewAndDelete();
497
498  if (FLAG_v) {
499    Printf("|| `[%p, %p]` || HighMem    ||\n", kHighMemBeg, kHighMemEnd);
500    Printf("|| `[%p, %p]` || HighShadow ||\n",
501           kHighShadowBeg, kHighShadowEnd);
502    Printf("|| `[%p, %p]` || ShadowGap  ||\n",
503           kShadowGapBeg, kShadowGapEnd);
504    Printf("|| `[%p, %p]` || LowShadow  ||\n",
505           kLowShadowBeg, kLowShadowEnd);
506    Printf("|| `[%p, %p]` || LowMem     ||\n", kLowMemBeg, kLowMemEnd);
507    Printf("MemToShadow(shadow): %p %p %p %p\n",
508           MEM_TO_SHADOW(kLowShadowBeg),
509           MEM_TO_SHADOW(kLowShadowEnd),
510           MEM_TO_SHADOW(kHighShadowBeg),
511           MEM_TO_SHADOW(kHighShadowEnd));
512    Printf("red_zone=%zu\n", (size_t)FLAG_redzone);
513    Printf("malloc_context_size=%zu\n", (size_t)FLAG_malloc_context_size);
514
515    Printf("SHADOW_SCALE: %zx\n", (size_t)SHADOW_SCALE);
516    Printf("SHADOW_GRANULARITY: %zx\n", (size_t)SHADOW_GRANULARITY);
517    Printf("SHADOW_OFFSET: %zx\n", (size_t)SHADOW_OFFSET);
518    CHECK(SHADOW_SCALE >= 3 && SHADOW_SCALE <= 7);
519  }
520
521  if (FLAG_disable_core) {
522    AsanDisableCoreDumper();
523  }
524
525  if (AsanShadowRangeIsAvailable()) {
526    if (kLowShadowBeg != kLowShadowEnd) {
527      // mmap the low shadow plus at least one page.
528      ReserveShadowMemoryRange(kLowShadowBeg - kMmapGranularity, kLowShadowEnd);
529    }
530    // mmap the high shadow.
531    ReserveShadowMemoryRange(kHighShadowBeg, kHighShadowEnd);
532    // protect the gap
533    void *prot = AsanMprotect(kShadowGapBeg, kShadowGapEnd - kShadowGapBeg + 1);
534    CHECK(prot == (void*)kShadowGapBeg);
535  } else {
536    Report("Shadow memory range interleaves with an existing memory mapping. "
537           "ASan cannot proceed correctly. ABORTING.\n");
538    AsanDumpProcessMap();
539    AsanDie();
540  }
541
542  InstallSignalHandlers();
543
544  // On Linux AsanThread::ThreadStart() calls malloc() that's why asan_inited
545  // should be set to 1 prior to initializing the threads.
546  asan_inited = 1;
547  asan_init_is_running = false;
548
549  asanThreadRegistry().Init();
550  asanThreadRegistry().GetMain()->ThreadStart();
551  force_interface_symbols();  // no-op.
552
553  if (FLAG_v) {
554    Report("AddressSanitizer Init done\n");
555  }
556}
557
558#if defined(ASAN_USE_PREINIT_ARRAY)
559  // On Linux, we force __asan_init to be called before anyone else
560  // by placing it into .preinit_array section.
561  // FIXME: do we have anything like this on Mac?
562  __attribute__((section(".preinit_array")))
563    typeof(__asan_init) *__asan_preinit =__asan_init;
564#elif defined(_WIN32) && defined(_DLL)
565  // On Windows, when using dynamic CRT (/MD), we can put a pointer
566  // to __asan_init into the global list of C initializers.
567  // See crt0dat.c in the CRT sources for the details.
568  #pragma section(".CRT$XIB", long, read)  // NOLINT
569  __declspec(allocate(".CRT$XIB")) void (*__asan_preinit)() = __asan_init;
570#endif
571