asan_rtl.cc revision ec3b0732a62bd0a52da7bbfc4e227038ccf9372c
1//===-- asan_rtl.cc -------------------------------------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is a part of AddressSanitizer, an address sanity checker.
11//
12// Main file of the ASan run-time library.
13//===----------------------------------------------------------------------===//
14#include "asan_allocator.h"
15#include "asan_interceptors.h"
16#include "asan_interface.h"
17#include "asan_internal.h"
18#include "asan_lock.h"
19#include "asan_mapping.h"
20#include "asan_report.h"
21#include "asan_stack.h"
22#include "asan_stats.h"
23#include "asan_thread.h"
24#include "asan_thread_registry.h"
25#include "sanitizer_common/sanitizer_atomic.h"
26#include "sanitizer_common/sanitizer_flags.h"
27#include "sanitizer_common/sanitizer_libc.h"
28
29namespace __sanitizer {
30using namespace __asan;
31
32void Die() {
33  static atomic_uint32_t num_calls;
34  if (atomic_fetch_add(&num_calls, 1, memory_order_relaxed) != 0) {
35    // Don't die twice - run a busy loop.
36    while (1) { }
37  }
38  if (flags()->sleep_before_dying) {
39    Report("Sleeping for %d second(s)\n", flags()->sleep_before_dying);
40    SleepForSeconds(flags()->sleep_before_dying);
41  }
42  if (flags()->unmap_shadow_on_exit)
43    UnmapOrDie((void*)kLowShadowBeg, kHighShadowEnd - kLowShadowBeg);
44  if (death_callback)
45    death_callback();
46  if (flags()->abort_on_error)
47    Abort();
48  Exit(flags()->exitcode);
49}
50
51SANITIZER_INTERFACE_ATTRIBUTE
52void CheckFailed(const char *file, int line, const char *cond, u64 v1, u64 v2) {
53  AsanReport("AddressSanitizer CHECK failed: %s:%d \"%s\" (0x%zx, 0x%zx)\n",
54             file, line, cond, (uptr)v1, (uptr)v2);
55  PRINT_CURRENT_STACK();
56  ShowStatsAndAbort();
57}
58
59}  // namespace __sanitizer
60
61namespace __asan {
62
63// -------------------------- Flags ------------------------- {{{1
64static const int kMallocContextSize = 30;
65
66static Flags asan_flags;
67
68Flags *flags() {
69  return &asan_flags;
70}
71
72static void ParseFlagsFromString(Flags *f, const char *str) {
73  ParseFlag(str, &f->quarantine_size, "quarantine_size");
74  ParseFlag(str, &f->symbolize, "symbolize");
75  ParseFlag(str, &f->verbosity, "verbosity");
76  ParseFlag(str, &f->redzone, "redzone");
77  CHECK(f->redzone >= 16);
78  CHECK(IsPowerOfTwo(f->redzone));
79
80  ParseFlag(str, &f->debug, "debug");
81  ParseFlag(str, &f->report_globals, "report_globals");
82  ParseFlag(str, &f->malloc_context_size, "malloc_context_size");
83  CHECK(f->malloc_context_size <= kMallocContextSize);
84
85  ParseFlag(str, &f->replace_str, "replace_str");
86  ParseFlag(str, &f->replace_intrin, "replace_intrin");
87  ParseFlag(str, &f->replace_cfallocator, "replace_cfallocator");
88  ParseFlag(str, &f->mac_ignore_invalid_free, "mac_ignore_invalid_free");
89  ParseFlag(str, &f->use_fake_stack, "use_fake_stack");
90  ParseFlag(str, &f->max_malloc_fill_size, "max_malloc_fill_size");
91  ParseFlag(str, &f->exitcode, "exitcode");
92  ParseFlag(str, &f->allow_user_poisoning, "allow_user_poisoning");
93  ParseFlag(str, &f->sleep_before_dying, "sleep_before_dying");
94  ParseFlag(str, &f->handle_segv, "handle_segv");
95  ParseFlag(str, &f->use_sigaltstack, "use_sigaltstack");
96  ParseFlag(str, &f->check_malloc_usable_size, "check_malloc_usable_size");
97  ParseFlag(str, &f->unmap_shadow_on_exit, "unmap_shadow_on_exit");
98  ParseFlag(str, &f->abort_on_error, "abort_on_error");
99  ParseFlag(str, &f->atexit, "atexit");
100  ParseFlag(str, &f->disable_core, "disable_core");
101  ParseFlag(str, &f->strip_path_prefix, "strip_path_prefix");
102}
103
104extern "C" {
105SANITIZER_WEAK_ATTRIBUTE
106SANITIZER_INTERFACE_ATTRIBUTE
107const char* __asan_default_options() { return ""; }
108}  // extern "C"
109
110void InitializeFlags(Flags *f, const char *env) {
111  internal_memset(f, 0, sizeof(*f));
112
113  f->quarantine_size = (ASAN_LOW_MEMORY) ? 1UL << 24 : 1UL << 28;
114  f->symbolize = false;
115  f->verbosity = 0;
116  f->redzone = (ASAN_LOW_MEMORY) ? 64 : 128;
117  f->debug = false;
118  f->report_globals = 1;
119  f->malloc_context_size = kMallocContextSize;
120  f->replace_str = true;
121  f->replace_intrin = true;
122  f->replace_cfallocator = true;
123  f->mac_ignore_invalid_free = false;
124  f->use_fake_stack = true;
125  f->max_malloc_fill_size = 0;
126  f->exitcode = ASAN_DEFAULT_FAILURE_EXITCODE;
127  f->allow_user_poisoning = true;
128  f->sleep_before_dying = 0;
129  f->handle_segv = ASAN_NEEDS_SEGV;
130  f->use_sigaltstack = false;
131  f->check_malloc_usable_size = true;
132  f->unmap_shadow_on_exit = false;
133  f->abort_on_error = false;
134  f->atexit = false;
135  f->disable_core = (__WORDSIZE == 64);
136  f->strip_path_prefix = "";
137
138  // Override from user-specified string.
139  ParseFlagsFromString(f, __asan_default_options());
140  if (flags()->verbosity) {
141    Report("Using the defaults from __asan_default_options: %s\n",
142           __asan_default_options());
143  }
144
145  // Override from command line.
146  ParseFlagsFromString(f, env);
147}
148
149// -------------------------- Globals --------------------- {{{1
150int asan_inited;
151bool asan_init_is_running;
152void (*death_callback)(void);
153
154// -------------------------- Misc ---------------- {{{1
155void ShowStatsAndAbort() {
156  __asan_print_accumulated_stats();
157  Die();
158}
159
160// ---------------------- mmap -------------------- {{{1
161// Reserve memory range [beg, end].
162static void ReserveShadowMemoryRange(uptr beg, uptr end) {
163  CHECK((beg % kPageSize) == 0);
164  CHECK(((end + 1) % kPageSize) == 0);
165  uptr size = end - beg + 1;
166  void *res = MmapFixedNoReserve(beg, size);
167  CHECK(res == (void*)beg && "ReserveShadowMemoryRange failed");
168}
169
170// ---------------------- LowLevelAllocator ------------- {{{1
171void *LowLevelAllocator::Allocate(uptr size) {
172  CHECK((size & (size - 1)) == 0 && "size must be a power of two");
173  if (allocated_end_ - allocated_current_ < (sptr)size) {
174    uptr size_to_allocate = Max(size, kPageSize);
175    allocated_current_ =
176        (char*)MmapOrDie(size_to_allocate, __FUNCTION__);
177    allocated_end_ = allocated_current_ + size_to_allocate;
178    PoisonShadow((uptr)allocated_current_, size_to_allocate,
179                 kAsanInternalHeapMagic);
180  }
181  CHECK(allocated_end_ - allocated_current_ >= (sptr)size);
182  void *res = allocated_current_;
183  allocated_current_ += size;
184  return res;
185}
186
187// -------------------------- Run-time entry ------------------- {{{1
188// exported functions
189#define ASAN_REPORT_ERROR(type, is_write, size)                     \
190extern "C" NOINLINE INTERFACE_ATTRIBUTE                        \
191void __asan_report_ ## type ## size(uptr addr);                \
192void __asan_report_ ## type ## size(uptr addr) {               \
193  GET_CALLER_PC_BP_SP;                                              \
194  __asan_report_error(pc, bp, sp, addr, is_write, size);            \
195}
196
197ASAN_REPORT_ERROR(load, false, 1)
198ASAN_REPORT_ERROR(load, false, 2)
199ASAN_REPORT_ERROR(load, false, 4)
200ASAN_REPORT_ERROR(load, false, 8)
201ASAN_REPORT_ERROR(load, false, 16)
202ASAN_REPORT_ERROR(store, true, 1)
203ASAN_REPORT_ERROR(store, true, 2)
204ASAN_REPORT_ERROR(store, true, 4)
205ASAN_REPORT_ERROR(store, true, 8)
206ASAN_REPORT_ERROR(store, true, 16)
207
208// Force the linker to keep the symbols for various ASan interface functions.
209// We want to keep those in the executable in order to let the instrumented
210// dynamic libraries access the symbol even if it is not used by the executable
211// itself. This should help if the build system is removing dead code at link
212// time.
213static NOINLINE void force_interface_symbols() {
214  volatile int fake_condition = 0;  // prevent dead condition elimination.
215  // __asan_report_* functions are noreturn, so we need a switch to prevent
216  // the compiler from removing any of them.
217  switch (fake_condition) {
218    case 1: __asan_report_load1(0); break;
219    case 2: __asan_report_load2(0); break;
220    case 3: __asan_report_load4(0); break;
221    case 4: __asan_report_load8(0); break;
222    case 5: __asan_report_load16(0); break;
223    case 6: __asan_report_store1(0); break;
224    case 7: __asan_report_store2(0); break;
225    case 8: __asan_report_store4(0); break;
226    case 9: __asan_report_store8(0); break;
227    case 10: __asan_report_store16(0); break;
228    case 11: __asan_register_global(0, 0, 0); break;
229    case 12: __asan_register_globals(0, 0); break;
230    case 13: __asan_unregister_globals(0, 0); break;
231    case 14: __asan_set_death_callback(0); break;
232    case 15: __asan_set_error_report_callback(0); break;
233    case 16: __asan_handle_no_return(); break;
234    case 17: __asan_address_is_poisoned(0); break;
235    case 18: __asan_get_allocated_size(0); break;
236    case 19: __asan_get_current_allocated_bytes(); break;
237    case 20: __asan_get_estimated_allocated_size(0); break;
238    case 21: __asan_get_free_bytes(); break;
239    case 22: __asan_get_heap_size(); break;
240    case 23: __asan_get_ownership(0); break;
241    case 24: __asan_get_unmapped_bytes(); break;
242    case 25: __asan_poison_memory_region(0, 0); break;
243    case 26: __asan_unpoison_memory_region(0, 0); break;
244    case 27: __asan_set_error_exit_code(0); break;
245    case 28: __asan_stack_free(0, 0, 0); break;
246    case 29: __asan_stack_malloc(0, 0); break;
247    case 30: __asan_set_on_error_callback(0); break;
248    case 31: __asan_default_options(); break;
249  }
250}
251
252static void asan_atexit() {
253  AsanPrintf("AddressSanitizer exit stats:\n");
254  __asan_print_accumulated_stats();
255}
256
257}  // namespace __asan
258
259// ---------------------- Interface ---------------- {{{1
260using namespace __asan;  // NOLINT
261
262int NOINLINE __asan_set_error_exit_code(int exit_code) {
263  int old = flags()->exitcode;
264  flags()->exitcode = exit_code;
265  return old;
266}
267
268void NOINLINE __asan_handle_no_return() {
269  int local_stack;
270  AsanThread *curr_thread = asanThreadRegistry().GetCurrent();
271  CHECK(curr_thread);
272  uptr top = curr_thread->stack_top();
273  uptr bottom = ((uptr)&local_stack - kPageSize) & ~(kPageSize-1);
274  PoisonShadow(bottom, top - bottom, 0);
275}
276
277void NOINLINE __asan_set_death_callback(void (*callback)(void)) {
278  death_callback = callback;
279}
280
281void __asan_init() {
282  if (asan_inited) return;
283  asan_init_is_running = true;
284
285  // Make sure we are not statically linked.
286  AsanDoesNotSupportStaticLinkage();
287
288  // Initialize flags.
289  const char *options = GetEnv("ASAN_OPTIONS");
290  InitializeFlags(flags(), options);
291
292  if (flags()->verbosity && options) {
293    Report("Parsed ASAN_OPTIONS: %s\n", options);
294  }
295
296  if (flags()->atexit) {
297    Atexit(asan_atexit);
298  }
299
300  // interceptors
301  InitializeAsanInterceptors();
302
303  ReplaceSystemMalloc();
304  ReplaceOperatorsNewAndDelete();
305
306  if (flags()->verbosity) {
307    Printf("|| `[%p, %p]` || HighMem    ||\n",
308           (void*)kHighMemBeg, (void*)kHighMemEnd);
309    Printf("|| `[%p, %p]` || HighShadow ||\n",
310           (void*)kHighShadowBeg, (void*)kHighShadowEnd);
311    Printf("|| `[%p, %p]` || ShadowGap  ||\n",
312           (void*)kShadowGapBeg, (void*)kShadowGapEnd);
313    Printf("|| `[%p, %p]` || LowShadow  ||\n",
314           (void*)kLowShadowBeg, (void*)kLowShadowEnd);
315    Printf("|| `[%p, %p]` || LowMem     ||\n",
316           (void*)kLowMemBeg, (void*)kLowMemEnd);
317    Printf("MemToShadow(shadow): %p %p %p %p\n",
318           (void*)MEM_TO_SHADOW(kLowShadowBeg),
319           (void*)MEM_TO_SHADOW(kLowShadowEnd),
320           (void*)MEM_TO_SHADOW(kHighShadowBeg),
321           (void*)MEM_TO_SHADOW(kHighShadowEnd));
322    Printf("red_zone=%zu\n", (uptr)flags()->redzone);
323    Printf("malloc_context_size=%zu\n", (uptr)flags()->malloc_context_size);
324
325    Printf("SHADOW_SCALE: %zx\n", (uptr)SHADOW_SCALE);
326    Printf("SHADOW_GRANULARITY: %zx\n", (uptr)SHADOW_GRANULARITY);
327    Printf("SHADOW_OFFSET: %zx\n", (uptr)SHADOW_OFFSET);
328    CHECK(SHADOW_SCALE >= 3 && SHADOW_SCALE <= 7);
329  }
330
331  if (flags()->disable_core) {
332    DisableCoreDumper();
333  }
334
335  uptr shadow_start = kLowShadowBeg;
336  if (kLowShadowBeg > 0) shadow_start -= kMmapGranularity;
337  uptr shadow_end = kHighShadowEnd;
338  if (MemoryRangeIsAvailable(shadow_start, shadow_end)) {
339    if (kLowShadowBeg != kLowShadowEnd) {
340      // mmap the low shadow plus at least one page.
341      ReserveShadowMemoryRange(kLowShadowBeg - kMmapGranularity, kLowShadowEnd);
342    }
343    // mmap the high shadow.
344    ReserveShadowMemoryRange(kHighShadowBeg, kHighShadowEnd);
345    // protect the gap
346    void *prot = Mprotect(kShadowGapBeg, kShadowGapEnd - kShadowGapBeg + 1);
347    CHECK(prot == (void*)kShadowGapBeg);
348  } else {
349    Report("Shadow memory range interleaves with an existing memory mapping. "
350           "ASan cannot proceed correctly. ABORTING.\n");
351    DumpProcessMap();
352    Die();
353  }
354
355  InstallSignalHandlers();
356
357  // On Linux AsanThread::ThreadStart() calls malloc() that's why asan_inited
358  // should be set to 1 prior to initializing the threads.
359  asan_inited = 1;
360  asan_init_is_running = false;
361
362  asanThreadRegistry().Init();
363  asanThreadRegistry().GetMain()->ThreadStart();
364  force_interface_symbols();  // no-op.
365
366  if (flags()->verbosity) {
367    Report("AddressSanitizer Init done\n");
368  }
369}
370
371#if defined(ASAN_USE_PREINIT_ARRAY)
372  // On Linux, we force __asan_init to be called before anyone else
373  // by placing it into .preinit_array section.
374  // FIXME: do we have anything like this on Mac?
375  __attribute__((section(".preinit_array")))
376    typeof(__asan_init) *__asan_preinit =__asan_init;
377#elif defined(_WIN32) && defined(_DLL)
378  // On Windows, when using dynamic CRT (/MD), we can put a pointer
379  // to __asan_init into the global list of C initializers.
380  // See crt0dat.c in the CRT sources for the details.
381  #pragma section(".CRT$XIB", long, read)  // NOLINT
382  __declspec(allocate(".CRT$XIB")) void (*__asan_preinit)() = __asan_init;
383#endif
384