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