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