asan_rtl.cc revision 8f0e311767b783db4a15139dddfe7a924fa3724e
190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)//===-- asan_rtl.cc -------------------------------------------------------===//
290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)//
390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)//                     The LLVM Compiler Infrastructure
490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)//
590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)// This file is distributed under the University of Illinois Open Source
690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)// License. See LICENSE.TXT for details.
790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)//
890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)//===----------------------------------------------------------------------===//
990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)//
1090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)// This file is a part of AddressSanitizer, an address sanity checker.
1190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)//
1290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)// Main file of the ASan run-time library.
1390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)//===----------------------------------------------------------------------===//
1490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)#include "asan_allocator.h"
1590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)#include "asan_interceptors.h"
1690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)#include "asan_internal.h"
1790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)#include "asan_mapping.h"
18#include "asan_report.h"
19#include "asan_stack.h"
20#include "asan_stats.h"
21#include "asan_thread.h"
22#include "asan_thread_registry.h"
23#include "sanitizer/asan_interface.h"
24#include "sanitizer_common/sanitizer_atomic.h"
25#include "sanitizer_common/sanitizer_flags.h"
26#include "sanitizer_common/sanitizer_libc.h"
27#include "sanitizer_common/sanitizer_symbolizer.h"
28
29namespace __asan {
30
31static void AsanDie() {
32  static atomic_uint32_t num_calls;
33  if (atomic_fetch_add(&num_calls, 1, memory_order_relaxed) != 0) {
34    // Don't die twice - run a busy loop.
35    while (1) { }
36  }
37  if (flags()->sleep_before_dying) {
38    Report("Sleeping for %d second(s)\n", flags()->sleep_before_dying);
39    SleepForSeconds(flags()->sleep_before_dying);
40  }
41  if (flags()->unmap_shadow_on_exit)
42    UnmapOrDie((void*)kLowShadowBeg, kHighShadowEnd - kLowShadowBeg);
43  if (death_callback)
44    death_callback();
45  if (flags()->abort_on_error)
46    Abort();
47  Exit(flags()->exitcode);
48}
49
50static void AsanCheckFailed(const char *file, int line, const char *cond,
51                            u64 v1, u64 v2) {
52  Report("AddressSanitizer CHECK failed: %s:%d \"%s\" (0x%zx, 0x%zx)\n",
53             file, line, cond, (uptr)v1, (uptr)v2);
54  // FIXME: check for infinite recursion without a thread-local counter here.
55  PRINT_CURRENT_STACK();
56  Die();
57}
58
59// -------------------------- Flags ------------------------- {{{1
60static const int kDeafultMallocContextSize = 30;
61
62static Flags asan_flags;
63
64Flags *flags() {
65  return &asan_flags;
66}
67
68static const char *MaybeCallAsanDefaultOptions() {
69  return (&__asan_default_options) ? __asan_default_options() : "";
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((uptr)f->malloc_context_size <= kStackTraceMax);
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  ParseFlag(str, &f->allow_reexec, "allow_reexec");
104  ParseFlag(str, &f->print_full_thread_history, "print_full_thread_history");
105  ParseFlag(str, &f->log_path, "log_path");
106  ParseFlag(str, &f->fast_unwind_on_fatal, "fast_unwind_on_fatal");
107  ParseFlag(str, &f->fast_unwind_on_malloc, "fast_unwind_on_malloc");
108  ParseFlag(str, &f->poison_heap, "poison_heap");
109  ParseFlag(str, &f->alloc_dealloc_mismatch, "alloc_dealloc_mismatch");
110  ParseFlag(str, &f->use_stack_depot, "use_stack_depot");
111}
112
113void InitializeFlags(Flags *f, const char *env) {
114  internal_memset(f, 0, sizeof(*f));
115
116  f->quarantine_size = (ASAN_LOW_MEMORY) ? 1UL << 26 : 1UL << 28;
117  f->symbolize = false;
118  f->verbosity = 0;
119  f->redzone = ASAN_ALLOCATOR_VERSION == 2 ? 16 : (ASAN_LOW_MEMORY) ? 64 : 128;
120  f->debug = false;
121  f->report_globals = 1;
122  f->check_initialization_order = true;
123  f->malloc_context_size = kDeafultMallocContextSize;
124  f->replace_str = true;
125  f->replace_intrin = true;
126  f->replace_cfallocator = true;
127  f->mac_ignore_invalid_free = false;
128  f->use_fake_stack = true;
129  f->max_malloc_fill_size = 0;
130  f->exitcode = ASAN_DEFAULT_FAILURE_EXITCODE;
131  f->allow_user_poisoning = true;
132  f->sleep_before_dying = 0;
133  f->handle_segv = ASAN_NEEDS_SEGV;
134  f->use_sigaltstack = false;
135  f->check_malloc_usable_size = true;
136  f->unmap_shadow_on_exit = false;
137  f->abort_on_error = false;
138  f->atexit = false;
139  f->disable_core = (SANITIZER_WORDSIZE == 64);
140  f->strip_path_prefix = "";
141  f->allow_reexec = true;
142  f->print_full_thread_history = true;
143  f->log_path = 0;
144  f->fast_unwind_on_fatal = true;
145  f->fast_unwind_on_malloc = true;
146  f->poison_heap = true;
147  // Turn off alloc/dealloc mismatch checker on Mac for now.
148  // TODO(glider): Fix known issues and enable this back.
149  f->alloc_dealloc_mismatch = (ASAN_MAC == 0);
150  f->use_stack_depot = true;  // Only affects allocator2.
151
152  // Override from user-specified string.
153  ParseFlagsFromString(f, MaybeCallAsanDefaultOptions());
154  if (flags()->verbosity) {
155    Report("Using the defaults from __asan_default_options: %s\n",
156           MaybeCallAsanDefaultOptions());
157  }
158
159  // Override from command line.
160  ParseFlagsFromString(f, env);
161}
162
163// -------------------------- Globals --------------------- {{{1
164int asan_inited;
165bool asan_init_is_running;
166void (*death_callback)(void);
167
168// -------------------------- Misc ---------------- {{{1
169void ShowStatsAndAbort() {
170  __asan_print_accumulated_stats();
171  Die();
172}
173
174// ---------------------- mmap -------------------- {{{1
175// Reserve memory range [beg, end].
176static void ReserveShadowMemoryRange(uptr beg, uptr end) {
177  CHECK((beg % GetPageSizeCached()) == 0);
178  CHECK(((end + 1) % GetPageSizeCached()) == 0);
179  uptr size = end - beg + 1;
180  void *res = MmapFixedNoReserve(beg, size);
181  if (res != (void*)beg) {
182    Report("ReserveShadowMemoryRange failed while trying to map 0x%zx bytes. "
183           "Perhaps you're using ulimit -v\n", size);
184    Abort();
185  }
186}
187
188// --------------- LowLevelAllocateCallbac ---------- {{{1
189static void OnLowLevelAllocate(uptr ptr, uptr size) {
190  PoisonShadow(ptr, size, kAsanInternalHeapMagic);
191}
192
193// -------------------------- Run-time entry ------------------- {{{1
194// exported functions
195#define ASAN_REPORT_ERROR(type, is_write, size)                     \
196extern "C" NOINLINE INTERFACE_ATTRIBUTE                        \
197void __asan_report_ ## type ## size(uptr addr);                \
198void __asan_report_ ## type ## size(uptr addr) {               \
199  GET_CALLER_PC_BP_SP;                                              \
200  __asan_report_error(pc, bp, sp, addr, is_write, size);            \
201}
202
203ASAN_REPORT_ERROR(load, false, 1)
204ASAN_REPORT_ERROR(load, false, 2)
205ASAN_REPORT_ERROR(load, false, 4)
206ASAN_REPORT_ERROR(load, false, 8)
207ASAN_REPORT_ERROR(load, false, 16)
208ASAN_REPORT_ERROR(store, true, 1)
209ASAN_REPORT_ERROR(store, true, 2)
210ASAN_REPORT_ERROR(store, true, 4)
211ASAN_REPORT_ERROR(store, true, 8)
212ASAN_REPORT_ERROR(store, true, 16)
213
214// Force the linker to keep the symbols for various ASan interface functions.
215// We want to keep those in the executable in order to let the instrumented
216// dynamic libraries access the symbol even if it is not used by the executable
217// itself. This should help if the build system is removing dead code at link
218// time.
219static NOINLINE void force_interface_symbols() {
220  volatile int fake_condition = 0;  // prevent dead condition elimination.
221  // __asan_report_* functions are noreturn, so we need a switch to prevent
222  // the compiler from removing any of them.
223  switch (fake_condition) {
224    case 1: __asan_report_load1(0); break;
225    case 2: __asan_report_load2(0); break;
226    case 3: __asan_report_load4(0); break;
227    case 4: __asan_report_load8(0); break;
228    case 5: __asan_report_load16(0); break;
229    case 6: __asan_report_store1(0); break;
230    case 7: __asan_report_store2(0); break;
231    case 8: __asan_report_store4(0); break;
232    case 9: __asan_report_store8(0); break;
233    case 10: __asan_report_store16(0); break;
234    case 11: __asan_register_global(0, 0, 0); break;
235    case 12: __asan_register_globals(0, 0); break;
236    case 13: __asan_unregister_globals(0, 0); break;
237    case 14: __asan_set_death_callback(0); break;
238    case 15: __asan_set_error_report_callback(0); break;
239    case 16: __asan_handle_no_return(); break;
240    case 17: __asan_address_is_poisoned(0); break;
241    case 18: __asan_get_allocated_size(0); break;
242    case 19: __asan_get_current_allocated_bytes(); break;
243    case 20: __asan_get_estimated_allocated_size(0); break;
244    case 21: __asan_get_free_bytes(); break;
245    case 22: __asan_get_heap_size(); break;
246    case 23: __asan_get_ownership(0); break;
247    case 24: __asan_get_unmapped_bytes(); break;
248    case 25: __asan_poison_memory_region(0, 0); break;
249    case 26: __asan_unpoison_memory_region(0, 0); break;
250    case 27: __asan_set_error_exit_code(0); break;
251    case 28: __asan_stack_free(0, 0, 0); break;
252    case 29: __asan_stack_malloc(0, 0); break;
253    case 30: __asan_before_dynamic_init(0, 0); break;
254    case 31: __asan_after_dynamic_init(); break;
255    case 32: __asan_poison_stack_memory(0, 0); break;
256    case 33: __asan_unpoison_stack_memory(0, 0); break;
257    case 34: __asan_region_is_poisoned(0, 0); break;
258    case 35: __asan_describe_address(0); break;
259  }
260}
261
262static void asan_atexit() {
263  Printf("AddressSanitizer exit stats:\n");
264  __asan_print_accumulated_stats();
265}
266
267}  // namespace __asan
268
269// ---------------------- Interface ---------------- {{{1
270using namespace __asan;  // NOLINT
271
272#if !SANITIZER_SUPPORTS_WEAK_HOOKS
273extern "C" {
274SANITIZER_WEAK_ATTRIBUTE SANITIZER_INTERFACE_ATTRIBUTE
275const char* __asan_default_options() { return ""; }
276}  // extern "C"
277#endif
278
279int NOINLINE __asan_set_error_exit_code(int exit_code) {
280  int old = flags()->exitcode;
281  flags()->exitcode = exit_code;
282  return old;
283}
284
285void NOINLINE __asan_handle_no_return() {
286  int local_stack;
287  AsanThread *curr_thread = asanThreadRegistry().GetCurrent();
288  CHECK(curr_thread);
289  uptr PageSize = GetPageSizeCached();
290  uptr top = curr_thread->stack_top();
291  uptr bottom = ((uptr)&local_stack - PageSize) & ~(PageSize-1);
292  PoisonShadow(bottom, top - bottom, 0);
293}
294
295void NOINLINE __asan_set_death_callback(void (*callback)(void)) {
296  death_callback = callback;
297}
298
299void __asan_init() {
300  if (asan_inited) return;
301  CHECK(!asan_init_is_running && "ASan init calls itself!");
302  asan_init_is_running = true;
303
304  // Make sure we are not statically linked.
305  AsanDoesNotSupportStaticLinkage();
306
307  // Install tool-specific callbacks in sanitizer_common.
308  SetDieCallback(AsanDie);
309  SetCheckFailedCallback(AsanCheckFailed);
310  SetPrintfAndReportCallback(AppendToErrorMessageBuffer);
311
312  // Initialize flags. This must be done early, because most of the
313  // initialization steps look at flags().
314  const char *options = GetEnv("ASAN_OPTIONS");
315  InitializeFlags(flags(), options);
316  __sanitizer_set_report_path(flags()->log_path);
317
318  if (flags()->verbosity && options) {
319    Report("Parsed ASAN_OPTIONS: %s\n", options);
320  }
321
322  // Re-exec ourselves if we need to set additional env or command line args.
323  MaybeReexec();
324
325  // Setup internal allocator callback.
326  SetLowLevelAllocateCallback(OnLowLevelAllocate);
327
328  if (flags()->atexit) {
329    Atexit(asan_atexit);
330  }
331
332  // interceptors
333  InitializeAsanInterceptors();
334
335  ReplaceSystemMalloc();
336  ReplaceOperatorsNewAndDelete();
337
338  if (flags()->verbosity) {
339    Printf("|| `[%p, %p]` || HighMem    ||\n",
340           (void*)kHighMemBeg, (void*)kHighMemEnd);
341    Printf("|| `[%p, %p]` || HighShadow ||\n",
342           (void*)kHighShadowBeg, (void*)kHighShadowEnd);
343    Printf("|| `[%p, %p]` || ShadowGap  ||\n",
344           (void*)kShadowGapBeg, (void*)kShadowGapEnd);
345    Printf("|| `[%p, %p]` || LowShadow  ||\n",
346           (void*)kLowShadowBeg, (void*)kLowShadowEnd);
347    Printf("|| `[%p, %p]` || LowMem     ||\n",
348           (void*)kLowMemBeg, (void*)kLowMemEnd);
349    Printf("MemToShadow(shadow): %p %p %p %p\n",
350           (void*)MEM_TO_SHADOW(kLowShadowBeg),
351           (void*)MEM_TO_SHADOW(kLowShadowEnd),
352           (void*)MEM_TO_SHADOW(kHighShadowBeg),
353           (void*)MEM_TO_SHADOW(kHighShadowEnd));
354    Printf("red_zone=%zu\n", (uptr)flags()->redzone);
355    Printf("malloc_context_size=%zu\n", (uptr)flags()->malloc_context_size);
356
357    Printf("SHADOW_SCALE: %zx\n", (uptr)SHADOW_SCALE);
358    Printf("SHADOW_GRANULARITY: %zx\n", (uptr)SHADOW_GRANULARITY);
359    Printf("SHADOW_OFFSET: %zx\n", (uptr)SHADOW_OFFSET);
360    CHECK(SHADOW_SCALE >= 3 && SHADOW_SCALE <= 7);
361  }
362
363  if (flags()->disable_core) {
364    DisableCoreDumper();
365  }
366
367  uptr shadow_start = kLowShadowBeg;
368  if (kLowShadowBeg > 0) shadow_start -= GetMmapGranularity();
369  uptr shadow_end = kHighShadowEnd;
370  if (MemoryRangeIsAvailable(shadow_start, shadow_end)) {
371    if (kLowShadowBeg != kLowShadowEnd) {
372      // mmap the low shadow plus at least one page.
373      ReserveShadowMemoryRange(kLowShadowBeg - GetMmapGranularity(),
374                               kLowShadowEnd);
375    }
376    // mmap the high shadow.
377    ReserveShadowMemoryRange(kHighShadowBeg, kHighShadowEnd);
378    // protect the gap
379    void *prot = Mprotect(kShadowGapBeg, kShadowGapEnd - kShadowGapBeg + 1);
380    CHECK(prot == (void*)kShadowGapBeg);
381  } else {
382    Report("Shadow memory range interleaves with an existing memory mapping. "
383           "ASan cannot proceed correctly. ABORTING.\n");
384    DumpProcessMap();
385    Die();
386  }
387
388  InstallSignalHandlers();
389  // Start symbolizer process if necessary.
390  if (flags()->symbolize) {
391    const char *external_symbolizer = GetEnv("ASAN_SYMBOLIZER_PATH");
392    if (external_symbolizer) {
393      InitializeExternalSymbolizer(external_symbolizer);
394    }
395  }
396
397  // On Linux AsanThread::ThreadStart() calls malloc() that's why asan_inited
398  // should be set to 1 prior to initializing the threads.
399  asan_inited = 1;
400  asan_init_is_running = false;
401
402  asanThreadRegistry().Init();
403  asanThreadRegistry().GetMain()->ThreadStart();
404  force_interface_symbols();  // no-op.
405
406  if (flags()->verbosity) {
407    Report("AddressSanitizer Init done\n");
408  }
409}
410
411#if defined(ASAN_USE_PREINIT_ARRAY)
412  // On Linux, we force __asan_init to be called before anyone else
413  // by placing it into .preinit_array section.
414  // FIXME: do we have anything like this on Mac?
415  __attribute__((section(".preinit_array")))
416    typeof(__asan_init) *__asan_preinit =__asan_init;
417#elif defined(_WIN32) && defined(_DLL)
418  // On Windows, when using dynamic CRT (/MD), we can put a pointer
419  // to __asan_init into the global list of C initializers.
420  // See crt0dat.c in the CRT sources for the details.
421  #pragma section(".CRT$XIB", long, read)  // NOLINT
422  __declspec(allocate(".CRT$XIB")) void (*__asan_preinit)() = __asan_init;
423#endif
424