asan_rtl.cc revision 366984e3aa286f7b4fb45f5c9e703f2768c407ed
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_internal.h"
17#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_common/sanitizer_atomic.h"
24#include "sanitizer_common/sanitizer_flags.h"
25#include "sanitizer_common/sanitizer_libc.h"
26#include "sanitizer_common/sanitizer_symbolizer.h"
27
28namespace __asan {
29
30uptr AsanMappingProfile[kAsanMappingProfileSize];
31
32static void AsanDie() {
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    if (kMidMemBeg) {
44      UnmapOrDie((void*)kLowShadowBeg, kMidMemBeg - kLowShadowBeg);
45      UnmapOrDie((void*)kMidMemEnd, kHighShadowEnd - kMidMemEnd);
46    } else {
47      UnmapOrDie((void*)kLowShadowBeg, kHighShadowEnd - kLowShadowBeg);
48    }
49  }
50  if (death_callback)
51    death_callback();
52  if (flags()->abort_on_error)
53    Abort();
54  Exit(flags()->exitcode);
55}
56
57static void AsanCheckFailed(const char *file, int line, const char *cond,
58                            u64 v1, u64 v2) {
59  Report("AddressSanitizer CHECK failed: %s:%d \"%s\" (0x%zx, 0x%zx)\n",
60             file, line, cond, (uptr)v1, (uptr)v2);
61  // FIXME: check for infinite recursion without a thread-local counter here.
62  PRINT_CURRENT_STACK();
63  Die();
64}
65
66// -------------------------- Flags ------------------------- {{{1
67static const int kDeafultMallocContextSize = 30;
68
69static Flags asan_flags;
70
71Flags *flags() {
72  return &asan_flags;
73}
74
75static const char *MaybeCallAsanDefaultOptions() {
76  return (&__asan_default_options) ? __asan_default_options() : "";
77}
78
79static void ParseFlagsFromString(Flags *f, const char *str) {
80  ParseFlag(str, &f->quarantine_size, "quarantine_size");
81  ParseFlag(str, &f->symbolize, "symbolize");
82  ParseFlag(str, &f->verbosity, "verbosity");
83  ParseFlag(str, &f->redzone, "redzone");
84  CHECK(f->redzone >= 16);
85  CHECK(IsPowerOfTwo(f->redzone));
86
87  ParseFlag(str, &f->debug, "debug");
88  ParseFlag(str, &f->report_globals, "report_globals");
89  ParseFlag(str, &f->check_initialization_order, "initialization_order");
90  ParseFlag(str, &f->malloc_context_size, "malloc_context_size");
91  CHECK((uptr)f->malloc_context_size <= kStackTraceMax);
92
93  ParseFlag(str, &f->replace_str, "replace_str");
94  ParseFlag(str, &f->replace_intrin, "replace_intrin");
95  ParseFlag(str, &f->mac_ignore_invalid_free, "mac_ignore_invalid_free");
96  ParseFlag(str, &f->use_fake_stack, "use_fake_stack");
97  ParseFlag(str, &f->max_malloc_fill_size, "max_malloc_fill_size");
98  ParseFlag(str, &f->exitcode, "exitcode");
99  ParseFlag(str, &f->allow_user_poisoning, "allow_user_poisoning");
100  ParseFlag(str, &f->sleep_before_dying, "sleep_before_dying");
101  ParseFlag(str, &f->handle_segv, "handle_segv");
102  ParseFlag(str, &f->use_sigaltstack, "use_sigaltstack");
103  ParseFlag(str, &f->check_malloc_usable_size, "check_malloc_usable_size");
104  ParseFlag(str, &f->unmap_shadow_on_exit, "unmap_shadow_on_exit");
105  ParseFlag(str, &f->abort_on_error, "abort_on_error");
106  ParseFlag(str, &f->print_stats, "print_stats");
107  ParseFlag(str, &f->print_legend, "print_legend");
108  ParseFlag(str, &f->atexit, "atexit");
109  ParseFlag(str, &f->disable_core, "disable_core");
110  ParseFlag(str, &f->strip_path_prefix, "strip_path_prefix");
111  ParseFlag(str, &f->allow_reexec, "allow_reexec");
112  ParseFlag(str, &f->print_full_thread_history, "print_full_thread_history");
113  ParseFlag(str, &f->log_path, "log_path");
114  ParseFlag(str, &f->fast_unwind_on_fatal, "fast_unwind_on_fatal");
115  ParseFlag(str, &f->fast_unwind_on_malloc, "fast_unwind_on_malloc");
116  ParseFlag(str, &f->poison_heap, "poison_heap");
117  ParseFlag(str, &f->alloc_dealloc_mismatch, "alloc_dealloc_mismatch");
118  ParseFlag(str, &f->use_stack_depot, "use_stack_depot");
119}
120
121void InitializeFlags(Flags *f, const char *env) {
122  internal_memset(f, 0, sizeof(*f));
123
124  f->quarantine_size = (ASAN_LOW_MEMORY) ? 1UL << 26 : 1UL << 28;
125  f->symbolize = false;
126  f->verbosity = 0;
127  f->redzone = ASAN_ALLOCATOR_VERSION == 2 ? 16 : (ASAN_LOW_MEMORY) ? 64 : 128;
128  f->debug = false;
129  f->report_globals = 1;
130  f->check_initialization_order = true;
131  f->malloc_context_size = kDeafultMallocContextSize;
132  f->replace_str = true;
133  f->replace_intrin = true;
134  f->mac_ignore_invalid_free = false;
135  f->use_fake_stack = true;
136  f->max_malloc_fill_size = 0;
137  f->exitcode = ASAN_DEFAULT_FAILURE_EXITCODE;
138  f->allow_user_poisoning = true;
139  f->sleep_before_dying = 0;
140  f->handle_segv = ASAN_NEEDS_SEGV;
141  f->use_sigaltstack = false;
142  f->check_malloc_usable_size = true;
143  f->unmap_shadow_on_exit = false;
144  f->abort_on_error = false;
145  f->print_stats = false;
146  f->print_legend = true;
147  f->atexit = false;
148  f->disable_core = (SANITIZER_WORDSIZE == 64);
149  f->strip_path_prefix = "";
150  f->allow_reexec = true;
151  f->print_full_thread_history = true;
152  f->log_path = 0;
153  f->fast_unwind_on_fatal = false;
154  f->fast_unwind_on_malloc = true;
155  f->poison_heap = true;
156  f->alloc_dealloc_mismatch = true;
157  f->use_stack_depot = true;  // Only affects allocator2.
158
159  // Override from user-specified string.
160  ParseFlagsFromString(f, MaybeCallAsanDefaultOptions());
161  if (flags()->verbosity) {
162    Report("Using the defaults from __asan_default_options: %s\n",
163           MaybeCallAsanDefaultOptions());
164  }
165
166  // Override from command line.
167  ParseFlagsFromString(f, env);
168}
169
170// -------------------------- Globals --------------------- {{{1
171int asan_inited;
172bool asan_init_is_running;
173void (*death_callback)(void);
174
175#if !ASAN_FIXED_MAPPING
176uptr kHighMemEnd, kMidMemBeg, kMidMemEnd;
177#endif
178
179// -------------------------- Misc ---------------- {{{1
180void ShowStatsAndAbort() {
181  __asan_print_accumulated_stats();
182  Die();
183}
184
185// ---------------------- mmap -------------------- {{{1
186// Reserve memory range [beg, end].
187static void ReserveShadowMemoryRange(uptr beg, uptr end) {
188  CHECK((beg % GetPageSizeCached()) == 0);
189  CHECK(((end + 1) % GetPageSizeCached()) == 0);
190  uptr size = end - beg + 1;
191  void *res = MmapFixedNoReserve(beg, size);
192  if (res != (void*)beg) {
193    Report("ReserveShadowMemoryRange failed while trying to map 0x%zx bytes. "
194           "Perhaps you're using ulimit -v\n", size);
195    Abort();
196  }
197}
198
199// --------------- LowLevelAllocateCallbac ---------- {{{1
200static void OnLowLevelAllocate(uptr ptr, uptr size) {
201  PoisonShadow(ptr, size, kAsanInternalHeapMagic);
202}
203
204// -------------------------- Run-time entry ------------------- {{{1
205// exported functions
206#define ASAN_REPORT_ERROR(type, is_write, size)                     \
207extern "C" NOINLINE INTERFACE_ATTRIBUTE                        \
208void __asan_report_ ## type ## size(uptr addr);                \
209void __asan_report_ ## type ## size(uptr addr) {               \
210  GET_CALLER_PC_BP_SP;                                              \
211  __asan_report_error(pc, bp, sp, addr, is_write, size);            \
212}
213
214ASAN_REPORT_ERROR(load, false, 1)
215ASAN_REPORT_ERROR(load, false, 2)
216ASAN_REPORT_ERROR(load, false, 4)
217ASAN_REPORT_ERROR(load, false, 8)
218ASAN_REPORT_ERROR(load, false, 16)
219ASAN_REPORT_ERROR(store, true, 1)
220ASAN_REPORT_ERROR(store, true, 2)
221ASAN_REPORT_ERROR(store, true, 4)
222ASAN_REPORT_ERROR(store, true, 8)
223ASAN_REPORT_ERROR(store, true, 16)
224
225#define ASAN_REPORT_ERROR_N(type, is_write)                    \
226extern "C" NOINLINE INTERFACE_ATTRIBUTE                        \
227void __asan_report_ ## type ## _n(uptr addr, uptr size);       \
228void __asan_report_ ## type ## _n(uptr addr, uptr size) {      \
229  GET_CALLER_PC_BP_SP;                                         \
230  __asan_report_error(pc, bp, sp, addr, is_write, size);       \
231}
232
233ASAN_REPORT_ERROR_N(load, false)
234ASAN_REPORT_ERROR_N(store, true)
235
236// Force the linker to keep the symbols for various ASan interface functions.
237// We want to keep those in the executable in order to let the instrumented
238// dynamic libraries access the symbol even if it is not used by the executable
239// itself. This should help if the build system is removing dead code at link
240// time.
241static NOINLINE void force_interface_symbols() {
242  volatile int fake_condition = 0;  // prevent dead condition elimination.
243  // __asan_report_* functions are noreturn, so we need a switch to prevent
244  // the compiler from removing any of them.
245  switch (fake_condition) {
246    case 1: __asan_report_load1(0); break;
247    case 2: __asan_report_load2(0); break;
248    case 3: __asan_report_load4(0); break;
249    case 4: __asan_report_load8(0); break;
250    case 5: __asan_report_load16(0); break;
251    case 6: __asan_report_store1(0); break;
252    case 7: __asan_report_store2(0); break;
253    case 8: __asan_report_store4(0); break;
254    case 9: __asan_report_store8(0); break;
255    case 10: __asan_report_store16(0); break;
256    case 12: __asan_register_globals(0, 0); break;
257    case 13: __asan_unregister_globals(0, 0); break;
258    case 14: __asan_set_death_callback(0); break;
259    case 15: __asan_set_error_report_callback(0); break;
260    case 16: __asan_handle_no_return(); break;
261    case 17: __asan_address_is_poisoned(0); break;
262    case 18: __asan_get_allocated_size(0); break;
263    case 19: __asan_get_current_allocated_bytes(); break;
264    case 20: __asan_get_estimated_allocated_size(0); break;
265    case 21: __asan_get_free_bytes(); break;
266    case 22: __asan_get_heap_size(); break;
267    case 23: __asan_get_ownership(0); break;
268    case 24: __asan_get_unmapped_bytes(); break;
269    case 25: __asan_poison_memory_region(0, 0); break;
270    case 26: __asan_unpoison_memory_region(0, 0); break;
271    case 27: __asan_set_error_exit_code(0); break;
272    case 28: __asan_stack_free(0, 0, 0); break;
273    case 29: __asan_stack_malloc(0, 0); break;
274    case 30: __asan_before_dynamic_init(0, 0); break;
275    case 31: __asan_after_dynamic_init(); break;
276    case 32: __asan_poison_stack_memory(0, 0); break;
277    case 33: __asan_unpoison_stack_memory(0, 0); break;
278    case 34: __asan_region_is_poisoned(0, 0); break;
279    case 35: __asan_describe_address(0); break;
280  }
281}
282
283static void asan_atexit() {
284  Printf("AddressSanitizer exit stats:\n");
285  __asan_print_accumulated_stats();
286  // Print AsanMappingProfile.
287  for (uptr i = 0; i < kAsanMappingProfileSize; i++) {
288    if (AsanMappingProfile[i] == 0) continue;
289    Printf("asan_mapping.h:%zd -- %zd\n", i, AsanMappingProfile[i]);
290  }
291}
292
293static void InitializeHighMemEnd() {
294#if !ASAN_FIXED_MAPPING
295#if SANITIZER_WORDSIZE == 64
296# if defined(__powerpc64__)
297  // FIXME:
298  // On PowerPC64 we have two different address space layouts: 44- and 46-bit.
299  // We somehow need to figure our which one we are using now and choose
300  // one of 0x00000fffffffffffUL and 0x00003fffffffffffUL.
301  // Note that with 'ulimit -s unlimited' the stack is moved away from the top
302  // of the address space, so simply checking the stack address is not enough.
303  kHighMemEnd = (1ULL << 44) - 1;  // 0x00000fffffffffffUL
304# else
305  kHighMemEnd = (1ULL << 47) - 1;  // 0x00007fffffffffffUL;
306# endif
307#else  // SANITIZER_WORDSIZE == 32
308  kHighMemEnd = (1ULL << 32) - 1;  // 0xffffffff;
309#endif  // SANITIZER_WORDSIZE
310#endif  // !ASAN_FIXED_MAPPING
311}
312
313static void ProtectGap(uptr a, uptr size) {
314  CHECK_EQ(a, (uptr)Mprotect(a, size));
315}
316
317static void PrintAddressSpaceLayout() {
318  Printf("|| `[%p, %p]` || HighMem    ||\n",
319         (void*)kHighMemBeg, (void*)kHighMemEnd);
320  Printf("|| `[%p, %p]` || HighShadow ||\n",
321         (void*)kHighShadowBeg, (void*)kHighShadowEnd);
322  if (kMidMemBeg) {
323    Printf("|| `[%p, %p]` || ShadowGap3 ||\n",
324           (void*)kShadowGap3Beg, (void*)kShadowGap3End);
325    Printf("|| `[%p, %p]` || MidMem     ||\n",
326           (void*)kMidMemBeg, (void*)kMidMemEnd);
327    Printf("|| `[%p, %p]` || ShadowGap2 ||\n",
328           (void*)kShadowGap2Beg, (void*)kShadowGap2End);
329    Printf("|| `[%p, %p]` || MidShadow  ||\n",
330           (void*)kMidShadowBeg, (void*)kMidShadowEnd);
331  }
332  Printf("|| `[%p, %p]` || ShadowGap  ||\n",
333         (void*)kShadowGapBeg, (void*)kShadowGapEnd);
334  if (kLowShadowBeg) {
335    Printf("|| `[%p, %p]` || LowShadow  ||\n",
336           (void*)kLowShadowBeg, (void*)kLowShadowEnd);
337    Printf("|| `[%p, %p]` || LowMem     ||\n",
338           (void*)kLowMemBeg, (void*)kLowMemEnd);
339  }
340  Printf("MemToShadow(shadow): %p %p %p %p",
341         (void*)MEM_TO_SHADOW(kLowShadowBeg),
342         (void*)MEM_TO_SHADOW(kLowShadowEnd),
343         (void*)MEM_TO_SHADOW(kHighShadowBeg),
344         (void*)MEM_TO_SHADOW(kHighShadowEnd));
345  if (kMidMemBeg) {
346    Printf(" %p %p",
347           (void*)MEM_TO_SHADOW(kMidShadowBeg),
348           (void*)MEM_TO_SHADOW(kMidShadowEnd));
349  }
350  Printf("\n");
351  Printf("red_zone=%zu\n", (uptr)flags()->redzone);
352  Printf("malloc_context_size=%zu\n", (uptr)flags()->malloc_context_size);
353
354  Printf("SHADOW_SCALE: %zx\n", (uptr)SHADOW_SCALE);
355  Printf("SHADOW_GRANULARITY: %zx\n", (uptr)SHADOW_GRANULARITY);
356  Printf("SHADOW_OFFSET: %zx\n", (uptr)SHADOW_OFFSET);
357  CHECK(SHADOW_SCALE >= 3 && SHADOW_SCALE <= 7);
358  if (kMidMemBeg)
359    CHECK(kMidShadowBeg > kLowShadowEnd &&
360          kMidMemBeg > kMidShadowEnd &&
361          kHighShadowBeg > kMidMemEnd);
362}
363
364}  // namespace __asan
365
366// ---------------------- Interface ---------------- {{{1
367using namespace __asan;  // NOLINT
368
369#if !SANITIZER_SUPPORTS_WEAK_HOOKS
370extern "C" {
371SANITIZER_WEAK_ATTRIBUTE SANITIZER_INTERFACE_ATTRIBUTE
372const char* __asan_default_options() { return ""; }
373}  // extern "C"
374#endif
375
376int NOINLINE __asan_set_error_exit_code(int exit_code) {
377  int old = flags()->exitcode;
378  flags()->exitcode = exit_code;
379  return old;
380}
381
382void NOINLINE __asan_handle_no_return() {
383  int local_stack;
384  AsanThread *curr_thread = asanThreadRegistry().GetCurrent();
385  CHECK(curr_thread);
386  uptr PageSize = GetPageSizeCached();
387  uptr top = curr_thread->stack_top();
388  uptr bottom = ((uptr)&local_stack - PageSize) & ~(PageSize-1);
389  PoisonShadow(bottom, top - bottom, 0);
390}
391
392void NOINLINE __asan_set_death_callback(void (*callback)(void)) {
393  death_callback = callback;
394}
395
396void __asan_init() {
397  if (asan_inited) return;
398  SanitizerToolName = "AddressSanitizer";
399  CHECK(!asan_init_is_running && "ASan init calls itself!");
400  asan_init_is_running = true;
401  InitializeHighMemEnd();
402
403  // Make sure we are not statically linked.
404  AsanDoesNotSupportStaticLinkage();
405
406  // Install tool-specific callbacks in sanitizer_common.
407  SetDieCallback(AsanDie);
408  SetCheckFailedCallback(AsanCheckFailed);
409  SetPrintfAndReportCallback(AppendToErrorMessageBuffer);
410
411  // Initialize flags. This must be done early, because most of the
412  // initialization steps look at flags().
413  const char *options = GetEnv("ASAN_OPTIONS");
414  InitializeFlags(flags(), options);
415  __sanitizer_set_report_path(flags()->log_path);
416
417  if (flags()->verbosity && options) {
418    Report("Parsed ASAN_OPTIONS: %s\n", options);
419  }
420
421  // Re-exec ourselves if we need to set additional env or command line args.
422  MaybeReexec();
423
424  // Setup internal allocator callback.
425  SetLowLevelAllocateCallback(OnLowLevelAllocate);
426
427  if (flags()->atexit) {
428    Atexit(asan_atexit);
429  }
430
431  // interceptors
432  InitializeAsanInterceptors();
433
434  ReplaceSystemMalloc();
435  ReplaceOperatorsNewAndDelete();
436
437  uptr shadow_start = kLowShadowBeg;
438  if (kLowShadowBeg) shadow_start -= GetMmapGranularity();
439  uptr shadow_end = kHighShadowEnd;
440  bool full_shadow_is_available =
441      MemoryRangeIsAvailable(shadow_start, shadow_end);
442
443#if ASAN_LINUX && defined(__x86_64__) && !ASAN_FIXED_MAPPING
444  if (!full_shadow_is_available) {
445    kMidMemBeg = kLowMemEnd < 0x3000000000ULL ? 0x3000000000ULL : 0;
446    kMidMemEnd = kLowMemEnd < 0x3000000000ULL ? 0x3fffffffffULL : 0;
447  }
448#endif
449
450  if (flags()->verbosity)
451    PrintAddressSpaceLayout();
452
453  if (flags()->disable_core) {
454    DisableCoreDumper();
455  }
456
457  if (full_shadow_is_available) {
458    // mmap the low shadow plus at least one page at the left.
459    if (kLowShadowBeg)
460      ReserveShadowMemoryRange(shadow_start, kLowShadowEnd);
461    // mmap the high shadow.
462    ReserveShadowMemoryRange(kHighShadowBeg, kHighShadowEnd);
463    // protect the gap.
464    ProtectGap(kShadowGapBeg, kShadowGapEnd - kShadowGapBeg + 1);
465  } else if (kMidMemBeg &&
466      MemoryRangeIsAvailable(shadow_start, kMidMemBeg - 1) &&
467      MemoryRangeIsAvailable(kMidMemEnd + 1, shadow_end)) {
468    CHECK(kLowShadowBeg != kLowShadowEnd);
469    // mmap the low shadow plus at least one page at the left.
470    ReserveShadowMemoryRange(shadow_start, kLowShadowEnd);
471    // mmap the mid shadow.
472    ReserveShadowMemoryRange(kMidShadowBeg, kMidShadowEnd);
473    // mmap the high shadow.
474    ReserveShadowMemoryRange(kHighShadowBeg, kHighShadowEnd);
475    // protect the gaps.
476    ProtectGap(kShadowGapBeg, kShadowGapEnd - kShadowGapBeg + 1);
477    ProtectGap(kShadowGap2Beg, kShadowGap2End - kShadowGap2Beg + 1);
478    ProtectGap(kShadowGap3Beg, kShadowGap3End - kShadowGap3Beg + 1);
479  } else {
480    Report("Shadow memory range interleaves with an existing memory mapping. "
481           "ASan cannot proceed correctly. ABORTING.\n");
482    DumpProcessMap();
483    Die();
484  }
485
486  InstallSignalHandlers();
487  // Start symbolizer process if necessary.
488  if (flags()->symbolize) {
489    const char *external_symbolizer = GetEnv("ASAN_SYMBOLIZER_PATH");
490    if (external_symbolizer) {
491      InitializeExternalSymbolizer(external_symbolizer);
492    }
493  }
494
495  // On Linux AsanThread::ThreadStart() calls malloc() that's why asan_inited
496  // should be set to 1 prior to initializing the threads.
497  asan_inited = 1;
498  asan_init_is_running = false;
499
500  asanThreadRegistry().Init();
501  asanThreadRegistry().GetMain()->ThreadStart();
502  force_interface_symbols();  // no-op.
503
504  InitializeAllocator();
505
506  if (flags()->verbosity) {
507    Report("AddressSanitizer Init done\n");
508  }
509}
510
511#if defined(ASAN_USE_PREINIT_ARRAY)
512  // On Linux, we force __asan_init to be called before anyone else
513  // by placing it into .preinit_array section.
514  // FIXME: do we have anything like this on Mac?
515  __attribute__((section(".preinit_array")))
516    typeof(__asan_init) *__asan_preinit =__asan_init;
517#elif defined(_WIN32) && defined(_DLL)
518  // On Windows, when using dynamic CRT (/MD), we can put a pointer
519  // to __asan_init into the global list of C initializers.
520  // See crt0dat.c in the CRT sources for the details.
521  #pragma section(".CRT$XIB", long, read)  // NOLINT
522  __declspec(allocate(".CRT$XIB")) void (*__asan_preinit)() = __asan_init;
523#endif
524