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