asan_rtl.cc revision e31eca900a1f8849af75100c2d92e838d79d0920
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_internal.h" 17#include "asan_mapping.h" 18#include "asan_report.h" 19#include "asan_stack.h" 20#include "asan_stats.h" 21#include "asan_thread.h" 22#include "asan_thread_registry.h" 23#include "sanitizer_common/sanitizer_atomic.h" 24#include "sanitizer_common/sanitizer_flags.h" 25#include "sanitizer_common/sanitizer_libc.h" 26#include "sanitizer_common/sanitizer_symbolizer.h" 27 28namespace __asan { 29 30uptr AsanMappingProfile[kAsanMappingProfileSize]; 31 32static void AsanDie() { 33 static atomic_uint32_t num_calls; 34 if (atomic_fetch_add(&num_calls, 1, memory_order_relaxed) != 0) { 35 // Don't die twice - run a busy loop. 36 while (1) { } 37 } 38 if (flags()->sleep_before_dying) { 39 Report("Sleeping for %d second(s)\n", flags()->sleep_before_dying); 40 SleepForSeconds(flags()->sleep_before_dying); 41 } 42 if (flags()->unmap_shadow_on_exit) { 43 if (kMidMemBeg) { 44 UnmapOrDie((void*)kLowShadowBeg, kMidMemBeg - kLowShadowBeg); 45 UnmapOrDie((void*)kMidMemEnd, kHighShadowEnd - kMidMemEnd); 46 } else { 47 UnmapOrDie((void*)kLowShadowBeg, kHighShadowEnd - kLowShadowBeg); 48 } 49 } 50 if (death_callback) 51 death_callback(); 52 if (flags()->abort_on_error) 53 Abort(); 54 Exit(flags()->exitcode); 55} 56 57static void AsanCheckFailed(const char *file, int line, const char *cond, 58 u64 v1, u64 v2) { 59 Report("AddressSanitizer CHECK failed: %s:%d \"%s\" (0x%zx, 0x%zx)\n", 60 file, line, cond, (uptr)v1, (uptr)v2); 61 // FIXME: check for infinite recursion without a thread-local counter here. 62 PRINT_CURRENT_STACK(); 63 Die(); 64} 65 66// -------------------------- Flags ------------------------- {{{1 67static const int kDeafultMallocContextSize = 30; 68 69static Flags asan_flags; 70 71Flags *flags() { 72 return &asan_flags; 73} 74 75static const char *MaybeCallAsanDefaultOptions() { 76 return (&__asan_default_options) ? __asan_default_options() : ""; 77} 78 79static void ParseFlagsFromString(Flags *f, const char *str) { 80 ParseFlag(str, &f->quarantine_size, "quarantine_size"); 81 ParseFlag(str, &f->symbolize, "symbolize"); 82 ParseFlag(str, &f->verbosity, "verbosity"); 83 ParseFlag(str, &f->redzone, "redzone"); 84 CHECK(f->redzone >= 16); 85 CHECK(IsPowerOfTwo(f->redzone)); 86 87 ParseFlag(str, &f->debug, "debug"); 88 ParseFlag(str, &f->report_globals, "report_globals"); 89 ParseFlag(str, &f->check_initialization_order, "initialization_order"); 90 ParseFlag(str, &f->malloc_context_size, "malloc_context_size"); 91 CHECK((uptr)f->malloc_context_size <= kStackTraceMax); 92 93 ParseFlag(str, &f->replace_str, "replace_str"); 94 ParseFlag(str, &f->replace_intrin, "replace_intrin"); 95 ParseFlag(str, &f->mac_ignore_invalid_free, "mac_ignore_invalid_free"); 96 ParseFlag(str, &f->use_fake_stack, "use_fake_stack"); 97 ParseFlag(str, &f->max_malloc_fill_size, "max_malloc_fill_size"); 98 ParseFlag(str, &f->exitcode, "exitcode"); 99 ParseFlag(str, &f->allow_user_poisoning, "allow_user_poisoning"); 100 ParseFlag(str, &f->sleep_before_dying, "sleep_before_dying"); 101 ParseFlag(str, &f->handle_segv, "handle_segv"); 102 ParseFlag(str, &f->use_sigaltstack, "use_sigaltstack"); 103 ParseFlag(str, &f->check_malloc_usable_size, "check_malloc_usable_size"); 104 ParseFlag(str, &f->unmap_shadow_on_exit, "unmap_shadow_on_exit"); 105 ParseFlag(str, &f->abort_on_error, "abort_on_error"); 106 ParseFlag(str, &f->print_stats, "print_stats"); 107 ParseFlag(str, &f->print_legend, "print_legend"); 108 ParseFlag(str, &f->atexit, "atexit"); 109 ParseFlag(str, &f->disable_core, "disable_core"); 110 ParseFlag(str, &f->strip_path_prefix, "strip_path_prefix"); 111 ParseFlag(str, &f->allow_reexec, "allow_reexec"); 112 ParseFlag(str, &f->print_full_thread_history, "print_full_thread_history"); 113 ParseFlag(str, &f->log_path, "log_path"); 114 ParseFlag(str, &f->fast_unwind_on_fatal, "fast_unwind_on_fatal"); 115 ParseFlag(str, &f->fast_unwind_on_malloc, "fast_unwind_on_malloc"); 116 ParseFlag(str, &f->poison_heap, "poison_heap"); 117 ParseFlag(str, &f->alloc_dealloc_mismatch, "alloc_dealloc_mismatch"); 118 ParseFlag(str, &f->use_stack_depot, "use_stack_depot"); 119} 120 121void InitializeFlags(Flags *f, const char *env) { 122 internal_memset(f, 0, sizeof(*f)); 123 124 f->quarantine_size = (ASAN_LOW_MEMORY) ? 1UL << 26 : 1UL << 28; 125 f->symbolize = false; 126 f->verbosity = 0; 127 f->redzone = ASAN_ALLOCATOR_VERSION == 2 ? 16 : (ASAN_LOW_MEMORY) ? 64 : 128; 128 f->debug = false; 129 f->report_globals = 1; 130 f->check_initialization_order = true; 131 f->malloc_context_size = kDeafultMallocContextSize; 132 f->replace_str = true; 133 f->replace_intrin = true; 134 f->mac_ignore_invalid_free = false; 135 f->use_fake_stack = true; 136 f->max_malloc_fill_size = 0; 137 f->exitcode = ASAN_DEFAULT_FAILURE_EXITCODE; 138 f->allow_user_poisoning = true; 139 f->sleep_before_dying = 0; 140 f->handle_segv = ASAN_NEEDS_SEGV; 141 f->use_sigaltstack = false; 142 f->check_malloc_usable_size = true; 143 f->unmap_shadow_on_exit = false; 144 f->abort_on_error = false; 145 f->print_stats = false; 146 f->print_legend = true; 147 f->atexit = false; 148 f->disable_core = (SANITIZER_WORDSIZE == 64); 149 f->strip_path_prefix = ""; 150 f->allow_reexec = true; 151 f->print_full_thread_history = true; 152 f->log_path = 0; 153 f->fast_unwind_on_fatal = false; 154 f->fast_unwind_on_malloc = true; 155 f->poison_heap = true; 156 f->alloc_dealloc_mismatch = true; 157 f->use_stack_depot = true; // Only affects allocator2. 158 159 // Override from user-specified string. 160 ParseFlagsFromString(f, MaybeCallAsanDefaultOptions()); 161 if (flags()->verbosity) { 162 Report("Using the defaults from __asan_default_options: %s\n", 163 MaybeCallAsanDefaultOptions()); 164 } 165 166 // Override from command line. 167 ParseFlagsFromString(f, env); 168} 169 170// -------------------------- Globals --------------------- {{{1 171int asan_inited; 172bool asan_init_is_running; 173void (*death_callback)(void); 174 175#if !ASAN_FIXED_MAPPING 176uptr kHighMemEnd, kMidMemBeg, kMidMemEnd; 177#endif 178 179// -------------------------- Misc ---------------- {{{1 180void ShowStatsAndAbort() { 181 __asan_print_accumulated_stats(); 182 Die(); 183} 184 185// ---------------------- mmap -------------------- {{{1 186// Reserve memory range [beg, end]. 187static void ReserveShadowMemoryRange(uptr beg, uptr end) { 188 CHECK((beg % GetPageSizeCached()) == 0); 189 CHECK(((end + 1) % GetPageSizeCached()) == 0); 190 uptr size = end - beg + 1; 191 void *res = MmapFixedNoReserve(beg, size); 192 if (res != (void*)beg) { 193 Report("ReserveShadowMemoryRange failed while trying to map 0x%zx bytes. " 194 "Perhaps you're using ulimit -v\n", size); 195 Abort(); 196 } 197} 198 199// --------------- LowLevelAllocateCallbac ---------- {{{1 200static void OnLowLevelAllocate(uptr ptr, uptr size) { 201 PoisonShadow(ptr, size, kAsanInternalHeapMagic); 202} 203 204// -------------------------- Run-time entry ------------------- {{{1 205// exported functions 206#define ASAN_REPORT_ERROR(type, is_write, size) \ 207extern "C" NOINLINE INTERFACE_ATTRIBUTE \ 208void __asan_report_ ## type ## size(uptr addr); \ 209void __asan_report_ ## type ## size(uptr addr) { \ 210 GET_CALLER_PC_BP_SP; \ 211 __asan_report_error(pc, bp, sp, addr, is_write, size); \ 212} 213 214ASAN_REPORT_ERROR(load, false, 1) 215ASAN_REPORT_ERROR(load, false, 2) 216ASAN_REPORT_ERROR(load, false, 4) 217ASAN_REPORT_ERROR(load, false, 8) 218ASAN_REPORT_ERROR(load, false, 16) 219ASAN_REPORT_ERROR(store, true, 1) 220ASAN_REPORT_ERROR(store, true, 2) 221ASAN_REPORT_ERROR(store, true, 4) 222ASAN_REPORT_ERROR(store, true, 8) 223ASAN_REPORT_ERROR(store, true, 16) 224 225// Force the linker to keep the symbols for various ASan interface functions. 226// We want to keep those in the executable in order to let the instrumented 227// dynamic libraries access the symbol even if it is not used by the executable 228// itself. This should help if the build system is removing dead code at link 229// time. 230static NOINLINE void force_interface_symbols() { 231 volatile int fake_condition = 0; // prevent dead condition elimination. 232 // __asan_report_* functions are noreturn, so we need a switch to prevent 233 // the compiler from removing any of them. 234 switch (fake_condition) { 235 case 1: __asan_report_load1(0); break; 236 case 2: __asan_report_load2(0); break; 237 case 3: __asan_report_load4(0); break; 238 case 4: __asan_report_load8(0); break; 239 case 5: __asan_report_load16(0); break; 240 case 6: __asan_report_store1(0); break; 241 case 7: __asan_report_store2(0); break; 242 case 8: __asan_report_store4(0); break; 243 case 9: __asan_report_store8(0); break; 244 case 10: __asan_report_store16(0); break; 245 case 12: __asan_register_globals(0, 0); break; 246 case 13: __asan_unregister_globals(0, 0); break; 247 case 14: __asan_set_death_callback(0); break; 248 case 15: __asan_set_error_report_callback(0); break; 249 case 16: __asan_handle_no_return(); break; 250 case 17: __asan_address_is_poisoned(0); break; 251 case 18: __asan_get_allocated_size(0); break; 252 case 19: __asan_get_current_allocated_bytes(); break; 253 case 20: __asan_get_estimated_allocated_size(0); break; 254 case 21: __asan_get_free_bytes(); break; 255 case 22: __asan_get_heap_size(); break; 256 case 23: __asan_get_ownership(0); break; 257 case 24: __asan_get_unmapped_bytes(); break; 258 case 25: __asan_poison_memory_region(0, 0); break; 259 case 26: __asan_unpoison_memory_region(0, 0); break; 260 case 27: __asan_set_error_exit_code(0); break; 261 case 28: __asan_stack_free(0, 0, 0); break; 262 case 29: __asan_stack_malloc(0, 0); break; 263 case 30: __asan_before_dynamic_init(0, 0); break; 264 case 31: __asan_after_dynamic_init(); break; 265 case 32: __asan_poison_stack_memory(0, 0); break; 266 case 33: __asan_unpoison_stack_memory(0, 0); break; 267 case 34: __asan_region_is_poisoned(0, 0); break; 268 case 35: __asan_describe_address(0); break; 269 } 270} 271 272static void asan_atexit() { 273 Printf("AddressSanitizer exit stats:\n"); 274 __asan_print_accumulated_stats(); 275 // Print AsanMappingProfile. 276 for (uptr i = 0; i < kAsanMappingProfileSize; i++) { 277 if (AsanMappingProfile[i] == 0) continue; 278 Printf("asan_mapping.h:%zd -- %zd\n", i, AsanMappingProfile[i]); 279 } 280} 281 282static void InitializeHighMemEnd() { 283#if !ASAN_FIXED_MAPPING 284#if SANITIZER_WORDSIZE == 64 285# if defined(__powerpc64__) 286 // FIXME: 287 // On PowerPC64 we have two different address space layouts: 44- and 46-bit. 288 // We somehow need to figure our which one we are using now and choose 289 // one of 0x00000fffffffffffUL and 0x00003fffffffffffUL. 290 // Note that with 'ulimit -s unlimited' the stack is moved away from the top 291 // of the address space, so simply checking the stack address is not enough. 292 kHighMemEnd = (1ULL << 44) - 1; // 0x00000fffffffffffUL 293# else 294 kHighMemEnd = (1ULL << 47) - 1; // 0x00007fffffffffffUL; 295# endif 296#else // SANITIZER_WORDSIZE == 32 297 kHighMemEnd = (1ULL << 32) - 1; // 0xffffffff; 298#endif // SANITIZER_WORDSIZE 299#endif // !ASAN_FIXED_MAPPING 300} 301 302static void ProtectGap(uptr a, uptr size) { 303 CHECK_EQ(a, (uptr)Mprotect(a, size)); 304} 305 306static void PrintAddressSpaceLayout() { 307 Printf("|| `[%p, %p]` || HighMem ||\n", 308 (void*)kHighMemBeg, (void*)kHighMemEnd); 309 Printf("|| `[%p, %p]` || HighShadow ||\n", 310 (void*)kHighShadowBeg, (void*)kHighShadowEnd); 311 if (kMidMemBeg) { 312 Printf("|| `[%p, %p]` || ShadowGap3 ||\n", 313 (void*)kShadowGap3Beg, (void*)kShadowGap3End); 314 Printf("|| `[%p, %p]` || MidMem ||\n", 315 (void*)kMidMemBeg, (void*)kMidMemEnd); 316 Printf("|| `[%p, %p]` || ShadowGap2 ||\n", 317 (void*)kShadowGap2Beg, (void*)kShadowGap2End); 318 Printf("|| `[%p, %p]` || MidShadow ||\n", 319 (void*)kMidShadowBeg, (void*)kMidShadowEnd); 320 } 321 Printf("|| `[%p, %p]` || ShadowGap ||\n", 322 (void*)kShadowGapBeg, (void*)kShadowGapEnd); 323 if (kLowShadowBeg) { 324 Printf("|| `[%p, %p]` || LowShadow ||\n", 325 (void*)kLowShadowBeg, (void*)kLowShadowEnd); 326 Printf("|| `[%p, %p]` || LowMem ||\n", 327 (void*)kLowMemBeg, (void*)kLowMemEnd); 328 } 329 Printf("MemToShadow(shadow): %p %p %p %p", 330 (void*)MEM_TO_SHADOW(kLowShadowBeg), 331 (void*)MEM_TO_SHADOW(kLowShadowEnd), 332 (void*)MEM_TO_SHADOW(kHighShadowBeg), 333 (void*)MEM_TO_SHADOW(kHighShadowEnd)); 334 if (kMidMemBeg) { 335 Printf(" %p %p", 336 (void*)MEM_TO_SHADOW(kMidShadowBeg), 337 (void*)MEM_TO_SHADOW(kMidShadowEnd)); 338 } 339 Printf("\n"); 340 Printf("red_zone=%zu\n", (uptr)flags()->redzone); 341 Printf("malloc_context_size=%zu\n", (uptr)flags()->malloc_context_size); 342 343 Printf("SHADOW_SCALE: %zx\n", (uptr)SHADOW_SCALE); 344 Printf("SHADOW_GRANULARITY: %zx\n", (uptr)SHADOW_GRANULARITY); 345 Printf("SHADOW_OFFSET: %zx\n", (uptr)SHADOW_OFFSET); 346 CHECK(SHADOW_SCALE >= 3 && SHADOW_SCALE <= 7); 347 if (kMidMemBeg) 348 CHECK(kMidShadowBeg > kLowShadowEnd && 349 kMidMemBeg > kMidShadowEnd && 350 kHighShadowBeg > kMidMemEnd); 351} 352 353} // namespace __asan 354 355// ---------------------- Interface ---------------- {{{1 356using namespace __asan; // NOLINT 357 358#if !SANITIZER_SUPPORTS_WEAK_HOOKS 359extern "C" { 360SANITIZER_WEAK_ATTRIBUTE SANITIZER_INTERFACE_ATTRIBUTE 361const char* __asan_default_options() { return ""; } 362} // extern "C" 363#endif 364 365int NOINLINE __asan_set_error_exit_code(int exit_code) { 366 int old = flags()->exitcode; 367 flags()->exitcode = exit_code; 368 return old; 369} 370 371void NOINLINE __asan_handle_no_return() { 372 int local_stack; 373 AsanThread *curr_thread = asanThreadRegistry().GetCurrent(); 374 CHECK(curr_thread); 375 uptr PageSize = GetPageSizeCached(); 376 uptr top = curr_thread->stack_top(); 377 uptr bottom = ((uptr)&local_stack - PageSize) & ~(PageSize-1); 378 PoisonShadow(bottom, top - bottom, 0); 379} 380 381void NOINLINE __asan_set_death_callback(void (*callback)(void)) { 382 death_callback = callback; 383} 384 385void __asan_init() { 386 if (asan_inited) return; 387 SanitizerToolName = "AddressSanitizer"; 388 CHECK(!asan_init_is_running && "ASan init calls itself!"); 389 asan_init_is_running = true; 390 InitializeHighMemEnd(); 391 392 // Make sure we are not statically linked. 393 AsanDoesNotSupportStaticLinkage(); 394 395 // Install tool-specific callbacks in sanitizer_common. 396 SetDieCallback(AsanDie); 397 SetCheckFailedCallback(AsanCheckFailed); 398 SetPrintfAndReportCallback(AppendToErrorMessageBuffer); 399 400 // Initialize flags. This must be done early, because most of the 401 // initialization steps look at flags(). 402 const char *options = GetEnv("ASAN_OPTIONS"); 403 InitializeFlags(flags(), options); 404 __sanitizer_set_report_path(flags()->log_path); 405 406 if (flags()->verbosity && options) { 407 Report("Parsed ASAN_OPTIONS: %s\n", options); 408 } 409 410 // Re-exec ourselves if we need to set additional env or command line args. 411 MaybeReexec(); 412 413 // Setup internal allocator callback. 414 SetLowLevelAllocateCallback(OnLowLevelAllocate); 415 416 if (flags()->atexit) { 417 Atexit(asan_atexit); 418 } 419 420 // interceptors 421 InitializeAsanInterceptors(); 422 423 ReplaceSystemMalloc(); 424 ReplaceOperatorsNewAndDelete(); 425 426 uptr shadow_start = kLowShadowBeg; 427 if (kLowShadowBeg) shadow_start -= GetMmapGranularity(); 428 uptr shadow_end = kHighShadowEnd; 429 bool full_shadow_is_available = 430 MemoryRangeIsAvailable(shadow_start, shadow_end); 431 432#if ASAN_LINUX && defined(__x86_64__) && !ASAN_FIXED_MAPPING 433 if (!full_shadow_is_available) { 434 kMidMemBeg = kLowMemEnd < 0x3000000000ULL ? 0x3000000000ULL : 0; 435 kMidMemEnd = kLowMemEnd < 0x3000000000ULL ? 0x3fffffffffULL : 0; 436 } 437#endif 438 439 if (flags()->verbosity) 440 PrintAddressSpaceLayout(); 441 442 if (flags()->disable_core) { 443 DisableCoreDumper(); 444 } 445 446 if (full_shadow_is_available) { 447 // mmap the low shadow plus at least one page at the left. 448 if (kLowShadowBeg) 449 ReserveShadowMemoryRange(shadow_start, kLowShadowEnd); 450 // mmap the high shadow. 451 ReserveShadowMemoryRange(kHighShadowBeg, kHighShadowEnd); 452 // protect the gap. 453 ProtectGap(kShadowGapBeg, kShadowGapEnd - kShadowGapBeg + 1); 454 } else if (kMidMemBeg && 455 MemoryRangeIsAvailable(shadow_start, kMidMemBeg - 1) && 456 MemoryRangeIsAvailable(kMidMemEnd + 1, shadow_end)) { 457 CHECK(kLowShadowBeg != kLowShadowEnd); 458 // mmap the low shadow plus at least one page at the left. 459 ReserveShadowMemoryRange(shadow_start, kLowShadowEnd); 460 // mmap the mid shadow. 461 ReserveShadowMemoryRange(kMidShadowBeg, kMidShadowEnd); 462 // mmap the high shadow. 463 ReserveShadowMemoryRange(kHighShadowBeg, kHighShadowEnd); 464 // protect the gaps. 465 ProtectGap(kShadowGapBeg, kShadowGapEnd - kShadowGapBeg + 1); 466 ProtectGap(kShadowGap2Beg, kShadowGap2End - kShadowGap2Beg + 1); 467 ProtectGap(kShadowGap3Beg, kShadowGap3End - kShadowGap3Beg + 1); 468 } else { 469 Report("Shadow memory range interleaves with an existing memory mapping. " 470 "ASan cannot proceed correctly. ABORTING.\n"); 471 DumpProcessMap(); 472 Die(); 473 } 474 475 InstallSignalHandlers(); 476 // Start symbolizer process if necessary. 477 if (flags()->symbolize) { 478 const char *external_symbolizer = GetEnv("ASAN_SYMBOLIZER_PATH"); 479 if (external_symbolizer) { 480 InitializeExternalSymbolizer(external_symbolizer); 481 } 482 } 483 484 // On Linux AsanThread::ThreadStart() calls malloc() that's why asan_inited 485 // should be set to 1 prior to initializing the threads. 486 asan_inited = 1; 487 asan_init_is_running = false; 488 489 asanThreadRegistry().Init(); 490 asanThreadRegistry().GetMain()->ThreadStart(); 491 force_interface_symbols(); // no-op. 492 493 InitializeAllocator(); 494 495 if (flags()->verbosity) { 496 Report("AddressSanitizer Init done\n"); 497 } 498} 499 500#if defined(ASAN_USE_PREINIT_ARRAY) 501 // On Linux, we force __asan_init to be called before anyone else 502 // by placing it into .preinit_array section. 503 // FIXME: do we have anything like this on Mac? 504 __attribute__((section(".preinit_array"))) 505 typeof(__asan_init) *__asan_preinit =__asan_init; 506#elif defined(_WIN32) && defined(_DLL) 507 // On Windows, when using dynamic CRT (/MD), we can put a pointer 508 // to __asan_init into the global list of C initializers. 509 // See crt0dat.c in the CRT sources for the details. 510 #pragma section(".CRT$XIB", long, read) // NOLINT 511 __declspec(allocate(".CRT$XIB")) void (*__asan_preinit)() = __asan_init; 512#endif 513