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