blob: 299f647e1716ee482bd025afd82335ca693d92bc [file] [log] [blame]
Kostya Serebryany1e172b42011-11-30 01:07:02 +00001//===-- asan_rtl.cc ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is a part of AddressSanitizer, an address sanity checker.
11//
12// Main file of the ASan run-time library.
13//===----------------------------------------------------------------------===//
14#include "asan_allocator.h"
15#include "asan_interceptors.h"
16#include "asan_interface.h"
17#include "asan_internal.h"
18#include "asan_lock.h"
19#ifdef __APPLE__
20#include "asan_mac.h"
21#endif
22#include "asan_mapping.h"
23#include "asan_stack.h"
24#include "asan_stats.h"
25#include "asan_thread.h"
26#include "asan_thread_registry.h"
27
Kostya Serebryany2d8b3bd2011-12-02 18:42:04 +000028#include <new>
Kostya Serebryany1e172b42011-11-30 01:07:02 +000029#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>
Kostya Serebryany6413ec32011-12-28 20:22:21 +000042#ifndef ANDROID
Kostya Serebryany1e172b42011-11-30 01:07:02 +000043#include <sys/ucontext.h>
Kostya Serebryany6413ec32011-12-28 20:22:21 +000044#endif
Kostya Serebryany1e172b42011-11-30 01:07:02 +000045#include <sys/time.h>
46#include <sys/resource.h>
47#include <unistd.h>
48// must not include <setjmp.h> on Linux
49
Kostya Serebryany1e172b42011-11-30 01:07:02 +000050namespace __asan {
51
52// -------------------------- Flags ------------------------- {{{1
53static const size_t kMallocContextSize = 30;
54static int FLAG_atexit;
55bool FLAG_fast_unwind = true;
56
57size_t FLAG_redzone; // power of two, >= 32
Kostya Serebryany1e172b42011-11-30 01:07:02 +000058size_t FLAG_quarantine_size;
59int FLAG_demangle;
60bool FLAG_symbolize;
61int FLAG_v;
62int FLAG_debug;
63bool FLAG_poison_shadow;
64int FLAG_report_globals;
65size_t FLAG_malloc_context_size = kMallocContextSize;
66uintptr_t FLAG_large_malloc;
67bool FLAG_lazy_shadow;
68bool FLAG_handle_segv;
69bool FLAG_handle_sigill;
70bool FLAG_replace_str;
71bool FLAG_replace_intrin;
72bool FLAG_replace_cfallocator; // Used on Mac only.
Kostya Serebryany1e172b42011-11-30 01:07:02 +000073size_t FLAG_max_malloc_fill_size = 0;
74bool FLAG_use_fake_stack;
75int FLAG_exitcode = EXIT_FAILURE;
76bool FLAG_allow_user_poisoning;
77
78// -------------------------- Globals --------------------- {{{1
79int asan_inited;
80bool asan_init_is_running;
81
82// -------------------------- Interceptors ---------------- {{{1
83typedef int (*sigaction_f)(int signum, const struct sigaction *act,
84 struct sigaction *oldact);
85typedef sig_t (*signal_f)(int signum, sig_t handler);
86typedef void (*longjmp_f)(void *env, int val);
87typedef longjmp_f _longjmp_f;
88typedef longjmp_f siglongjmp_f;
89typedef void (*__cxa_throw_f)(void *, void *, void *);
90typedef int (*pthread_create_f)(pthread_t *thread, const pthread_attr_t *attr,
91 void *(*start_routine) (void *), void *arg);
92#ifdef __APPLE__
93dispatch_async_f_f real_dispatch_async_f;
94dispatch_sync_f_f real_dispatch_sync_f;
95dispatch_after_f_f real_dispatch_after_f;
96dispatch_barrier_async_f_f real_dispatch_barrier_async_f;
97dispatch_group_async_f_f real_dispatch_group_async_f;
98pthread_workqueue_additem_np_f real_pthread_workqueue_additem_np;
99#endif
100
101sigaction_f real_sigaction;
102signal_f real_signal;
103longjmp_f real_longjmp;
104_longjmp_f real__longjmp;
105siglongjmp_f real_siglongjmp;
106__cxa_throw_f real___cxa_throw;
107pthread_create_f real_pthread_create;
108
109// -------------------------- Misc ---------------- {{{1
110void ShowStatsAndAbort() {
111 __asan_print_accumulated_stats();
112 ASAN_DIE;
113}
114
115static void PrintBytes(const char *before, uintptr_t *a) {
116 uint8_t *bytes = (uint8_t*)a;
117 size_t byte_num = (__WORDSIZE) / 8;
118 Printf("%s%p:", before, (uintptr_t)a);
119 for (size_t i = 0; i < byte_num; i++) {
120 Printf(" %lx%lx", bytes[i] >> 4, bytes[i] & 15);
121 }
122 Printf("\n");
123}
124
Kostya Serebryanyde496f42011-12-28 22:58:01 +0000125// Opens the file 'file_name" and reads up to 'max_len' bytes.
126// The resulting buffer is mmaped and stored in '*buff'.
127// Returns the number of read bytes or -1 if file can not be opened.
128static ssize_t ReadFileToBuffer(const char *file_name, char **buff,
129 size_t max_len) {
130 const size_t kMinFileLen = kPageSize;
131 ssize_t read_len = -1;
132 *buff = 0;
133 size_t maped_size = 0;
134 // The files we usually open are not seekable, so try different buffer sizes.
135 for (size_t size = kMinFileLen; size <= max_len; size *= 2) {
136 int fd = AsanOpenReadonly(file_name);
137 if (fd < 0) return -1;
138 AsanUnmapOrDie(*buff, maped_size);
139 maped_size = size;
140 *buff = (char*)AsanMmapSomewhereOrDie(size, __FUNCTION__);
141 read_len = AsanRead(fd, *buff, size);
142 AsanClose(fd);
143 if (read_len < size) // We've read the whole file.
144 break;
145 }
146 return read_len;
147}
148
149// Like getenv, but reads env directly from /proc and does not use libc.
150// This function should be called first inside __asan_init.
151static const char* GetEnvFromProcSelfEnviron(const char* name) {
152 static char *environ;
153 static ssize_t len;
154 static bool inited;
155 if (!inited) {
156 inited = true;
157 len = ReadFileToBuffer("/proc/self/environ", &environ, 1 << 20);
158 }
159 if (!environ || len <= 0) return NULL;
160 size_t namelen = internal_strlen(name);
161 const char *p = environ;
162 while (*p != '\0') { // will happen at the \0\0 that terminates the buffer
163 // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
164 const char* endp =
165 (char*)internal_memchr(p, '\0', len - (p - environ));
166 if (endp == NULL) // this entry isn't NUL terminated
167 return NULL;
168 else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=') // Match.
169 return p + namelen + 1; // point after =
170 p = endp + 1;
171 }
172 return NULL; // Not found.
173}
174
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000175// ---------------------- Thread ------------------------- {{{1
176static void *asan_thread_start(void *arg) {
177 AsanThread *t= (AsanThread*)arg;
178 asanThreadRegistry().SetCurrent(t);
179 return t->ThreadStart();
180}
181
182// ---------------------- mmap -------------------- {{{1
Kostya Serebryanyde496f42011-12-28 22:58:01 +0000183void OutOfMemoryMessageAndDie(const char *mem_type, size_t size) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000184 Report("ERROR: AddressSanitizer failed to allocate "
185 "0x%lx (%ld) bytes of %s\n",
186 size, size, mem_type);
Kostya Serebryanyde496f42011-12-28 22:58:01 +0000187 PRINT_CURRENT_STACK();
188 ShowStatsAndAbort();
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000189}
190
191static char *mmap_pages(size_t start_page, size_t n_pages, const char *mem_type,
192 bool abort_on_failure = true) {
193 void *res = asan_mmap((void*)start_page, kPageSize * n_pages,
194 PROT_READ | PROT_WRITE,
195 MAP_PRIVATE | MAP_ANON | MAP_FIXED | MAP_NORESERVE, 0, 0);
196 // Printf("%p => %p\n", (void*)start_page, res);
197 char *ch = (char*)res;
198 if (res == (void*)-1L && abort_on_failure) {
Kostya Serebryanyde496f42011-12-28 22:58:01 +0000199 OutOfMemoryMessageAndDie(mem_type, n_pages * kPageSize);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000200 }
201 CHECK(res == (void*)start_page || res == (void*)-1L);
202 return ch;
203}
204
205// mmap range [beg, end]
206static char *mmap_range(uintptr_t beg, uintptr_t end, const char *mem_type) {
207 CHECK((beg % kPageSize) == 0);
208 CHECK(((end + 1) % kPageSize) == 0);
209 // Printf("mmap_range %p %p %ld\n", beg, end, (end - beg) / kPageSize);
210 return mmap_pages(beg, (end - beg + 1) / kPageSize, mem_type);
211}
212
213// protect range [beg, end]
214static void protect_range(uintptr_t beg, uintptr_t end) {
215 CHECK((beg % kPageSize) == 0);
216 CHECK(((end+1) % kPageSize) == 0);
217 // Printf("protect_range %p %p %ld\n", beg, end, (end - beg) / kPageSize);
218 void *res = asan_mmap((void*)beg, end - beg + 1,
219 PROT_NONE,
220 MAP_PRIVATE | MAP_ANON | MAP_FIXED | MAP_NORESERVE, 0, 0);
221 CHECK(res == (void*)beg);
222}
223
Kostya Serebryanyb89567c2011-12-02 21:02:20 +0000224// ---------------------- LowLevelAllocator ------------- {{{1
225void *LowLevelAllocator::Allocate(size_t size) {
226 CHECK((size & (size - 1)) == 0 && "size must be a power of two");
227 if (allocated_end_ - allocated_current_ < size) {
228 size_t size_to_allocate = Max(size, kPageSize);
Kostya Serebryanyde496f42011-12-28 22:58:01 +0000229 allocated_current_ =
230 (char*)AsanMmapSomewhereOrDie(size_to_allocate, __FUNCTION__);
Kostya Serebryanyb89567c2011-12-02 21:02:20 +0000231 allocated_end_ = allocated_current_ + size_to_allocate;
Kostya Serebryany6b30e2c2011-12-15 17:41:30 +0000232 PoisonShadow((uintptr_t)allocated_current_, size_to_allocate,
233 kAsanInternalHeapMagic);
Kostya Serebryanyb89567c2011-12-02 21:02:20 +0000234 }
235 CHECK(allocated_end_ - allocated_current_ >= size);
236 void *res = allocated_current_;
237 allocated_current_ += size;
238 return res;
239}
240
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000241// ---------------------- DescribeAddress -------------------- {{{1
242static bool DescribeStackAddress(uintptr_t addr, uintptr_t access_size) {
243 AsanThread *t = asanThreadRegistry().FindThreadByStackAddress(addr);
244 if (!t) return false;
245 const intptr_t kBufSize = 4095;
246 char buf[kBufSize];
247 uintptr_t offset = 0;
248 const char *frame_descr = t->GetFrameNameByAddr(addr, &offset);
249 // This string is created by the compiler and has the following form:
250 // "FunctioName n alloc_1 alloc_2 ... alloc_n"
251 // where alloc_i looks like "offset size len ObjectName ".
252 CHECK(frame_descr);
253 // Report the function name and the offset.
254 const char *name_end = real_strchr(frame_descr, ' ');
255 CHECK(name_end);
256 buf[0] = 0;
257 strncat(buf, frame_descr,
Kostya Serebryany2d8b3bd2011-12-02 18:42:04 +0000258 Min(kBufSize, static_cast<intptr_t>(name_end - frame_descr)));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000259 Printf("Address %p is located at offset %ld "
260 "in frame <%s> of T%d's stack:\n",
261 addr, offset, buf, t->tid());
262 // Report the number of stack objects.
263 char *p;
264 size_t n_objects = strtol(name_end, &p, 10);
265 CHECK(n_objects > 0);
266 Printf(" This frame has %ld object(s):\n", n_objects);
267 // Report all objects in this frame.
268 for (size_t i = 0; i < n_objects; i++) {
269 size_t beg, size;
270 intptr_t len;
271 beg = strtol(p, &p, 10);
272 size = strtol(p, &p, 10);
273 len = strtol(p, &p, 10);
274 if (beg <= 0 || size <= 0 || len < 0 || *p != ' ') {
275 Printf("AddressSanitizer can't parse the stack frame descriptor: |%s|\n",
276 frame_descr);
277 break;
278 }
279 p++;
280 buf[0] = 0;
Kostya Serebryany2d8b3bd2011-12-02 18:42:04 +0000281 strncat(buf, p, Min(kBufSize, len));
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000282 p += len;
283 Printf(" [%ld, %ld) '%s'\n", beg, beg + size, buf);
284 }
285 Printf("HINT: this may be a false positive if your program uses "
286 "some custom stack unwind mechanism\n"
287 " (longjmp and C++ exceptions *are* supported)\n");
288 t->summary()->Announce();
289 return true;
290}
291
292__attribute__((noinline))
293static void DescribeAddress(uintptr_t addr, uintptr_t access_size) {
294 // Check if this is a global.
295 if (DescribeAddrIfGlobal(addr))
296 return;
297
298 if (DescribeStackAddress(addr, access_size))
299 return;
300
301 // finally, check if this is a heap.
302 DescribeHeapAddress(addr, access_size);
303}
304
305// -------------------------- Run-time entry ------------------- {{{1
306void GetPcSpBpAx(void *context,
307 uintptr_t *pc, uintptr_t *sp, uintptr_t *bp, uintptr_t *ax) {
Kostya Serebryany6413ec32011-12-28 20:22:21 +0000308#ifndef ANDROID
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000309 ucontext_t *ucontext = (ucontext_t*)context;
Kostya Serebryany6413ec32011-12-28 20:22:21 +0000310#endif
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000311#ifdef __APPLE__
312# if __WORDSIZE == 64
313 *pc = ucontext->uc_mcontext->__ss.__rip;
314 *bp = ucontext->uc_mcontext->__ss.__rbp;
315 *sp = ucontext->uc_mcontext->__ss.__rsp;
316 *ax = ucontext->uc_mcontext->__ss.__rax;
317# else
Daniel Dunbar78552752011-12-02 00:52:55 +0000318 *pc = ucontext->uc_mcontext->__ss.__eip;
319 *bp = ucontext->uc_mcontext->__ss.__ebp;
320 *sp = ucontext->uc_mcontext->__ss.__esp;
321 *ax = ucontext->uc_mcontext->__ss.__eax;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000322# endif // __WORDSIZE
323#else // assume linux
Kostya Serebryany6413ec32011-12-28 20:22:21 +0000324# if defined (ANDROID)
325 *pc = *sp = *bp = *ax = 0;
326# elif defined(__arm__)
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000327 *pc = ucontext->uc_mcontext.arm_pc;
328 *bp = ucontext->uc_mcontext.arm_fp;
329 *sp = ucontext->uc_mcontext.arm_sp;
330 *ax = ucontext->uc_mcontext.arm_r0;
331# elif __WORDSIZE == 64
332 *pc = ucontext->uc_mcontext.gregs[REG_RIP];
333 *bp = ucontext->uc_mcontext.gregs[REG_RBP];
334 *sp = ucontext->uc_mcontext.gregs[REG_RSP];
335 *ax = ucontext->uc_mcontext.gregs[REG_RAX];
336# else
337 *pc = ucontext->uc_mcontext.gregs[REG_EIP];
338 *bp = ucontext->uc_mcontext.gregs[REG_EBP];
339 *sp = ucontext->uc_mcontext.gregs[REG_ESP];
340 *ax = ucontext->uc_mcontext.gregs[REG_EAX];
341# endif // __WORDSIZE
342#endif
343}
344
345static void ASAN_OnSIGSEGV(int, siginfo_t *siginfo, void *context) {
346 uintptr_t addr = (uintptr_t)siginfo->si_addr;
347 if (AddrIsInShadow(addr) && FLAG_lazy_shadow) {
348 // We traped on access to a shadow address. Just map a large chunk around
349 // this address.
350 const uintptr_t chunk_size = kPageSize << 10; // 4M
351 uintptr_t chunk = addr & ~(chunk_size - 1);
352 asan_mmap((void*)chunk, chunk_size,
353 PROT_READ | PROT_WRITE,
354 MAP_PRIVATE | MAP_ANON | MAP_FIXED, 0, 0);
355 return;
356 }
357 // Write the first message using the bullet-proof write.
Kostya Serebryanyde496f42011-12-28 22:58:01 +0000358 if (13 != AsanWrite(2, "ASAN:SIGSEGV\n", 13)) ASAN_DIE;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000359 uintptr_t pc, sp, bp, ax;
360 GetPcSpBpAx(context, &pc, &sp, &bp, &ax);
361 Report("ERROR: AddressSanitizer crashed on unknown address %p"
362 " (pc %p sp %p bp %p ax %p T%d)\n",
363 addr, pc, sp, bp, ax,
364 asanThreadRegistry().GetCurrentTidOrMinusOne());
365 Printf("AddressSanitizer can not provide additional info. ABORTING\n");
366 GET_STACK_TRACE_WITH_PC_AND_BP(kStackTraceMax, false, pc, bp);
367 stack.PrintStack();
368 ShowStatsAndAbort();
369}
370
371static void ASAN_OnSIGILL(int, siginfo_t *siginfo, void *context) {
372 // Write the first message using the bullet-proof write.
Kostya Serebryanyde496f42011-12-28 22:58:01 +0000373 if (12 != AsanWrite(2, "ASAN:SIGILL\n", 12)) ASAN_DIE;
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000374 uintptr_t pc, sp, bp, ax;
375 GetPcSpBpAx(context, &pc, &sp, &bp, &ax);
376
377 uintptr_t addr = ax;
378
379 uint8_t *insn = (uint8_t*)pc;
380 CHECK(insn[0] == 0x0f && insn[1] == 0x0b); // ud2
381 unsigned access_size_and_type = insn[2] - 0x50;
382 CHECK(access_size_and_type < 16);
383 bool is_write = access_size_and_type & 8;
384 int access_size = 1 << (access_size_and_type & 7);
385 __asan_report_error(pc, bp, sp, addr, is_write, access_size);
386}
387
388// exported functions
Kostya Serebryany51e75c42011-12-28 00:59:39 +0000389#define ASAN_REPORT_ERROR(type, is_write, size) \
390extern "C" void __asan_report_ ## type ## size(uintptr_t addr) \
391 __attribute__((visibility("default"))) __attribute__((noinline)); \
392extern "C" void __asan_report_ ## type ## size(uintptr_t addr) { \
393 GET_BP_PC_SP; \
394 __asan_report_error(pc, bp, sp, addr, is_write, size); \
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000395}
396
397ASAN_REPORT_ERROR(load, false, 1)
398ASAN_REPORT_ERROR(load, false, 2)
399ASAN_REPORT_ERROR(load, false, 4)
400ASAN_REPORT_ERROR(load, false, 8)
401ASAN_REPORT_ERROR(load, false, 16)
402ASAN_REPORT_ERROR(store, true, 1)
403ASAN_REPORT_ERROR(store, true, 2)
404ASAN_REPORT_ERROR(store, true, 4)
405ASAN_REPORT_ERROR(store, true, 8)
406ASAN_REPORT_ERROR(store, true, 16)
407
408// Force the linker to keep the symbols for various ASan interface functions.
409// We want to keep those in the executable in order to let the instrumented
410// dynamic libraries access the symbol even if it is not used by the executable
411// itself. This should help if the build system is removing dead code at link
412// time.
Kostya Serebryany51e75c42011-12-28 00:59:39 +0000413static void force_interface_symbols() {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000414 volatile int fake_condition = 0; // prevent dead condition elimination.
415 if (fake_condition) {
416 __asan_report_load1(NULL);
417 __asan_report_load2(NULL);
418 __asan_report_load4(NULL);
419 __asan_report_load8(NULL);
420 __asan_report_load16(NULL);
421 __asan_report_store1(NULL);
422 __asan_report_store2(NULL);
423 __asan_report_store4(NULL);
424 __asan_report_store8(NULL);
425 __asan_report_store16(NULL);
426 __asan_register_global(0, 0, NULL);
427 __asan_register_globals(NULL, 0);
428 }
429}
430
431// -------------------------- Init ------------------- {{{1
432static int64_t IntFlagValue(const char *flags, const char *flag,
433 int64_t default_val) {
434 if (!flags) return default_val;
435 const char *str = strstr(flags, flag);
436 if (!str) return default_val;
437 return atoll(str + internal_strlen(flag));
438}
439
440static void asan_atexit() {
441 Printf("AddressSanitizer exit stats:\n");
442 __asan_print_accumulated_stats();
443}
444
445void CheckFailed(const char *cond, const char *file, int line) {
446 Report("CHECK failed: %s at %s:%d, pthread_self=%p\n",
447 cond, file, line, pthread_self());
448 PRINT_CURRENT_STACK();
449 ShowStatsAndAbort();
450}
451
452} // namespace __asan
453
454// -------------------------- Interceptors ------------------- {{{1
455using namespace __asan; // NOLINT
456
457#define OPERATOR_NEW_BODY \
458 GET_STACK_TRACE_HERE_FOR_MALLOC;\
459 return asan_memalign(0, size, &stack);
460
Kostya Serebryany9a200262011-12-27 23:11:09 +0000461#ifdef ANDROID
462void *operator new(size_t size) { OPERATOR_NEW_BODY; }
463void *operator new[](size_t size) { OPERATOR_NEW_BODY; }
464#else
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000465void *operator new(size_t size) throw(std::bad_alloc) { OPERATOR_NEW_BODY; }
466void *operator new[](size_t size) throw(std::bad_alloc) { OPERATOR_NEW_BODY; }
467void *operator new(size_t size, std::nothrow_t const&) throw()
468{ OPERATOR_NEW_BODY; }
469void *operator new[](size_t size, std::nothrow_t const&) throw()
470{ OPERATOR_NEW_BODY; }
Kostya Serebryany9a200262011-12-27 23:11:09 +0000471#endif
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000472
473#define OPERATOR_DELETE_BODY \
474 GET_STACK_TRACE_HERE_FOR_FREE(ptr);\
475 asan_free(ptr, &stack);
476
477void operator delete(void *ptr) throw() { OPERATOR_DELETE_BODY; }
478void operator delete[](void *ptr) throw() { OPERATOR_DELETE_BODY; }
479void operator delete(void *ptr, std::nothrow_t const&) throw()
480{ OPERATOR_DELETE_BODY; }
481void operator delete[](void *ptr, std::nothrow_t const&) throw()
482{ OPERATOR_DELETE_BODY;}
483
484extern "C"
485#ifndef __APPLE__
486__attribute__((visibility("default")))
487#endif
488int WRAP(pthread_create)(pthread_t *thread, const pthread_attr_t *attr,
489 void *(*start_routine) (void *), void *arg) {
490 GET_STACK_TRACE_HERE(kStackTraceMax, /*fast_unwind*/false);
491 AsanThread *t = (AsanThread*)asan_malloc(sizeof(AsanThread), &stack);
492 AsanThread *curr_thread = asanThreadRegistry().GetCurrent();
493 CHECK(curr_thread || asanThreadRegistry().IsCurrentThreadDying());
494 new(t) AsanThread(asanThreadRegistry().GetCurrentTidOrMinusOne(),
495 start_routine, arg, &stack);
496 return real_pthread_create(thread, attr, asan_thread_start, t);
497}
498
499static bool MySignal(int signum) {
500 if (FLAG_handle_sigill && signum == SIGILL) return true;
501 if (FLAG_handle_segv && signum == SIGSEGV) return true;
502#ifdef __APPLE__
503 if (FLAG_handle_segv && signum == SIGBUS) return true;
504#endif
505 return false;
506}
507
508static void MaybeInstallSigaction(int signum,
509 void (*handler)(int, siginfo_t *, void *)) {
510 if (!MySignal(signum))
511 return;
512 struct sigaction sigact;
513 real_memset(&sigact, 0, sizeof(sigact));
514 sigact.sa_sigaction = handler;
515 sigact.sa_flags = SA_SIGINFO;
516 CHECK(0 == real_sigaction(signum, &sigact, 0));
517}
518
519extern "C"
520sig_t WRAP(signal)(int signum, sig_t handler) {
521 if (!MySignal(signum)) {
522 return real_signal(signum, handler);
523 }
524 return NULL;
525}
526
527extern "C"
528int WRAP(sigaction)(int signum, const struct sigaction *act,
529 struct sigaction *oldact) {
530 if (!MySignal(signum)) {
531 return real_sigaction(signum, act, oldact);
532 }
533 return 0;
534}
535
536
537static void UnpoisonStackFromHereToTop() {
538 int local_stack;
539 AsanThread *curr_thread = asanThreadRegistry().GetCurrent();
540 CHECK(curr_thread);
541 uintptr_t top = curr_thread->stack_top();
542 uintptr_t bottom = ((uintptr_t)&local_stack - kPageSize) & ~(kPageSize-1);
Kostya Serebryany218a9b72011-11-30 18:50:23 +0000543 PoisonShadow(bottom, top - bottom, 0);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000544}
545
546extern "C" void WRAP(longjmp)(void *env, int val) {
547 UnpoisonStackFromHereToTop();
548 real_longjmp(env, val);
549}
550
551extern "C" void WRAP(_longjmp)(void *env, int val) {
552 UnpoisonStackFromHereToTop();
553 real__longjmp(env, val);
554}
555
556extern "C" void WRAP(siglongjmp)(void *env, int val) {
557 UnpoisonStackFromHereToTop();
558 real_siglongjmp(env, val);
559}
560
561extern "C" void __cxa_throw(void *a, void *b, void *c);
562
Kostya Serebryanyc6f22232011-12-08 18:30:42 +0000563#if ASAN_HAS_EXCEPTIONS == 1
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000564extern "C" void WRAP(__cxa_throw)(void *a, void *b, void *c) {
Kostya Serebryanyb3010e72011-12-05 17:56:32 +0000565 CHECK(&real___cxa_throw);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000566 UnpoisonStackFromHereToTop();
567 real___cxa_throw(a, b, c);
568}
569#endif
570
571extern "C" {
572// intercept mlock and friends.
573// Since asan maps 16T of RAM, mlock is completely unfriendly to asan.
574// All functions return 0 (success).
575static void MlockIsUnsupported() {
576 static bool printed = 0;
577 if (printed) return;
578 printed = true;
579 Printf("INFO: AddressSanitizer ignores mlock/mlockall/munlock/munlockall\n");
580}
581int mlock(const void *addr, size_t len) {
582 MlockIsUnsupported();
583 return 0;
584}
585int munlock(const void *addr, size_t len) {
586 MlockIsUnsupported();
587 return 0;
588}
589int mlockall(int flags) {
590 MlockIsUnsupported();
591 return 0;
592}
593int munlockall(void) {
594 MlockIsUnsupported();
595 return 0;
596}
597} // extern "C"
598
599// ---------------------- Interface ---------------- {{{1
600int __asan_set_error_exit_code(int exit_code) {
601 int old = FLAG_exitcode;
602 FLAG_exitcode = exit_code;
603 return old;
604}
605
606void __asan_report_error(uintptr_t pc, uintptr_t bp, uintptr_t sp,
607 uintptr_t addr, bool is_write, size_t access_size) {
608 // Do not print more than one report, otherwise they will mix up.
609 static int num_calls = 0;
610 if (AtomicInc(&num_calls) > 1) return;
611
612 Printf("=================================================================\n");
613 const char *bug_descr = "unknown-crash";
614 if (AddrIsInMem(addr)) {
615 uint8_t *shadow_addr = (uint8_t*)MemToShadow(addr);
Kostya Serebryanyacd5c612011-12-07 21:30:20 +0000616 // If we are accessing 16 bytes, look at the second shadow byte.
617 if (*shadow_addr == 0 && access_size > SHADOW_GRANULARITY)
618 shadow_addr++;
619 // If we are in the partial right redzone, look at the next shadow byte.
620 if (*shadow_addr > 0 && *shadow_addr < 128)
621 shadow_addr++;
622 switch (*shadow_addr) {
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000623 case kAsanHeapLeftRedzoneMagic:
624 case kAsanHeapRightRedzoneMagic:
625 bug_descr = "heap-buffer-overflow";
626 break;
627 case kAsanHeapFreeMagic:
628 bug_descr = "heap-use-after-free";
629 break;
630 case kAsanStackLeftRedzoneMagic:
631 bug_descr = "stack-buffer-underflow";
632 break;
633 case kAsanStackMidRedzoneMagic:
634 case kAsanStackRightRedzoneMagic:
635 case kAsanStackPartialRedzoneMagic:
636 bug_descr = "stack-buffer-overflow";
637 break;
638 case kAsanStackAfterReturnMagic:
639 bug_descr = "stack-use-after-return";
640 break;
641 case kAsanUserPoisonedMemoryMagic:
642 bug_descr = "use-after-poison";
643 break;
644 case kAsanGlobalRedzoneMagic:
645 bug_descr = "global-buffer-overflow";
646 break;
647 }
648 }
649
Kostya Serebryanyc4b34d92011-12-09 01:49:31 +0000650 AsanThread *curr_thread = asanThreadRegistry().GetCurrent();
651 int curr_tid = asanThreadRegistry().GetCurrentTidOrMinusOne();
652
653 if (curr_thread) {
654 // We started reporting an error message. Stop using the fake stack
655 // in case we will call an instrumented function from a symbolizer.
656 curr_thread->fake_stack().StopUsingFakeStack();
657 }
658
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000659 Report("ERROR: AddressSanitizer %s on address "
660 "%p at pc 0x%lx bp 0x%lx sp 0x%lx\n",
661 bug_descr, addr, pc, bp, sp);
662
663 Printf("%s of size %d at %p thread T%d\n",
664 access_size ? (is_write ? "WRITE" : "READ") : "ACCESS",
Kostya Serebryanyc4b34d92011-12-09 01:49:31 +0000665 access_size, addr, curr_tid);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000666
667 if (FLAG_debug) {
668 PrintBytes("PC: ", (uintptr_t*)pc);
669 }
670
671 GET_STACK_TRACE_WITH_PC_AND_BP(kStackTraceMax,
672 false, // FLAG_fast_unwind,
673 pc, bp);
674 stack.PrintStack();
675
676 CHECK(AddrIsInMem(addr));
677
678 DescribeAddress(addr, access_size);
679
680 uintptr_t shadow_addr = MemToShadow(addr);
681 Report("ABORTING\n");
682 __asan_print_accumulated_stats();
683 Printf("Shadow byte and word:\n");
684 Printf(" %p: %x\n", shadow_addr, *(unsigned char*)shadow_addr);
685 uintptr_t aligned_shadow = shadow_addr & ~(kWordSize - 1);
686 PrintBytes(" ", (uintptr_t*)(aligned_shadow));
687 Printf("More shadow bytes:\n");
688 PrintBytes(" ", (uintptr_t*)(aligned_shadow-4*kWordSize));
689 PrintBytes(" ", (uintptr_t*)(aligned_shadow-3*kWordSize));
690 PrintBytes(" ", (uintptr_t*)(aligned_shadow-2*kWordSize));
691 PrintBytes(" ", (uintptr_t*)(aligned_shadow-1*kWordSize));
692 PrintBytes("=>", (uintptr_t*)(aligned_shadow+0*kWordSize));
693 PrintBytes(" ", (uintptr_t*)(aligned_shadow+1*kWordSize));
694 PrintBytes(" ", (uintptr_t*)(aligned_shadow+2*kWordSize));
695 PrintBytes(" ", (uintptr_t*)(aligned_shadow+3*kWordSize));
696 PrintBytes(" ", (uintptr_t*)(aligned_shadow+4*kWordSize));
697 ASAN_DIE;
698}
699
700void __asan_init() {
701 if (asan_inited) return;
702 asan_init_is_running = true;
703
704 // Make sure we are not statically linked.
705 AsanDoesNotSupportStaticLinkage();
706
707 // flags
Kostya Serebryanyde496f42011-12-28 22:58:01 +0000708 const char *options = GetEnvFromProcSelfEnviron("ASAN_OPTIONS");
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000709 FLAG_malloc_context_size =
710 IntFlagValue(options, "malloc_context_size=", kMallocContextSize);
711 CHECK(FLAG_malloc_context_size <= kMallocContextSize);
712
713 FLAG_max_malloc_fill_size =
714 IntFlagValue(options, "max_malloc_fill_size=", 0);
715
716 FLAG_v = IntFlagValue(options, "verbosity=", 0);
717
718 FLAG_redzone = IntFlagValue(options, "redzone=", 128);
719 CHECK(FLAG_redzone >= 32);
720 CHECK((FLAG_redzone & (FLAG_redzone - 1)) == 0);
721
722 FLAG_atexit = IntFlagValue(options, "atexit=", 0);
723 FLAG_poison_shadow = IntFlagValue(options, "poison_shadow=", 1);
724 FLAG_report_globals = IntFlagValue(options, "report_globals=", 1);
725 FLAG_lazy_shadow = IntFlagValue(options, "lazy_shadow=", 0);
Kostya Serebryanyc6f22232011-12-08 18:30:42 +0000726 FLAG_handle_segv = IntFlagValue(options, "handle_segv=", ASAN_NEEDS_SEGV);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000727 FLAG_handle_sigill = IntFlagValue(options, "handle_sigill=", 0);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000728 FLAG_symbolize = IntFlagValue(options, "symbolize=", 1);
729 FLAG_demangle = IntFlagValue(options, "demangle=", 1);
730 FLAG_debug = IntFlagValue(options, "debug=", 0);
731 FLAG_replace_cfallocator = IntFlagValue(options, "replace_cfallocator=", 1);
732 FLAG_fast_unwind = IntFlagValue(options, "fast_unwind=", 1);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000733 FLAG_replace_str = IntFlagValue(options, "replace_str=", 1);
Kostya Serebryany0ffe35c2011-12-28 19:55:30 +0000734 FLAG_replace_intrin = IntFlagValue(options, "replace_intrin=", 1);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000735 FLAG_use_fake_stack = IntFlagValue(options, "use_fake_stack=", 1);
736 FLAG_exitcode = IntFlagValue(options, "exitcode=", EXIT_FAILURE);
737 FLAG_allow_user_poisoning = IntFlagValue(options,
738 "allow_user_poisoning=", 1);
739
740 if (FLAG_atexit) {
741 atexit(asan_atexit);
742 }
743
744 FLAG_quarantine_size =
745 IntFlagValue(options, "quarantine_size=", 1UL << 28);
746
747 // interceptors
748 InitializeAsanInterceptors();
749
750 ReplaceSystemMalloc();
751
752 INTERCEPT_FUNCTION(sigaction);
753 INTERCEPT_FUNCTION(signal);
754 INTERCEPT_FUNCTION(longjmp);
755 INTERCEPT_FUNCTION(_longjmp);
Kostya Serebryanyb3010e72011-12-05 17:56:32 +0000756 INTERCEPT_FUNCTION_IF_EXISTS(__cxa_throw);
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000757 INTERCEPT_FUNCTION(pthread_create);
758#ifdef __APPLE__
759 INTERCEPT_FUNCTION(dispatch_async_f);
760 INTERCEPT_FUNCTION(dispatch_sync_f);
761 INTERCEPT_FUNCTION(dispatch_after_f);
762 INTERCEPT_FUNCTION(dispatch_barrier_async_f);
763 INTERCEPT_FUNCTION(dispatch_group_async_f);
764 // We don't need to intercept pthread_workqueue_additem_np() to support the
765 // libdispatch API, but it helps us to debug the unsupported functions. Let's
766 // intercept it only during verbose runs.
767 if (FLAG_v >= 2) {
768 INTERCEPT_FUNCTION(pthread_workqueue_additem_np);
769 }
770#else
771 // On Darwin siglongjmp tailcalls longjmp, so we don't want to intercept it
772 // there.
773 INTERCEPT_FUNCTION(siglongjmp);
774#endif
775
776 MaybeInstallSigaction(SIGSEGV, ASAN_OnSIGSEGV);
777 MaybeInstallSigaction(SIGBUS, ASAN_OnSIGSEGV);
778 MaybeInstallSigaction(SIGILL, ASAN_OnSIGILL);
779
780 if (FLAG_v) {
781 Printf("|| `[%p, %p]` || HighMem ||\n", kHighMemBeg, kHighMemEnd);
782 Printf("|| `[%p, %p]` || HighShadow ||\n",
783 kHighShadowBeg, kHighShadowEnd);
784 Printf("|| `[%p, %p]` || ShadowGap ||\n",
785 kShadowGapBeg, kShadowGapEnd);
786 Printf("|| `[%p, %p]` || LowShadow ||\n",
787 kLowShadowBeg, kLowShadowEnd);
788 Printf("|| `[%p, %p]` || LowMem ||\n", kLowMemBeg, kLowMemEnd);
789 Printf("MemToShadow(shadow): %p %p %p %p\n",
790 MEM_TO_SHADOW(kLowShadowBeg),
791 MEM_TO_SHADOW(kLowShadowEnd),
792 MEM_TO_SHADOW(kHighShadowBeg),
793 MEM_TO_SHADOW(kHighShadowEnd));
794 Printf("red_zone=%ld\n", FLAG_redzone);
795 Printf("malloc_context_size=%ld\n", (int)FLAG_malloc_context_size);
796 Printf("fast_unwind=%d\n", (int)FLAG_fast_unwind);
797
798 Printf("SHADOW_SCALE: %lx\n", SHADOW_SCALE);
799 Printf("SHADOW_GRANULARITY: %lx\n", SHADOW_GRANULARITY);
800 Printf("SHADOW_OFFSET: %lx\n", SHADOW_OFFSET);
801 CHECK(SHADOW_SCALE >= 3 && SHADOW_SCALE <= 7);
802 }
803
804 if (__WORDSIZE == 64) {
805 // Disable core dumper -- it makes little sense to dump 16T+ core.
806 struct rlimit nocore;
807 nocore.rlim_cur = 0;
808 nocore.rlim_max = 0;
809 setrlimit(RLIMIT_CORE, &nocore);
810 }
811
812 {
813 if (!FLAG_lazy_shadow) {
814 if (kLowShadowBeg != kLowShadowEnd) {
815 // mmap the low shadow plus one page.
816 mmap_range(kLowShadowBeg - kPageSize, kLowShadowEnd, "LowShadow");
817 }
818 // mmap the high shadow.
819 mmap_range(kHighShadowBeg, kHighShadowEnd, "HighShadow");
820 }
821 // protect the gap
822 protect_range(kShadowGapBeg, kShadowGapEnd);
823 }
824
825 // On Linux AsanThread::ThreadStart() calls malloc() that's why asan_inited
826 // should be set to 1 prior to initializing the threads.
827 asan_inited = 1;
828 asan_init_is_running = false;
829
830 asanThreadRegistry().Init();
831 asanThreadRegistry().GetMain()->ThreadStart();
Kostya Serebryany51e75c42011-12-28 00:59:39 +0000832 force_interface_symbols(); // no-op.
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000833
834 if (FLAG_v) {
Kostya Serebryanyd6567c52011-12-01 21:40:52 +0000835 Report("AddressSanitizer Init done\n");
Kostya Serebryany1e172b42011-11-30 01:07:02 +0000836 }
837}