asan_rtl.cc revision 9b1b10193420f5adc769eda0d5bd548e429e0ce2
1//===-- asan_rtl.cc -------------------------------------------------------===// 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#include "asan_mapping.h" 20#include "asan_stack.h" 21#include "asan_stats.h" 22#include "asan_thread.h" 23#include "asan_thread_registry.h" 24#include "sanitizer_common/sanitizer_atomic.h" 25#include "sanitizer_common/sanitizer_flags.h" 26#include "sanitizer_common/sanitizer_libc.h" 27 28namespace __sanitizer { 29using namespace __asan; 30 31void Die() { 32 static atomic_uint32_t num_calls; 33 if (atomic_fetch_add(&num_calls, 1, memory_order_relaxed) != 0) { 34 // Don't die twice - run a busy loop. 35 while (1) { } 36 } 37 if (flags()->sleep_before_dying) { 38 Report("Sleeping for %zd second(s)\n", flags()->sleep_before_dying); 39 SleepForSeconds(flags()->sleep_before_dying); 40 } 41 if (flags()->unmap_shadow_on_exit) 42 UnmapOrDie((void*)kLowShadowBeg, kHighShadowEnd - kLowShadowBeg); 43 if (death_callback) 44 death_callback(); 45 if (flags()->abort_on_error) 46 Abort(); 47 Exit(flags()->exitcode); 48} 49 50void CheckFailed(const char *file, int line, const char *cond, u64 v1, u64 v2) { 51 AsanReport("AddressSanitizer CHECK failed: %s:%d \"%s\" (%zx, %zx)\n", 52 file, line, cond, (uptr)v1, (uptr)v2); 53 PRINT_CURRENT_STACK(); 54 ShowStatsAndAbort(); 55} 56 57} // namespace __sanitizer 58 59namespace __asan { 60 61// -------------------------- Flags ------------------------- {{{1 62static const int kMallocContextSize = 30; 63 64static Flags asan_flags; 65 66Flags *flags() { 67 return &asan_flags; 68} 69 70static void ParseFlagsFromString(Flags *f, const char *str) { 71 ParseFlag(str, &f->quarantine_size, "quarantine_size"); 72 ParseFlag(str, &f->symbolize, "symbolize"); 73 ParseFlag(str, &f->verbosity, "verbosity"); 74 ParseFlag(str, &f->redzone, "redzone"); 75 CHECK(f->redzone >= 16); 76 CHECK(IsPowerOfTwo(f->redzone)); 77 78 ParseFlag(str, &f->debug, "debug"); 79 ParseFlag(str, &f->report_globals, "report_globals"); 80 ParseFlag(str, &f->malloc_context_size, "malloc_context_size"); 81 CHECK(f->malloc_context_size <= kMallocContextSize); 82 83 ParseFlag(str, &f->replace_str, "replace_str"); 84 ParseFlag(str, &f->replace_intrin, "replace_intrin"); 85 ParseFlag(str, &f->replace_cfallocator, "replace_cfallocator"); 86 ParseFlag(str, &f->mac_ignore_invalid_free, "mac_ignore_invalid_free"); 87 ParseFlag(str, &f->use_fake_stack, "use_fake_stack"); 88 ParseFlag(str, &f->max_malloc_fill_size, "max_malloc_fill_size"); 89 ParseFlag(str, &f->exitcode, "exitcode"); 90 ParseFlag(str, &f->allow_user_poisoning, "allow_user_poisoning"); 91 ParseFlag(str, &f->sleep_before_dying, "sleep_before_dying"); 92 ParseFlag(str, &f->handle_segv, "handle_segv"); 93 ParseFlag(str, &f->use_sigaltstack, "use_sigaltstack"); 94 ParseFlag(str, &f->check_malloc_usable_size, "check_malloc_usable_size"); 95 ParseFlag(str, &f->unmap_shadow_on_exit, "unmap_shadow_on_exit"); 96 ParseFlag(str, &f->abort_on_error, "abort_on_error"); 97 ParseFlag(str, &f->atexit, "atexit"); 98 ParseFlag(str, &f->disable_core, "disable_core"); 99} 100 101void InitializeFlags(Flags *f, const char *env) { 102 internal_memset(f, 0, sizeof(*f)); 103 104 f->quarantine_size = (ASAN_LOW_MEMORY) ? 1UL << 24 : 1UL << 28; 105 f->symbolize = false; 106 f->verbosity = 0; 107 f->redzone = (ASAN_LOW_MEMORY) ? 64 : 128; 108 f->debug = false; 109 f->report_globals = 1; 110 f->malloc_context_size = kMallocContextSize; 111 f->replace_str = true; 112 f->replace_intrin = true; 113 f->replace_cfallocator = true; 114 f->mac_ignore_invalid_free = false; 115 f->use_fake_stack = true; 116 f->max_malloc_fill_size = 0; 117 f->exitcode = ASAN_DEFAULT_FAILURE_EXITCODE; 118 f->allow_user_poisoning = true; 119 f->sleep_before_dying = 0; 120 f->handle_segv = ASAN_NEEDS_SEGV; 121 f->use_sigaltstack = false; 122 f->check_malloc_usable_size = true; 123 f->unmap_shadow_on_exit = false; 124 f->abort_on_error = false; 125 f->atexit = false; 126 f->disable_core = (__WORDSIZE == 64); 127 128 // Override from user-specified string. 129#if !defined(_WIN32) 130 if (__asan_default_options) { 131 ParseFlagsFromString(f, __asan_default_options); 132 if (flags()->verbosity) { 133 Report("Using the defaults from __asan_default_options: %s\n", 134 __asan_default_options); 135 } 136 } 137#endif 138 139 // Override from command line. 140 ParseFlagsFromString(f, env); 141} 142 143// -------------------------- Globals --------------------- {{{1 144int asan_inited; 145bool asan_init_is_running; 146void (*death_callback)(void); 147static void (*error_report_callback)(const char*); 148char *error_message_buffer = 0; 149uptr error_message_buffer_pos = 0; 150uptr error_message_buffer_size = 0; 151 152// -------------------------- Misc ---------------- {{{1 153void ShowStatsAndAbort() { 154 __asan_print_accumulated_stats(); 155 Die(); 156} 157 158static void PrintBytes(const char *before, uptr *a) { 159 u8 *bytes = (u8*)a; 160 uptr byte_num = (__WORDSIZE) / 8; 161 AsanPrintf("%s%p:", before, (void*)a); 162 for (uptr i = 0; i < byte_num; i++) { 163 AsanPrintf(" %x%x", bytes[i] >> 4, bytes[i] & 15); 164 } 165 AsanPrintf("\n"); 166} 167 168void AppendToErrorMessageBuffer(const char *buffer) { 169 if (error_message_buffer) { 170 uptr length = internal_strlen(buffer); 171 CHECK_GE(error_message_buffer_size, error_message_buffer_pos); 172 uptr remaining = error_message_buffer_size - error_message_buffer_pos; 173 internal_strncpy(error_message_buffer + error_message_buffer_pos, 174 buffer, remaining); 175 error_message_buffer[error_message_buffer_size - 1] = '\0'; 176 // FIXME: reallocate the buffer instead of truncating the message. 177 error_message_buffer_pos += remaining > length ? length : remaining; 178 } 179} 180 181// ---------------------- mmap -------------------- {{{1 182// Reserve memory range [beg, end]. 183static void ReserveShadowMemoryRange(uptr beg, uptr end) { 184 CHECK((beg % kPageSize) == 0); 185 CHECK(((end + 1) % kPageSize) == 0); 186 uptr size = end - beg + 1; 187 void *res = MmapFixedNoReserve(beg, size); 188 CHECK(res == (void*)beg && "ReserveShadowMemoryRange failed"); 189} 190 191// ---------------------- LowLevelAllocator ------------- {{{1 192void *LowLevelAllocator::Allocate(uptr size) { 193 CHECK((size & (size - 1)) == 0 && "size must be a power of two"); 194 if (allocated_end_ - allocated_current_ < (sptr)size) { 195 uptr size_to_allocate = Max(size, kPageSize); 196 allocated_current_ = 197 (char*)MmapOrDie(size_to_allocate, __FUNCTION__); 198 allocated_end_ = allocated_current_ + size_to_allocate; 199 PoisonShadow((uptr)allocated_current_, size_to_allocate, 200 kAsanInternalHeapMagic); 201 } 202 CHECK(allocated_end_ - allocated_current_ >= (sptr)size); 203 void *res = allocated_current_; 204 allocated_current_ += size; 205 return res; 206} 207 208// ---------------------- DescribeAddress -------------------- {{{1 209static bool DescribeStackAddress(uptr addr, uptr access_size) { 210 AsanThread *t = asanThreadRegistry().FindThreadByStackAddress(addr); 211 if (!t) return false; 212 const sptr kBufSize = 4095; 213 char buf[kBufSize]; 214 uptr offset = 0; 215 const char *frame_descr = t->GetFrameNameByAddr(addr, &offset); 216 // This string is created by the compiler and has the following form: 217 // "FunctioName n alloc_1 alloc_2 ... alloc_n" 218 // where alloc_i looks like "offset size len ObjectName ". 219 CHECK(frame_descr); 220 // Report the function name and the offset. 221 const char *name_end = internal_strchr(frame_descr, ' '); 222 CHECK(name_end); 223 buf[0] = 0; 224 internal_strncat(buf, frame_descr, 225 Min(kBufSize, 226 static_cast<sptr>(name_end - frame_descr))); 227 AsanPrintf("Address %p is located at offset %zu " 228 "in frame <%s> of T%d's stack:\n", 229 (void*)addr, offset, buf, t->tid()); 230 // Report the number of stack objects. 231 char *p; 232 uptr n_objects = internal_simple_strtoll(name_end, &p, 10); 233 CHECK(n_objects > 0); 234 AsanPrintf(" This frame has %zu object(s):\n", n_objects); 235 // Report all objects in this frame. 236 for (uptr i = 0; i < n_objects; i++) { 237 uptr beg, size; 238 sptr len; 239 beg = internal_simple_strtoll(p, &p, 10); 240 size = internal_simple_strtoll(p, &p, 10); 241 len = internal_simple_strtoll(p, &p, 10); 242 if (beg <= 0 || size <= 0 || len < 0 || *p != ' ') { 243 AsanPrintf("AddressSanitizer can't parse the stack frame " 244 "descriptor: |%s|\n", frame_descr); 245 break; 246 } 247 p++; 248 buf[0] = 0; 249 internal_strncat(buf, p, Min(kBufSize, len)); 250 p += len; 251 AsanPrintf(" [%zu, %zu) '%s'\n", beg, beg + size, buf); 252 } 253 AsanPrintf("HINT: this may be a false positive if your program uses " 254 "some custom stack unwind mechanism\n" 255 " (longjmp and C++ exceptions *are* supported)\n"); 256 t->summary()->Announce(); 257 return true; 258} 259 260static NOINLINE void DescribeAddress(uptr addr, uptr access_size) { 261 // Check if this is a global. 262 if (DescribeAddrIfGlobal(addr)) 263 return; 264 265 if (DescribeStackAddress(addr, access_size)) 266 return; 267 268 // finally, check if this is a heap. 269 DescribeHeapAddress(addr, access_size); 270} 271 272// -------------------------- Run-time entry ------------------- {{{1 273// exported functions 274#define ASAN_REPORT_ERROR(type, is_write, size) \ 275extern "C" NOINLINE INTERFACE_ATTRIBUTE \ 276void __asan_report_ ## type ## size(uptr addr); \ 277void __asan_report_ ## type ## size(uptr addr) { \ 278 GET_CALLER_PC_BP_SP; \ 279 __asan_report_error(pc, bp, sp, addr, is_write, size); \ 280} 281 282ASAN_REPORT_ERROR(load, false, 1) 283ASAN_REPORT_ERROR(load, false, 2) 284ASAN_REPORT_ERROR(load, false, 4) 285ASAN_REPORT_ERROR(load, false, 8) 286ASAN_REPORT_ERROR(load, false, 16) 287ASAN_REPORT_ERROR(store, true, 1) 288ASAN_REPORT_ERROR(store, true, 2) 289ASAN_REPORT_ERROR(store, true, 4) 290ASAN_REPORT_ERROR(store, true, 8) 291ASAN_REPORT_ERROR(store, true, 16) 292 293// Force the linker to keep the symbols for various ASan interface functions. 294// We want to keep those in the executable in order to let the instrumented 295// dynamic libraries access the symbol even if it is not used by the executable 296// itself. This should help if the build system is removing dead code at link 297// time. 298static NOINLINE void force_interface_symbols() { 299 volatile int fake_condition = 0; // prevent dead condition elimination. 300 if (fake_condition) { 301 __asan_report_load1(0); 302 __asan_report_load2(0); 303 __asan_report_load4(0); 304 __asan_report_load8(0); 305 __asan_report_load16(0); 306 __asan_report_store1(0); 307 __asan_report_store2(0); 308 __asan_report_store4(0); 309 __asan_report_store8(0); 310 __asan_report_store16(0); 311 __asan_register_global(0, 0, 0); 312 __asan_register_globals(0, 0); 313 __asan_unregister_globals(0, 0); 314 __asan_set_death_callback(0); 315 __asan_set_error_report_callback(0); 316 __asan_handle_no_return(); 317 } 318} 319 320// -------------------------- Init ------------------- {{{1 321static void asan_atexit() { 322 AsanPrintf("AddressSanitizer exit stats:\n"); 323 __asan_print_accumulated_stats(); 324} 325 326} // namespace __asan 327 328// ---------------------- Interface ---------------- {{{1 329using namespace __asan; // NOLINT 330 331int __asan_set_error_exit_code(int exit_code) { 332 int old = flags()->exitcode; 333 flags()->exitcode = exit_code; 334 return old; 335} 336 337void NOINLINE __asan_handle_no_return() { 338 int local_stack; 339 AsanThread *curr_thread = asanThreadRegistry().GetCurrent(); 340 CHECK(curr_thread); 341 uptr top = curr_thread->stack_top(); 342 uptr bottom = ((uptr)&local_stack - kPageSize) & ~(kPageSize-1); 343 PoisonShadow(bottom, top - bottom, 0); 344} 345 346void NOINLINE __asan_set_death_callback(void (*callback)(void)) { 347 death_callback = callback; 348} 349 350void NOINLINE __asan_set_error_report_callback(void (*callback)(const char*)) { 351 error_report_callback = callback; 352 if (callback) { 353 error_message_buffer_size = 1 << 16; 354 error_message_buffer = 355 (char*)MmapOrDie(error_message_buffer_size, __FUNCTION__); 356 error_message_buffer_pos = 0; 357 } 358} 359 360void __asan_report_error(uptr pc, uptr bp, uptr sp, 361 uptr addr, bool is_write, uptr access_size) { 362 // Do not print more than one report, otherwise they will mix up. 363 static atomic_uint32_t num_calls; 364 if (atomic_fetch_add(&num_calls, 1, memory_order_relaxed) != 0) return; 365 366 AsanPrintf("====================================================" 367 "=============\n"); 368 const char *bug_descr = "unknown-crash"; 369 if (AddrIsInMem(addr)) { 370 u8 *shadow_addr = (u8*)MemToShadow(addr); 371 // If we are accessing 16 bytes, look at the second shadow byte. 372 if (*shadow_addr == 0 && access_size > SHADOW_GRANULARITY) 373 shadow_addr++; 374 // If we are in the partial right redzone, look at the next shadow byte. 375 if (*shadow_addr > 0 && *shadow_addr < 128) 376 shadow_addr++; 377 switch (*shadow_addr) { 378 case kAsanHeapLeftRedzoneMagic: 379 case kAsanHeapRightRedzoneMagic: 380 bug_descr = "heap-buffer-overflow"; 381 break; 382 case kAsanHeapFreeMagic: 383 bug_descr = "heap-use-after-free"; 384 break; 385 case kAsanStackLeftRedzoneMagic: 386 bug_descr = "stack-buffer-underflow"; 387 break; 388 case kAsanStackMidRedzoneMagic: 389 case kAsanStackRightRedzoneMagic: 390 case kAsanStackPartialRedzoneMagic: 391 bug_descr = "stack-buffer-overflow"; 392 break; 393 case kAsanStackAfterReturnMagic: 394 bug_descr = "stack-use-after-return"; 395 break; 396 case kAsanUserPoisonedMemoryMagic: 397 bug_descr = "use-after-poison"; 398 break; 399 case kAsanGlobalRedzoneMagic: 400 bug_descr = "global-buffer-overflow"; 401 break; 402 } 403 } 404 405 AsanThread *curr_thread = asanThreadRegistry().GetCurrent(); 406 u32 curr_tid = asanThreadRegistry().GetCurrentTidOrInvalid(); 407 408 if (curr_thread) { 409 // We started reporting an error message. Stop using the fake stack 410 // in case we will call an instrumented function from a symbolizer. 411 curr_thread->fake_stack().StopUsingFakeStack(); 412 } 413 414 AsanReport("ERROR: AddressSanitizer %s on address " 415 "%p at pc 0x%zx bp 0x%zx sp 0x%zx\n", 416 bug_descr, (void*)addr, pc, bp, sp); 417 418 AsanPrintf("%s of size %zu at %p thread T%d\n", 419 access_size ? (is_write ? "WRITE" : "READ") : "ACCESS", 420 access_size, (void*)addr, curr_tid); 421 422 if (flags()->debug) { 423 PrintBytes("PC: ", (uptr*)pc); 424 } 425 426 GET_STACK_TRACE_WITH_PC_AND_BP(kStackTraceMax, pc, bp); 427 stack.PrintStack(); 428 429 CHECK(AddrIsInMem(addr)); 430 431 DescribeAddress(addr, access_size); 432 433 uptr shadow_addr = MemToShadow(addr); 434 AsanReport("ABORTING\n"); 435 __asan_print_accumulated_stats(); 436 AsanPrintf("Shadow byte and word:\n"); 437 AsanPrintf(" %p: %x\n", (void*)shadow_addr, *(unsigned char*)shadow_addr); 438 uptr aligned_shadow = shadow_addr & ~(kWordSize - 1); 439 PrintBytes(" ", (uptr*)(aligned_shadow)); 440 AsanPrintf("More shadow bytes:\n"); 441 PrintBytes(" ", (uptr*)(aligned_shadow-4*kWordSize)); 442 PrintBytes(" ", (uptr*)(aligned_shadow-3*kWordSize)); 443 PrintBytes(" ", (uptr*)(aligned_shadow-2*kWordSize)); 444 PrintBytes(" ", (uptr*)(aligned_shadow-1*kWordSize)); 445 PrintBytes("=>", (uptr*)(aligned_shadow+0*kWordSize)); 446 PrintBytes(" ", (uptr*)(aligned_shadow+1*kWordSize)); 447 PrintBytes(" ", (uptr*)(aligned_shadow+2*kWordSize)); 448 PrintBytes(" ", (uptr*)(aligned_shadow+3*kWordSize)); 449 PrintBytes(" ", (uptr*)(aligned_shadow+4*kWordSize)); 450 if (error_report_callback) { 451 error_report_callback(error_message_buffer); 452 } 453 Die(); 454} 455 456 457void __asan_init() { 458 if (asan_inited) return; 459 asan_init_is_running = true; 460 461 // Make sure we are not statically linked. 462 AsanDoesNotSupportStaticLinkage(); 463 464 // Initialize flags. 465 const char *options = GetEnv("ASAN_OPTIONS"); 466 InitializeFlags(flags(), options); 467 468 if (flags()->verbosity && options) { 469 Report("Parsed ASAN_OPTIONS: %s\n", options); 470 } 471 472 if (flags()->atexit) { 473 Atexit(asan_atexit); 474 } 475 476 // interceptors 477 InitializeAsanInterceptors(); 478 479 ReplaceSystemMalloc(); 480 ReplaceOperatorsNewAndDelete(); 481 482 if (flags()->verbosity) { 483 Printf("|| `[%p, %p]` || HighMem ||\n", 484 (void*)kHighMemBeg, (void*)kHighMemEnd); 485 Printf("|| `[%p, %p]` || HighShadow ||\n", 486 (void*)kHighShadowBeg, (void*)kHighShadowEnd); 487 Printf("|| `[%p, %p]` || ShadowGap ||\n", 488 (void*)kShadowGapBeg, (void*)kShadowGapEnd); 489 Printf("|| `[%p, %p]` || LowShadow ||\n", 490 (void*)kLowShadowBeg, (void*)kLowShadowEnd); 491 Printf("|| `[%p, %p]` || LowMem ||\n", 492 (void*)kLowMemBeg, (void*)kLowMemEnd); 493 Printf("MemToShadow(shadow): %p %p %p %p\n", 494 (void*)MEM_TO_SHADOW(kLowShadowBeg), 495 (void*)MEM_TO_SHADOW(kLowShadowEnd), 496 (void*)MEM_TO_SHADOW(kHighShadowBeg), 497 (void*)MEM_TO_SHADOW(kHighShadowEnd)); 498 Printf("red_zone=%zu\n", (uptr)flags()->redzone); 499 Printf("malloc_context_size=%zu\n", (uptr)flags()->malloc_context_size); 500 501 Printf("SHADOW_SCALE: %zx\n", (uptr)SHADOW_SCALE); 502 Printf("SHADOW_GRANULARITY: %zx\n", (uptr)SHADOW_GRANULARITY); 503 Printf("SHADOW_OFFSET: %zx\n", (uptr)SHADOW_OFFSET); 504 CHECK(SHADOW_SCALE >= 3 && SHADOW_SCALE <= 7); 505 } 506 507 if (flags()->disable_core) { 508 DisableCoreDumper(); 509 } 510 511 uptr shadow_start = kLowShadowBeg; 512 if (kLowShadowBeg > 0) shadow_start -= kMmapGranularity; 513 uptr shadow_end = kHighShadowEnd; 514 if (MemoryRangeIsAvailable(shadow_start, shadow_end)) { 515 if (kLowShadowBeg != kLowShadowEnd) { 516 // mmap the low shadow plus at least one page. 517 ReserveShadowMemoryRange(kLowShadowBeg - kMmapGranularity, kLowShadowEnd); 518 } 519 // mmap the high shadow. 520 ReserveShadowMemoryRange(kHighShadowBeg, kHighShadowEnd); 521 // protect the gap 522 void *prot = Mprotect(kShadowGapBeg, kShadowGapEnd - kShadowGapBeg + 1); 523 CHECK(prot == (void*)kShadowGapBeg); 524 } else { 525 Report("Shadow memory range interleaves with an existing memory mapping. " 526 "ASan cannot proceed correctly. ABORTING.\n"); 527 DumpProcessMap(); 528 Die(); 529 } 530 531 InstallSignalHandlers(); 532 533 // On Linux AsanThread::ThreadStart() calls malloc() that's why asan_inited 534 // should be set to 1 prior to initializing the threads. 535 asan_inited = 1; 536 asan_init_is_running = false; 537 538 asanThreadRegistry().Init(); 539 asanThreadRegistry().GetMain()->ThreadStart(); 540 force_interface_symbols(); // no-op. 541 542 if (flags()->verbosity) { 543 Report("AddressSanitizer Init done\n"); 544 } 545} 546 547#if defined(ASAN_USE_PREINIT_ARRAY) 548 // On Linux, we force __asan_init to be called before anyone else 549 // by placing it into .preinit_array section. 550 // FIXME: do we have anything like this on Mac? 551 __attribute__((section(".preinit_array"))) 552 typeof(__asan_init) *__asan_preinit =__asan_init; 553#elif defined(_WIN32) && defined(_DLL) 554 // On Windows, when using dynamic CRT (/MD), we can put a pointer 555 // to __asan_init into the global list of C initializers. 556 // See crt0dat.c in the CRT sources for the details. 557 #pragma section(".CRT$XIB", long, read) // NOLINT 558 __declspec(allocate(".CRT$XIB")) void (*__asan_preinit)() = __asan_init; 559#endif 560