asan_rtl.cc revision f5b925fde9c855eab4fbc71354e79cc777ed19ec
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_report.h" 21#include "asan_stack.h" 22#include "asan_stats.h" 23#include "asan_thread.h" 24#include "asan_thread_registry.h" 25#include "sanitizer_common/sanitizer_atomic.h" 26#include "sanitizer_common/sanitizer_flags.h" 27#include "sanitizer_common/sanitizer_libc.h" 28#include "sanitizer_common/sanitizer_symbolizer.h" 29 30namespace __sanitizer { 31using namespace __asan; 32 33void Die() { 34 static atomic_uint32_t num_calls; 35 if (atomic_fetch_add(&num_calls, 1, memory_order_relaxed) != 0) { 36 // Don't die twice - run a busy loop. 37 while (1) { } 38 } 39 if (flags()->sleep_before_dying) { 40 Report("Sleeping for %d second(s)\n", flags()->sleep_before_dying); 41 SleepForSeconds(flags()->sleep_before_dying); 42 } 43 if (flags()->unmap_shadow_on_exit) 44 UnmapOrDie((void*)kLowShadowBeg, kHighShadowEnd - kLowShadowBeg); 45 if (death_callback) 46 death_callback(); 47 if (flags()->abort_on_error) 48 Abort(); 49 Exit(flags()->exitcode); 50} 51 52SANITIZER_INTERFACE_ATTRIBUTE 53void CheckFailed(const char *file, int line, const char *cond, u64 v1, u64 v2) { 54 AsanReport("AddressSanitizer CHECK failed: %s:%d \"%s\" (0x%zx, 0x%zx)\n", 55 file, line, cond, (uptr)v1, (uptr)v2); 56 PRINT_CURRENT_STACK(); 57 ShowStatsAndAbort(); 58} 59 60} // namespace __sanitizer 61 62namespace __asan { 63 64// -------------------------- Flags ------------------------- {{{1 65static const int kMallocContextSize = 30; 66 67static Flags asan_flags; 68 69Flags *flags() { 70 return &asan_flags; 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(f->malloc_context_size <= kMallocContextSize); 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} 106 107extern "C" { 108SANITIZER_WEAK_ATTRIBUTE 109SANITIZER_INTERFACE_ATTRIBUTE 110const char* __asan_default_options() { return ""; } 111} // extern "C" 112 113void InitializeFlags(Flags *f, const char *env) { 114 internal_memset(f, 0, sizeof(*f)); 115 116 f->quarantine_size = (ASAN_LOW_MEMORY) ? 1UL << 24 : 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 = kMallocContextSize; 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 = (__WORDSIZE == 64); 140 f->strip_path_prefix = ""; 141 f->allow_reexec = true; 142 143 // Override from user-specified string. 144 ParseFlagsFromString(f, __asan_default_options()); 145 if (flags()->verbosity) { 146 Report("Using the defaults from __asan_default_options: %s\n", 147 __asan_default_options()); 148 } 149 150 // Override from command line. 151 ParseFlagsFromString(f, env); 152} 153 154// -------------------------- Globals --------------------- {{{1 155int asan_inited; 156bool asan_init_is_running; 157void (*death_callback)(void); 158 159// -------------------------- Misc ---------------- {{{1 160void ShowStatsAndAbort() { 161 __asan_print_accumulated_stats(); 162 Die(); 163} 164 165// ---------------------- mmap -------------------- {{{1 166// Reserve memory range [beg, end]. 167static void ReserveShadowMemoryRange(uptr beg, uptr end) { 168 CHECK((beg % kPageSize) == 0); 169 CHECK(((end + 1) % kPageSize) == 0); 170 uptr size = end - beg + 1; 171 void *res = MmapFixedNoReserve(beg, size); 172 CHECK(res == (void*)beg && "ReserveShadowMemoryRange failed"); 173} 174 175// ---------------------- LowLevelAllocator ------------- {{{1 176void *LowLevelAllocator::Allocate(uptr size) { 177 CHECK((size & (size - 1)) == 0 && "size must be a power of two"); 178 if (allocated_end_ - allocated_current_ < (sptr)size) { 179 uptr size_to_allocate = Max(size, kPageSize); 180 allocated_current_ = 181 (char*)MmapOrDie(size_to_allocate, __FUNCTION__); 182 allocated_end_ = allocated_current_ + size_to_allocate; 183 PoisonShadow((uptr)allocated_current_, size_to_allocate, 184 kAsanInternalHeapMagic); 185 } 186 CHECK(allocated_end_ - allocated_current_ >= (sptr)size); 187 void *res = allocated_current_; 188 allocated_current_ += size; 189 return res; 190} 191 192// -------------------------- Run-time entry ------------------- {{{1 193// exported functions 194#define ASAN_REPORT_ERROR(type, is_write, size) \ 195extern "C" NOINLINE INTERFACE_ATTRIBUTE \ 196void __asan_report_ ## type ## size(uptr addr); \ 197void __asan_report_ ## type ## size(uptr addr) { \ 198 GET_CALLER_PC_BP_SP; \ 199 __asan_report_error(pc, bp, sp, addr, is_write, size); \ 200} 201 202ASAN_REPORT_ERROR(load, false, 1) 203ASAN_REPORT_ERROR(load, false, 2) 204ASAN_REPORT_ERROR(load, false, 4) 205ASAN_REPORT_ERROR(load, false, 8) 206ASAN_REPORT_ERROR(load, false, 16) 207ASAN_REPORT_ERROR(store, true, 1) 208ASAN_REPORT_ERROR(store, true, 2) 209ASAN_REPORT_ERROR(store, true, 4) 210ASAN_REPORT_ERROR(store, true, 8) 211ASAN_REPORT_ERROR(store, true, 16) 212 213// Force the linker to keep the symbols for various ASan interface functions. 214// We want to keep those in the executable in order to let the instrumented 215// dynamic libraries access the symbol even if it is not used by the executable 216// itself. This should help if the build system is removing dead code at link 217// time. 218static NOINLINE void force_interface_symbols() { 219 volatile int fake_condition = 0; // prevent dead condition elimination. 220 // __asan_report_* functions are noreturn, so we need a switch to prevent 221 // the compiler from removing any of them. 222 switch (fake_condition) { 223 case 1: __asan_report_load1(0); break; 224 case 2: __asan_report_load2(0); break; 225 case 3: __asan_report_load4(0); break; 226 case 4: __asan_report_load8(0); break; 227 case 5: __asan_report_load16(0); break; 228 case 6: __asan_report_store1(0); break; 229 case 7: __asan_report_store2(0); break; 230 case 8: __asan_report_store4(0); break; 231 case 9: __asan_report_store8(0); break; 232 case 10: __asan_report_store16(0); break; 233 case 11: __asan_register_global(0, 0, 0); break; 234 case 12: __asan_register_globals(0, 0); break; 235 case 13: __asan_unregister_globals(0, 0); break; 236 case 14: __asan_set_death_callback(0); break; 237 case 15: __asan_set_error_report_callback(0); break; 238 case 16: __asan_handle_no_return(); break; 239 case 17: __asan_address_is_poisoned(0); break; 240 case 18: __asan_get_allocated_size(0); break; 241 case 19: __asan_get_current_allocated_bytes(); break; 242 case 20: __asan_get_estimated_allocated_size(0); break; 243 case 21: __asan_get_free_bytes(); break; 244 case 22: __asan_get_heap_size(); break; 245 case 23: __asan_get_ownership(0); break; 246 case 24: __asan_get_unmapped_bytes(); break; 247 case 25: __asan_poison_memory_region(0, 0); break; 248 case 26: __asan_unpoison_memory_region(0, 0); break; 249 case 27: __asan_set_error_exit_code(0); break; 250 case 28: __asan_stack_free(0, 0, 0); break; 251 case 29: __asan_stack_malloc(0, 0); break; 252 case 30: __asan_set_on_error_callback(0); break; 253 case 31: __asan_default_options(); break; 254 case 32: __asan_before_dynamic_init(0, 0); break; 255 case 33: __asan_after_dynamic_init(); break; 256 case 34: __asan_malloc_hook(0, 0); break; 257 case 35: __asan_free_hook(0); break; 258 case 36: __asan_set_symbolize_callback(0); break; 259 } 260} 261 262static void asan_atexit() { 263 AsanPrintf("AddressSanitizer exit stats:\n"); 264 __asan_print_accumulated_stats(); 265} 266 267} // namespace __asan 268 269// ---------------------- Interface ---------------- {{{1 270using namespace __asan; // NOLINT 271 272int NOINLINE __asan_set_error_exit_code(int exit_code) { 273 int old = flags()->exitcode; 274 flags()->exitcode = exit_code; 275 return old; 276} 277 278void NOINLINE __asan_handle_no_return() { 279 int local_stack; 280 AsanThread *curr_thread = asanThreadRegistry().GetCurrent(); 281 CHECK(curr_thread); 282 uptr top = curr_thread->stack_top(); 283 uptr bottom = ((uptr)&local_stack - kPageSize) & ~(kPageSize-1); 284 PoisonShadow(bottom, top - bottom, 0); 285} 286 287void NOINLINE __asan_set_death_callback(void (*callback)(void)) { 288 death_callback = callback; 289} 290 291void __asan_init() { 292 if (asan_inited) return; 293 asan_init_is_running = true; 294 295 // Make sure we are not statically linked. 296 AsanDoesNotSupportStaticLinkage(); 297 298 // Initialize flags. This must be done early, because most of the 299 // initialization steps look at flags(). 300 const char *options = GetEnv("ASAN_OPTIONS"); 301 InitializeFlags(flags(), options); 302 303 if (flags()->verbosity && options) { 304 Report("Parsed ASAN_OPTIONS: %s\n", options); 305 } 306 307 // Re-exec ourselves if we need to set additional env or command line args. 308 MaybeReexec(); 309 310 if (flags()->atexit) { 311 Atexit(asan_atexit); 312 } 313 314 // interceptors 315 InitializeAsanInterceptors(); 316 317 ReplaceSystemMalloc(); 318 ReplaceOperatorsNewAndDelete(); 319 320 if (flags()->verbosity) { 321 Printf("|| `[%p, %p]` || HighMem ||\n", 322 (void*)kHighMemBeg, (void*)kHighMemEnd); 323 Printf("|| `[%p, %p]` || HighShadow ||\n", 324 (void*)kHighShadowBeg, (void*)kHighShadowEnd); 325 Printf("|| `[%p, %p]` || ShadowGap ||\n", 326 (void*)kShadowGapBeg, (void*)kShadowGapEnd); 327 Printf("|| `[%p, %p]` || LowShadow ||\n", 328 (void*)kLowShadowBeg, (void*)kLowShadowEnd); 329 Printf("|| `[%p, %p]` || LowMem ||\n", 330 (void*)kLowMemBeg, (void*)kLowMemEnd); 331 Printf("MemToShadow(shadow): %p %p %p %p\n", 332 (void*)MEM_TO_SHADOW(kLowShadowBeg), 333 (void*)MEM_TO_SHADOW(kLowShadowEnd), 334 (void*)MEM_TO_SHADOW(kHighShadowBeg), 335 (void*)MEM_TO_SHADOW(kHighShadowEnd)); 336 Printf("red_zone=%zu\n", (uptr)flags()->redzone); 337 Printf("malloc_context_size=%zu\n", (uptr)flags()->malloc_context_size); 338 339 Printf("SHADOW_SCALE: %zx\n", (uptr)SHADOW_SCALE); 340 Printf("SHADOW_GRANULARITY: %zx\n", (uptr)SHADOW_GRANULARITY); 341 Printf("SHADOW_OFFSET: %zx\n", (uptr)SHADOW_OFFSET); 342 CHECK(SHADOW_SCALE >= 3 && SHADOW_SCALE <= 7); 343 } 344 345 if (flags()->disable_core) { 346 DisableCoreDumper(); 347 } 348 349 uptr shadow_start = kLowShadowBeg; 350 if (kLowShadowBeg > 0) shadow_start -= kMmapGranularity; 351 uptr shadow_end = kHighShadowEnd; 352 if (MemoryRangeIsAvailable(shadow_start, shadow_end)) { 353 if (kLowShadowBeg != kLowShadowEnd) { 354 // mmap the low shadow plus at least one page. 355 ReserveShadowMemoryRange(kLowShadowBeg - kMmapGranularity, kLowShadowEnd); 356 } 357 // mmap the high shadow. 358 ReserveShadowMemoryRange(kHighShadowBeg, kHighShadowEnd); 359 // protect the gap 360 void *prot = Mprotect(kShadowGapBeg, kShadowGapEnd - kShadowGapBeg + 1); 361 CHECK(prot == (void*)kShadowGapBeg); 362 } else { 363 Report("Shadow memory range interleaves with an existing memory mapping. " 364 "ASan cannot proceed correctly. ABORTING.\n"); 365 DumpProcessMap(); 366 Die(); 367 } 368 369 InstallSignalHandlers(); 370 // Start symbolizer process if necessary. 371 if (flags()->symbolize) { 372 const char *external_symbolizer = GetEnv("ASAN_SYMBOLIZER_PATH"); 373 if (external_symbolizer) { 374 InitializeExternalSymbolizer(external_symbolizer); 375 } 376 } 377#ifdef _WIN32 378 __asan_set_symbolize_callback(WinSymbolize); 379#endif // _WIN32 380 381 // On Linux AsanThread::ThreadStart() calls malloc() that's why asan_inited 382 // should be set to 1 prior to initializing the threads. 383 asan_inited = 1; 384 asan_init_is_running = false; 385 386 asanThreadRegistry().Init(); 387 asanThreadRegistry().GetMain()->ThreadStart(); 388 force_interface_symbols(); // no-op. 389 390 if (flags()->verbosity) { 391 Report("AddressSanitizer Init done\n"); 392 } 393} 394 395#if defined(ASAN_USE_PREINIT_ARRAY) 396 // On Linux, we force __asan_init to be called before anyone else 397 // by placing it into .preinit_array section. 398 // FIXME: do we have anything like this on Mac? 399 __attribute__((section(".preinit_array"))) 400 typeof(__asan_init) *__asan_preinit =__asan_init; 401#elif defined(_WIN32) && defined(_DLL) 402 // On Windows, when using dynamic CRT (/MD), we can put a pointer 403 // to __asan_init into the global list of C initializers. 404 // See crt0dat.c in the CRT sources for the details. 405 #pragma section(".CRT$XIB", long, read) // NOLINT 406 __declspec(allocate(".CRT$XIB")) void (*__asan_preinit)() = __asan_init; 407#endif 408