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