]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/asan/asan_rtl.cc
Import libcxxrt master 1cb607e89f6135bbc10f3d3b6fba1f983e258dcc.
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / asan / asan_rtl.cc
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_activation.h"
15 #include "asan_allocator.h"
16 #include "asan_interceptors.h"
17 #include "asan_interface_internal.h"
18 #include "asan_internal.h"
19 #include "asan_mapping.h"
20 #include "asan_poisoning.h"
21 #include "asan_report.h"
22 #include "asan_stack.h"
23 #include "asan_stats.h"
24 #include "asan_suppressions.h"
25 #include "asan_thread.h"
26 #include "sanitizer_common/sanitizer_atomic.h"
27 #include "sanitizer_common/sanitizer_flags.h"
28 #include "sanitizer_common/sanitizer_libc.h"
29 #include "sanitizer_common/sanitizer_symbolizer.h"
30 #include "lsan/lsan_common.h"
31
32 int __asan_option_detect_stack_use_after_return;  // Global interface symbol.
33 uptr *__asan_test_only_reported_buggy_pointer;  // Used only for testing asan.
34
35 namespace __asan {
36
37 uptr AsanMappingProfile[kAsanMappingProfileSize];
38
39 static void AsanDie() {
40   static atomic_uint32_t num_calls;
41   if (atomic_fetch_add(&num_calls, 1, memory_order_relaxed) != 0) {
42     // Don't die twice - run a busy loop.
43     while (1) { }
44   }
45   if (flags()->sleep_before_dying) {
46     Report("Sleeping for %d second(s)\n", flags()->sleep_before_dying);
47     SleepForSeconds(flags()->sleep_before_dying);
48   }
49   if (flags()->unmap_shadow_on_exit) {
50     if (kMidMemBeg) {
51       UnmapOrDie((void*)kLowShadowBeg, kMidMemBeg - kLowShadowBeg);
52       UnmapOrDie((void*)kMidMemEnd, kHighShadowEnd - kMidMemEnd);
53     } else {
54       UnmapOrDie((void*)kLowShadowBeg, kHighShadowEnd - kLowShadowBeg);
55     }
56   }
57   if (common_flags()->coverage)
58     __sanitizer_cov_dump();
59   if (death_callback)
60     death_callback();
61   if (flags()->abort_on_error)
62     Abort();
63   internal__exit(flags()->exitcode);
64 }
65
66 static void AsanCheckFailed(const char *file, int line, const char *cond,
67                             u64 v1, u64 v2) {
68   Report("AddressSanitizer CHECK failed: %s:%d \"%s\" (0x%zx, 0x%zx)\n", file,
69          line, cond, (uptr)v1, (uptr)v2);
70   // FIXME: check for infinite recursion without a thread-local counter here.
71   PRINT_CURRENT_STACK_CHECK();
72   Die();
73 }
74
75 // -------------------------- Flags ------------------------- {{{1
76 static const int kDefaultMallocContextSize = 30;
77
78 Flags asan_flags_dont_use_directly;  // use via flags().
79
80 static const char *MaybeCallAsanDefaultOptions() {
81   return (&__asan_default_options) ? __asan_default_options() : "";
82 }
83
84 static const char *MaybeUseAsanDefaultOptionsCompileDefinition() {
85 #ifdef ASAN_DEFAULT_OPTIONS
86 // Stringize the macro value.
87 # define ASAN_STRINGIZE(x) #x
88 # define ASAN_STRINGIZE_OPTIONS(options) ASAN_STRINGIZE(options)
89   return ASAN_STRINGIZE_OPTIONS(ASAN_DEFAULT_OPTIONS);
90 #else
91   return "";
92 #endif
93 }
94
95 static void ParseFlagsFromString(Flags *f, const char *str) {
96   CommonFlags *cf = common_flags();
97   ParseCommonFlagsFromString(cf, str);
98   CHECK((uptr)cf->malloc_context_size <= kStackTraceMax);
99   // Please write meaningful flag descriptions when adding new flags.
100   ParseFlag(str, &f->quarantine_size, "quarantine_size",
101             "Size (in bytes) of quarantine used to detect use-after-free "
102             "errors. Lower value may reduce memory usage but increase the "
103             "chance of false negatives.");
104   ParseFlag(str, &f->redzone, "redzone",
105             "Minimal size (in bytes) of redzones around heap objects. "
106             "Requirement: redzone >= 16, is a power of two.");
107   ParseFlag(str, &f->max_redzone, "max_redzone",
108             "Maximal size (in bytes) of redzones around heap objects.");
109   CHECK_GE(f->redzone, 16);
110   CHECK_GE(f->max_redzone, f->redzone);
111   CHECK_LE(f->max_redzone, 2048);
112   CHECK(IsPowerOfTwo(f->redzone));
113   CHECK(IsPowerOfTwo(f->max_redzone));
114
115   ParseFlag(str, &f->debug, "debug",
116       "If set, prints some debugging information and does additional checks.");
117   ParseFlag(str, &f->report_globals, "report_globals",
118       "Controls the way to handle globals (0 - don't detect buffer overflow on "
119       "globals, 1 - detect buffer overflow, 2 - print data about registered "
120       "globals).");
121
122   ParseFlag(str, &f->check_initialization_order,
123       "check_initialization_order",
124       "If set, attempts to catch initialization order issues.");
125
126   ParseFlag(str, &f->replace_str, "replace_str",
127       "If set, uses custom wrappers and replacements for libc string functions "
128       "to find more errors.");
129
130   ParseFlag(str, &f->replace_intrin, "replace_intrin",
131       "If set, uses custom wrappers for memset/memcpy/memmove intinsics.");
132   ParseFlag(str, &f->mac_ignore_invalid_free, "mac_ignore_invalid_free",
133       "Ignore invalid free() calls to work around some bugs. Used on OS X "
134       "only.");
135   ParseFlag(str, &f->detect_stack_use_after_return,
136       "detect_stack_use_after_return",
137       "Enables stack-use-after-return checking at run-time.");
138   ParseFlag(str, &f->min_uar_stack_size_log, "min_uar_stack_size_log",
139       "Minimum fake stack size log.");
140   ParseFlag(str, &f->max_uar_stack_size_log, "max_uar_stack_size_log",
141       "Maximum fake stack size log.");
142   ParseFlag(str, &f->uar_noreserve, "uar_noreserve",
143       "Use mmap with 'norserve' flag to allocate fake stack.");
144   ParseFlag(str, &f->max_malloc_fill_size, "max_malloc_fill_size",
145       "ASan allocator flag. max_malloc_fill_size is the maximal amount of "
146       "bytes that will be filled with malloc_fill_byte on malloc.");
147   ParseFlag(str, &f->malloc_fill_byte, "malloc_fill_byte",
148       "Value used to fill the newly allocated memory.");
149   ParseFlag(str, &f->exitcode, "exitcode",
150       "Override the program exit status if the tool found an error.");
151   ParseFlag(str, &f->allow_user_poisoning, "allow_user_poisoning",
152       "If set, user may manually mark memory regions as poisoned or "
153       "unpoisoned.");
154   ParseFlag(str, &f->sleep_before_dying, "sleep_before_dying",
155       "Number of seconds to sleep between printing an error report and "
156       "terminating the program. Useful for debugging purposes (e.g. when one "
157       "needs to attach gdb).");
158
159   ParseFlag(str, &f->check_malloc_usable_size, "check_malloc_usable_size",
160       "Allows the users to work around the bug in Nvidia drivers prior to "
161       "295.*.");
162
163   ParseFlag(str, &f->unmap_shadow_on_exit, "unmap_shadow_on_exit",
164       "If set, explicitly unmaps the (huge) shadow at exit.");
165   ParseFlag(str, &f->abort_on_error, "abort_on_error",
166       "If set, the tool calls abort() instead of _exit() after printing the "
167       "error report.");
168   ParseFlag(str, &f->print_stats, "print_stats",
169       "Print various statistics after printing an error message or if "
170       "atexit=1.");
171   ParseFlag(str, &f->print_legend, "print_legend",
172       "Print the legend for the shadow bytes.");
173   ParseFlag(str, &f->atexit, "atexit",
174       "If set, prints ASan exit stats even after program terminates "
175       "successfully.");
176
177   ParseFlag(str, &f->allow_reexec, "allow_reexec",
178       "Allow the tool to re-exec the program. This may interfere badly with "
179       "the debugger.");
180
181   ParseFlag(str, &f->print_full_thread_history,
182       "print_full_thread_history",
183       "If set, prints thread creation stacks for the threads involved in the "
184       "report and their ancestors up to the main thread.");
185
186   ParseFlag(str, &f->poison_heap, "poison_heap",
187       "Poison (or not) the heap memory on [de]allocation. Zero value is useful "
188       "for benchmarking the allocator or instrumentator.");
189
190   ParseFlag(str, &f->poison_array_cookie, "poison_array_cookie",
191       "Poison (or not) the array cookie after operator new[].");
192
193   ParseFlag(str, &f->poison_partial, "poison_partial",
194       "If true, poison partially addressable 8-byte aligned words "
195       "(default=true). This flag affects heap and global buffers, but not "
196       "stack buffers.");
197
198   ParseFlag(str, &f->alloc_dealloc_mismatch, "alloc_dealloc_mismatch",
199       "Report errors on malloc/delete, new/free, new/delete[], etc.");
200
201   ParseFlag(str, &f->new_delete_type_mismatch, "new_delete_type_mismatch",
202       "Report errors on mismatch betwen size of new and delete.");
203
204   ParseFlag(str, &f->strict_memcmp, "strict_memcmp",
205       "If true, assume that memcmp(p1, p2, n) always reads n bytes before "
206       "comparing p1 and p2.");
207
208   ParseFlag(str, &f->strict_init_order, "strict_init_order",
209       "If true, assume that dynamic initializers can never access globals from "
210       "other modules, even if the latter are already initialized.");
211
212   ParseFlag(str, &f->start_deactivated, "start_deactivated",
213       "If true, ASan tweaks a bunch of other flags (quarantine, redzone, heap "
214       "poisoning) to reduce memory consumption as much as possible, and "
215       "restores them to original values when the first instrumented module is "
216       "loaded into the process. This is mainly intended to be used on "
217       "Android. ");
218
219   ParseFlag(str, &f->detect_invalid_pointer_pairs,
220       "detect_invalid_pointer_pairs",
221       "If non-zero, try to detect operations like <, <=, >, >= and - on "
222       "invalid pointer pairs (e.g. when pointers belong to different objects). "
223       "The bigger the value the harder we try.");
224
225   ParseFlag(str, &f->detect_container_overflow,
226       "detect_container_overflow",
227       "If true, honor the container overflow  annotations. "
228       "See https://code.google.com/p/address-sanitizer/wiki/ContainerOverflow");
229
230   ParseFlag(str, &f->detect_odr_violation, "detect_odr_violation",
231             "If >=2, detect violation of One-Definition-Rule (ODR); "
232             "If ==1, detect ODR-violation only if the two variables "
233             "have different sizes");
234
235   ParseFlag(str, &f->dump_instruction_bytes, "dump_instruction_bytes",
236       "If true, dump 16 bytes starting at the instruction that caused SEGV");
237 }
238
239 void InitializeFlags(Flags *f, const char *env) {
240   CommonFlags *cf = common_flags();
241   SetCommonFlagsDefaults(cf);
242   cf->detect_leaks = CAN_SANITIZE_LEAKS;
243   cf->external_symbolizer_path = GetEnv("ASAN_SYMBOLIZER_PATH");
244   cf->malloc_context_size = kDefaultMallocContextSize;
245   cf->intercept_tls_get_addr = true;
246   cf->coverage = false;
247
248   internal_memset(f, 0, sizeof(*f));
249   f->quarantine_size = (ASAN_LOW_MEMORY) ? 1UL << 26 : 1UL << 28;
250   f->redzone = 16;
251   f->max_redzone = 2048;
252   f->debug = false;
253   f->report_globals = 1;
254   f->check_initialization_order = false;
255   f->replace_str = true;
256   f->replace_intrin = true;
257   f->mac_ignore_invalid_free = false;
258   f->detect_stack_use_after_return = false;  // Also needs the compiler flag.
259   f->min_uar_stack_size_log = 16;  // We can't do smaller anyway.
260   f->max_uar_stack_size_log = 20;  // 1Mb per size class, i.e. ~11Mb per thread.
261   f->uar_noreserve = false;
262   f->max_malloc_fill_size = 0x1000;  // By default, fill only the first 4K.
263   f->malloc_fill_byte = 0xbe;
264   f->exitcode = ASAN_DEFAULT_FAILURE_EXITCODE;
265   f->allow_user_poisoning = true;
266   f->sleep_before_dying = 0;
267   f->check_malloc_usable_size = true;
268   f->unmap_shadow_on_exit = false;
269   f->abort_on_error = false;
270   f->print_stats = false;
271   f->print_legend = true;
272   f->atexit = false;
273   f->allow_reexec = true;
274   f->print_full_thread_history = true;
275   f->poison_heap = true;
276   f->poison_array_cookie = true;
277   f->poison_partial = true;
278   // Turn off alloc/dealloc mismatch checker on Mac and Windows for now.
279   // https://code.google.com/p/address-sanitizer/issues/detail?id=131
280   // https://code.google.com/p/address-sanitizer/issues/detail?id=309
281   // TODO(glider,timurrrr): Fix known issues and enable this back.
282   f->alloc_dealloc_mismatch = (SANITIZER_MAC == 0) && (SANITIZER_WINDOWS == 0);
283   f->new_delete_type_mismatch = true;
284   f->strict_memcmp = true;
285   f->strict_init_order = false;
286   f->start_deactivated = false;
287   f->detect_invalid_pointer_pairs = 0;
288   f->detect_container_overflow = true;
289   f->detect_odr_violation = 2;
290   f->dump_instruction_bytes = false;
291
292   // Override from compile definition.
293   ParseFlagsFromString(f, MaybeUseAsanDefaultOptionsCompileDefinition());
294
295   // Override from user-specified string.
296   ParseFlagsFromString(f, MaybeCallAsanDefaultOptions());
297   VReport(1, "Using the defaults from __asan_default_options: %s\n",
298           MaybeCallAsanDefaultOptions());
299
300   // Override from command line.
301   ParseFlagsFromString(f, env);
302   if (common_flags()->help) {
303     PrintFlagDescriptions();
304   }
305
306   if (!CAN_SANITIZE_LEAKS && cf->detect_leaks) {
307     Report("%s: detect_leaks is not supported on this platform.\n",
308            SanitizerToolName);
309     cf->detect_leaks = false;
310   }
311
312   // Make "strict_init_order" imply "check_initialization_order".
313   // TODO(samsonov): Use a single runtime flag for an init-order checker.
314   if (f->strict_init_order) {
315     f->check_initialization_order = true;
316   }
317 }
318
319 // Parse flags that may change between startup and activation.
320 // On Android they come from a system property.
321 // On other platforms this is no-op.
322 void ParseExtraActivationFlags() {
323   char buf[100];
324   GetExtraActivationFlags(buf, sizeof(buf));
325   ParseFlagsFromString(flags(), buf);
326   if (buf[0] != '\0')
327     VReport(1, "Extra activation flags: %s\n", buf);
328 }
329
330 // -------------------------- Globals --------------------- {{{1
331 int asan_inited;
332 bool asan_init_is_running;
333 void (*death_callback)(void);
334
335 #if !ASAN_FIXED_MAPPING
336 uptr kHighMemEnd, kMidMemBeg, kMidMemEnd;
337 #endif
338
339 // -------------------------- Misc ---------------- {{{1
340 void ShowStatsAndAbort() {
341   __asan_print_accumulated_stats();
342   Die();
343 }
344
345 // ---------------------- mmap -------------------- {{{1
346 // Reserve memory range [beg, end].
347 static void ReserveShadowMemoryRange(uptr beg, uptr end) {
348   CHECK_EQ((beg % GetPageSizeCached()), 0);
349   CHECK_EQ(((end + 1) % GetPageSizeCached()), 0);
350   uptr size = end - beg + 1;
351   DecreaseTotalMmap(size);  // Don't count the shadow against mmap_limit_mb.
352   void *res = MmapFixedNoReserve(beg, size);
353   if (res != (void*)beg) {
354     Report("ReserveShadowMemoryRange failed while trying to map 0x%zx bytes. "
355            "Perhaps you're using ulimit -v\n", size);
356     Abort();
357   }
358 }
359
360 // --------------- LowLevelAllocateCallbac ---------- {{{1
361 static void OnLowLevelAllocate(uptr ptr, uptr size) {
362   PoisonShadow(ptr, size, kAsanInternalHeapMagic);
363 }
364
365 // -------------------------- Run-time entry ------------------- {{{1
366 // exported functions
367 #define ASAN_REPORT_ERROR(type, is_write, size)                     \
368 extern "C" NOINLINE INTERFACE_ATTRIBUTE                        \
369 void __asan_report_ ## type ## size(uptr addr);                \
370 void __asan_report_ ## type ## size(uptr addr) {               \
371   GET_CALLER_PC_BP_SP;                                              \
372   __asan_report_error(pc, bp, sp, addr, is_write, size);            \
373 }
374
375 ASAN_REPORT_ERROR(load, false, 1)
376 ASAN_REPORT_ERROR(load, false, 2)
377 ASAN_REPORT_ERROR(load, false, 4)
378 ASAN_REPORT_ERROR(load, false, 8)
379 ASAN_REPORT_ERROR(load, false, 16)
380 ASAN_REPORT_ERROR(store, true, 1)
381 ASAN_REPORT_ERROR(store, true, 2)
382 ASAN_REPORT_ERROR(store, true, 4)
383 ASAN_REPORT_ERROR(store, true, 8)
384 ASAN_REPORT_ERROR(store, true, 16)
385
386 #define ASAN_REPORT_ERROR_N(type, is_write)                    \
387 extern "C" NOINLINE INTERFACE_ATTRIBUTE                        \
388 void __asan_report_ ## type ## _n(uptr addr, uptr size);       \
389 void __asan_report_ ## type ## _n(uptr addr, uptr size) {      \
390   GET_CALLER_PC_BP_SP;                                         \
391   __asan_report_error(pc, bp, sp, addr, is_write, size);       \
392 }
393
394 ASAN_REPORT_ERROR_N(load, false)
395 ASAN_REPORT_ERROR_N(store, true)
396
397 #define ASAN_MEMORY_ACCESS_CALLBACK(type, is_write, size)                      \
398   extern "C" NOINLINE INTERFACE_ATTRIBUTE void __asan_##type##size(uptr addr); \
399   void __asan_##type##size(uptr addr) {                                        \
400     uptr sp = MEM_TO_SHADOW(addr);                                             \
401     uptr s = size <= SHADOW_GRANULARITY ? *reinterpret_cast<u8 *>(sp)          \
402                                         : *reinterpret_cast<u16 *>(sp);        \
403     if (UNLIKELY(s)) {                                                         \
404       if (UNLIKELY(size >= SHADOW_GRANULARITY ||                               \
405                    ((s8)((addr & (SHADOW_GRANULARITY - 1)) + size - 1)) >=     \
406                        (s8)s)) {                                               \
407         if (__asan_test_only_reported_buggy_pointer) {                         \
408           *__asan_test_only_reported_buggy_pointer = addr;                     \
409         } else {                                                               \
410           GET_CALLER_PC_BP_SP;                                                 \
411           __asan_report_error(pc, bp, sp, addr, is_write, size);               \
412         }                                                                      \
413       }                                                                        \
414     }                                                                          \
415   }
416
417 ASAN_MEMORY_ACCESS_CALLBACK(load, false, 1)
418 ASAN_MEMORY_ACCESS_CALLBACK(load, false, 2)
419 ASAN_MEMORY_ACCESS_CALLBACK(load, false, 4)
420 ASAN_MEMORY_ACCESS_CALLBACK(load, false, 8)
421 ASAN_MEMORY_ACCESS_CALLBACK(load, false, 16)
422 ASAN_MEMORY_ACCESS_CALLBACK(store, true, 1)
423 ASAN_MEMORY_ACCESS_CALLBACK(store, true, 2)
424 ASAN_MEMORY_ACCESS_CALLBACK(store, true, 4)
425 ASAN_MEMORY_ACCESS_CALLBACK(store, true, 8)
426 ASAN_MEMORY_ACCESS_CALLBACK(store, true, 16)
427
428 extern "C"
429 NOINLINE INTERFACE_ATTRIBUTE void __asan_loadN(uptr addr, uptr size) {
430   if (__asan_region_is_poisoned(addr, size)) {
431     GET_CALLER_PC_BP_SP;
432     __asan_report_error(pc, bp, sp, addr, false, size);
433   }
434 }
435
436 extern "C"
437 NOINLINE INTERFACE_ATTRIBUTE void __asan_storeN(uptr addr, uptr size) {
438   if (__asan_region_is_poisoned(addr, size)) {
439     GET_CALLER_PC_BP_SP;
440     __asan_report_error(pc, bp, sp, addr, true, size);
441   }
442 }
443
444 // Force the linker to keep the symbols for various ASan interface functions.
445 // We want to keep those in the executable in order to let the instrumented
446 // dynamic libraries access the symbol even if it is not used by the executable
447 // itself. This should help if the build system is removing dead code at link
448 // time.
449 static NOINLINE void force_interface_symbols() {
450   volatile int fake_condition = 0;  // prevent dead condition elimination.
451   // __asan_report_* functions are noreturn, so we need a switch to prevent
452   // the compiler from removing any of them.
453   switch (fake_condition) {
454     case 1: __asan_report_load1(0); break;
455     case 2: __asan_report_load2(0); break;
456     case 3: __asan_report_load4(0); break;
457     case 4: __asan_report_load8(0); break;
458     case 5: __asan_report_load16(0); break;
459     case 6: __asan_report_store1(0); break;
460     case 7: __asan_report_store2(0); break;
461     case 8: __asan_report_store4(0); break;
462     case 9: __asan_report_store8(0); break;
463     case 10: __asan_report_store16(0); break;
464     case 12: __asan_register_globals(0, 0); break;
465     case 13: __asan_unregister_globals(0, 0); break;
466     case 14: __asan_set_death_callback(0); break;
467     case 15: __asan_set_error_report_callback(0); break;
468     case 16: __asan_handle_no_return(); break;
469     case 17: __asan_address_is_poisoned(0); break;
470     case 25: __asan_poison_memory_region(0, 0); break;
471     case 26: __asan_unpoison_memory_region(0, 0); break;
472     case 27: __asan_set_error_exit_code(0); break;
473     case 30: __asan_before_dynamic_init(0); break;
474     case 31: __asan_after_dynamic_init(); break;
475     case 32: __asan_poison_stack_memory(0, 0); break;
476     case 33: __asan_unpoison_stack_memory(0, 0); break;
477     case 34: __asan_region_is_poisoned(0, 0); break;
478     case 35: __asan_describe_address(0); break;
479   }
480 }
481
482 static void asan_atexit() {
483   Printf("AddressSanitizer exit stats:\n");
484   __asan_print_accumulated_stats();
485   // Print AsanMappingProfile.
486   for (uptr i = 0; i < kAsanMappingProfileSize; i++) {
487     if (AsanMappingProfile[i] == 0) continue;
488     Printf("asan_mapping.h:%zd -- %zd\n", i, AsanMappingProfile[i]);
489   }
490 }
491
492 static void InitializeHighMemEnd() {
493 #if !ASAN_FIXED_MAPPING
494   kHighMemEnd = GetMaxVirtualAddress();
495   // Increase kHighMemEnd to make sure it's properly
496   // aligned together with kHighMemBeg:
497   kHighMemEnd |= SHADOW_GRANULARITY * GetPageSizeCached() - 1;
498 #endif  // !ASAN_FIXED_MAPPING
499   CHECK_EQ((kHighMemBeg % GetPageSizeCached()), 0);
500 }
501
502 static void ProtectGap(uptr a, uptr size) {
503   CHECK_EQ(a, (uptr)Mprotect(a, size));
504 }
505
506 static void PrintAddressSpaceLayout() {
507   Printf("|| `[%p, %p]` || HighMem    ||\n",
508          (void*)kHighMemBeg, (void*)kHighMemEnd);
509   Printf("|| `[%p, %p]` || HighShadow ||\n",
510          (void*)kHighShadowBeg, (void*)kHighShadowEnd);
511   if (kMidMemBeg) {
512     Printf("|| `[%p, %p]` || ShadowGap3 ||\n",
513            (void*)kShadowGap3Beg, (void*)kShadowGap3End);
514     Printf("|| `[%p, %p]` || MidMem     ||\n",
515            (void*)kMidMemBeg, (void*)kMidMemEnd);
516     Printf("|| `[%p, %p]` || ShadowGap2 ||\n",
517            (void*)kShadowGap2Beg, (void*)kShadowGap2End);
518     Printf("|| `[%p, %p]` || MidShadow  ||\n",
519            (void*)kMidShadowBeg, (void*)kMidShadowEnd);
520   }
521   Printf("|| `[%p, %p]` || ShadowGap  ||\n",
522          (void*)kShadowGapBeg, (void*)kShadowGapEnd);
523   if (kLowShadowBeg) {
524     Printf("|| `[%p, %p]` || LowShadow  ||\n",
525            (void*)kLowShadowBeg, (void*)kLowShadowEnd);
526     Printf("|| `[%p, %p]` || LowMem     ||\n",
527            (void*)kLowMemBeg, (void*)kLowMemEnd);
528   }
529   Printf("MemToShadow(shadow): %p %p %p %p",
530          (void*)MEM_TO_SHADOW(kLowShadowBeg),
531          (void*)MEM_TO_SHADOW(kLowShadowEnd),
532          (void*)MEM_TO_SHADOW(kHighShadowBeg),
533          (void*)MEM_TO_SHADOW(kHighShadowEnd));
534   if (kMidMemBeg) {
535     Printf(" %p %p",
536            (void*)MEM_TO_SHADOW(kMidShadowBeg),
537            (void*)MEM_TO_SHADOW(kMidShadowEnd));
538   }
539   Printf("\n");
540   Printf("redzone=%zu\n", (uptr)flags()->redzone);
541   Printf("max_redzone=%zu\n", (uptr)flags()->max_redzone);
542   Printf("quarantine_size=%zuM\n", (uptr)flags()->quarantine_size >> 20);
543   Printf("malloc_context_size=%zu\n",
544          (uptr)common_flags()->malloc_context_size);
545
546   Printf("SHADOW_SCALE: %zx\n", (uptr)SHADOW_SCALE);
547   Printf("SHADOW_GRANULARITY: %zx\n", (uptr)SHADOW_GRANULARITY);
548   Printf("SHADOW_OFFSET: %zx\n", (uptr)SHADOW_OFFSET);
549   CHECK(SHADOW_SCALE >= 3 && SHADOW_SCALE <= 7);
550   if (kMidMemBeg)
551     CHECK(kMidShadowBeg > kLowShadowEnd &&
552           kMidMemBeg > kMidShadowEnd &&
553           kHighShadowBeg > kMidMemEnd);
554 }
555
556 static void AsanInitInternal() {
557   if (LIKELY(asan_inited)) return;
558   SanitizerToolName = "AddressSanitizer";
559   CHECK(!asan_init_is_running && "ASan init calls itself!");
560   asan_init_is_running = true;
561
562   // Initialize flags. This must be done early, because most of the
563   // initialization steps look at flags().
564   const char *options = GetEnv("ASAN_OPTIONS");
565   InitializeFlags(flags(), options);
566
567   InitializeHighMemEnd();
568
569   // Make sure we are not statically linked.
570   AsanDoesNotSupportStaticLinkage();
571
572   // Install tool-specific callbacks in sanitizer_common.
573   SetDieCallback(AsanDie);
574   SetCheckFailedCallback(AsanCheckFailed);
575   SetPrintfAndReportCallback(AppendToErrorMessageBuffer);
576
577   if (!flags()->start_deactivated)
578     ParseExtraActivationFlags();
579
580   __sanitizer_set_report_path(common_flags()->log_path);
581   __asan_option_detect_stack_use_after_return =
582       flags()->detect_stack_use_after_return;
583   CHECK_LE(flags()->min_uar_stack_size_log, flags()->max_uar_stack_size_log);
584
585   if (options) {
586     VReport(1, "Parsed ASAN_OPTIONS: %s\n", options);
587   }
588
589   if (flags()->start_deactivated)
590     AsanStartDeactivated();
591
592   // Re-exec ourselves if we need to set additional env or command line args.
593   MaybeReexec();
594
595   // Setup internal allocator callback.
596   SetLowLevelAllocateCallback(OnLowLevelAllocate);
597
598   InitializeAsanInterceptors();
599
600   // Enable system log ("adb logcat") on Android.
601   // Doing this before interceptors are initialized crashes in:
602   // AsanInitInternal -> android_log_write -> __interceptor_strcmp
603   AndroidLogInit();
604
605   ReplaceSystemMalloc();
606
607   uptr shadow_start = kLowShadowBeg;
608   if (kLowShadowBeg)
609     shadow_start -= GetMmapGranularity();
610   bool full_shadow_is_available =
611       MemoryRangeIsAvailable(shadow_start, kHighShadowEnd);
612
613 #if SANITIZER_LINUX && defined(__x86_64__) && defined(_LP64) &&                \
614     !ASAN_FIXED_MAPPING
615   if (!full_shadow_is_available) {
616     kMidMemBeg = kLowMemEnd < 0x3000000000ULL ? 0x3000000000ULL : 0;
617     kMidMemEnd = kLowMemEnd < 0x3000000000ULL ? 0x4fffffffffULL : 0;
618   }
619 #endif
620
621   if (common_flags()->verbosity)
622     PrintAddressSpaceLayout();
623
624   DisableCoreDumperIfNecessary();
625
626   if (full_shadow_is_available) {
627     // mmap the low shadow plus at least one page at the left.
628     if (kLowShadowBeg)
629       ReserveShadowMemoryRange(shadow_start, kLowShadowEnd);
630     // mmap the high shadow.
631     ReserveShadowMemoryRange(kHighShadowBeg, kHighShadowEnd);
632     // protect the gap.
633     ProtectGap(kShadowGapBeg, kShadowGapEnd - kShadowGapBeg + 1);
634     CHECK_EQ(kShadowGapEnd, kHighShadowBeg - 1);
635   } else if (kMidMemBeg &&
636       MemoryRangeIsAvailable(shadow_start, kMidMemBeg - 1) &&
637       MemoryRangeIsAvailable(kMidMemEnd + 1, kHighShadowEnd)) {
638     CHECK(kLowShadowBeg != kLowShadowEnd);
639     // mmap the low shadow plus at least one page at the left.
640     ReserveShadowMemoryRange(shadow_start, kLowShadowEnd);
641     // mmap the mid shadow.
642     ReserveShadowMemoryRange(kMidShadowBeg, kMidShadowEnd);
643     // mmap the high shadow.
644     ReserveShadowMemoryRange(kHighShadowBeg, kHighShadowEnd);
645     // protect the gaps.
646     ProtectGap(kShadowGapBeg, kShadowGapEnd - kShadowGapBeg + 1);
647     ProtectGap(kShadowGap2Beg, kShadowGap2End - kShadowGap2Beg + 1);
648     ProtectGap(kShadowGap3Beg, kShadowGap3End - kShadowGap3Beg + 1);
649   } else {
650     Report("Shadow memory range interleaves with an existing memory mapping. "
651            "ASan cannot proceed correctly. ABORTING.\n");
652     DumpProcessMap();
653     Die();
654   }
655
656   AsanTSDInit(PlatformTSDDtor);
657   InstallDeadlySignalHandlers(AsanOnSIGSEGV);
658
659   InitializeAllocator();
660
661   // On Linux AsanThread::ThreadStart() calls malloc() that's why asan_inited
662   // should be set to 1 prior to initializing the threads.
663   asan_inited = 1;
664   asan_init_is_running = false;
665
666   if (flags()->atexit)
667     Atexit(asan_atexit);
668
669   if (common_flags()->coverage) {
670     __sanitizer_cov_init();
671     Atexit(__sanitizer_cov_dump);
672   }
673
674   // interceptors
675   InitTlsSize();
676
677   // Create main thread.
678   AsanThread *main_thread = AsanThread::Create(
679       /* start_routine */ nullptr, /* arg */ nullptr, /* parent_tid */ 0,
680       /* stack */ nullptr, /* detached */ true);
681   CHECK_EQ(0, main_thread->tid());
682   SetCurrentThread(main_thread);
683   main_thread->ThreadStart(internal_getpid(),
684                            /* signal_thread_is_registered */ nullptr);
685   force_interface_symbols();  // no-op.
686   SanitizerInitializeUnwinder();
687
688 #if CAN_SANITIZE_LEAKS
689   __lsan::InitCommonLsan(false);
690   if (common_flags()->detect_leaks && common_flags()->leak_check_at_exit) {
691     Atexit(__lsan::DoLeakCheck);
692   }
693 #endif  // CAN_SANITIZE_LEAKS
694
695   InitializeSuppressions();
696
697   VReport(1, "AddressSanitizer Init done\n");
698 }
699
700 // Initialize as requested from some part of ASan runtime library (interceptors,
701 // allocator, etc).
702 void AsanInitFromRtl() {
703   AsanInitInternal();
704 }
705
706 #if ASAN_DYNAMIC
707 // Initialize runtime in case it's LD_PRELOAD-ed into unsanitized executable
708 // (and thus normal initializer from .preinit_array haven't run).
709
710 class AsanInitializer {
711 public:  // NOLINT
712   AsanInitializer() {
713     AsanCheckIncompatibleRT();
714     AsanCheckDynamicRTPrereqs();
715     AsanInitFromRtl();
716   }
717 };
718
719 static AsanInitializer asan_initializer;
720 #endif  // ASAN_DYNAMIC
721
722 }  // namespace __asan
723
724 // ---------------------- Interface ---------------- {{{1
725 using namespace __asan;  // NOLINT
726
727 #if !SANITIZER_SUPPORTS_WEAK_HOOKS
728 extern "C" {
729 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
730 const char* __asan_default_options() { return ""; }
731 }  // extern "C"
732 #endif
733
734 int NOINLINE __asan_set_error_exit_code(int exit_code) {
735   int old = flags()->exitcode;
736   flags()->exitcode = exit_code;
737   return old;
738 }
739
740 void NOINLINE __asan_handle_no_return() {
741   int local_stack;
742   AsanThread *curr_thread = GetCurrentThread();
743   CHECK(curr_thread);
744   uptr PageSize = GetPageSizeCached();
745   uptr top = curr_thread->stack_top();
746   uptr bottom = ((uptr)&local_stack - PageSize) & ~(PageSize-1);
747   static const uptr kMaxExpectedCleanupSize = 64 << 20;  // 64M
748   if (top - bottom > kMaxExpectedCleanupSize) {
749     static bool reported_warning = false;
750     if (reported_warning)
751       return;
752     reported_warning = true;
753     Report("WARNING: ASan is ignoring requested __asan_handle_no_return: "
754            "stack top: %p; bottom %p; size: %p (%zd)\n"
755            "False positive error reports may follow\n"
756            "For details see "
757            "http://code.google.com/p/address-sanitizer/issues/detail?id=189\n",
758            top, bottom, top - bottom, top - bottom);
759     return;
760   }
761   PoisonShadow(bottom, top - bottom, 0);
762   if (curr_thread->has_fake_stack())
763     curr_thread->fake_stack()->HandleNoReturn();
764 }
765
766 void NOINLINE __asan_set_death_callback(void (*callback)(void)) {
767   death_callback = callback;
768 }
769
770 // Initialize as requested from instrumented application code.
771 // We use this call as a trigger to wake up ASan from deactivated state.
772 void __asan_init() {
773   AsanCheckIncompatibleRT();
774   AsanActivate();
775   AsanInitInternal();
776 }