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