blob: efd044c502c3c2189da400f9868723b328037de3 [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"
Kostya Serebryany019b76f2011-11-30 01:07:0219#include "asan_mac.h"
Kostya Serebryany019b76f2011-11-30 01:07:0220#include "asan_mapping.h"
Kostya Serebryanycd271f52012-01-05 00:44:3321#include "asan_procmaps.h"
Kostya Serebryany019b76f2011-11-30 01:07:0222#include "asan_stack.h"
23#include "asan_stats.h"
24#include "asan_thread.h"
25#include "asan_thread_registry.h"
26
Kostya Serebryany2d27cdf2011-12-02 18:42:0427#include <new>
Kostya Serebryany019b76f2011-11-30 01:07:0228#include <dlfcn.h>
Kostya Serebryany019b76f2011-11-30 01:07:0229#include <fcntl.h>
30#include <pthread.h>
31#include <signal.h>
32#include <stdarg.h>
33#include <stdint.h>
34#include <stdio.h>
35#include <stdlib.h>
36#include <string.h>
Kostya Serebryany019b76f2011-11-30 01:07:0237#include <sys/stat.h>
38#include <sys/types.h>
Kostya Serebryany2b87e402011-12-28 20:22:2139#ifndef ANDROID
Kostya Serebryany019b76f2011-11-30 01:07:0240#include <sys/ucontext.h>
Kostya Serebryany2b87e402011-12-28 20:22:2141#endif
Kostya Serebryany019b76f2011-11-30 01:07:0242// must not include <setjmp.h> on Linux
43
Kostya Serebryany019b76f2011-11-30 01:07:0244namespace __asan {
45
46// -------------------------- Flags ------------------------- {{{1
47static const size_t kMallocContextSize = 30;
48static int FLAG_atexit;
49bool FLAG_fast_unwind = true;
50
51size_t FLAG_redzone; // power of two, >= 32
Kostya Serebryany019b76f2011-11-30 01:07:0252size_t FLAG_quarantine_size;
53int FLAG_demangle;
54bool FLAG_symbolize;
55int FLAG_v;
56int FLAG_debug;
57bool FLAG_poison_shadow;
58int FLAG_report_globals;
59size_t FLAG_malloc_context_size = kMallocContextSize;
60uintptr_t FLAG_large_malloc;
61bool FLAG_lazy_shadow;
62bool FLAG_handle_segv;
63bool FLAG_handle_sigill;
64bool FLAG_replace_str;
65bool FLAG_replace_intrin;
66bool FLAG_replace_cfallocator; // Used on Mac only.
Kostya Serebryany019b76f2011-11-30 01:07:0267size_t FLAG_max_malloc_fill_size = 0;
68bool FLAG_use_fake_stack;
69int FLAG_exitcode = EXIT_FAILURE;
70bool FLAG_allow_user_poisoning;
71
72// -------------------------- Globals --------------------- {{{1
73int asan_inited;
74bool asan_init_is_running;
75
76// -------------------------- Interceptors ---------------- {{{1
77typedef int (*sigaction_f)(int signum, const struct sigaction *act,
78 struct sigaction *oldact);
79typedef sig_t (*signal_f)(int signum, sig_t handler);
80typedef void (*longjmp_f)(void *env, int val);
81typedef longjmp_f _longjmp_f;
82typedef longjmp_f siglongjmp_f;
83typedef void (*__cxa_throw_f)(void *, void *, void *);
84typedef int (*pthread_create_f)(pthread_t *thread, const pthread_attr_t *attr,
85 void *(*start_routine) (void *), void *arg);
86#ifdef __APPLE__
87dispatch_async_f_f real_dispatch_async_f;
88dispatch_sync_f_f real_dispatch_sync_f;
89dispatch_after_f_f real_dispatch_after_f;
90dispatch_barrier_async_f_f real_dispatch_barrier_async_f;
91dispatch_group_async_f_f real_dispatch_group_async_f;
92pthread_workqueue_additem_np_f real_pthread_workqueue_additem_np;
93#endif
94
95sigaction_f real_sigaction;
96signal_f real_signal;
97longjmp_f real_longjmp;
98_longjmp_f real__longjmp;
99siglongjmp_f real_siglongjmp;
100__cxa_throw_f real___cxa_throw;
101pthread_create_f real_pthread_create;
102
103// -------------------------- Misc ---------------- {{{1
104void ShowStatsAndAbort() {
105 __asan_print_accumulated_stats();
106 ASAN_DIE;
107}
108
109static void PrintBytes(const char *before, uintptr_t *a) {
110 uint8_t *bytes = (uint8_t*)a;
111 size_t byte_num = (__WORDSIZE) / 8;
112 Printf("%s%p:", before, (uintptr_t)a);
113 for (size_t i = 0; i < byte_num; i++) {
114 Printf(" %lx%lx", bytes[i] >> 4, bytes[i] & 15);
115 }
116 Printf("\n");
117}
118
Kostya Serebryanycd271f52012-01-05 00:44:33119ssize_t ReadFileToBuffer(const char *file_name, char **buff,
120 size_t *buff_size, size_t max_len) {
Kostya Serebryany6c4bd802011-12-28 22:58:01121 const size_t kMinFileLen = kPageSize;
122 ssize_t read_len = -1;
123 *buff = 0;
Kostya Serebryanycd271f52012-01-05 00:44:33124 *buff_size = 0;
Kostya Serebryany6c4bd802011-12-28 22:58:01125 // The files we usually open are not seekable, so try different buffer sizes.
126 for (size_t size = kMinFileLen; size <= max_len; size *= 2) {
127 int fd = AsanOpenReadonly(file_name);
128 if (fd < 0) return -1;
Kostya Serebryanycd271f52012-01-05 00:44:33129 AsanUnmapOrDie(*buff, *buff_size);
Kostya Serebryany6c4bd802011-12-28 22:58:01130 *buff = (char*)AsanMmapSomewhereOrDie(size, __FUNCTION__);
Kostya Serebryanycd271f52012-01-05 00:44:33131 *buff_size = size;
Kostya Serebryany6c4bd802011-12-28 22:58:01132 read_len = AsanRead(fd, *buff, size);
133 AsanClose(fd);
134 if (read_len < size) // We've read the whole file.
135 break;
136 }
137 return read_len;
138}
139
140// Like getenv, but reads env directly from /proc and does not use libc.
141// This function should be called first inside __asan_init.
142static const char* GetEnvFromProcSelfEnviron(const char* name) {
143 static char *environ;
144 static ssize_t len;
145 static bool inited;
146 if (!inited) {
147 inited = true;
Kostya Serebryanycd271f52012-01-05 00:44:33148 size_t environ_size;
149 len = ReadFileToBuffer("/proc/self/environ",
150 &environ, &environ_size, 1 << 20);
Kostya Serebryany6c4bd802011-12-28 22:58:01151 }
152 if (!environ || len <= 0) return NULL;
153 size_t namelen = internal_strlen(name);
154 const char *p = environ;
155 while (*p != '\0') { // will happen at the \0\0 that terminates the buffer
156 // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
157 const char* endp =
158 (char*)internal_memchr(p, '\0', len - (p - environ));
159 if (endp == NULL) // this entry isn't NUL terminated
160 return NULL;
161 else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=') // Match.
162 return p + namelen + 1; // point after =
163 p = endp + 1;
164 }
165 return NULL; // Not found.
166}
167
Kostya Serebryany019b76f2011-11-30 01:07:02168// ---------------------- Thread ------------------------- {{{1
169static void *asan_thread_start(void *arg) {
170 AsanThread *t= (AsanThread*)arg;
171 asanThreadRegistry().SetCurrent(t);
172 return t->ThreadStart();
173}
174
175// ---------------------- mmap -------------------- {{{1
Kostya Serebryany6c4bd802011-12-28 22:58:01176void OutOfMemoryMessageAndDie(const char *mem_type, size_t size) {
Kostya Serebryany019b76f2011-11-30 01:07:02177 Report("ERROR: AddressSanitizer failed to allocate "
178 "0x%lx (%ld) bytes of %s\n",
179 size, size, mem_type);
Kostya Serebryany6c4bd802011-12-28 22:58:01180 PRINT_CURRENT_STACK();
181 ShowStatsAndAbort();
Kostya Serebryany019b76f2011-11-30 01:07:02182}
183
Kostya Serebryanya7720962011-12-28 23:28:54184// Reserve memory range [beg, end].
185static void ReserveShadowMemoryRange(uintptr_t beg, uintptr_t end) {
Kostya Serebryany019b76f2011-11-30 01:07:02186 CHECK((beg % kPageSize) == 0);
187 CHECK(((end + 1) % kPageSize) == 0);
Kostya Serebryanya7720962011-12-28 23:28:54188 size_t size = end - beg + 1;
189 void *res = AsanMmapFixedNoReserve(beg, size);
190 CHECK(res == (void*)beg && "ReserveShadowMemoryRange failed");
Kostya Serebryany019b76f2011-11-30 01:07:02191}
192
Kostya Serebryanye4bada22011-12-02 21:02:20193// ---------------------- LowLevelAllocator ------------- {{{1
194void *LowLevelAllocator::Allocate(size_t size) {
195 CHECK((size & (size - 1)) == 0 && "size must be a power of two");
196 if (allocated_end_ - allocated_current_ < size) {
197 size_t size_to_allocate = Max(size, kPageSize);
Kostya Serebryany6c4bd802011-12-28 22:58:01198 allocated_current_ =
199 (char*)AsanMmapSomewhereOrDie(size_to_allocate, __FUNCTION__);
Kostya Serebryanye4bada22011-12-02 21:02:20200 allocated_end_ = allocated_current_ + size_to_allocate;
Kostya Serebryany7fb33a32011-12-15 17:41:30201 PoisonShadow((uintptr_t)allocated_current_, size_to_allocate,
202 kAsanInternalHeapMagic);
Kostya Serebryanye4bada22011-12-02 21:02:20203 }
204 CHECK(allocated_end_ - allocated_current_ >= size);
205 void *res = allocated_current_;
206 allocated_current_ += size;
207 return res;
208}
209
Kostya Serebryany019b76f2011-11-30 01:07:02210// ---------------------- DescribeAddress -------------------- {{{1
211static bool DescribeStackAddress(uintptr_t addr, uintptr_t access_size) {
212 AsanThread *t = asanThreadRegistry().FindThreadByStackAddress(addr);
213 if (!t) return false;
214 const intptr_t kBufSize = 4095;
215 char buf[kBufSize];
216 uintptr_t offset = 0;
217 const char *frame_descr = t->GetFrameNameByAddr(addr, &offset);
218 // This string is created by the compiler and has the following form:
219 // "FunctioName n alloc_1 alloc_2 ... alloc_n"
220 // where alloc_i looks like "offset size len ObjectName ".
221 CHECK(frame_descr);
222 // Report the function name and the offset.
223 const char *name_end = real_strchr(frame_descr, ' ');
224 CHECK(name_end);
225 buf[0] = 0;
226 strncat(buf, frame_descr,
Kostya Serebryany2d27cdf2011-12-02 18:42:04227 Min(kBufSize, static_cast<intptr_t>(name_end - frame_descr)));
Kostya Serebryany019b76f2011-11-30 01:07:02228 Printf("Address %p is located at offset %ld "
229 "in frame <%s> of T%d's stack:\n",
230 addr, offset, buf, t->tid());
231 // Report the number of stack objects.
232 char *p;
233 size_t n_objects = strtol(name_end, &p, 10);
234 CHECK(n_objects > 0);
235 Printf(" This frame has %ld object(s):\n", n_objects);
236 // Report all objects in this frame.
237 for (size_t i = 0; i < n_objects; i++) {
238 size_t beg, size;
239 intptr_t len;
240 beg = strtol(p, &p, 10);
241 size = strtol(p, &p, 10);
242 len = strtol(p, &p, 10);
243 if (beg <= 0 || size <= 0 || len < 0 || *p != ' ') {
244 Printf("AddressSanitizer can't parse the stack frame descriptor: |%s|\n",
245 frame_descr);
246 break;
247 }
248 p++;
249 buf[0] = 0;
Kostya Serebryany2d27cdf2011-12-02 18:42:04250 strncat(buf, p, Min(kBufSize, len));
Kostya Serebryany019b76f2011-11-30 01:07:02251 p += len;
252 Printf(" [%ld, %ld) '%s'\n", beg, beg + size, buf);
253 }
254 Printf("HINT: this may be a false positive if your program uses "
255 "some custom stack unwind mechanism\n"
256 " (longjmp and C++ exceptions *are* supported)\n");
257 t->summary()->Announce();
258 return true;
259}
260
261__attribute__((noinline))
262static void DescribeAddress(uintptr_t addr, uintptr_t access_size) {
263 // Check if this is a global.
264 if (DescribeAddrIfGlobal(addr))
265 return;
266
267 if (DescribeStackAddress(addr, access_size))
268 return;
269
270 // finally, check if this is a heap.
271 DescribeHeapAddress(addr, access_size);
272}
273
274// -------------------------- Run-time entry ------------------- {{{1
275void GetPcSpBpAx(void *context,
276 uintptr_t *pc, uintptr_t *sp, uintptr_t *bp, uintptr_t *ax) {
Kostya Serebryany2b87e402011-12-28 20:22:21277#ifndef ANDROID
Kostya Serebryany019b76f2011-11-30 01:07:02278 ucontext_t *ucontext = (ucontext_t*)context;
Kostya Serebryany2b87e402011-12-28 20:22:21279#endif
Kostya Serebryany019b76f2011-11-30 01:07:02280#ifdef __APPLE__
281# if __WORDSIZE == 64
282 *pc = ucontext->uc_mcontext->__ss.__rip;
283 *bp = ucontext->uc_mcontext->__ss.__rbp;
284 *sp = ucontext->uc_mcontext->__ss.__rsp;
285 *ax = ucontext->uc_mcontext->__ss.__rax;
286# else
Daniel Dunbarcf7fb022011-12-02 00:52:55287 *pc = ucontext->uc_mcontext->__ss.__eip;
288 *bp = ucontext->uc_mcontext->__ss.__ebp;
289 *sp = ucontext->uc_mcontext->__ss.__esp;
290 *ax = ucontext->uc_mcontext->__ss.__eax;
Kostya Serebryany019b76f2011-11-30 01:07:02291# endif // __WORDSIZE
292#else // assume linux
Kostya Serebryany2b87e402011-12-28 20:22:21293# if defined (ANDROID)
294 *pc = *sp = *bp = *ax = 0;
295# elif defined(__arm__)
Kostya Serebryany019b76f2011-11-30 01:07:02296 *pc = ucontext->uc_mcontext.arm_pc;
297 *bp = ucontext->uc_mcontext.arm_fp;
298 *sp = ucontext->uc_mcontext.arm_sp;
299 *ax = ucontext->uc_mcontext.arm_r0;
300# elif __WORDSIZE == 64
301 *pc = ucontext->uc_mcontext.gregs[REG_RIP];
302 *bp = ucontext->uc_mcontext.gregs[REG_RBP];
303 *sp = ucontext->uc_mcontext.gregs[REG_RSP];
304 *ax = ucontext->uc_mcontext.gregs[REG_RAX];
305# else
306 *pc = ucontext->uc_mcontext.gregs[REG_EIP];
307 *bp = ucontext->uc_mcontext.gregs[REG_EBP];
308 *sp = ucontext->uc_mcontext.gregs[REG_ESP];
309 *ax = ucontext->uc_mcontext.gregs[REG_EAX];
310# endif // __WORDSIZE
311#endif
312}
313
314static void ASAN_OnSIGSEGV(int, siginfo_t *siginfo, void *context) {
315 uintptr_t addr = (uintptr_t)siginfo->si_addr;
316 if (AddrIsInShadow(addr) && FLAG_lazy_shadow) {
317 // We traped on access to a shadow address. Just map a large chunk around
318 // this address.
319 const uintptr_t chunk_size = kPageSize << 10; // 4M
320 uintptr_t chunk = addr & ~(chunk_size - 1);
Kostya Serebryanya7720962011-12-28 23:28:54321 AsanMmapFixedReserve(chunk, chunk_size);
Kostya Serebryany019b76f2011-11-30 01:07:02322 return;
323 }
324 // Write the first message using the bullet-proof write.
Kostya Serebryany6c4bd802011-12-28 22:58:01325 if (13 != AsanWrite(2, "ASAN:SIGSEGV\n", 13)) ASAN_DIE;
Kostya Serebryany019b76f2011-11-30 01:07:02326 uintptr_t pc, sp, bp, ax;
327 GetPcSpBpAx(context, &pc, &sp, &bp, &ax);
328 Report("ERROR: AddressSanitizer crashed on unknown address %p"
329 " (pc %p sp %p bp %p ax %p T%d)\n",
330 addr, pc, sp, bp, ax,
331 asanThreadRegistry().GetCurrentTidOrMinusOne());
332 Printf("AddressSanitizer can not provide additional info. ABORTING\n");
333 GET_STACK_TRACE_WITH_PC_AND_BP(kStackTraceMax, false, pc, bp);
334 stack.PrintStack();
335 ShowStatsAndAbort();
336}
337
338static void ASAN_OnSIGILL(int, siginfo_t *siginfo, void *context) {
339 // Write the first message using the bullet-proof write.
Kostya Serebryany6c4bd802011-12-28 22:58:01340 if (12 != AsanWrite(2, "ASAN:SIGILL\n", 12)) ASAN_DIE;
Kostya Serebryany019b76f2011-11-30 01:07:02341 uintptr_t pc, sp, bp, ax;
342 GetPcSpBpAx(context, &pc, &sp, &bp, &ax);
343
344 uintptr_t addr = ax;
345
346 uint8_t *insn = (uint8_t*)pc;
347 CHECK(insn[0] == 0x0f && insn[1] == 0x0b); // ud2
348 unsigned access_size_and_type = insn[2] - 0x50;
349 CHECK(access_size_and_type < 16);
350 bool is_write = access_size_and_type & 8;
351 int access_size = 1 << (access_size_and_type & 7);
352 __asan_report_error(pc, bp, sp, addr, is_write, access_size);
353}
354
355// exported functions
Kostya Serebryany46c70d32011-12-28 00:59:39356#define ASAN_REPORT_ERROR(type, is_write, size) \
357extern "C" void __asan_report_ ## type ## size(uintptr_t addr) \
358 __attribute__((visibility("default"))) __attribute__((noinline)); \
359extern "C" void __asan_report_ ## type ## size(uintptr_t addr) { \
360 GET_BP_PC_SP; \
361 __asan_report_error(pc, bp, sp, addr, is_write, size); \
Kostya Serebryany019b76f2011-11-30 01:07:02362}
363
364ASAN_REPORT_ERROR(load, false, 1)
365ASAN_REPORT_ERROR(load, false, 2)
366ASAN_REPORT_ERROR(load, false, 4)
367ASAN_REPORT_ERROR(load, false, 8)
368ASAN_REPORT_ERROR(load, false, 16)
369ASAN_REPORT_ERROR(store, true, 1)
370ASAN_REPORT_ERROR(store, true, 2)
371ASAN_REPORT_ERROR(store, true, 4)
372ASAN_REPORT_ERROR(store, true, 8)
373ASAN_REPORT_ERROR(store, true, 16)
374
375// Force the linker to keep the symbols for various ASan interface functions.
376// We want to keep those in the executable in order to let the instrumented
377// dynamic libraries access the symbol even if it is not used by the executable
378// itself. This should help if the build system is removing dead code at link
379// time.
Kostya Serebryany46c70d32011-12-28 00:59:39380static void force_interface_symbols() {
Kostya Serebryany019b76f2011-11-30 01:07:02381 volatile int fake_condition = 0; // prevent dead condition elimination.
382 if (fake_condition) {
383 __asan_report_load1(NULL);
384 __asan_report_load2(NULL);
385 __asan_report_load4(NULL);
386 __asan_report_load8(NULL);
387 __asan_report_load16(NULL);
388 __asan_report_store1(NULL);
389 __asan_report_store2(NULL);
390 __asan_report_store4(NULL);
391 __asan_report_store8(NULL);
392 __asan_report_store16(NULL);
393 __asan_register_global(0, 0, NULL);
394 __asan_register_globals(NULL, 0);
Kostya Serebryanyd2d043b2011-12-28 23:35:46395 __asan_unregister_globals(NULL, 0);
Kostya Serebryany019b76f2011-11-30 01:07:02396 }
397}
398
399// -------------------------- Init ------------------- {{{1
400static int64_t IntFlagValue(const char *flags, const char *flag,
401 int64_t default_val) {
402 if (!flags) return default_val;
403 const char *str = strstr(flags, flag);
404 if (!str) return default_val;
405 return atoll(str + internal_strlen(flag));
406}
407
408static void asan_atexit() {
409 Printf("AddressSanitizer exit stats:\n");
410 __asan_print_accumulated_stats();
411}
412
413void CheckFailed(const char *cond, const char *file, int line) {
414 Report("CHECK failed: %s at %s:%d, pthread_self=%p\n",
415 cond, file, line, pthread_self());
416 PRINT_CURRENT_STACK();
417 ShowStatsAndAbort();
418}
419
420} // namespace __asan
421
422// -------------------------- Interceptors ------------------- {{{1
423using namespace __asan; // NOLINT
424
425#define OPERATOR_NEW_BODY \
426 GET_STACK_TRACE_HERE_FOR_MALLOC;\
427 return asan_memalign(0, size, &stack);
428
Kostya Serebryanydd1386f2011-12-27 23:11:09429#ifdef ANDROID
430void *operator new(size_t size) { OPERATOR_NEW_BODY; }
431void *operator new[](size_t size) { OPERATOR_NEW_BODY; }
432#else
Kostya Serebryany019b76f2011-11-30 01:07:02433void *operator new(size_t size) throw(std::bad_alloc) { OPERATOR_NEW_BODY; }
434void *operator new[](size_t size) throw(std::bad_alloc) { OPERATOR_NEW_BODY; }
435void *operator new(size_t size, std::nothrow_t const&) throw()
436{ OPERATOR_NEW_BODY; }
437void *operator new[](size_t size, std::nothrow_t const&) throw()
438{ OPERATOR_NEW_BODY; }
Kostya Serebryanydd1386f2011-12-27 23:11:09439#endif
Kostya Serebryany019b76f2011-11-30 01:07:02440
441#define OPERATOR_DELETE_BODY \
442 GET_STACK_TRACE_HERE_FOR_FREE(ptr);\
443 asan_free(ptr, &stack);
444
445void operator delete(void *ptr) throw() { OPERATOR_DELETE_BODY; }
446void operator delete[](void *ptr) throw() { OPERATOR_DELETE_BODY; }
447void operator delete(void *ptr, std::nothrow_t const&) throw()
448{ OPERATOR_DELETE_BODY; }
449void operator delete[](void *ptr, std::nothrow_t const&) throw()
450{ OPERATOR_DELETE_BODY;}
451
452extern "C"
453#ifndef __APPLE__
454__attribute__((visibility("default")))
455#endif
456int WRAP(pthread_create)(pthread_t *thread, const pthread_attr_t *attr,
457 void *(*start_routine) (void *), void *arg) {
458 GET_STACK_TRACE_HERE(kStackTraceMax, /*fast_unwind*/false);
459 AsanThread *t = (AsanThread*)asan_malloc(sizeof(AsanThread), &stack);
460 AsanThread *curr_thread = asanThreadRegistry().GetCurrent();
461 CHECK(curr_thread || asanThreadRegistry().IsCurrentThreadDying());
462 new(t) AsanThread(asanThreadRegistry().GetCurrentTidOrMinusOne(),
463 start_routine, arg, &stack);
464 return real_pthread_create(thread, attr, asan_thread_start, t);
465}
466
467static bool MySignal(int signum) {
468 if (FLAG_handle_sigill && signum == SIGILL) return true;
469 if (FLAG_handle_segv && signum == SIGSEGV) return true;
470#ifdef __APPLE__
471 if (FLAG_handle_segv && signum == SIGBUS) return true;
472#endif
473 return false;
474}
475
476static void MaybeInstallSigaction(int signum,
477 void (*handler)(int, siginfo_t *, void *)) {
478 if (!MySignal(signum))
479 return;
480 struct sigaction sigact;
481 real_memset(&sigact, 0, sizeof(sigact));
482 sigact.sa_sigaction = handler;
483 sigact.sa_flags = SA_SIGINFO;
484 CHECK(0 == real_sigaction(signum, &sigact, 0));
485}
486
487extern "C"
488sig_t WRAP(signal)(int signum, sig_t handler) {
489 if (!MySignal(signum)) {
490 return real_signal(signum, handler);
491 }
492 return NULL;
493}
494
495extern "C"
496int WRAP(sigaction)(int signum, const struct sigaction *act,
497 struct sigaction *oldact) {
498 if (!MySignal(signum)) {
499 return real_sigaction(signum, act, oldact);
500 }
501 return 0;
502}
503
504
505static void UnpoisonStackFromHereToTop() {
506 int local_stack;
507 AsanThread *curr_thread = asanThreadRegistry().GetCurrent();
508 CHECK(curr_thread);
509 uintptr_t top = curr_thread->stack_top();
510 uintptr_t bottom = ((uintptr_t)&local_stack - kPageSize) & ~(kPageSize-1);
Kostya Serebryany15dd3f22011-11-30 18:50:23511 PoisonShadow(bottom, top - bottom, 0);
Kostya Serebryany019b76f2011-11-30 01:07:02512}
513
514extern "C" void WRAP(longjmp)(void *env, int val) {
515 UnpoisonStackFromHereToTop();
516 real_longjmp(env, val);
517}
518
519extern "C" void WRAP(_longjmp)(void *env, int val) {
520 UnpoisonStackFromHereToTop();
521 real__longjmp(env, val);
522}
523
524extern "C" void WRAP(siglongjmp)(void *env, int val) {
525 UnpoisonStackFromHereToTop();
526 real_siglongjmp(env, val);
527}
528
529extern "C" void __cxa_throw(void *a, void *b, void *c);
530
Kostya Serebryanyb50a5392011-12-08 18:30:42531#if ASAN_HAS_EXCEPTIONS == 1
Kostya Serebryany019b76f2011-11-30 01:07:02532extern "C" void WRAP(__cxa_throw)(void *a, void *b, void *c) {
Kostya Serebryany93927f92011-12-05 17:56:32533 CHECK(&real___cxa_throw);
Kostya Serebryany019b76f2011-11-30 01:07:02534 UnpoisonStackFromHereToTop();
535 real___cxa_throw(a, b, c);
536}
537#endif
538
539extern "C" {
540// intercept mlock and friends.
541// Since asan maps 16T of RAM, mlock is completely unfriendly to asan.
542// All functions return 0 (success).
543static void MlockIsUnsupported() {
544 static bool printed = 0;
545 if (printed) return;
546 printed = true;
547 Printf("INFO: AddressSanitizer ignores mlock/mlockall/munlock/munlockall\n");
548}
549int mlock(const void *addr, size_t len) {
550 MlockIsUnsupported();
551 return 0;
552}
553int munlock(const void *addr, size_t len) {
554 MlockIsUnsupported();
555 return 0;
556}
557int mlockall(int flags) {
558 MlockIsUnsupported();
559 return 0;
560}
561int munlockall(void) {
562 MlockIsUnsupported();
563 return 0;
564}
565} // extern "C"
566
567// ---------------------- Interface ---------------- {{{1
568int __asan_set_error_exit_code(int exit_code) {
569 int old = FLAG_exitcode;
570 FLAG_exitcode = exit_code;
571 return old;
572}
573
574void __asan_report_error(uintptr_t pc, uintptr_t bp, uintptr_t sp,
575 uintptr_t addr, bool is_write, size_t access_size) {
576 // Do not print more than one report, otherwise they will mix up.
577 static int num_calls = 0;
578 if (AtomicInc(&num_calls) > 1) return;
579
580 Printf("=================================================================\n");
581 const char *bug_descr = "unknown-crash";
582 if (AddrIsInMem(addr)) {
583 uint8_t *shadow_addr = (uint8_t*)MemToShadow(addr);
Kostya Serebryanyf0d799a2011-12-07 21:30:20584 // If we are accessing 16 bytes, look at the second shadow byte.
585 if (*shadow_addr == 0 && access_size > SHADOW_GRANULARITY)
586 shadow_addr++;
587 // If we are in the partial right redzone, look at the next shadow byte.
588 if (*shadow_addr > 0 && *shadow_addr < 128)
589 shadow_addr++;
590 switch (*shadow_addr) {
Kostya Serebryany019b76f2011-11-30 01:07:02591 case kAsanHeapLeftRedzoneMagic:
592 case kAsanHeapRightRedzoneMagic:
593 bug_descr = "heap-buffer-overflow";
594 break;
595 case kAsanHeapFreeMagic:
596 bug_descr = "heap-use-after-free";
597 break;
598 case kAsanStackLeftRedzoneMagic:
599 bug_descr = "stack-buffer-underflow";
600 break;
601 case kAsanStackMidRedzoneMagic:
602 case kAsanStackRightRedzoneMagic:
603 case kAsanStackPartialRedzoneMagic:
604 bug_descr = "stack-buffer-overflow";
605 break;
606 case kAsanStackAfterReturnMagic:
607 bug_descr = "stack-use-after-return";
608 break;
609 case kAsanUserPoisonedMemoryMagic:
610 bug_descr = "use-after-poison";
611 break;
612 case kAsanGlobalRedzoneMagic:
613 bug_descr = "global-buffer-overflow";
614 break;
615 }
616 }
617
Kostya Serebryany72fde372011-12-09 01:49:31618 AsanThread *curr_thread = asanThreadRegistry().GetCurrent();
619 int curr_tid = asanThreadRegistry().GetCurrentTidOrMinusOne();
620
621 if (curr_thread) {
622 // We started reporting an error message. Stop using the fake stack
623 // in case we will call an instrumented function from a symbolizer.
624 curr_thread->fake_stack().StopUsingFakeStack();
625 }
626
Kostya Serebryany019b76f2011-11-30 01:07:02627 Report("ERROR: AddressSanitizer %s on address "
628 "%p at pc 0x%lx bp 0x%lx sp 0x%lx\n",
629 bug_descr, addr, pc, bp, sp);
630
631 Printf("%s of size %d at %p thread T%d\n",
632 access_size ? (is_write ? "WRITE" : "READ") : "ACCESS",
Kostya Serebryany72fde372011-12-09 01:49:31633 access_size, addr, curr_tid);
Kostya Serebryany019b76f2011-11-30 01:07:02634
635 if (FLAG_debug) {
636 PrintBytes("PC: ", (uintptr_t*)pc);
637 }
638
639 GET_STACK_TRACE_WITH_PC_AND_BP(kStackTraceMax,
640 false, // FLAG_fast_unwind,
641 pc, bp);
642 stack.PrintStack();
643
644 CHECK(AddrIsInMem(addr));
645
646 DescribeAddress(addr, access_size);
647
648 uintptr_t shadow_addr = MemToShadow(addr);
649 Report("ABORTING\n");
650 __asan_print_accumulated_stats();
651 Printf("Shadow byte and word:\n");
652 Printf(" %p: %x\n", shadow_addr, *(unsigned char*)shadow_addr);
653 uintptr_t aligned_shadow = shadow_addr & ~(kWordSize - 1);
654 PrintBytes(" ", (uintptr_t*)(aligned_shadow));
655 Printf("More shadow bytes:\n");
656 PrintBytes(" ", (uintptr_t*)(aligned_shadow-4*kWordSize));
657 PrintBytes(" ", (uintptr_t*)(aligned_shadow-3*kWordSize));
658 PrintBytes(" ", (uintptr_t*)(aligned_shadow-2*kWordSize));
659 PrintBytes(" ", (uintptr_t*)(aligned_shadow-1*kWordSize));
660 PrintBytes("=>", (uintptr_t*)(aligned_shadow+0*kWordSize));
661 PrintBytes(" ", (uintptr_t*)(aligned_shadow+1*kWordSize));
662 PrintBytes(" ", (uintptr_t*)(aligned_shadow+2*kWordSize));
663 PrintBytes(" ", (uintptr_t*)(aligned_shadow+3*kWordSize));
664 PrintBytes(" ", (uintptr_t*)(aligned_shadow+4*kWordSize));
665 ASAN_DIE;
666}
667
668void __asan_init() {
669 if (asan_inited) return;
670 asan_init_is_running = true;
671
672 // Make sure we are not statically linked.
673 AsanDoesNotSupportStaticLinkage();
674
675 // flags
Kostya Serebryany6c4bd802011-12-28 22:58:01676 const char *options = GetEnvFromProcSelfEnviron("ASAN_OPTIONS");
Kostya Serebryany019b76f2011-11-30 01:07:02677 FLAG_malloc_context_size =
678 IntFlagValue(options, "malloc_context_size=", kMallocContextSize);
679 CHECK(FLAG_malloc_context_size <= kMallocContextSize);
680
681 FLAG_max_malloc_fill_size =
682 IntFlagValue(options, "max_malloc_fill_size=", 0);
683
684 FLAG_v = IntFlagValue(options, "verbosity=", 0);
685
686 FLAG_redzone = IntFlagValue(options, "redzone=", 128);
687 CHECK(FLAG_redzone >= 32);
688 CHECK((FLAG_redzone & (FLAG_redzone - 1)) == 0);
689
690 FLAG_atexit = IntFlagValue(options, "atexit=", 0);
691 FLAG_poison_shadow = IntFlagValue(options, "poison_shadow=", 1);
692 FLAG_report_globals = IntFlagValue(options, "report_globals=", 1);
693 FLAG_lazy_shadow = IntFlagValue(options, "lazy_shadow=", 0);
Kostya Serebryanyb50a5392011-12-08 18:30:42694 FLAG_handle_segv = IntFlagValue(options, "handle_segv=", ASAN_NEEDS_SEGV);
Kostya Serebryany019b76f2011-11-30 01:07:02695 FLAG_handle_sigill = IntFlagValue(options, "handle_sigill=", 0);
Kostya Serebryany019b76f2011-11-30 01:07:02696 FLAG_symbolize = IntFlagValue(options, "symbolize=", 1);
697 FLAG_demangle = IntFlagValue(options, "demangle=", 1);
698 FLAG_debug = IntFlagValue(options, "debug=", 0);
699 FLAG_replace_cfallocator = IntFlagValue(options, "replace_cfallocator=", 1);
700 FLAG_fast_unwind = IntFlagValue(options, "fast_unwind=", 1);
Kostya Serebryany019b76f2011-11-30 01:07:02701 FLAG_replace_str = IntFlagValue(options, "replace_str=", 1);
Kostya Serebryany76eca5e2011-12-28 19:55:30702 FLAG_replace_intrin = IntFlagValue(options, "replace_intrin=", 1);
Kostya Serebryany019b76f2011-11-30 01:07:02703 FLAG_use_fake_stack = IntFlagValue(options, "use_fake_stack=", 1);
704 FLAG_exitcode = IntFlagValue(options, "exitcode=", EXIT_FAILURE);
705 FLAG_allow_user_poisoning = IntFlagValue(options,
706 "allow_user_poisoning=", 1);
707
708 if (FLAG_atexit) {
709 atexit(asan_atexit);
710 }
711
712 FLAG_quarantine_size =
713 IntFlagValue(options, "quarantine_size=", 1UL << 28);
714
715 // interceptors
716 InitializeAsanInterceptors();
717
718 ReplaceSystemMalloc();
719
720 INTERCEPT_FUNCTION(sigaction);
721 INTERCEPT_FUNCTION(signal);
722 INTERCEPT_FUNCTION(longjmp);
723 INTERCEPT_FUNCTION(_longjmp);
Kostya Serebryany93927f92011-12-05 17:56:32724 INTERCEPT_FUNCTION_IF_EXISTS(__cxa_throw);
Kostya Serebryany019b76f2011-11-30 01:07:02725 INTERCEPT_FUNCTION(pthread_create);
726#ifdef __APPLE__
727 INTERCEPT_FUNCTION(dispatch_async_f);
728 INTERCEPT_FUNCTION(dispatch_sync_f);
729 INTERCEPT_FUNCTION(dispatch_after_f);
730 INTERCEPT_FUNCTION(dispatch_barrier_async_f);
731 INTERCEPT_FUNCTION(dispatch_group_async_f);
732 // We don't need to intercept pthread_workqueue_additem_np() to support the
733 // libdispatch API, but it helps us to debug the unsupported functions. Let's
734 // intercept it only during verbose runs.
735 if (FLAG_v >= 2) {
736 INTERCEPT_FUNCTION(pthread_workqueue_additem_np);
737 }
738#else
739 // On Darwin siglongjmp tailcalls longjmp, so we don't want to intercept it
740 // there.
741 INTERCEPT_FUNCTION(siglongjmp);
742#endif
743
744 MaybeInstallSigaction(SIGSEGV, ASAN_OnSIGSEGV);
745 MaybeInstallSigaction(SIGBUS, ASAN_OnSIGSEGV);
746 MaybeInstallSigaction(SIGILL, ASAN_OnSIGILL);
747
748 if (FLAG_v) {
749 Printf("|| `[%p, %p]` || HighMem ||\n", kHighMemBeg, kHighMemEnd);
750 Printf("|| `[%p, %p]` || HighShadow ||\n",
751 kHighShadowBeg, kHighShadowEnd);
752 Printf("|| `[%p, %p]` || ShadowGap ||\n",
753 kShadowGapBeg, kShadowGapEnd);
754 Printf("|| `[%p, %p]` || LowShadow ||\n",
755 kLowShadowBeg, kLowShadowEnd);
756 Printf("|| `[%p, %p]` || LowMem ||\n", kLowMemBeg, kLowMemEnd);
757 Printf("MemToShadow(shadow): %p %p %p %p\n",
758 MEM_TO_SHADOW(kLowShadowBeg),
759 MEM_TO_SHADOW(kLowShadowEnd),
760 MEM_TO_SHADOW(kHighShadowBeg),
761 MEM_TO_SHADOW(kHighShadowEnd));
762 Printf("red_zone=%ld\n", FLAG_redzone);
763 Printf("malloc_context_size=%ld\n", (int)FLAG_malloc_context_size);
764 Printf("fast_unwind=%d\n", (int)FLAG_fast_unwind);
765
766 Printf("SHADOW_SCALE: %lx\n", SHADOW_SCALE);
767 Printf("SHADOW_GRANULARITY: %lx\n", SHADOW_GRANULARITY);
768 Printf("SHADOW_OFFSET: %lx\n", SHADOW_OFFSET);
769 CHECK(SHADOW_SCALE >= 3 && SHADOW_SCALE <= 7);
770 }
771
772 if (__WORDSIZE == 64) {
773 // Disable core dumper -- it makes little sense to dump 16T+ core.
Kostya Serebryany2b087182012-01-06 02:12:25774 AsanDisableCoreDumper();
Kostya Serebryany019b76f2011-11-30 01:07:02775 }
776
777 {
778 if (!FLAG_lazy_shadow) {
779 if (kLowShadowBeg != kLowShadowEnd) {
780 // mmap the low shadow plus one page.
Kostya Serebryanya7720962011-12-28 23:28:54781 ReserveShadowMemoryRange(kLowShadowBeg - kPageSize, kLowShadowEnd);
Kostya Serebryany019b76f2011-11-30 01:07:02782 }
783 // mmap the high shadow.
Kostya Serebryanya7720962011-12-28 23:28:54784 ReserveShadowMemoryRange(kHighShadowBeg, kHighShadowEnd);
Kostya Serebryany019b76f2011-11-30 01:07:02785 }
786 // protect the gap
Kostya Serebryanya7720962011-12-28 23:28:54787 void *prot = AsanMprotect(kShadowGapBeg, kShadowGapEnd - kShadowGapBeg + 1);
788 CHECK(prot == (void*)kShadowGapBeg);
Kostya Serebryany019b76f2011-11-30 01:07:02789 }
790
791 // On Linux AsanThread::ThreadStart() calls malloc() that's why asan_inited
792 // should be set to 1 prior to initializing the threads.
793 asan_inited = 1;
794 asan_init_is_running = false;
795
796 asanThreadRegistry().Init();
797 asanThreadRegistry().GetMain()->ThreadStart();
Kostya Serebryany46c70d32011-12-28 00:59:39798 force_interface_symbols(); // no-op.
Kostya Serebryany019b76f2011-11-30 01:07:02799
800 if (FLAG_v) {
Kostya Serebryany5dfa4da2011-12-01 21:40:52801 Report("AddressSanitizer Init done\n");
Kostya Serebryany019b76f2011-11-30 01:07:02802 }
803}