asan_rtl.cc revision f2b1df7cb8f53f51bcb105e0d2930d99325bb681
1//===-- asan_rtl.cc ---------------------------------------------*- C++ -*-===//
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_stack.h"
21#include "asan_stats.h"
22#include "asan_thread.h"
23#include "asan_thread_registry.h"
24
25namespace __asan {
26
27// -------------------------- Flags ------------------------- {{{1
28static const size_t kMallocContextSize = 30;
29static int    FLAG_atexit;
30
31size_t FLAG_redzone;  // power of two, >= 32
32size_t FLAG_quarantine_size;
33int    FLAG_demangle;
34bool   FLAG_symbolize;
35int    FLAG_v;
36int    FLAG_debug;
37bool   FLAG_poison_shadow;
38int    FLAG_report_globals;
39size_t FLAG_malloc_context_size = kMallocContextSize;
40uintptr_t FLAG_large_malloc;
41bool   FLAG_handle_segv;
42bool   FLAG_use_sigaltstack;
43bool   FLAG_replace_str;
44bool   FLAG_replace_intrin;
45bool   FLAG_replace_cfallocator;  // Used on Mac only.
46size_t FLAG_max_malloc_fill_size = 0;
47bool   FLAG_use_fake_stack;
48bool   FLAG_abort_on_error;
49int    FLAG_exitcode = ASAN_DEFAULT_FAILURE_EXITCODE;
50bool   FLAG_allow_user_poisoning;
51int    FLAG_sleep_before_dying;
52bool   FLAG_unmap_shadow_on_exit;
53bool   FLAG_disable_core;
54
55// -------------------------- Globals --------------------- {{{1
56int asan_inited;
57bool asan_init_is_running;
58static void (*death_callback)(void);
59static void (*error_report_callback)(const char*);
60char *error_message_buffer = NULL;
61size_t error_message_buffer_pos = 0;
62size_t error_message_buffer_size = 0;
63
64// -------------------------- Misc ---------------- {{{1
65void ShowStatsAndAbort() {
66  __asan_print_accumulated_stats();
67  AsanDie();
68}
69
70static void PrintBytes(const char *before, uintptr_t *a) {
71  uint8_t *bytes = (uint8_t*)a;
72  size_t byte_num = (__WORDSIZE) / 8;
73  Printf("%s%p:", before, (void*)a);
74  for (size_t i = 0; i < byte_num; i++) {
75    Printf(" %x%x", bytes[i] >> 4, bytes[i] & 15);
76  }
77  Printf("\n");
78}
79
80size_t ReadFileToBuffer(const char *file_name, char **buff,
81                         size_t *buff_size, size_t max_len) {
82  const size_t kMinFileLen = kPageSize;
83  size_t read_len = 0;
84  *buff = 0;
85  *buff_size = 0;
86  // The files we usually open are not seekable, so try different buffer sizes.
87  for (size_t size = kMinFileLen; size <= max_len; size *= 2) {
88    int fd = AsanOpenReadonly(file_name);
89    if (fd < 0) return 0;
90    AsanUnmapOrDie(*buff, *buff_size);
91    *buff = (char*)AsanMmapSomewhereOrDie(size, __FUNCTION__);
92    *buff_size = size;
93    // Read up to one page at a time.
94    read_len = 0;
95    bool reached_eof = false;
96    while (read_len + kPageSize <= size) {
97      size_t just_read = AsanRead(fd, *buff + read_len, kPageSize);
98      if (just_read == 0) {
99        reached_eof = true;
100        break;
101      }
102      read_len += just_read;
103    }
104    AsanClose(fd);
105    if (reached_eof)  // We've read the whole file.
106      break;
107  }
108  return read_len;
109}
110
111void AsanDie() {
112  static int num_calls = 0;
113  if (AtomicInc(&num_calls) > 1) {
114    // Don't die twice - run a busy loop.
115    while (1) { }
116  }
117  if (FLAG_sleep_before_dying) {
118    Report("Sleeping for %d second(s)\n", FLAG_sleep_before_dying);
119    SleepForSeconds(FLAG_sleep_before_dying);
120  }
121  if (FLAG_unmap_shadow_on_exit)
122    AsanUnmapOrDie((void*)kLowShadowBeg, kHighShadowEnd - kLowShadowBeg);
123  if (death_callback)
124    death_callback();
125  if (FLAG_abort_on_error)
126    Abort();
127  Exit(FLAG_exitcode);
128}
129
130// ---------------------- mmap -------------------- {{{1
131void OutOfMemoryMessageAndDie(const char *mem_type, size_t size) {
132  Report("ERROR: AddressSanitizer failed to allocate "
133         "0x%zx (%zd) bytes of %s\n",
134         size, size, mem_type);
135  PRINT_CURRENT_STACK();
136  ShowStatsAndAbort();
137}
138
139// Reserve memory range [beg, end].
140static void ReserveShadowMemoryRange(uintptr_t beg, uintptr_t end) {
141  CHECK((beg % kPageSize) == 0);
142  CHECK(((end + 1) % kPageSize) == 0);
143  size_t size = end - beg + 1;
144  void *res = AsanMmapFixedNoReserve(beg, size);
145  CHECK(res == (void*)beg && "ReserveShadowMemoryRange failed");
146}
147
148// ---------------------- LowLevelAllocator ------------- {{{1
149void *LowLevelAllocator::Allocate(size_t size) {
150  CHECK((size & (size - 1)) == 0 && "size must be a power of two");
151  if (allocated_end_ - allocated_current_ < size) {
152    size_t size_to_allocate = Max(size, kPageSize);
153    allocated_current_ =
154        (char*)AsanMmapSomewhereOrDie(size_to_allocate, __FUNCTION__);
155    allocated_end_ = allocated_current_ + size_to_allocate;
156    PoisonShadow((uintptr_t)allocated_current_, size_to_allocate,
157                 kAsanInternalHeapMagic);
158  }
159  CHECK(allocated_end_ - allocated_current_ >= size);
160  void *res = allocated_current_;
161  allocated_current_ += size;
162  return res;
163}
164
165// ---------------------- DescribeAddress -------------------- {{{1
166static bool DescribeStackAddress(uintptr_t addr, uintptr_t access_size) {
167  AsanThread *t = asanThreadRegistry().FindThreadByStackAddress(addr);
168  if (!t) return false;
169  const intptr_t kBufSize = 4095;
170  char buf[kBufSize];
171  uintptr_t offset = 0;
172  const char *frame_descr = t->GetFrameNameByAddr(addr, &offset);
173  // This string is created by the compiler and has the following form:
174  // "FunctioName n alloc_1 alloc_2 ... alloc_n"
175  // where alloc_i looks like "offset size len ObjectName ".
176  CHECK(frame_descr);
177  // Report the function name and the offset.
178  const char *name_end = internal_strchr(frame_descr, ' ');
179  CHECK(name_end);
180  buf[0] = 0;
181  internal_strncat(buf, frame_descr,
182                   Min(kBufSize,
183                       static_cast<intptr_t>(name_end - frame_descr)));
184  Printf("Address %p is located at offset %zu "
185         "in frame <%s> of T%d's stack:\n",
186         addr, offset, buf, t->tid());
187  // Report the number of stack objects.
188  char *p;
189  size_t n_objects = internal_simple_strtoll(name_end, &p, 10);
190  CHECK(n_objects > 0);
191  Printf("  This frame has %zu object(s):\n", n_objects);
192  // Report all objects in this frame.
193  for (size_t i = 0; i < n_objects; i++) {
194    size_t beg, size;
195    intptr_t len;
196    beg  = internal_simple_strtoll(p, &p, 10);
197    size = internal_simple_strtoll(p, &p, 10);
198    len  = internal_simple_strtoll(p, &p, 10);
199    if (beg <= 0 || size <= 0 || len < 0 || *p != ' ') {
200      Printf("AddressSanitizer can't parse the stack frame descriptor: |%s|\n",
201             frame_descr);
202      break;
203    }
204    p++;
205    buf[0] = 0;
206    internal_strncat(buf, p, Min(kBufSize, len));
207    p += len;
208    Printf("    [%zu, %zu) '%s'\n", beg, beg + size, buf);
209  }
210  Printf("HINT: this may be a false positive if your program uses "
211         "some custom stack unwind mechanism\n"
212         "      (longjmp and C++ exceptions *are* supported)\n");
213  t->summary()->Announce();
214  return true;
215}
216
217static NOINLINE void DescribeAddress(uintptr_t addr, uintptr_t access_size) {
218  // Check if this is a global.
219  if (DescribeAddrIfGlobal(addr))
220    return;
221
222  if (DescribeStackAddress(addr, access_size))
223    return;
224
225  // finally, check if this is a heap.
226  DescribeHeapAddress(addr, access_size);
227}
228
229// -------------------------- Run-time entry ------------------- {{{1
230// exported functions
231#define ASAN_REPORT_ERROR(type, is_write, size)                     \
232extern "C" NOINLINE ASAN_INTERFACE_ATTRIBUTE                        \
233void __asan_report_ ## type ## size(uintptr_t addr);                \
234void __asan_report_ ## type ## size(uintptr_t addr) {               \
235  GET_CALLER_PC_BP_SP;                                              \
236  __asan_report_error(pc, bp, sp, addr, is_write, size);            \
237}
238
239ASAN_REPORT_ERROR(load, false, 1)
240ASAN_REPORT_ERROR(load, false, 2)
241ASAN_REPORT_ERROR(load, false, 4)
242ASAN_REPORT_ERROR(load, false, 8)
243ASAN_REPORT_ERROR(load, false, 16)
244ASAN_REPORT_ERROR(store, true, 1)
245ASAN_REPORT_ERROR(store, true, 2)
246ASAN_REPORT_ERROR(store, true, 4)
247ASAN_REPORT_ERROR(store, true, 8)
248ASAN_REPORT_ERROR(store, true, 16)
249
250// Force the linker to keep the symbols for various ASan interface functions.
251// We want to keep those in the executable in order to let the instrumented
252// dynamic libraries access the symbol even if it is not used by the executable
253// itself. This should help if the build system is removing dead code at link
254// time.
255static NOINLINE void force_interface_symbols() {
256  volatile int fake_condition = 0;  // prevent dead condition elimination.
257  if (fake_condition) {
258    __asan_report_load1(0);
259    __asan_report_load2(0);
260    __asan_report_load4(0);
261    __asan_report_load8(0);
262    __asan_report_load16(0);
263    __asan_report_store1(0);
264    __asan_report_store2(0);
265    __asan_report_store4(0);
266    __asan_report_store8(0);
267    __asan_report_store16(0);
268    __asan_register_global(0, 0, NULL);
269    __asan_register_globals(NULL, 0);
270    __asan_unregister_globals(NULL, 0);
271    __asan_set_death_callback(NULL);
272    __asan_set_error_report_callback(NULL);
273    __asan_handle_no_return();
274  }
275}
276
277// -------------------------- Init ------------------- {{{1
278static int64_t IntFlagValue(const char *flags, const char *flag,
279                            int64_t default_val) {
280  if (!flags) return default_val;
281  const char *str = internal_strstr(flags, flag);
282  if (!str) return default_val;
283  return internal_atoll(str + internal_strlen(flag));
284}
285
286static void asan_atexit() {
287  Printf("AddressSanitizer exit stats:\n");
288  __asan_print_accumulated_stats();
289}
290
291void CheckFailed(const char *cond, const char *file, int line) {
292  Report("CHECK failed: %s at %s:%d\n", cond, file, line);
293  PRINT_CURRENT_STACK();
294  ShowStatsAndAbort();
295}
296
297}  // namespace __asan
298
299// ---------------------- Interface ---------------- {{{1
300using namespace __asan;  // NOLINT
301
302int __asan_set_error_exit_code(int exit_code) {
303  int old = FLAG_exitcode;
304  FLAG_exitcode = exit_code;
305  return old;
306}
307
308void NOINLINE __asan_handle_no_return() {
309  int local_stack;
310  AsanThread *curr_thread = asanThreadRegistry().GetCurrent();
311  CHECK(curr_thread);
312  uintptr_t top = curr_thread->stack_top();
313  uintptr_t bottom = ((uintptr_t)&local_stack - kPageSize) & ~(kPageSize-1);
314  PoisonShadow(bottom, top - bottom, 0);
315}
316
317void NOINLINE __asan_set_death_callback(void (*callback)(void)) {
318  death_callback = callback;
319}
320
321void NOINLINE __asan_set_error_report_callback(void (*callback)(const char*)) {
322  error_report_callback = callback;
323  if (callback) {
324    error_message_buffer_size = 1 << 14;
325    error_message_buffer =
326        (char*)AsanMmapSomewhereOrDie(error_message_buffer_size, __FUNCTION__);
327    error_message_buffer_pos = 0;
328  }
329}
330
331void __asan_report_error(uintptr_t pc, uintptr_t bp, uintptr_t sp,
332                         uintptr_t addr, bool is_write, size_t access_size) {
333  // Do not print more than one report, otherwise they will mix up.
334  static int num_calls = 0;
335  if (AtomicInc(&num_calls) > 1) return;
336
337  Printf("=================================================================\n");
338  const char *bug_descr = "unknown-crash";
339  if (AddrIsInMem(addr)) {
340    uint8_t *shadow_addr = (uint8_t*)MemToShadow(addr);
341    // If we are accessing 16 bytes, look at the second shadow byte.
342    if (*shadow_addr == 0 && access_size > SHADOW_GRANULARITY)
343      shadow_addr++;
344    // If we are in the partial right redzone, look at the next shadow byte.
345    if (*shadow_addr > 0 && *shadow_addr < 128)
346      shadow_addr++;
347    switch (*shadow_addr) {
348      case kAsanHeapLeftRedzoneMagic:
349      case kAsanHeapRightRedzoneMagic:
350        bug_descr = "heap-buffer-overflow";
351        break;
352      case kAsanHeapFreeMagic:
353        bug_descr = "heap-use-after-free";
354        break;
355      case kAsanStackLeftRedzoneMagic:
356        bug_descr = "stack-buffer-underflow";
357        break;
358      case kAsanStackMidRedzoneMagic:
359      case kAsanStackRightRedzoneMagic:
360      case kAsanStackPartialRedzoneMagic:
361        bug_descr = "stack-buffer-overflow";
362        break;
363      case kAsanStackAfterReturnMagic:
364        bug_descr = "stack-use-after-return";
365        break;
366      case kAsanUserPoisonedMemoryMagic:
367        bug_descr = "use-after-poison";
368        break;
369      case kAsanGlobalRedzoneMagic:
370        bug_descr = "global-buffer-overflow";
371        break;
372    }
373  }
374
375  AsanThread *curr_thread = asanThreadRegistry().GetCurrent();
376  int curr_tid = asanThreadRegistry().GetCurrentTidOrMinusOne();
377
378  if (curr_thread) {
379    // We started reporting an error message. Stop using the fake stack
380    // in case we will call an instrumented function from a symbolizer.
381    curr_thread->fake_stack().StopUsingFakeStack();
382  }
383
384  Report("ERROR: AddressSanitizer %s on address "
385         "%p at pc 0x%zx bp 0x%zx sp 0x%zx\n",
386         bug_descr, addr, pc, bp, sp);
387
388  Printf("%s of size %zu at %p thread T%d\n",
389         access_size ? (is_write ? "WRITE" : "READ") : "ACCESS",
390         access_size, addr, curr_tid);
391
392  if (FLAG_debug) {
393    PrintBytes("PC: ", (uintptr_t*)pc);
394  }
395
396  GET_STACK_TRACE_WITH_PC_AND_BP(kStackTraceMax, pc, bp);
397  stack.PrintStack();
398
399  CHECK(AddrIsInMem(addr));
400
401  DescribeAddress(addr, access_size);
402
403  uintptr_t shadow_addr = MemToShadow(addr);
404  Report("ABORTING\n");
405  __asan_print_accumulated_stats();
406  Printf("Shadow byte and word:\n");
407  Printf("  %p: %x\n", shadow_addr, *(unsigned char*)shadow_addr);
408  uintptr_t aligned_shadow = shadow_addr & ~(kWordSize - 1);
409  PrintBytes("  ", (uintptr_t*)(aligned_shadow));
410  Printf("More shadow bytes:\n");
411  PrintBytes("  ", (uintptr_t*)(aligned_shadow-4*kWordSize));
412  PrintBytes("  ", (uintptr_t*)(aligned_shadow-3*kWordSize));
413  PrintBytes("  ", (uintptr_t*)(aligned_shadow-2*kWordSize));
414  PrintBytes("  ", (uintptr_t*)(aligned_shadow-1*kWordSize));
415  PrintBytes("=>", (uintptr_t*)(aligned_shadow+0*kWordSize));
416  PrintBytes("  ", (uintptr_t*)(aligned_shadow+1*kWordSize));
417  PrintBytes("  ", (uintptr_t*)(aligned_shadow+2*kWordSize));
418  PrintBytes("  ", (uintptr_t*)(aligned_shadow+3*kWordSize));
419  PrintBytes("  ", (uintptr_t*)(aligned_shadow+4*kWordSize));
420  if (error_report_callback) {
421    error_report_callback(error_message_buffer);
422  }
423  AsanDie();
424}
425
426void __asan_init() {
427  if (asan_inited) return;
428  asan_init_is_running = true;
429
430  // Make sure we are not statically linked.
431  AsanDoesNotSupportStaticLinkage();
432
433  // flags
434  const char *options = AsanGetEnv("ASAN_OPTIONS");
435  FLAG_malloc_context_size =
436      IntFlagValue(options, "malloc_context_size=", kMallocContextSize);
437  CHECK(FLAG_malloc_context_size <= kMallocContextSize);
438
439  FLAG_max_malloc_fill_size =
440      IntFlagValue(options, "max_malloc_fill_size=", 0);
441
442  FLAG_v = IntFlagValue(options, "verbosity=", 0);
443
444  FLAG_redzone = IntFlagValue(options, "redzone=",
445      (ASAN_LOW_MEMORY) ? 64 : 128);
446  CHECK(FLAG_redzone >= 32);
447  CHECK((FLAG_redzone & (FLAG_redzone - 1)) == 0);
448
449  FLAG_atexit = IntFlagValue(options, "atexit=", 0);
450  FLAG_poison_shadow = IntFlagValue(options, "poison_shadow=", 1);
451  FLAG_report_globals = IntFlagValue(options, "report_globals=", 1);
452  FLAG_handle_segv = IntFlagValue(options, "handle_segv=", ASAN_NEEDS_SEGV);
453  FLAG_use_sigaltstack = IntFlagValue(options, "use_sigaltstack=", 0);
454  FLAG_symbolize = IntFlagValue(options, "symbolize=", 1);
455  FLAG_demangle = IntFlagValue(options, "demangle=", 1);
456  FLAG_debug = IntFlagValue(options, "debug=", 0);
457  FLAG_replace_cfallocator = IntFlagValue(options, "replace_cfallocator=", 1);
458  FLAG_replace_str = IntFlagValue(options, "replace_str=", 1);
459  FLAG_replace_intrin = IntFlagValue(options, "replace_intrin=", 1);
460  FLAG_use_fake_stack = IntFlagValue(options, "use_fake_stack=", 1);
461  FLAG_exitcode = IntFlagValue(options, "exitcode=",
462                               ASAN_DEFAULT_FAILURE_EXITCODE);
463  FLAG_allow_user_poisoning = IntFlagValue(options,
464                                           "allow_user_poisoning=", 1);
465  FLAG_sleep_before_dying = IntFlagValue(options, "sleep_before_dying=", 0);
466  FLAG_abort_on_error = IntFlagValue(options, "abort_on_error=", 0);
467  FLAG_unmap_shadow_on_exit = IntFlagValue(options, "unmap_shadow_on_exit=", 0);
468  // By default, disable core dumper on 64-bit --
469  // it makes little sense to dump 16T+ core.
470  FLAG_disable_core = IntFlagValue(options, "disable_core=", __WORDSIZE == 64);
471
472  FLAG_quarantine_size = IntFlagValue(options, "quarantine_size=",
473      (ASAN_LOW_MEMORY) ? 1UL << 24 : 1UL << 28);
474
475  if (FLAG_v) {
476    Report("Parsed ASAN_OPTIONS: %s\n", options);
477  }
478
479  if (FLAG_atexit) {
480    Atexit(asan_atexit);
481  }
482
483  // interceptors
484  InitializeAsanInterceptors();
485
486  ReplaceSystemMalloc();
487  ReplaceOperatorsNewAndDelete();
488
489  if (FLAG_v) {
490    Printf("|| `[%p, %p]` || HighMem    ||\n", kHighMemBeg, kHighMemEnd);
491    Printf("|| `[%p, %p]` || HighShadow ||\n",
492           kHighShadowBeg, kHighShadowEnd);
493    Printf("|| `[%p, %p]` || ShadowGap  ||\n",
494           kShadowGapBeg, kShadowGapEnd);
495    Printf("|| `[%p, %p]` || LowShadow  ||\n",
496           kLowShadowBeg, kLowShadowEnd);
497    Printf("|| `[%p, %p]` || LowMem     ||\n", kLowMemBeg, kLowMemEnd);
498    Printf("MemToShadow(shadow): %p %p %p %p\n",
499           MEM_TO_SHADOW(kLowShadowBeg),
500           MEM_TO_SHADOW(kLowShadowEnd),
501           MEM_TO_SHADOW(kHighShadowBeg),
502           MEM_TO_SHADOW(kHighShadowEnd));
503    Printf("red_zone=%zu\n", (size_t)FLAG_redzone);
504    Printf("malloc_context_size=%zu\n", (size_t)FLAG_malloc_context_size);
505
506    Printf("SHADOW_SCALE: %zx\n", (size_t)SHADOW_SCALE);
507    Printf("SHADOW_GRANULARITY: %zx\n", (size_t)SHADOW_GRANULARITY);
508    Printf("SHADOW_OFFSET: %zx\n", (size_t)SHADOW_OFFSET);
509    CHECK(SHADOW_SCALE >= 3 && SHADOW_SCALE <= 7);
510  }
511
512  if (FLAG_disable_core) {
513    AsanDisableCoreDumper();
514  }
515
516  if (AsanShadowRangeIsAvailable()) {
517    if (kLowShadowBeg != kLowShadowEnd) {
518      // mmap the low shadow plus at least one page.
519      ReserveShadowMemoryRange(kLowShadowBeg - kMmapGranularity, kLowShadowEnd);
520    }
521    // mmap the high shadow.
522    ReserveShadowMemoryRange(kHighShadowBeg, kHighShadowEnd);
523    // protect the gap
524    void *prot = AsanMprotect(kShadowGapBeg, kShadowGapEnd - kShadowGapBeg + 1);
525    CHECK(prot == (void*)kShadowGapBeg);
526  } else {
527    Report("Shadow memory range interleaves with an existing memory mapping. "
528           "ASan cannot proceed correctly. ABORTING.\n");
529    AsanDumpProcessMap();
530    AsanDie();
531  }
532
533  InstallSignalHandlers();
534
535  // On Linux AsanThread::ThreadStart() calls malloc() that's why asan_inited
536  // should be set to 1 prior to initializing the threads.
537  asan_inited = 1;
538  asan_init_is_running = false;
539
540  asanThreadRegistry().Init();
541  asanThreadRegistry().GetMain()->ThreadStart();
542  force_interface_symbols();  // no-op.
543
544  if (FLAG_v) {
545    Report("AddressSanitizer Init done\n");
546  }
547}
548
549#if defined(ASAN_USE_PREINIT_ARRAY)
550  // On Linux, we force __asan_init to be called before anyone else
551  // by placing it into .preinit_array section.
552  // FIXME: do we have anything like this on Mac?
553  __attribute__((section(".preinit_array")))
554    typeof(__asan_init) *__asan_preinit =__asan_init;
555#elif defined(_WIN32) && defined(_DLL)
556  // On Windows, when using dynamic CRT (/MD), we can put a pointer
557  // to __asan_init into the global list of C initializers.
558  // See crt0dat.c in the CRT sources for the details.
559  #pragma section(".CRT$XIB", long, read)  // NOLINT
560  __declspec(allocate(".CRT$XIB")) void (*__asan_preinit)() = __asan_init;
561#endif
562