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