blob: bb9c7b1d62cdb775998dd3cb6e8ea210260e627e [file] [log] [blame]
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001//===-- 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#ifdef __APPLE__
20#include "asan_mac.h"
21#endif
22#include "asan_mapping.h"
23#include "asan_stack.h"
24#include "asan_stats.h"
25#include "asan_thread.h"
26#include "asan_thread_registry.h"
27
28#include <algorithm>
29#include <map>
30#include <dlfcn.h>
31#include <execinfo.h>
32#include <fcntl.h>
33#include <pthread.h>
34#include <signal.h>
35#include <stdarg.h>
36#include <stdint.h>
37#include <stdio.h>
38#include <stdlib.h>
39#include <string.h>
40#include <sys/mman.h>
41#include <sys/stat.h>
42#include <sys/types.h>
43#include <sys/ucontext.h>
44#include <sys/time.h>
45#include <sys/resource.h>
46#include <unistd.h>
47// must not include <setjmp.h> on Linux
48
49#ifndef ASAN_NEEDS_SEGV
50# define ASAN_NEEDS_SEGV 1
51#endif
52
53namespace __asan {
54
55// -------------------------- Flags ------------------------- {{{1
56static const size_t kMallocContextSize = 30;
57static int FLAG_atexit;
58bool FLAG_fast_unwind = true;
59
60size_t FLAG_redzone; // power of two, >= 32
61bool FLAG_mt; // set to 0 if you have only one thread.
62size_t FLAG_quarantine_size;
63int FLAG_demangle;
64bool FLAG_symbolize;
65int FLAG_v;
66int FLAG_debug;
67bool FLAG_poison_shadow;
68int FLAG_report_globals;
69size_t FLAG_malloc_context_size = kMallocContextSize;
70uintptr_t FLAG_large_malloc;
71bool FLAG_lazy_shadow;
72bool FLAG_handle_segv;
73bool FLAG_handle_sigill;
74bool FLAG_replace_str;
75bool FLAG_replace_intrin;
76bool FLAG_replace_cfallocator; // Used on Mac only.
77bool FLAG_stats;
78size_t FLAG_max_malloc_fill_size = 0;
79bool FLAG_use_fake_stack;
80int FLAG_exitcode = EXIT_FAILURE;
81bool FLAG_allow_user_poisoning;
82
83// -------------------------- Globals --------------------- {{{1
84int asan_inited;
85bool asan_init_is_running;
86
87// -------------------------- Interceptors ---------------- {{{1
88typedef int (*sigaction_f)(int signum, const struct sigaction *act,
89 struct sigaction *oldact);
90typedef sig_t (*signal_f)(int signum, sig_t handler);
91typedef void (*longjmp_f)(void *env, int val);
92typedef longjmp_f _longjmp_f;
93typedef longjmp_f siglongjmp_f;
94typedef void (*__cxa_throw_f)(void *, void *, void *);
95typedef int (*pthread_create_f)(pthread_t *thread, const pthread_attr_t *attr,
96 void *(*start_routine) (void *), void *arg);
97#ifdef __APPLE__
98dispatch_async_f_f real_dispatch_async_f;
99dispatch_sync_f_f real_dispatch_sync_f;
100dispatch_after_f_f real_dispatch_after_f;
101dispatch_barrier_async_f_f real_dispatch_barrier_async_f;
102dispatch_group_async_f_f real_dispatch_group_async_f;
103pthread_workqueue_additem_np_f real_pthread_workqueue_additem_np;
104#endif
105
106sigaction_f real_sigaction;
107signal_f real_signal;
108longjmp_f real_longjmp;
109_longjmp_f real__longjmp;
110siglongjmp_f real_siglongjmp;
111__cxa_throw_f real___cxa_throw;
112pthread_create_f real_pthread_create;
113
114// -------------------------- Misc ---------------- {{{1
115void ShowStatsAndAbort() {
116 __asan_print_accumulated_stats();
117 ASAN_DIE;
118}
119
120static void PrintBytes(const char *before, uintptr_t *a) {
121 uint8_t *bytes = (uint8_t*)a;
122 size_t byte_num = (__WORDSIZE) / 8;
123 Printf("%s%p:", before, (uintptr_t)a);
124 for (size_t i = 0; i < byte_num; i++) {
125 Printf(" %lx%lx", bytes[i] >> 4, bytes[i] & 15);
126 }
127 Printf("\n");
128}
129
130// ---------------------- Thread ------------------------- {{{1
131static void *asan_thread_start(void *arg) {
132 AsanThread *t= (AsanThread*)arg;
133 asanThreadRegistry().SetCurrent(t);
134 return t->ThreadStart();
135}
136
137// ---------------------- mmap -------------------- {{{1
138static void OutOfMemoryMessage(const char *mem_type, size_t size) {
139 Report("ERROR: AddressSanitizer failed to allocate "
140 "0x%lx (%ld) bytes of %s\n",
141 size, size, mem_type);
142}
143
144static char *mmap_pages(size_t start_page, size_t n_pages, const char *mem_type,
145 bool abort_on_failure = true) {
146 void *res = asan_mmap((void*)start_page, kPageSize * n_pages,
147 PROT_READ | PROT_WRITE,
148 MAP_PRIVATE | MAP_ANON | MAP_FIXED | MAP_NORESERVE, 0, 0);
149 // Printf("%p => %p\n", (void*)start_page, res);
150 char *ch = (char*)res;
151 if (res == (void*)-1L && abort_on_failure) {
152 OutOfMemoryMessage(mem_type, n_pages * kPageSize);
153 ShowStatsAndAbort();
154 }
155 CHECK(res == (void*)start_page || res == (void*)-1L);
156 return ch;
157}
158
159// mmap range [beg, end]
160static char *mmap_range(uintptr_t beg, uintptr_t end, const char *mem_type) {
161 CHECK((beg % kPageSize) == 0);
162 CHECK(((end + 1) % kPageSize) == 0);
163 // Printf("mmap_range %p %p %ld\n", beg, end, (end - beg) / kPageSize);
164 return mmap_pages(beg, (end - beg + 1) / kPageSize, mem_type);
165}
166
167// protect range [beg, end]
168static void protect_range(uintptr_t beg, uintptr_t end) {
169 CHECK((beg % kPageSize) == 0);
170 CHECK(((end+1) % kPageSize) == 0);
171 // Printf("protect_range %p %p %ld\n", beg, end, (end - beg) / kPageSize);
172 void *res = asan_mmap((void*)beg, end - beg + 1,
173 PROT_NONE,
174 MAP_PRIVATE | MAP_ANON | MAP_FIXED | MAP_NORESERVE, 0, 0);
175 CHECK(res == (void*)beg);
176}
177
178// ---------------------- DescribeAddress -------------------- {{{1
179static bool DescribeStackAddress(uintptr_t addr, uintptr_t access_size) {
180 AsanThread *t = asanThreadRegistry().FindThreadByStackAddress(addr);
181 if (!t) return false;
182 const intptr_t kBufSize = 4095;
183 char buf[kBufSize];
184 uintptr_t offset = 0;
185 const char *frame_descr = t->GetFrameNameByAddr(addr, &offset);
186 // This string is created by the compiler and has the following form:
187 // "FunctioName n alloc_1 alloc_2 ... alloc_n"
188 // where alloc_i looks like "offset size len ObjectName ".
189 CHECK(frame_descr);
190 // Report the function name and the offset.
191 const char *name_end = real_strchr(frame_descr, ' ');
192 CHECK(name_end);
193 buf[0] = 0;
194 strncat(buf, frame_descr,
195 std::min(kBufSize, static_cast<intptr_t>(name_end - frame_descr)));
196 Printf("Address %p is located at offset %ld "
197 "in frame <%s> of T%d's stack:\n",
198 addr, offset, buf, t->tid());
199 // Report the number of stack objects.
200 char *p;
201 size_t n_objects = strtol(name_end, &p, 10);
202 CHECK(n_objects > 0);
203 Printf(" This frame has %ld object(s):\n", n_objects);
204 // Report all objects in this frame.
205 for (size_t i = 0; i < n_objects; i++) {
206 size_t beg, size;
207 intptr_t len;
208 beg = strtol(p, &p, 10);
209 size = strtol(p, &p, 10);
210 len = strtol(p, &p, 10);
211 if (beg <= 0 || size <= 0 || len < 0 || *p != ' ') {
212 Printf("AddressSanitizer can't parse the stack frame descriptor: |%s|\n",
213 frame_descr);
214 break;
215 }
216 p++;
217 buf[0] = 0;
218 strncat(buf, p, std::min(kBufSize, len));
219 p += len;
220 Printf(" [%ld, %ld) '%s'\n", beg, beg + size, buf);
221 }
222 Printf("HINT: this may be a false positive if your program uses "
223 "some custom stack unwind mechanism\n"
224 " (longjmp and C++ exceptions *are* supported)\n");
225 t->summary()->Announce();
226 return true;
227}
228
229__attribute__((noinline))
230static void DescribeAddress(uintptr_t addr, uintptr_t access_size) {
231 // Check if this is a global.
232 if (DescribeAddrIfGlobal(addr))
233 return;
234
235 if (DescribeStackAddress(addr, access_size))
236 return;
237
238 // finally, check if this is a heap.
239 DescribeHeapAddress(addr, access_size);
240}
241
242// -------------------------- Run-time entry ------------------- {{{1
243void GetPcSpBpAx(void *context,
244 uintptr_t *pc, uintptr_t *sp, uintptr_t *bp, uintptr_t *ax) {
245 ucontext_t *ucontext = (ucontext_t*)context;
246#ifdef __APPLE__
247# if __WORDSIZE == 64
248 *pc = ucontext->uc_mcontext->__ss.__rip;
249 *bp = ucontext->uc_mcontext->__ss.__rbp;
250 *sp = ucontext->uc_mcontext->__ss.__rsp;
251 *ax = ucontext->uc_mcontext->__ss.__rax;
252# else
253 *pc = ucontext->uc_mcontext->__ss.__eip;
254 *bp = ucontext->uc_mcontext->__ss.__ebp;
255 *sp = ucontext->uc_mcontext->__ss.__esp;
256 *ax = ucontext->uc_mcontext->__ss.__eax;
257# endif // __WORDSIZE
258#else // assume linux
259# if defined(__arm__)
260 *pc = ucontext->uc_mcontext.arm_pc;
261 *bp = ucontext->uc_mcontext.arm_fp;
262 *sp = ucontext->uc_mcontext.arm_sp;
263 *ax = ucontext->uc_mcontext.arm_r0;
264# elif __WORDSIZE == 64
265 *pc = ucontext->uc_mcontext.gregs[REG_RIP];
266 *bp = ucontext->uc_mcontext.gregs[REG_RBP];
267 *sp = ucontext->uc_mcontext.gregs[REG_RSP];
268 *ax = ucontext->uc_mcontext.gregs[REG_RAX];
269# else
270 *pc = ucontext->uc_mcontext.gregs[REG_EIP];
271 *bp = ucontext->uc_mcontext.gregs[REG_EBP];
272 *sp = ucontext->uc_mcontext.gregs[REG_ESP];
273 *ax = ucontext->uc_mcontext.gregs[REG_EAX];
274# endif // __WORDSIZE
275#endif
276}
277
278static void ASAN_OnSIGSEGV(int, siginfo_t *siginfo, void *context) {
279 uintptr_t addr = (uintptr_t)siginfo->si_addr;
280 if (AddrIsInShadow(addr) && FLAG_lazy_shadow) {
281 // We traped on access to a shadow address. Just map a large chunk around
282 // this address.
283 const uintptr_t chunk_size = kPageSize << 10; // 4M
284 uintptr_t chunk = addr & ~(chunk_size - 1);
285 asan_mmap((void*)chunk, chunk_size,
286 PROT_READ | PROT_WRITE,
287 MAP_PRIVATE | MAP_ANON | MAP_FIXED, 0, 0);
288 return;
289 }
290 // Write the first message using the bullet-proof write.
291 if (13 != asan_write(2, "ASAN:SIGSEGV\n", 13)) ASAN_DIE;
292 uintptr_t pc, sp, bp, ax;
293 GetPcSpBpAx(context, &pc, &sp, &bp, &ax);
294 Report("ERROR: AddressSanitizer crashed on unknown address %p"
295 " (pc %p sp %p bp %p ax %p T%d)\n",
296 addr, pc, sp, bp, ax,
297 asanThreadRegistry().GetCurrentTidOrMinusOne());
298 Printf("AddressSanitizer can not provide additional info. ABORTING\n");
299 GET_STACK_TRACE_WITH_PC_AND_BP(kStackTraceMax, false, pc, bp);
300 stack.PrintStack();
301 ShowStatsAndAbort();
302}
303
304static void ASAN_OnSIGILL(int, siginfo_t *siginfo, void *context) {
305 // Write the first message using the bullet-proof write.
306 if (12 != asan_write(2, "ASAN:SIGILL\n", 12)) ASAN_DIE;
307 uintptr_t pc, sp, bp, ax;
308 GetPcSpBpAx(context, &pc, &sp, &bp, &ax);
309
310 uintptr_t addr = ax;
311
312 uint8_t *insn = (uint8_t*)pc;
313 CHECK(insn[0] == 0x0f && insn[1] == 0x0b); // ud2
314 unsigned access_size_and_type = insn[2] - 0x50;
315 CHECK(access_size_and_type < 16);
316 bool is_write = access_size_and_type & 8;
317 int access_size = 1 << (access_size_and_type & 7);
318 __asan_report_error(pc, bp, sp, addr, is_write, access_size);
319}
320
321// exported functions
322#define ASAN_REPORT_ERROR(type, is_write, size) \
323extern "C" void __asan_report_ ## type ## size(uintptr_t addr) \
324 __attribute__((visibility("default"))); \
325extern "C" void __asan_report_ ## type ## size(uintptr_t addr) { \
326 GET_BP_PC_SP; \
327 __asan_report_error(pc, bp, sp, addr, is_write, size); \
328}
329
330ASAN_REPORT_ERROR(load, false, 1)
331ASAN_REPORT_ERROR(load, false, 2)
332ASAN_REPORT_ERROR(load, false, 4)
333ASAN_REPORT_ERROR(load, false, 8)
334ASAN_REPORT_ERROR(load, false, 16)
335ASAN_REPORT_ERROR(store, true, 1)
336ASAN_REPORT_ERROR(store, true, 2)
337ASAN_REPORT_ERROR(store, true, 4)
338ASAN_REPORT_ERROR(store, true, 8)
339ASAN_REPORT_ERROR(store, true, 16)
340
341// Force the linker to keep the symbols for various ASan interface functions.
342// We want to keep those in the executable in order to let the instrumented
343// dynamic libraries access the symbol even if it is not used by the executable
344// itself. This should help if the build system is removing dead code at link
345// time.
346extern "C"
347void __asan_force_interface_symbols() {
348 volatile int fake_condition = 0; // prevent dead condition elimination.
349 if (fake_condition) {
350 __asan_report_load1(NULL);
351 __asan_report_load2(NULL);
352 __asan_report_load4(NULL);
353 __asan_report_load8(NULL);
354 __asan_report_load16(NULL);
355 __asan_report_store1(NULL);
356 __asan_report_store2(NULL);
357 __asan_report_store4(NULL);
358 __asan_report_store8(NULL);
359 __asan_report_store16(NULL);
360 __asan_register_global(0, 0, NULL);
361 __asan_register_globals(NULL, 0);
362 }
363}
364
365// -------------------------- Init ------------------- {{{1
366static int64_t IntFlagValue(const char *flags, const char *flag,
367 int64_t default_val) {
368 if (!flags) return default_val;
369 const char *str = strstr(flags, flag);
370 if (!str) return default_val;
371 return atoll(str + internal_strlen(flag));
372}
373
374static void asan_atexit() {
375 Printf("AddressSanitizer exit stats:\n");
376 __asan_print_accumulated_stats();
377}
378
379void CheckFailed(const char *cond, const char *file, int line) {
380 Report("CHECK failed: %s at %s:%d, pthread_self=%p\n",
381 cond, file, line, pthread_self());
382 PRINT_CURRENT_STACK();
383 ShowStatsAndAbort();
384}
385
386} // namespace __asan
387
388// -------------------------- Interceptors ------------------- {{{1
389using namespace __asan; // NOLINT
390
391#define OPERATOR_NEW_BODY \
392 GET_STACK_TRACE_HERE_FOR_MALLOC;\
393 return asan_memalign(0, size, &stack);
394
395void *operator new(size_t size) throw(std::bad_alloc) { OPERATOR_NEW_BODY; }
396void *operator new[](size_t size) throw(std::bad_alloc) { OPERATOR_NEW_BODY; }
397void *operator new(size_t size, std::nothrow_t const&) throw()
398{ OPERATOR_NEW_BODY; }
399void *operator new[](size_t size, std::nothrow_t const&) throw()
400{ OPERATOR_NEW_BODY; }
401
402#define OPERATOR_DELETE_BODY \
403 GET_STACK_TRACE_HERE_FOR_FREE(ptr);\
404 asan_free(ptr, &stack);
405
406void operator delete(void *ptr) throw() { OPERATOR_DELETE_BODY; }
407void operator delete[](void *ptr) throw() { OPERATOR_DELETE_BODY; }
408void operator delete(void *ptr, std::nothrow_t const&) throw()
409{ OPERATOR_DELETE_BODY; }
410void operator delete[](void *ptr, std::nothrow_t const&) throw()
411{ OPERATOR_DELETE_BODY;}
412
413extern "C"
414#ifndef __APPLE__
415__attribute__((visibility("default")))
416#endif
417int WRAP(pthread_create)(pthread_t *thread, const pthread_attr_t *attr,
418 void *(*start_routine) (void *), void *arg) {
419 GET_STACK_TRACE_HERE(kStackTraceMax, /*fast_unwind*/false);
420 AsanThread *t = (AsanThread*)asan_malloc(sizeof(AsanThread), &stack);
421 AsanThread *curr_thread = asanThreadRegistry().GetCurrent();
422 CHECK(curr_thread || asanThreadRegistry().IsCurrentThreadDying());
423 new(t) AsanThread(asanThreadRegistry().GetCurrentTidOrMinusOne(),
424 start_routine, arg, &stack);
425 return real_pthread_create(thread, attr, asan_thread_start, t);
426}
427
428static bool MySignal(int signum) {
429 if (FLAG_handle_sigill && signum == SIGILL) return true;
430 if (FLAG_handle_segv && signum == SIGSEGV) return true;
431#ifdef __APPLE__
432 if (FLAG_handle_segv && signum == SIGBUS) return true;
433#endif
434 return false;
435}
436
437static void MaybeInstallSigaction(int signum,
438 void (*handler)(int, siginfo_t *, void *)) {
439 if (!MySignal(signum))
440 return;
441 struct sigaction sigact;
442 real_memset(&sigact, 0, sizeof(sigact));
443 sigact.sa_sigaction = handler;
444 sigact.sa_flags = SA_SIGINFO;
445 CHECK(0 == real_sigaction(signum, &sigact, 0));
446}
447
448extern "C"
449sig_t WRAP(signal)(int signum, sig_t handler) {
450 if (!MySignal(signum)) {
451 return real_signal(signum, handler);
452 }
453 return NULL;
454}
455
456extern "C"
457int WRAP(sigaction)(int signum, const struct sigaction *act,
458 struct sigaction *oldact) {
459 if (!MySignal(signum)) {
460 return real_sigaction(signum, act, oldact);
461 }
462 return 0;
463}
464
465
466static void UnpoisonStackFromHereToTop() {
467 int local_stack;
468 AsanThread *curr_thread = asanThreadRegistry().GetCurrent();
469 CHECK(curr_thread);
470 uintptr_t top = curr_thread->stack_top();
471 uintptr_t bottom = ((uintptr_t)&local_stack - kPageSize) & ~(kPageSize-1);
Kostya Serebryany218a9b72011-11-30 18:50:23 +0000472 PoisonShadow(bottom, top - bottom, 0);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000473}
474
475extern "C" void WRAP(longjmp)(void *env, int val) {
476 UnpoisonStackFromHereToTop();
477 real_longjmp(env, val);
478}
479
480extern "C" void WRAP(_longjmp)(void *env, int val) {
481 UnpoisonStackFromHereToTop();
482 real__longjmp(env, val);
483}
484
485extern "C" void WRAP(siglongjmp)(void *env, int val) {
486 UnpoisonStackFromHereToTop();
487 real_siglongjmp(env, val);
488}
489
490extern "C" void __cxa_throw(void *a, void *b, void *c);
491
492#if ASAN_HAS_EXCEPTIONS
493extern "C" void WRAP(__cxa_throw)(void *a, void *b, void *c) {
494 UnpoisonStackFromHereToTop();
495 real___cxa_throw(a, b, c);
496}
497#endif
498
499extern "C" {
500// intercept mlock and friends.
501// Since asan maps 16T of RAM, mlock is completely unfriendly to asan.
502// All functions return 0 (success).
503static void MlockIsUnsupported() {
504 static bool printed = 0;
505 if (printed) return;
506 printed = true;
507 Printf("INFO: AddressSanitizer ignores mlock/mlockall/munlock/munlockall\n");
508}
509int mlock(const void *addr, size_t len) {
510 MlockIsUnsupported();
511 return 0;
512}
513int munlock(const void *addr, size_t len) {
514 MlockIsUnsupported();
515 return 0;
516}
517int mlockall(int flags) {
518 MlockIsUnsupported();
519 return 0;
520}
521int munlockall(void) {
522 MlockIsUnsupported();
523 return 0;
524}
525} // extern "C"
526
527// ---------------------- Interface ---------------- {{{1
528int __asan_set_error_exit_code(int exit_code) {
529 int old = FLAG_exitcode;
530 FLAG_exitcode = exit_code;
531 return old;
532}
533
534void __asan_report_error(uintptr_t pc, uintptr_t bp, uintptr_t sp,
535 uintptr_t addr, bool is_write, size_t access_size) {
536 // Do not print more than one report, otherwise they will mix up.
537 static int num_calls = 0;
538 if (AtomicInc(&num_calls) > 1) return;
539
540 Printf("=================================================================\n");
541 const char *bug_descr = "unknown-crash";
542 if (AddrIsInMem(addr)) {
543 uint8_t *shadow_addr = (uint8_t*)MemToShadow(addr);
544 uint8_t shadow_byte = shadow_addr[0];
545 if (shadow_byte > 0 && shadow_byte < 128) {
546 // we are in the partial right redzone, look at the next shadow byte.
547 shadow_byte = shadow_addr[1];
548 }
549 switch (shadow_byte) {
550 case kAsanHeapLeftRedzoneMagic:
551 case kAsanHeapRightRedzoneMagic:
552 bug_descr = "heap-buffer-overflow";
553 break;
554 case kAsanHeapFreeMagic:
555 bug_descr = "heap-use-after-free";
556 break;
557 case kAsanStackLeftRedzoneMagic:
558 bug_descr = "stack-buffer-underflow";
559 break;
560 case kAsanStackMidRedzoneMagic:
561 case kAsanStackRightRedzoneMagic:
562 case kAsanStackPartialRedzoneMagic:
563 bug_descr = "stack-buffer-overflow";
564 break;
565 case kAsanStackAfterReturnMagic:
566 bug_descr = "stack-use-after-return";
567 break;
568 case kAsanUserPoisonedMemoryMagic:
569 bug_descr = "use-after-poison";
570 break;
571 case kAsanGlobalRedzoneMagic:
572 bug_descr = "global-buffer-overflow";
573 break;
574 }
575 }
576
577 Report("ERROR: AddressSanitizer %s on address "
578 "%p at pc 0x%lx bp 0x%lx sp 0x%lx\n",
579 bug_descr, addr, pc, bp, sp);
580
581 Printf("%s of size %d at %p thread T%d\n",
582 access_size ? (is_write ? "WRITE" : "READ") : "ACCESS",
583 access_size, addr, asanThreadRegistry().GetCurrentTidOrMinusOne());
584
585 if (FLAG_debug) {
586 PrintBytes("PC: ", (uintptr_t*)pc);
587 }
588
589 GET_STACK_TRACE_WITH_PC_AND_BP(kStackTraceMax,
590 false, // FLAG_fast_unwind,
591 pc, bp);
592 stack.PrintStack();
593
594 CHECK(AddrIsInMem(addr));
595
596 DescribeAddress(addr, access_size);
597
598 uintptr_t shadow_addr = MemToShadow(addr);
599 Report("ABORTING\n");
600 __asan_print_accumulated_stats();
601 Printf("Shadow byte and word:\n");
602 Printf(" %p: %x\n", shadow_addr, *(unsigned char*)shadow_addr);
603 uintptr_t aligned_shadow = shadow_addr & ~(kWordSize - 1);
604 PrintBytes(" ", (uintptr_t*)(aligned_shadow));
605 Printf("More shadow bytes:\n");
606 PrintBytes(" ", (uintptr_t*)(aligned_shadow-4*kWordSize));
607 PrintBytes(" ", (uintptr_t*)(aligned_shadow-3*kWordSize));
608 PrintBytes(" ", (uintptr_t*)(aligned_shadow-2*kWordSize));
609 PrintBytes(" ", (uintptr_t*)(aligned_shadow-1*kWordSize));
610 PrintBytes("=>", (uintptr_t*)(aligned_shadow+0*kWordSize));
611 PrintBytes(" ", (uintptr_t*)(aligned_shadow+1*kWordSize));
612 PrintBytes(" ", (uintptr_t*)(aligned_shadow+2*kWordSize));
613 PrintBytes(" ", (uintptr_t*)(aligned_shadow+3*kWordSize));
614 PrintBytes(" ", (uintptr_t*)(aligned_shadow+4*kWordSize));
615 ASAN_DIE;
616}
617
618void __asan_init() {
619 if (asan_inited) return;
620 asan_init_is_running = true;
621
622 // Make sure we are not statically linked.
623 AsanDoesNotSupportStaticLinkage();
624
625 // flags
626 const char *options = getenv("ASAN_OPTIONS");
627 FLAG_malloc_context_size =
628 IntFlagValue(options, "malloc_context_size=", kMallocContextSize);
629 CHECK(FLAG_malloc_context_size <= kMallocContextSize);
630
631 FLAG_max_malloc_fill_size =
632 IntFlagValue(options, "max_malloc_fill_size=", 0);
633
634 FLAG_v = IntFlagValue(options, "verbosity=", 0);
635
636 FLAG_redzone = IntFlagValue(options, "redzone=", 128);
637 CHECK(FLAG_redzone >= 32);
638 CHECK((FLAG_redzone & (FLAG_redzone - 1)) == 0);
639
640 FLAG_atexit = IntFlagValue(options, "atexit=", 0);
641 FLAG_poison_shadow = IntFlagValue(options, "poison_shadow=", 1);
642 FLAG_report_globals = IntFlagValue(options, "report_globals=", 1);
643 FLAG_lazy_shadow = IntFlagValue(options, "lazy_shadow=", 0);
644 FLAG_handle_segv = IntFlagValue(options, "handle_segv=",
645 ASAN_NEEDS_SEGV);
646 FLAG_handle_sigill = IntFlagValue(options, "handle_sigill=", 0);
647 FLAG_stats = IntFlagValue(options, "stats=", 0);
648 FLAG_symbolize = IntFlagValue(options, "symbolize=", 1);
649 FLAG_demangle = IntFlagValue(options, "demangle=", 1);
650 FLAG_debug = IntFlagValue(options, "debug=", 0);
651 FLAG_replace_cfallocator = IntFlagValue(options, "replace_cfallocator=", 1);
652 FLAG_fast_unwind = IntFlagValue(options, "fast_unwind=", 1);
653 FLAG_mt = IntFlagValue(options, "mt=", 1);
654 FLAG_replace_str = IntFlagValue(options, "replace_str=", 1);
655 FLAG_replace_intrin = IntFlagValue(options, "replace_intrin=", 0);
656 FLAG_use_fake_stack = IntFlagValue(options, "use_fake_stack=", 1);
657 FLAG_exitcode = IntFlagValue(options, "exitcode=", EXIT_FAILURE);
658 FLAG_allow_user_poisoning = IntFlagValue(options,
659 "allow_user_poisoning=", 1);
660
661 if (FLAG_atexit) {
662 atexit(asan_atexit);
663 }
664
665 FLAG_quarantine_size =
666 IntFlagValue(options, "quarantine_size=", 1UL << 28);
667
668 // interceptors
669 InitializeAsanInterceptors();
670
671 ReplaceSystemMalloc();
672
673 INTERCEPT_FUNCTION(sigaction);
674 INTERCEPT_FUNCTION(signal);
675 INTERCEPT_FUNCTION(longjmp);
676 INTERCEPT_FUNCTION(_longjmp);
677 INTERCEPT_FUNCTION(__cxa_throw);
678 INTERCEPT_FUNCTION(pthread_create);
679#ifdef __APPLE__
680 INTERCEPT_FUNCTION(dispatch_async_f);
681 INTERCEPT_FUNCTION(dispatch_sync_f);
682 INTERCEPT_FUNCTION(dispatch_after_f);
683 INTERCEPT_FUNCTION(dispatch_barrier_async_f);
684 INTERCEPT_FUNCTION(dispatch_group_async_f);
685 // We don't need to intercept pthread_workqueue_additem_np() to support the
686 // libdispatch API, but it helps us to debug the unsupported functions. Let's
687 // intercept it only during verbose runs.
688 if (FLAG_v >= 2) {
689 INTERCEPT_FUNCTION(pthread_workqueue_additem_np);
690 }
691#else
692 // On Darwin siglongjmp tailcalls longjmp, so we don't want to intercept it
693 // there.
694 INTERCEPT_FUNCTION(siglongjmp);
695#endif
696
697 MaybeInstallSigaction(SIGSEGV, ASAN_OnSIGSEGV);
698 MaybeInstallSigaction(SIGBUS, ASAN_OnSIGSEGV);
699 MaybeInstallSigaction(SIGILL, ASAN_OnSIGILL);
700
701 if (FLAG_v) {
702 Printf("|| `[%p, %p]` || HighMem ||\n", kHighMemBeg, kHighMemEnd);
703 Printf("|| `[%p, %p]` || HighShadow ||\n",
704 kHighShadowBeg, kHighShadowEnd);
705 Printf("|| `[%p, %p]` || ShadowGap ||\n",
706 kShadowGapBeg, kShadowGapEnd);
707 Printf("|| `[%p, %p]` || LowShadow ||\n",
708 kLowShadowBeg, kLowShadowEnd);
709 Printf("|| `[%p, %p]` || LowMem ||\n", kLowMemBeg, kLowMemEnd);
710 Printf("MemToShadow(shadow): %p %p %p %p\n",
711 MEM_TO_SHADOW(kLowShadowBeg),
712 MEM_TO_SHADOW(kLowShadowEnd),
713 MEM_TO_SHADOW(kHighShadowBeg),
714 MEM_TO_SHADOW(kHighShadowEnd));
715 Printf("red_zone=%ld\n", FLAG_redzone);
716 Printf("malloc_context_size=%ld\n", (int)FLAG_malloc_context_size);
717 Printf("fast_unwind=%d\n", (int)FLAG_fast_unwind);
718
719 Printf("SHADOW_SCALE: %lx\n", SHADOW_SCALE);
720 Printf("SHADOW_GRANULARITY: %lx\n", SHADOW_GRANULARITY);
721 Printf("SHADOW_OFFSET: %lx\n", SHADOW_OFFSET);
722 CHECK(SHADOW_SCALE >= 3 && SHADOW_SCALE <= 7);
723 }
724
725 if (__WORDSIZE == 64) {
726 // Disable core dumper -- it makes little sense to dump 16T+ core.
727 struct rlimit nocore;
728 nocore.rlim_cur = 0;
729 nocore.rlim_max = 0;
730 setrlimit(RLIMIT_CORE, &nocore);
731 }
732
733 {
734 if (!FLAG_lazy_shadow) {
735 if (kLowShadowBeg != kLowShadowEnd) {
736 // mmap the low shadow plus one page.
737 mmap_range(kLowShadowBeg - kPageSize, kLowShadowEnd, "LowShadow");
738 }
739 // mmap the high shadow.
740 mmap_range(kHighShadowBeg, kHighShadowEnd, "HighShadow");
741 }
742 // protect the gap
743 protect_range(kShadowGapBeg, kShadowGapEnd);
744 }
745
746 // On Linux AsanThread::ThreadStart() calls malloc() that's why asan_inited
747 // should be set to 1 prior to initializing the threads.
748 asan_inited = 1;
749 asan_init_is_running = false;
750
751 asanThreadRegistry().Init();
752 asanThreadRegistry().GetMain()->ThreadStart();
753 __asan_force_interface_symbols(); // no-op.
754
755 if (FLAG_v) {
756 Report("AddressSanitizer r%s Init done ***\n", ASAN_REVISION);
757 }
758}