blob: 50be6df6b0162a0c2f6fbc2c2169ded3db87c0c2 [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"
21#include "asan_stack.h"
22#include "asan_stats.h"
23#include "asan_thread.h"
24#include "asan_thread_registry.h"
25
Kostya Serebryany2d27cdf2011-12-02 18:42:0426#include <new>
Kostya Serebryany019b76f2011-11-30 01:07:0227#include <dlfcn.h>
28#include <execinfo.h>
29#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#include <sys/time.h>
43#include <sys/resource.h>
44#include <unistd.h>
45// must not include <setjmp.h> on Linux
46
Kostya Serebryany019b76f2011-11-30 01:07:0247namespace __asan {
48
49// -------------------------- Flags ------------------------- {{{1
50static const size_t kMallocContextSize = 30;
51static int FLAG_atexit;
52bool FLAG_fast_unwind = true;
53
54size_t FLAG_redzone; // power of two, >= 32
Kostya Serebryany019b76f2011-11-30 01:07:0255size_t FLAG_quarantine_size;
56int FLAG_demangle;
57bool FLAG_symbolize;
58int FLAG_v;
59int FLAG_debug;
60bool FLAG_poison_shadow;
61int FLAG_report_globals;
62size_t FLAG_malloc_context_size = kMallocContextSize;
63uintptr_t FLAG_large_malloc;
64bool FLAG_lazy_shadow;
65bool FLAG_handle_segv;
66bool FLAG_handle_sigill;
67bool FLAG_replace_str;
68bool FLAG_replace_intrin;
69bool FLAG_replace_cfallocator; // Used on Mac only.
Kostya Serebryany019b76f2011-11-30 01:07:0270size_t FLAG_max_malloc_fill_size = 0;
71bool FLAG_use_fake_stack;
72int FLAG_exitcode = EXIT_FAILURE;
73bool FLAG_allow_user_poisoning;
74
75// -------------------------- Globals --------------------- {{{1
76int asan_inited;
77bool asan_init_is_running;
78
79// -------------------------- Interceptors ---------------- {{{1
80typedef int (*sigaction_f)(int signum, const struct sigaction *act,
81 struct sigaction *oldact);
82typedef sig_t (*signal_f)(int signum, sig_t handler);
83typedef void (*longjmp_f)(void *env, int val);
84typedef longjmp_f _longjmp_f;
85typedef longjmp_f siglongjmp_f;
86typedef void (*__cxa_throw_f)(void *, void *, void *);
87typedef int (*pthread_create_f)(pthread_t *thread, const pthread_attr_t *attr,
88 void *(*start_routine) (void *), void *arg);
89#ifdef __APPLE__
90dispatch_async_f_f real_dispatch_async_f;
91dispatch_sync_f_f real_dispatch_sync_f;
92dispatch_after_f_f real_dispatch_after_f;
93dispatch_barrier_async_f_f real_dispatch_barrier_async_f;
94dispatch_group_async_f_f real_dispatch_group_async_f;
95pthread_workqueue_additem_np_f real_pthread_workqueue_additem_np;
96#endif
97
98sigaction_f real_sigaction;
99signal_f real_signal;
100longjmp_f real_longjmp;
101_longjmp_f real__longjmp;
102siglongjmp_f real_siglongjmp;
103__cxa_throw_f real___cxa_throw;
104pthread_create_f real_pthread_create;
105
106// -------------------------- Misc ---------------- {{{1
107void ShowStatsAndAbort() {
108 __asan_print_accumulated_stats();
109 ASAN_DIE;
110}
111
112static void PrintBytes(const char *before, uintptr_t *a) {
113 uint8_t *bytes = (uint8_t*)a;
114 size_t byte_num = (__WORDSIZE) / 8;
115 Printf("%s%p:", before, (uintptr_t)a);
116 for (size_t i = 0; i < byte_num; i++) {
117 Printf(" %lx%lx", bytes[i] >> 4, bytes[i] & 15);
118 }
119 Printf("\n");
120}
121
Kostya Serebryany6c4bd802011-12-28 22:58:01122// Opens the file 'file_name" and reads up to 'max_len' bytes.
123// The resulting buffer is mmaped and stored in '*buff'.
124// Returns the number of read bytes or -1 if file can not be opened.
125static ssize_t ReadFileToBuffer(const char *file_name, char **buff,
126 size_t max_len) {
127 const size_t kMinFileLen = kPageSize;
128 ssize_t read_len = -1;
129 *buff = 0;
130 size_t maped_size = 0;
131 // The files we usually open are not seekable, so try different buffer sizes.
132 for (size_t size = kMinFileLen; size <= max_len; size *= 2) {
133 int fd = AsanOpenReadonly(file_name);
134 if (fd < 0) return -1;
135 AsanUnmapOrDie(*buff, maped_size);
136 maped_size = size;
137 *buff = (char*)AsanMmapSomewhereOrDie(size, __FUNCTION__);
138 read_len = AsanRead(fd, *buff, size);
139 AsanClose(fd);
140 if (read_len < size) // We've read the whole file.
141 break;
142 }
143 return read_len;
144}
145
146// Like getenv, but reads env directly from /proc and does not use libc.
147// This function should be called first inside __asan_init.
148static const char* GetEnvFromProcSelfEnviron(const char* name) {
149 static char *environ;
150 static ssize_t len;
151 static bool inited;
152 if (!inited) {
153 inited = true;
154 len = ReadFileToBuffer("/proc/self/environ", &environ, 1 << 20);
155 }
156 if (!environ || len <= 0) return NULL;
157 size_t namelen = internal_strlen(name);
158 const char *p = environ;
159 while (*p != '\0') { // will happen at the \0\0 that terminates the buffer
160 // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
161 const char* endp =
162 (char*)internal_memchr(p, '\0', len - (p - environ));
163 if (endp == NULL) // this entry isn't NUL terminated
164 return NULL;
165 else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=') // Match.
166 return p + namelen + 1; // point after =
167 p = endp + 1;
168 }
169 return NULL; // Not found.
170}
171
Kostya Serebryany019b76f2011-11-30 01:07:02172// ---------------------- Thread ------------------------- {{{1
173static void *asan_thread_start(void *arg) {
174 AsanThread *t= (AsanThread*)arg;
175 asanThreadRegistry().SetCurrent(t);
176 return t->ThreadStart();
177}
178
179// ---------------------- mmap -------------------- {{{1
Kostya Serebryany6c4bd802011-12-28 22:58:01180void OutOfMemoryMessageAndDie(const char *mem_type, size_t size) {
Kostya Serebryany019b76f2011-11-30 01:07:02181 Report("ERROR: AddressSanitizer failed to allocate "
182 "0x%lx (%ld) bytes of %s\n",
183 size, size, mem_type);
Kostya Serebryany6c4bd802011-12-28 22:58:01184 PRINT_CURRENT_STACK();
185 ShowStatsAndAbort();
Kostya Serebryany019b76f2011-11-30 01:07:02186}
187
Kostya Serebryanya7720962011-12-28 23:28:54188// Reserve memory range [beg, end].
189static void ReserveShadowMemoryRange(uintptr_t beg, uintptr_t end) {
Kostya Serebryany019b76f2011-11-30 01:07:02190 CHECK((beg % kPageSize) == 0);
191 CHECK(((end + 1) % kPageSize) == 0);
Kostya Serebryanya7720962011-12-28 23:28:54192 size_t size = end - beg + 1;
193 void *res = AsanMmapFixedNoReserve(beg, size);
194 CHECK(res == (void*)beg && "ReserveShadowMemoryRange failed");
Kostya Serebryany019b76f2011-11-30 01:07:02195}
196
Kostya Serebryanye4bada22011-12-02 21:02:20197// ---------------------- LowLevelAllocator ------------- {{{1
198void *LowLevelAllocator::Allocate(size_t size) {
199 CHECK((size & (size - 1)) == 0 && "size must be a power of two");
200 if (allocated_end_ - allocated_current_ < size) {
201 size_t size_to_allocate = Max(size, kPageSize);
Kostya Serebryany6c4bd802011-12-28 22:58:01202 allocated_current_ =
203 (char*)AsanMmapSomewhereOrDie(size_to_allocate, __FUNCTION__);
Kostya Serebryanye4bada22011-12-02 21:02:20204 allocated_end_ = allocated_current_ + size_to_allocate;
Kostya Serebryany7fb33a32011-12-15 17:41:30205 PoisonShadow((uintptr_t)allocated_current_, size_to_allocate,
206 kAsanInternalHeapMagic);
Kostya Serebryanye4bada22011-12-02 21:02:20207 }
208 CHECK(allocated_end_ - allocated_current_ >= size);
209 void *res = allocated_current_;
210 allocated_current_ += size;
211 return res;
212}
213
Kostya Serebryany019b76f2011-11-30 01:07:02214// ---------------------- DescribeAddress -------------------- {{{1
215static bool DescribeStackAddress(uintptr_t addr, uintptr_t access_size) {
216 AsanThread *t = asanThreadRegistry().FindThreadByStackAddress(addr);
217 if (!t) return false;
218 const intptr_t kBufSize = 4095;
219 char buf[kBufSize];
220 uintptr_t offset = 0;
221 const char *frame_descr = t->GetFrameNameByAddr(addr, &offset);
222 // This string is created by the compiler and has the following form:
223 // "FunctioName n alloc_1 alloc_2 ... alloc_n"
224 // where alloc_i looks like "offset size len ObjectName ".
225 CHECK(frame_descr);
226 // Report the function name and the offset.
227 const char *name_end = real_strchr(frame_descr, ' ');
228 CHECK(name_end);
229 buf[0] = 0;
230 strncat(buf, frame_descr,
Kostya Serebryany2d27cdf2011-12-02 18:42:04231 Min(kBufSize, static_cast<intptr_t>(name_end - frame_descr)));
Kostya Serebryany019b76f2011-11-30 01:07:02232 Printf("Address %p is located at offset %ld "
233 "in frame <%s> of T%d's stack:\n",
234 addr, offset, buf, t->tid());
235 // Report the number of stack objects.
236 char *p;
237 size_t n_objects = strtol(name_end, &p, 10);
238 CHECK(n_objects > 0);
239 Printf(" This frame has %ld object(s):\n", n_objects);
240 // Report all objects in this frame.
241 for (size_t i = 0; i < n_objects; i++) {
242 size_t beg, size;
243 intptr_t len;
244 beg = strtol(p, &p, 10);
245 size = strtol(p, &p, 10);
246 len = strtol(p, &p, 10);
247 if (beg <= 0 || size <= 0 || len < 0 || *p != ' ') {
248 Printf("AddressSanitizer can't parse the stack frame descriptor: |%s|\n",
249 frame_descr);
250 break;
251 }
252 p++;
253 buf[0] = 0;
Kostya Serebryany2d27cdf2011-12-02 18:42:04254 strncat(buf, p, Min(kBufSize, len));
Kostya Serebryany019b76f2011-11-30 01:07:02255 p += len;
256 Printf(" [%ld, %ld) '%s'\n", beg, beg + size, buf);
257 }
258 Printf("HINT: this may be a false positive if your program uses "
259 "some custom stack unwind mechanism\n"
260 " (longjmp and C++ exceptions *are* supported)\n");
261 t->summary()->Announce();
262 return true;
263}
264
265__attribute__((noinline))
266static void DescribeAddress(uintptr_t addr, uintptr_t access_size) {
267 // Check if this is a global.
268 if (DescribeAddrIfGlobal(addr))
269 return;
270
271 if (DescribeStackAddress(addr, access_size))
272 return;
273
274 // finally, check if this is a heap.
275 DescribeHeapAddress(addr, access_size);
276}
277
278// -------------------------- Run-time entry ------------------- {{{1
279void GetPcSpBpAx(void *context,
280 uintptr_t *pc, uintptr_t *sp, uintptr_t *bp, uintptr_t *ax) {
Kostya Serebryany2b87e402011-12-28 20:22:21281#ifndef ANDROID
Kostya Serebryany019b76f2011-11-30 01:07:02282 ucontext_t *ucontext = (ucontext_t*)context;
Kostya Serebryany2b87e402011-12-28 20:22:21283#endif
Kostya Serebryany019b76f2011-11-30 01:07:02284#ifdef __APPLE__
285# if __WORDSIZE == 64
286 *pc = ucontext->uc_mcontext->__ss.__rip;
287 *bp = ucontext->uc_mcontext->__ss.__rbp;
288 *sp = ucontext->uc_mcontext->__ss.__rsp;
289 *ax = ucontext->uc_mcontext->__ss.__rax;
290# else
Daniel Dunbarcf7fb022011-12-02 00:52:55291 *pc = ucontext->uc_mcontext->__ss.__eip;
292 *bp = ucontext->uc_mcontext->__ss.__ebp;
293 *sp = ucontext->uc_mcontext->__ss.__esp;
294 *ax = ucontext->uc_mcontext->__ss.__eax;
Kostya Serebryany019b76f2011-11-30 01:07:02295# endif // __WORDSIZE
296#else // assume linux
Kostya Serebryany2b87e402011-12-28 20:22:21297# if defined (ANDROID)
298 *pc = *sp = *bp = *ax = 0;
299# elif defined(__arm__)
Kostya Serebryany019b76f2011-11-30 01:07:02300 *pc = ucontext->uc_mcontext.arm_pc;
301 *bp = ucontext->uc_mcontext.arm_fp;
302 *sp = ucontext->uc_mcontext.arm_sp;
303 *ax = ucontext->uc_mcontext.arm_r0;
304# elif __WORDSIZE == 64
305 *pc = ucontext->uc_mcontext.gregs[REG_RIP];
306 *bp = ucontext->uc_mcontext.gregs[REG_RBP];
307 *sp = ucontext->uc_mcontext.gregs[REG_RSP];
308 *ax = ucontext->uc_mcontext.gregs[REG_RAX];
309# else
310 *pc = ucontext->uc_mcontext.gregs[REG_EIP];
311 *bp = ucontext->uc_mcontext.gregs[REG_EBP];
312 *sp = ucontext->uc_mcontext.gregs[REG_ESP];
313 *ax = ucontext->uc_mcontext.gregs[REG_EAX];
314# endif // __WORDSIZE
315#endif
316}
317
318static void ASAN_OnSIGSEGV(int, siginfo_t *siginfo, void *context) {
319 uintptr_t addr = (uintptr_t)siginfo->si_addr;
320 if (AddrIsInShadow(addr) && FLAG_lazy_shadow) {
321 // We traped on access to a shadow address. Just map a large chunk around
322 // this address.
323 const uintptr_t chunk_size = kPageSize << 10; // 4M
324 uintptr_t chunk = addr & ~(chunk_size - 1);
Kostya Serebryanya7720962011-12-28 23:28:54325 AsanMmapFixedReserve(chunk, chunk_size);
Kostya Serebryany019b76f2011-11-30 01:07:02326 return;
327 }
328 // Write the first message using the bullet-proof write.
Kostya Serebryany6c4bd802011-12-28 22:58:01329 if (13 != AsanWrite(2, "ASAN:SIGSEGV\n", 13)) ASAN_DIE;
Kostya Serebryany019b76f2011-11-30 01:07:02330 uintptr_t pc, sp, bp, ax;
331 GetPcSpBpAx(context, &pc, &sp, &bp, &ax);
332 Report("ERROR: AddressSanitizer crashed on unknown address %p"
333 " (pc %p sp %p bp %p ax %p T%d)\n",
334 addr, pc, sp, bp, ax,
335 asanThreadRegistry().GetCurrentTidOrMinusOne());
336 Printf("AddressSanitizer can not provide additional info. ABORTING\n");
337 GET_STACK_TRACE_WITH_PC_AND_BP(kStackTraceMax, false, pc, bp);
338 stack.PrintStack();
339 ShowStatsAndAbort();
340}
341
342static void ASAN_OnSIGILL(int, siginfo_t *siginfo, void *context) {
343 // Write the first message using the bullet-proof write.
Kostya Serebryany6c4bd802011-12-28 22:58:01344 if (12 != AsanWrite(2, "ASAN:SIGILL\n", 12)) ASAN_DIE;
Kostya Serebryany019b76f2011-11-30 01:07:02345 uintptr_t pc, sp, bp, ax;
346 GetPcSpBpAx(context, &pc, &sp, &bp, &ax);
347
348 uintptr_t addr = ax;
349
350 uint8_t *insn = (uint8_t*)pc;
351 CHECK(insn[0] == 0x0f && insn[1] == 0x0b); // ud2
352 unsigned access_size_and_type = insn[2] - 0x50;
353 CHECK(access_size_and_type < 16);
354 bool is_write = access_size_and_type & 8;
355 int access_size = 1 << (access_size_and_type & 7);
356 __asan_report_error(pc, bp, sp, addr, is_write, access_size);
357}
358
359// exported functions
Kostya Serebryany46c70d32011-12-28 00:59:39360#define ASAN_REPORT_ERROR(type, is_write, size) \
361extern "C" void __asan_report_ ## type ## size(uintptr_t addr) \
362 __attribute__((visibility("default"))) __attribute__((noinline)); \
363extern "C" void __asan_report_ ## type ## size(uintptr_t addr) { \
364 GET_BP_PC_SP; \
365 __asan_report_error(pc, bp, sp, addr, is_write, size); \
Kostya Serebryany019b76f2011-11-30 01:07:02366}
367
368ASAN_REPORT_ERROR(load, false, 1)
369ASAN_REPORT_ERROR(load, false, 2)
370ASAN_REPORT_ERROR(load, false, 4)
371ASAN_REPORT_ERROR(load, false, 8)
372ASAN_REPORT_ERROR(load, false, 16)
373ASAN_REPORT_ERROR(store, true, 1)
374ASAN_REPORT_ERROR(store, true, 2)
375ASAN_REPORT_ERROR(store, true, 4)
376ASAN_REPORT_ERROR(store, true, 8)
377ASAN_REPORT_ERROR(store, true, 16)
378
379// Force the linker to keep the symbols for various ASan interface functions.
380// We want to keep those in the executable in order to let the instrumented
381// dynamic libraries access the symbol even if it is not used by the executable
382// itself. This should help if the build system is removing dead code at link
383// time.
Kostya Serebryany46c70d32011-12-28 00:59:39384static void force_interface_symbols() {
Kostya Serebryany019b76f2011-11-30 01:07:02385 volatile int fake_condition = 0; // prevent dead condition elimination.
386 if (fake_condition) {
387 __asan_report_load1(NULL);
388 __asan_report_load2(NULL);
389 __asan_report_load4(NULL);
390 __asan_report_load8(NULL);
391 __asan_report_load16(NULL);
392 __asan_report_store1(NULL);
393 __asan_report_store2(NULL);
394 __asan_report_store4(NULL);
395 __asan_report_store8(NULL);
396 __asan_report_store16(NULL);
397 __asan_register_global(0, 0, NULL);
398 __asan_register_globals(NULL, 0);
399 }
400}
401
402// -------------------------- Init ------------------- {{{1
403static int64_t IntFlagValue(const char *flags, const char *flag,
404 int64_t default_val) {
405 if (!flags) return default_val;
406 const char *str = strstr(flags, flag);
407 if (!str) return default_val;
408 return atoll(str + internal_strlen(flag));
409}
410
411static void asan_atexit() {
412 Printf("AddressSanitizer exit stats:\n");
413 __asan_print_accumulated_stats();
414}
415
416void CheckFailed(const char *cond, const char *file, int line) {
417 Report("CHECK failed: %s at %s:%d, pthread_self=%p\n",
418 cond, file, line, pthread_self());
419 PRINT_CURRENT_STACK();
420 ShowStatsAndAbort();
421}
422
423} // namespace __asan
424
425// -------------------------- Interceptors ------------------- {{{1
426using namespace __asan; // NOLINT
427
428#define OPERATOR_NEW_BODY \
429 GET_STACK_TRACE_HERE_FOR_MALLOC;\
430 return asan_memalign(0, size, &stack);
431
Kostya Serebryanydd1386f2011-12-27 23:11:09432#ifdef ANDROID
433void *operator new(size_t size) { OPERATOR_NEW_BODY; }
434void *operator new[](size_t size) { OPERATOR_NEW_BODY; }
435#else
Kostya Serebryany019b76f2011-11-30 01:07:02436void *operator new(size_t size) throw(std::bad_alloc) { OPERATOR_NEW_BODY; }
437void *operator new[](size_t size) throw(std::bad_alloc) { OPERATOR_NEW_BODY; }
438void *operator new(size_t size, std::nothrow_t const&) throw()
439{ OPERATOR_NEW_BODY; }
440void *operator new[](size_t size, std::nothrow_t const&) throw()
441{ OPERATOR_NEW_BODY; }
Kostya Serebryanydd1386f2011-12-27 23:11:09442#endif
Kostya Serebryany019b76f2011-11-30 01:07:02443
444#define OPERATOR_DELETE_BODY \
445 GET_STACK_TRACE_HERE_FOR_FREE(ptr);\
446 asan_free(ptr, &stack);
447
448void operator delete(void *ptr) throw() { OPERATOR_DELETE_BODY; }
449void operator delete[](void *ptr) throw() { OPERATOR_DELETE_BODY; }
450void operator delete(void *ptr, std::nothrow_t const&) throw()
451{ OPERATOR_DELETE_BODY; }
452void operator delete[](void *ptr, std::nothrow_t const&) throw()
453{ OPERATOR_DELETE_BODY;}
454
455extern "C"
456#ifndef __APPLE__
457__attribute__((visibility("default")))
458#endif
459int WRAP(pthread_create)(pthread_t *thread, const pthread_attr_t *attr,
460 void *(*start_routine) (void *), void *arg) {
461 GET_STACK_TRACE_HERE(kStackTraceMax, /*fast_unwind*/false);
462 AsanThread *t = (AsanThread*)asan_malloc(sizeof(AsanThread), &stack);
463 AsanThread *curr_thread = asanThreadRegistry().GetCurrent();
464 CHECK(curr_thread || asanThreadRegistry().IsCurrentThreadDying());
465 new(t) AsanThread(asanThreadRegistry().GetCurrentTidOrMinusOne(),
466 start_routine, arg, &stack);
467 return real_pthread_create(thread, attr, asan_thread_start, t);
468}
469
470static bool MySignal(int signum) {
471 if (FLAG_handle_sigill && signum == SIGILL) return true;
472 if (FLAG_handle_segv && signum == SIGSEGV) return true;
473#ifdef __APPLE__
474 if (FLAG_handle_segv && signum == SIGBUS) return true;
475#endif
476 return false;
477}
478
479static void MaybeInstallSigaction(int signum,
480 void (*handler)(int, siginfo_t *, void *)) {
481 if (!MySignal(signum))
482 return;
483 struct sigaction sigact;
484 real_memset(&sigact, 0, sizeof(sigact));
485 sigact.sa_sigaction = handler;
486 sigact.sa_flags = SA_SIGINFO;
487 CHECK(0 == real_sigaction(signum, &sigact, 0));
488}
489
490extern "C"
491sig_t WRAP(signal)(int signum, sig_t handler) {
492 if (!MySignal(signum)) {
493 return real_signal(signum, handler);
494 }
495 return NULL;
496}
497
498extern "C"
499int WRAP(sigaction)(int signum, const struct sigaction *act,
500 struct sigaction *oldact) {
501 if (!MySignal(signum)) {
502 return real_sigaction(signum, act, oldact);
503 }
504 return 0;
505}
506
507
508static void UnpoisonStackFromHereToTop() {
509 int local_stack;
510 AsanThread *curr_thread = asanThreadRegistry().GetCurrent();
511 CHECK(curr_thread);
512 uintptr_t top = curr_thread->stack_top();
513 uintptr_t bottom = ((uintptr_t)&local_stack - kPageSize) & ~(kPageSize-1);
Kostya Serebryany15dd3f22011-11-30 18:50:23514 PoisonShadow(bottom, top - bottom, 0);
Kostya Serebryany019b76f2011-11-30 01:07:02515}
516
517extern "C" void WRAP(longjmp)(void *env, int val) {
518 UnpoisonStackFromHereToTop();
519 real_longjmp(env, val);
520}
521
522extern "C" void WRAP(_longjmp)(void *env, int val) {
523 UnpoisonStackFromHereToTop();
524 real__longjmp(env, val);
525}
526
527extern "C" void WRAP(siglongjmp)(void *env, int val) {
528 UnpoisonStackFromHereToTop();
529 real_siglongjmp(env, val);
530}
531
532extern "C" void __cxa_throw(void *a, void *b, void *c);
533
Kostya Serebryanyb50a5392011-12-08 18:30:42534#if ASAN_HAS_EXCEPTIONS == 1
Kostya Serebryany019b76f2011-11-30 01:07:02535extern "C" void WRAP(__cxa_throw)(void *a, void *b, void *c) {
Kostya Serebryany93927f92011-12-05 17:56:32536 CHECK(&real___cxa_throw);
Kostya Serebryany019b76f2011-11-30 01:07:02537 UnpoisonStackFromHereToTop();
538 real___cxa_throw(a, b, c);
539}
540#endif
541
542extern "C" {
543// intercept mlock and friends.
544// Since asan maps 16T of RAM, mlock is completely unfriendly to asan.
545// All functions return 0 (success).
546static void MlockIsUnsupported() {
547 static bool printed = 0;
548 if (printed) return;
549 printed = true;
550 Printf("INFO: AddressSanitizer ignores mlock/mlockall/munlock/munlockall\n");
551}
552int mlock(const void *addr, size_t len) {
553 MlockIsUnsupported();
554 return 0;
555}
556int munlock(const void *addr, size_t len) {
557 MlockIsUnsupported();
558 return 0;
559}
560int mlockall(int flags) {
561 MlockIsUnsupported();
562 return 0;
563}
564int munlockall(void) {
565 MlockIsUnsupported();
566 return 0;
567}
568} // extern "C"
569
570// ---------------------- Interface ---------------- {{{1
571int __asan_set_error_exit_code(int exit_code) {
572 int old = FLAG_exitcode;
573 FLAG_exitcode = exit_code;
574 return old;
575}
576
577void __asan_report_error(uintptr_t pc, uintptr_t bp, uintptr_t sp,
578 uintptr_t addr, bool is_write, size_t access_size) {
579 // Do not print more than one report, otherwise they will mix up.
580 static int num_calls = 0;
581 if (AtomicInc(&num_calls) > 1) return;
582
583 Printf("=================================================================\n");
584 const char *bug_descr = "unknown-crash";
585 if (AddrIsInMem(addr)) {
586 uint8_t *shadow_addr = (uint8_t*)MemToShadow(addr);
Kostya Serebryanyf0d799a2011-12-07 21:30:20587 // If we are accessing 16 bytes, look at the second shadow byte.
588 if (*shadow_addr == 0 && access_size > SHADOW_GRANULARITY)
589 shadow_addr++;
590 // If we are in the partial right redzone, look at the next shadow byte.
591 if (*shadow_addr > 0 && *shadow_addr < 128)
592 shadow_addr++;
593 switch (*shadow_addr) {
Kostya Serebryany019b76f2011-11-30 01:07:02594 case kAsanHeapLeftRedzoneMagic:
595 case kAsanHeapRightRedzoneMagic:
596 bug_descr = "heap-buffer-overflow";
597 break;
598 case kAsanHeapFreeMagic:
599 bug_descr = "heap-use-after-free";
600 break;
601 case kAsanStackLeftRedzoneMagic:
602 bug_descr = "stack-buffer-underflow";
603 break;
604 case kAsanStackMidRedzoneMagic:
605 case kAsanStackRightRedzoneMagic:
606 case kAsanStackPartialRedzoneMagic:
607 bug_descr = "stack-buffer-overflow";
608 break;
609 case kAsanStackAfterReturnMagic:
610 bug_descr = "stack-use-after-return";
611 break;
612 case kAsanUserPoisonedMemoryMagic:
613 bug_descr = "use-after-poison";
614 break;
615 case kAsanGlobalRedzoneMagic:
616 bug_descr = "global-buffer-overflow";
617 break;
618 }
619 }
620
Kostya Serebryany72fde372011-12-09 01:49:31621 AsanThread *curr_thread = asanThreadRegistry().GetCurrent();
622 int curr_tid = asanThreadRegistry().GetCurrentTidOrMinusOne();
623
624 if (curr_thread) {
625 // We started reporting an error message. Stop using the fake stack
626 // in case we will call an instrumented function from a symbolizer.
627 curr_thread->fake_stack().StopUsingFakeStack();
628 }
629
Kostya Serebryany019b76f2011-11-30 01:07:02630 Report("ERROR: AddressSanitizer %s on address "
631 "%p at pc 0x%lx bp 0x%lx sp 0x%lx\n",
632 bug_descr, addr, pc, bp, sp);
633
634 Printf("%s of size %d at %p thread T%d\n",
635 access_size ? (is_write ? "WRITE" : "READ") : "ACCESS",
Kostya Serebryany72fde372011-12-09 01:49:31636 access_size, addr, curr_tid);
Kostya Serebryany019b76f2011-11-30 01:07:02637
638 if (FLAG_debug) {
639 PrintBytes("PC: ", (uintptr_t*)pc);
640 }
641
642 GET_STACK_TRACE_WITH_PC_AND_BP(kStackTraceMax,
643 false, // FLAG_fast_unwind,
644 pc, bp);
645 stack.PrintStack();
646
647 CHECK(AddrIsInMem(addr));
648
649 DescribeAddress(addr, access_size);
650
651 uintptr_t shadow_addr = MemToShadow(addr);
652 Report("ABORTING\n");
653 __asan_print_accumulated_stats();
654 Printf("Shadow byte and word:\n");
655 Printf(" %p: %x\n", shadow_addr, *(unsigned char*)shadow_addr);
656 uintptr_t aligned_shadow = shadow_addr & ~(kWordSize - 1);
657 PrintBytes(" ", (uintptr_t*)(aligned_shadow));
658 Printf("More shadow bytes:\n");
659 PrintBytes(" ", (uintptr_t*)(aligned_shadow-4*kWordSize));
660 PrintBytes(" ", (uintptr_t*)(aligned_shadow-3*kWordSize));
661 PrintBytes(" ", (uintptr_t*)(aligned_shadow-2*kWordSize));
662 PrintBytes(" ", (uintptr_t*)(aligned_shadow-1*kWordSize));
663 PrintBytes("=>", (uintptr_t*)(aligned_shadow+0*kWordSize));
664 PrintBytes(" ", (uintptr_t*)(aligned_shadow+1*kWordSize));
665 PrintBytes(" ", (uintptr_t*)(aligned_shadow+2*kWordSize));
666 PrintBytes(" ", (uintptr_t*)(aligned_shadow+3*kWordSize));
667 PrintBytes(" ", (uintptr_t*)(aligned_shadow+4*kWordSize));
668 ASAN_DIE;
669}
670
671void __asan_init() {
672 if (asan_inited) return;
673 asan_init_is_running = true;
674
675 // Make sure we are not statically linked.
676 AsanDoesNotSupportStaticLinkage();
677
678 // flags
Kostya Serebryany6c4bd802011-12-28 22:58:01679 const char *options = GetEnvFromProcSelfEnviron("ASAN_OPTIONS");
Kostya Serebryany019b76f2011-11-30 01:07:02680 FLAG_malloc_context_size =
681 IntFlagValue(options, "malloc_context_size=", kMallocContextSize);
682 CHECK(FLAG_malloc_context_size <= kMallocContextSize);
683
684 FLAG_max_malloc_fill_size =
685 IntFlagValue(options, "max_malloc_fill_size=", 0);
686
687 FLAG_v = IntFlagValue(options, "verbosity=", 0);
688
689 FLAG_redzone = IntFlagValue(options, "redzone=", 128);
690 CHECK(FLAG_redzone >= 32);
691 CHECK((FLAG_redzone & (FLAG_redzone - 1)) == 0);
692
693 FLAG_atexit = IntFlagValue(options, "atexit=", 0);
694 FLAG_poison_shadow = IntFlagValue(options, "poison_shadow=", 1);
695 FLAG_report_globals = IntFlagValue(options, "report_globals=", 1);
696 FLAG_lazy_shadow = IntFlagValue(options, "lazy_shadow=", 0);
Kostya Serebryanyb50a5392011-12-08 18:30:42697 FLAG_handle_segv = IntFlagValue(options, "handle_segv=", ASAN_NEEDS_SEGV);
Kostya Serebryany019b76f2011-11-30 01:07:02698 FLAG_handle_sigill = IntFlagValue(options, "handle_sigill=", 0);
Kostya Serebryany019b76f2011-11-30 01:07:02699 FLAG_symbolize = IntFlagValue(options, "symbolize=", 1);
700 FLAG_demangle = IntFlagValue(options, "demangle=", 1);
701 FLAG_debug = IntFlagValue(options, "debug=", 0);
702 FLAG_replace_cfallocator = IntFlagValue(options, "replace_cfallocator=", 1);
703 FLAG_fast_unwind = IntFlagValue(options, "fast_unwind=", 1);
Kostya Serebryany019b76f2011-11-30 01:07:02704 FLAG_replace_str = IntFlagValue(options, "replace_str=", 1);
Kostya Serebryany76eca5e2011-12-28 19:55:30705 FLAG_replace_intrin = IntFlagValue(options, "replace_intrin=", 1);
Kostya Serebryany019b76f2011-11-30 01:07:02706 FLAG_use_fake_stack = IntFlagValue(options, "use_fake_stack=", 1);
707 FLAG_exitcode = IntFlagValue(options, "exitcode=", EXIT_FAILURE);
708 FLAG_allow_user_poisoning = IntFlagValue(options,
709 "allow_user_poisoning=", 1);
710
711 if (FLAG_atexit) {
712 atexit(asan_atexit);
713 }
714
715 FLAG_quarantine_size =
716 IntFlagValue(options, "quarantine_size=", 1UL << 28);
717
718 // interceptors
719 InitializeAsanInterceptors();
720
721 ReplaceSystemMalloc();
722
723 INTERCEPT_FUNCTION(sigaction);
724 INTERCEPT_FUNCTION(signal);
725 INTERCEPT_FUNCTION(longjmp);
726 INTERCEPT_FUNCTION(_longjmp);
Kostya Serebryany93927f92011-12-05 17:56:32727 INTERCEPT_FUNCTION_IF_EXISTS(__cxa_throw);
Kostya Serebryany019b76f2011-11-30 01:07:02728 INTERCEPT_FUNCTION(pthread_create);
729#ifdef __APPLE__
730 INTERCEPT_FUNCTION(dispatch_async_f);
731 INTERCEPT_FUNCTION(dispatch_sync_f);
732 INTERCEPT_FUNCTION(dispatch_after_f);
733 INTERCEPT_FUNCTION(dispatch_barrier_async_f);
734 INTERCEPT_FUNCTION(dispatch_group_async_f);
735 // We don't need to intercept pthread_workqueue_additem_np() to support the
736 // libdispatch API, but it helps us to debug the unsupported functions. Let's
737 // intercept it only during verbose runs.
738 if (FLAG_v >= 2) {
739 INTERCEPT_FUNCTION(pthread_workqueue_additem_np);
740 }
741#else
742 // On Darwin siglongjmp tailcalls longjmp, so we don't want to intercept it
743 // there.
744 INTERCEPT_FUNCTION(siglongjmp);
745#endif
746
747 MaybeInstallSigaction(SIGSEGV, ASAN_OnSIGSEGV);
748 MaybeInstallSigaction(SIGBUS, ASAN_OnSIGSEGV);
749 MaybeInstallSigaction(SIGILL, ASAN_OnSIGILL);
750
751 if (FLAG_v) {
752 Printf("|| `[%p, %p]` || HighMem ||\n", kHighMemBeg, kHighMemEnd);
753 Printf("|| `[%p, %p]` || HighShadow ||\n",
754 kHighShadowBeg, kHighShadowEnd);
755 Printf("|| `[%p, %p]` || ShadowGap ||\n",
756 kShadowGapBeg, kShadowGapEnd);
757 Printf("|| `[%p, %p]` || LowShadow ||\n",
758 kLowShadowBeg, kLowShadowEnd);
759 Printf("|| `[%p, %p]` || LowMem ||\n", kLowMemBeg, kLowMemEnd);
760 Printf("MemToShadow(shadow): %p %p %p %p\n",
761 MEM_TO_SHADOW(kLowShadowBeg),
762 MEM_TO_SHADOW(kLowShadowEnd),
763 MEM_TO_SHADOW(kHighShadowBeg),
764 MEM_TO_SHADOW(kHighShadowEnd));
765 Printf("red_zone=%ld\n", FLAG_redzone);
766 Printf("malloc_context_size=%ld\n", (int)FLAG_malloc_context_size);
767 Printf("fast_unwind=%d\n", (int)FLAG_fast_unwind);
768
769 Printf("SHADOW_SCALE: %lx\n", SHADOW_SCALE);
770 Printf("SHADOW_GRANULARITY: %lx\n", SHADOW_GRANULARITY);
771 Printf("SHADOW_OFFSET: %lx\n", SHADOW_OFFSET);
772 CHECK(SHADOW_SCALE >= 3 && SHADOW_SCALE <= 7);
773 }
774
775 if (__WORDSIZE == 64) {
776 // Disable core dumper -- it makes little sense to dump 16T+ core.
777 struct rlimit nocore;
778 nocore.rlim_cur = 0;
779 nocore.rlim_max = 0;
780 setrlimit(RLIMIT_CORE, &nocore);
781 }
782
783 {
784 if (!FLAG_lazy_shadow) {
785 if (kLowShadowBeg != kLowShadowEnd) {
786 // mmap the low shadow plus one page.
Kostya Serebryanya7720962011-12-28 23:28:54787 ReserveShadowMemoryRange(kLowShadowBeg - kPageSize, kLowShadowEnd);
Kostya Serebryany019b76f2011-11-30 01:07:02788 }
789 // mmap the high shadow.
Kostya Serebryanya7720962011-12-28 23:28:54790 ReserveShadowMemoryRange(kHighShadowBeg, kHighShadowEnd);
Kostya Serebryany019b76f2011-11-30 01:07:02791 }
792 // protect the gap
Kostya Serebryanya7720962011-12-28 23:28:54793 void *prot = AsanMprotect(kShadowGapBeg, kShadowGapEnd - kShadowGapBeg + 1);
794 CHECK(prot == (void*)kShadowGapBeg);
Kostya Serebryany019b76f2011-11-30 01:07:02795 }
796
797 // On Linux AsanThread::ThreadStart() calls malloc() that's why asan_inited
798 // should be set to 1 prior to initializing the threads.
799 asan_inited = 1;
800 asan_init_is_running = false;
801
802 asanThreadRegistry().Init();
803 asanThreadRegistry().GetMain()->ThreadStart();
Kostya Serebryany46c70d32011-12-28 00:59:39804 force_interface_symbols(); // no-op.
Kostya Serebryany019b76f2011-11-30 01:07:02805
806 if (FLAG_v) {
Kostya Serebryany5dfa4da2011-12-01 21:40:52807 Report("AddressSanitizer Init done\n");
Kostya Serebryany019b76f2011-11-30 01:07:02808 }
809}