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