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