]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/asan/asan_rtl.cc
Merge compiler-rt r291274.
[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
15 #include "asan_activation.h"
16 #include "asan_allocator.h"
17 #include "asan_interceptors.h"
18 #include "asan_interface_internal.h"
19 #include "asan_internal.h"
20 #include "asan_mapping.h"
21 #include "asan_poisoning.h"
22 #include "asan_report.h"
23 #include "asan_stack.h"
24 #include "asan_stats.h"
25 #include "asan_suppressions.h"
26 #include "asan_thread.h"
27 #include "sanitizer_common/sanitizer_atomic.h"
28 #include "sanitizer_common/sanitizer_flags.h"
29 #include "sanitizer_common/sanitizer_libc.h"
30 #include "sanitizer_common/sanitizer_symbolizer.h"
31 #include "lsan/lsan_common.h"
32 #include "ubsan/ubsan_init.h"
33 #include "ubsan/ubsan_platform.h"
34
35 uptr __asan_shadow_memory_dynamic_address;  // Global interface symbol.
36 int __asan_option_detect_stack_use_after_return;  // Global interface symbol.
37 uptr *__asan_test_only_reported_buggy_pointer;  // Used only for testing asan.
38
39 namespace __asan {
40
41 uptr AsanMappingProfile[kAsanMappingProfileSize];
42
43 static void AsanDie() {
44   static atomic_uint32_t num_calls;
45   if (atomic_fetch_add(&num_calls, 1, memory_order_relaxed) != 0) {
46     // Don't die twice - run a busy loop.
47     while (1) { }
48   }
49   if (flags()->sleep_before_dying) {
50     Report("Sleeping for %d second(s)\n", flags()->sleep_before_dying);
51     SleepForSeconds(flags()->sleep_before_dying);
52   }
53   if (flags()->unmap_shadow_on_exit) {
54     if (kMidMemBeg) {
55       UnmapOrDie((void*)kLowShadowBeg, kMidMemBeg - kLowShadowBeg);
56       UnmapOrDie((void*)kMidMemEnd, kHighShadowEnd - kMidMemEnd);
57     } else {
58       UnmapOrDie((void*)kLowShadowBeg, kHighShadowEnd - kLowShadowBeg);
59     }
60   }
61 }
62
63 static void AsanCheckFailed(const char *file, int line, const char *cond,
64                             u64 v1, u64 v2) {
65   Report("AddressSanitizer CHECK failed: %s:%d \"%s\" (0x%zx, 0x%zx)\n", file,
66          line, cond, (uptr)v1, (uptr)v2);
67   // FIXME: check for infinite recursion without a thread-local counter here.
68   PRINT_CURRENT_STACK_CHECK();
69   Die();
70 }
71
72 // -------------------------- Globals --------------------- {{{1
73 int asan_inited;
74 bool asan_init_is_running;
75
76 #if !ASAN_FIXED_MAPPING
77 uptr kHighMemEnd, kMidMemBeg, kMidMemEnd;
78 #endif
79
80 // -------------------------- Misc ---------------- {{{1
81 void ShowStatsAndAbort() {
82   __asan_print_accumulated_stats();
83   Die();
84 }
85
86 // ---------------------- mmap -------------------- {{{1
87 // Reserve memory range [beg, end].
88 // We need to use inclusive range because end+1 may not be representable.
89 void ReserveShadowMemoryRange(uptr beg, uptr end, const char *name) {
90   CHECK_EQ((beg % GetMmapGranularity()), 0);
91   CHECK_EQ(((end + 1) % GetMmapGranularity()), 0);
92   uptr size = end - beg + 1;
93   DecreaseTotalMmap(size);  // Don't count the shadow against mmap_limit_mb.
94   void *res = MmapFixedNoReserve(beg, size, name);
95   if (res != (void*)beg) {
96     Report("ReserveShadowMemoryRange failed while trying to map 0x%zx bytes. "
97            "Perhaps you're using ulimit -v\n", size);
98     Abort();
99   }
100   if (common_flags()->no_huge_pages_for_shadow)
101     NoHugePagesInRegion(beg, size);
102   if (common_flags()->use_madv_dontdump)
103     DontDumpShadowMemory(beg, size);
104 }
105
106 // --------------- LowLevelAllocateCallbac ---------- {{{1
107 static void OnLowLevelAllocate(uptr ptr, uptr size) {
108   PoisonShadow(ptr, size, kAsanInternalHeapMagic);
109 }
110
111 // -------------------------- Run-time entry ------------------- {{{1
112 // exported functions
113 #define ASAN_REPORT_ERROR(type, is_write, size)                     \
114 extern "C" NOINLINE INTERFACE_ATTRIBUTE                             \
115 void __asan_report_ ## type ## size(uptr addr) {                    \
116   GET_CALLER_PC_BP_SP;                                              \
117   ReportGenericError(pc, bp, sp, addr, is_write, size, 0, true);    \
118 }                                                                   \
119 extern "C" NOINLINE INTERFACE_ATTRIBUTE                             \
120 void __asan_report_exp_ ## type ## size(uptr addr, u32 exp) {       \
121   GET_CALLER_PC_BP_SP;                                              \
122   ReportGenericError(pc, bp, sp, addr, is_write, size, exp, true);  \
123 }                                                                   \
124 extern "C" NOINLINE INTERFACE_ATTRIBUTE                             \
125 void __asan_report_ ## type ## size ## _noabort(uptr addr) {        \
126   GET_CALLER_PC_BP_SP;                                              \
127   ReportGenericError(pc, bp, sp, addr, is_write, size, 0, false);   \
128 }                                                                   \
129
130 ASAN_REPORT_ERROR(load, false, 1)
131 ASAN_REPORT_ERROR(load, false, 2)
132 ASAN_REPORT_ERROR(load, false, 4)
133 ASAN_REPORT_ERROR(load, false, 8)
134 ASAN_REPORT_ERROR(load, false, 16)
135 ASAN_REPORT_ERROR(store, true, 1)
136 ASAN_REPORT_ERROR(store, true, 2)
137 ASAN_REPORT_ERROR(store, true, 4)
138 ASAN_REPORT_ERROR(store, true, 8)
139 ASAN_REPORT_ERROR(store, true, 16)
140
141 #define ASAN_REPORT_ERROR_N(type, is_write)                                 \
142 extern "C" NOINLINE INTERFACE_ATTRIBUTE                                     \
143 void __asan_report_ ## type ## _n(uptr addr, uptr size) {                   \
144   GET_CALLER_PC_BP_SP;                                                      \
145   ReportGenericError(pc, bp, sp, addr, is_write, size, 0, true);            \
146 }                                                                           \
147 extern "C" NOINLINE INTERFACE_ATTRIBUTE                                     \
148 void __asan_report_exp_ ## type ## _n(uptr addr, uptr size, u32 exp) {      \
149   GET_CALLER_PC_BP_SP;                                                      \
150   ReportGenericError(pc, bp, sp, addr, is_write, size, exp, true);          \
151 }                                                                           \
152 extern "C" NOINLINE INTERFACE_ATTRIBUTE                                     \
153 void __asan_report_ ## type ## _n_noabort(uptr addr, uptr size) {           \
154   GET_CALLER_PC_BP_SP;                                                      \
155   ReportGenericError(pc, bp, sp, addr, is_write, size, 0, false);           \
156 }                                                                           \
157
158 ASAN_REPORT_ERROR_N(load, false)
159 ASAN_REPORT_ERROR_N(store, true)
160
161 #define ASAN_MEMORY_ACCESS_CALLBACK_BODY(type, is_write, size, exp_arg, fatal) \
162     uptr sp = MEM_TO_SHADOW(addr);                                             \
163     uptr s = size <= SHADOW_GRANULARITY ? *reinterpret_cast<u8 *>(sp)          \
164                                         : *reinterpret_cast<u16 *>(sp);        \
165     if (UNLIKELY(s)) {                                                         \
166       if (UNLIKELY(size >= SHADOW_GRANULARITY ||                               \
167                    ((s8)((addr & (SHADOW_GRANULARITY - 1)) + size - 1)) >=     \
168                        (s8)s)) {                                               \
169         if (__asan_test_only_reported_buggy_pointer) {                         \
170           *__asan_test_only_reported_buggy_pointer = addr;                     \
171         } else {                                                               \
172           GET_CALLER_PC_BP_SP;                                                 \
173           ReportGenericError(pc, bp, sp, addr, is_write, size, exp_arg,        \
174                               fatal);                                          \
175         }                                                                      \
176       }                                                                        \
177     }
178
179 #define ASAN_MEMORY_ACCESS_CALLBACK(type, is_write, size)                      \
180   extern "C" NOINLINE INTERFACE_ATTRIBUTE                                      \
181   void __asan_##type##size(uptr addr) {                                        \
182     ASAN_MEMORY_ACCESS_CALLBACK_BODY(type, is_write, size, 0, true)            \
183   }                                                                            \
184   extern "C" NOINLINE INTERFACE_ATTRIBUTE                                      \
185   void __asan_exp_##type##size(uptr addr, u32 exp) {                           \
186     ASAN_MEMORY_ACCESS_CALLBACK_BODY(type, is_write, size, exp, true)          \
187   }                                                                            \
188   extern "C" NOINLINE INTERFACE_ATTRIBUTE                                      \
189   void __asan_##type##size ## _noabort(uptr addr) {                            \
190     ASAN_MEMORY_ACCESS_CALLBACK_BODY(type, is_write, size, 0, false)           \
191   }                                                                            \
192
193 ASAN_MEMORY_ACCESS_CALLBACK(load, false, 1)
194 ASAN_MEMORY_ACCESS_CALLBACK(load, false, 2)
195 ASAN_MEMORY_ACCESS_CALLBACK(load, false, 4)
196 ASAN_MEMORY_ACCESS_CALLBACK(load, false, 8)
197 ASAN_MEMORY_ACCESS_CALLBACK(load, false, 16)
198 ASAN_MEMORY_ACCESS_CALLBACK(store, true, 1)
199 ASAN_MEMORY_ACCESS_CALLBACK(store, true, 2)
200 ASAN_MEMORY_ACCESS_CALLBACK(store, true, 4)
201 ASAN_MEMORY_ACCESS_CALLBACK(store, true, 8)
202 ASAN_MEMORY_ACCESS_CALLBACK(store, true, 16)
203
204 extern "C"
205 NOINLINE INTERFACE_ATTRIBUTE
206 void __asan_loadN(uptr addr, uptr size) {
207   if (__asan_region_is_poisoned(addr, size)) {
208     GET_CALLER_PC_BP_SP;
209     ReportGenericError(pc, bp, sp, addr, false, size, 0, true);
210   }
211 }
212
213 extern "C"
214 NOINLINE INTERFACE_ATTRIBUTE
215 void __asan_exp_loadN(uptr addr, uptr size, u32 exp) {
216   if (__asan_region_is_poisoned(addr, size)) {
217     GET_CALLER_PC_BP_SP;
218     ReportGenericError(pc, bp, sp, addr, false, size, exp, true);
219   }
220 }
221
222 extern "C"
223 NOINLINE INTERFACE_ATTRIBUTE
224 void __asan_loadN_noabort(uptr addr, uptr size) {
225   if (__asan_region_is_poisoned(addr, size)) {
226     GET_CALLER_PC_BP_SP;
227     ReportGenericError(pc, bp, sp, addr, false, size, 0, false);
228   }
229 }
230
231 extern "C"
232 NOINLINE INTERFACE_ATTRIBUTE
233 void __asan_storeN(uptr addr, uptr size) {
234   if (__asan_region_is_poisoned(addr, size)) {
235     GET_CALLER_PC_BP_SP;
236     ReportGenericError(pc, bp, sp, addr, true, size, 0, true);
237   }
238 }
239
240 extern "C"
241 NOINLINE INTERFACE_ATTRIBUTE
242 void __asan_exp_storeN(uptr addr, uptr size, u32 exp) {
243   if (__asan_region_is_poisoned(addr, size)) {
244     GET_CALLER_PC_BP_SP;
245     ReportGenericError(pc, bp, sp, addr, true, size, exp, true);
246   }
247 }
248
249 extern "C"
250 NOINLINE INTERFACE_ATTRIBUTE
251 void __asan_storeN_noabort(uptr addr, uptr size) {
252   if (__asan_region_is_poisoned(addr, size)) {
253     GET_CALLER_PC_BP_SP;
254     ReportGenericError(pc, bp, sp, addr, true, size, 0, false);
255   }
256 }
257
258 // Force the linker to keep the symbols for various ASan interface functions.
259 // We want to keep those in the executable in order to let the instrumented
260 // dynamic libraries access the symbol even if it is not used by the executable
261 // itself. This should help if the build system is removing dead code at link
262 // time.
263 static NOINLINE void force_interface_symbols() {
264   volatile int fake_condition = 0;  // prevent dead condition elimination.
265   // __asan_report_* functions are noreturn, so we need a switch to prevent
266   // the compiler from removing any of them.
267   // clang-format off
268   switch (fake_condition) {
269     case 1: __asan_report_load1(0); break;
270     case 2: __asan_report_load2(0); break;
271     case 3: __asan_report_load4(0); break;
272     case 4: __asan_report_load8(0); break;
273     case 5: __asan_report_load16(0); break;
274     case 6: __asan_report_load_n(0, 0); break;
275     case 7: __asan_report_store1(0); break;
276     case 8: __asan_report_store2(0); break;
277     case 9: __asan_report_store4(0); break;
278     case 10: __asan_report_store8(0); break;
279     case 11: __asan_report_store16(0); break;
280     case 12: __asan_report_store_n(0, 0); break;
281     case 13: __asan_report_exp_load1(0, 0); break;
282     case 14: __asan_report_exp_load2(0, 0); break;
283     case 15: __asan_report_exp_load4(0, 0); break;
284     case 16: __asan_report_exp_load8(0, 0); break;
285     case 17: __asan_report_exp_load16(0, 0); break;
286     case 18: __asan_report_exp_load_n(0, 0, 0); break;
287     case 19: __asan_report_exp_store1(0, 0); break;
288     case 20: __asan_report_exp_store2(0, 0); break;
289     case 21: __asan_report_exp_store4(0, 0); break;
290     case 22: __asan_report_exp_store8(0, 0); break;
291     case 23: __asan_report_exp_store16(0, 0); break;
292     case 24: __asan_report_exp_store_n(0, 0, 0); break;
293     case 25: __asan_register_globals(nullptr, 0); break;
294     case 26: __asan_unregister_globals(nullptr, 0); break;
295     case 27: __asan_set_death_callback(nullptr); break;
296     case 28: __asan_set_error_report_callback(nullptr); break;
297     case 29: __asan_handle_no_return(); break;
298     case 30: __asan_address_is_poisoned(nullptr); break;
299     case 31: __asan_poison_memory_region(nullptr, 0); break;
300     case 32: __asan_unpoison_memory_region(nullptr, 0); break;
301     case 34: __asan_before_dynamic_init(nullptr); break;
302     case 35: __asan_after_dynamic_init(); break;
303     case 36: __asan_poison_stack_memory(0, 0); break;
304     case 37: __asan_unpoison_stack_memory(0, 0); break;
305     case 38: __asan_region_is_poisoned(0, 0); break;
306     case 39: __asan_describe_address(0); break;
307     case 40: __asan_set_shadow_00(0, 0); break;
308     case 41: __asan_set_shadow_f1(0, 0); break;
309     case 42: __asan_set_shadow_f2(0, 0); break;
310     case 43: __asan_set_shadow_f3(0, 0); break;
311     case 44: __asan_set_shadow_f5(0, 0); break;
312     case 45: __asan_set_shadow_f8(0, 0); break;
313   }
314   // clang-format on
315 }
316
317 static void asan_atexit() {
318   Printf("AddressSanitizer exit stats:\n");
319   __asan_print_accumulated_stats();
320   // Print AsanMappingProfile.
321   for (uptr i = 0; i < kAsanMappingProfileSize; i++) {
322     if (AsanMappingProfile[i] == 0) continue;
323     Printf("asan_mapping.h:%zd -- %zd\n", i, AsanMappingProfile[i]);
324   }
325 }
326
327 static void InitializeHighMemEnd() {
328 #if !ASAN_FIXED_MAPPING
329   kHighMemEnd = GetMaxVirtualAddress();
330   // Increase kHighMemEnd to make sure it's properly
331   // aligned together with kHighMemBeg:
332   kHighMemEnd |= SHADOW_GRANULARITY * GetMmapGranularity() - 1;
333 #endif  // !ASAN_FIXED_MAPPING
334   CHECK_EQ((kHighMemBeg % GetMmapGranularity()), 0);
335 }
336
337 static void ProtectGap(uptr addr, uptr size) {
338   if (!flags()->protect_shadow_gap) {
339     // The shadow gap is unprotected, so there is a chance that someone
340     // is actually using this memory. Which means it needs a shadow...
341     uptr GapShadowBeg = RoundDownTo(MEM_TO_SHADOW(addr), GetPageSizeCached());
342     uptr GapShadowEnd =
343         RoundUpTo(MEM_TO_SHADOW(addr + size), GetPageSizeCached()) - 1;
344     if (Verbosity())
345       Printf("protect_shadow_gap=0:"
346              " not protecting shadow gap, allocating gap's shadow\n"
347              "|| `[%p, %p]` || ShadowGap's shadow ||\n", GapShadowBeg,
348              GapShadowEnd);
349     ReserveShadowMemoryRange(GapShadowBeg, GapShadowEnd,
350                              "unprotected gap shadow");
351     return;
352   }
353   void *res = MmapFixedNoAccess(addr, size, "shadow gap");
354   if (addr == (uptr)res)
355     return;
356   // A few pages at the start of the address space can not be protected.
357   // But we really want to protect as much as possible, to prevent this memory
358   // being returned as a result of a non-FIXED mmap().
359   if (addr == kZeroBaseShadowStart) {
360     uptr step = GetMmapGranularity();
361     while (size > step && addr < kZeroBaseMaxShadowStart) {
362       addr += step;
363       size -= step;
364       void *res = MmapFixedNoAccess(addr, size, "shadow gap");
365       if (addr == (uptr)res)
366         return;
367     }
368   }
369
370   Report("ERROR: Failed to protect the shadow gap. "
371          "ASan cannot proceed correctly. ABORTING.\n");
372   DumpProcessMap();
373   Die();
374 }
375
376 static void PrintAddressSpaceLayout() {
377   Printf("|| `[%p, %p]` || HighMem    ||\n",
378          (void*)kHighMemBeg, (void*)kHighMemEnd);
379   Printf("|| `[%p, %p]` || HighShadow ||\n",
380          (void*)kHighShadowBeg, (void*)kHighShadowEnd);
381   if (kMidMemBeg) {
382     Printf("|| `[%p, %p]` || ShadowGap3 ||\n",
383            (void*)kShadowGap3Beg, (void*)kShadowGap3End);
384     Printf("|| `[%p, %p]` || MidMem     ||\n",
385            (void*)kMidMemBeg, (void*)kMidMemEnd);
386     Printf("|| `[%p, %p]` || ShadowGap2 ||\n",
387            (void*)kShadowGap2Beg, (void*)kShadowGap2End);
388     Printf("|| `[%p, %p]` || MidShadow  ||\n",
389            (void*)kMidShadowBeg, (void*)kMidShadowEnd);
390   }
391   Printf("|| `[%p, %p]` || ShadowGap  ||\n",
392          (void*)kShadowGapBeg, (void*)kShadowGapEnd);
393   if (kLowShadowBeg) {
394     Printf("|| `[%p, %p]` || LowShadow  ||\n",
395            (void*)kLowShadowBeg, (void*)kLowShadowEnd);
396     Printf("|| `[%p, %p]` || LowMem     ||\n",
397            (void*)kLowMemBeg, (void*)kLowMemEnd);
398   }
399   Printf("MemToShadow(shadow): %p %p %p %p",
400          (void*)MEM_TO_SHADOW(kLowShadowBeg),
401          (void*)MEM_TO_SHADOW(kLowShadowEnd),
402          (void*)MEM_TO_SHADOW(kHighShadowBeg),
403          (void*)MEM_TO_SHADOW(kHighShadowEnd));
404   if (kMidMemBeg) {
405     Printf(" %p %p",
406            (void*)MEM_TO_SHADOW(kMidShadowBeg),
407            (void*)MEM_TO_SHADOW(kMidShadowEnd));
408   }
409   Printf("\n");
410   Printf("redzone=%zu\n", (uptr)flags()->redzone);
411   Printf("max_redzone=%zu\n", (uptr)flags()->max_redzone);
412   Printf("quarantine_size_mb=%zuM\n", (uptr)flags()->quarantine_size_mb);
413   Printf("thread_local_quarantine_size_kb=%zuK\n",
414          (uptr)flags()->thread_local_quarantine_size_kb);
415   Printf("malloc_context_size=%zu\n",
416          (uptr)common_flags()->malloc_context_size);
417
418   Printf("SHADOW_SCALE: %d\n", (int)SHADOW_SCALE);
419   Printf("SHADOW_GRANULARITY: %d\n", (int)SHADOW_GRANULARITY);
420   Printf("SHADOW_OFFSET: 0x%zx\n", (uptr)SHADOW_OFFSET);
421   CHECK(SHADOW_SCALE >= 3 && SHADOW_SCALE <= 7);
422   if (kMidMemBeg)
423     CHECK(kMidShadowBeg > kLowShadowEnd &&
424           kMidMemBeg > kMidShadowEnd &&
425           kHighShadowBeg > kMidMemEnd);
426 }
427
428 static void InitializeShadowMemory() {
429   // Set the shadow memory address to uninitialized.
430   __asan_shadow_memory_dynamic_address = kDefaultShadowSentinel;
431
432   uptr shadow_start = kLowShadowBeg;
433   // Detect if a dynamic shadow address must used and find a available location
434   // when necessary. When dynamic address is used, the macro |kLowShadowBeg|
435   // expands to |__asan_shadow_memory_dynamic_address| which is
436   // |kDefaultShadowSentinel|.
437   if (shadow_start == kDefaultShadowSentinel) {
438     __asan_shadow_memory_dynamic_address = 0;
439     CHECK_EQ(0, kLowShadowBeg);
440
441     uptr granularity = GetMmapGranularity();
442     uptr alignment = 8 * granularity;
443     uptr left_padding = granularity;
444     uptr space_size = kHighShadowEnd + left_padding;
445
446     shadow_start = FindAvailableMemoryRange(space_size, alignment, granularity);
447     CHECK_NE((uptr)0, shadow_start);
448     CHECK(IsAligned(shadow_start, alignment));
449   }
450   // Update the shadow memory address (potentially) used by instrumentation.
451   __asan_shadow_memory_dynamic_address = shadow_start;
452
453   if (kLowShadowBeg)
454     shadow_start -= GetMmapGranularity();
455   bool full_shadow_is_available =
456       MemoryRangeIsAvailable(shadow_start, kHighShadowEnd);
457
458 #if SANITIZER_LINUX && defined(__x86_64__) && defined(_LP64) &&                \
459     !ASAN_FIXED_MAPPING
460   if (!full_shadow_is_available) {
461     kMidMemBeg = kLowMemEnd < 0x3000000000ULL ? 0x3000000000ULL : 0;
462     kMidMemEnd = kLowMemEnd < 0x3000000000ULL ? 0x4fffffffffULL : 0;
463   }
464 #endif
465
466   if (Verbosity()) PrintAddressSpaceLayout();
467
468   if (full_shadow_is_available) {
469     // mmap the low shadow plus at least one page at the left.
470     if (kLowShadowBeg)
471       ReserveShadowMemoryRange(shadow_start, kLowShadowEnd, "low shadow");
472     // mmap the high shadow.
473     ReserveShadowMemoryRange(kHighShadowBeg, kHighShadowEnd, "high shadow");
474     // protect the gap.
475     ProtectGap(kShadowGapBeg, kShadowGapEnd - kShadowGapBeg + 1);
476     CHECK_EQ(kShadowGapEnd, kHighShadowBeg - 1);
477   } else if (kMidMemBeg &&
478       MemoryRangeIsAvailable(shadow_start, kMidMemBeg - 1) &&
479       MemoryRangeIsAvailable(kMidMemEnd + 1, kHighShadowEnd)) {
480     CHECK(kLowShadowBeg != kLowShadowEnd);
481     // mmap the low shadow plus at least one page at the left.
482     ReserveShadowMemoryRange(shadow_start, kLowShadowEnd, "low shadow");
483     // mmap the mid shadow.
484     ReserveShadowMemoryRange(kMidShadowBeg, kMidShadowEnd, "mid shadow");
485     // mmap the high shadow.
486     ReserveShadowMemoryRange(kHighShadowBeg, kHighShadowEnd, "high shadow");
487     // protect the gaps.
488     ProtectGap(kShadowGapBeg, kShadowGapEnd - kShadowGapBeg + 1);
489     ProtectGap(kShadowGap2Beg, kShadowGap2End - kShadowGap2Beg + 1);
490     ProtectGap(kShadowGap3Beg, kShadowGap3End - kShadowGap3Beg + 1);
491   } else {
492     Report("Shadow memory range interleaves with an existing memory mapping. "
493            "ASan cannot proceed correctly. ABORTING.\n");
494     Report("ASan shadow was supposed to be located in the [%p-%p] range.\n",
495            shadow_start, kHighShadowEnd);
496     DumpProcessMap();
497     Die();
498   }
499 }
500
501 static void AsanInitInternal() {
502   if (LIKELY(asan_inited)) return;
503   SanitizerToolName = "AddressSanitizer";
504   CHECK(!asan_init_is_running && "ASan init calls itself!");
505   asan_init_is_running = true;
506
507   CacheBinaryName();
508
509   // Initialize flags. This must be done early, because most of the
510   // initialization steps look at flags().
511   InitializeFlags();
512
513   AsanCheckIncompatibleRT();
514   AsanCheckDynamicRTPrereqs();
515   AvoidCVE_2016_2143();
516
517   SetCanPoisonMemory(flags()->poison_heap);
518   SetMallocContextSize(common_flags()->malloc_context_size);
519
520   InitializePlatformExceptionHandlers();
521
522   InitializeHighMemEnd();
523
524   // Make sure we are not statically linked.
525   AsanDoesNotSupportStaticLinkage();
526
527   // Install tool-specific callbacks in sanitizer_common.
528   AddDieCallback(AsanDie);
529   SetCheckFailedCallback(AsanCheckFailed);
530   SetPrintfAndReportCallback(AppendToErrorMessageBuffer);
531
532   __sanitizer_set_report_path(common_flags()->log_path);
533
534   __asan_option_detect_stack_use_after_return =
535       flags()->detect_stack_use_after_return;
536
537   // Re-exec ourselves if we need to set additional env or command line args.
538   MaybeReexec();
539
540   // Setup internal allocator callback.
541   SetLowLevelAllocateCallback(OnLowLevelAllocate);
542
543   InitializeAsanInterceptors();
544
545   // Enable system log ("adb logcat") on Android.
546   // Doing this before interceptors are initialized crashes in:
547   // AsanInitInternal -> android_log_write -> __interceptor_strcmp
548   AndroidLogInit();
549
550   ReplaceSystemMalloc();
551
552   DisableCoreDumperIfNecessary();
553
554   InitializeShadowMemory();
555
556   AsanTSDInit(PlatformTSDDtor);
557   InstallDeadlySignalHandlers(AsanOnDeadlySignal);
558
559   AllocatorOptions allocator_options;
560   allocator_options.SetFrom(flags(), common_flags());
561   InitializeAllocator(allocator_options);
562
563   MaybeStartBackgroudThread();
564   SetSoftRssLimitExceededCallback(AsanSoftRssLimitExceededCallback);
565
566   // On Linux AsanThread::ThreadStart() calls malloc() that's why asan_inited
567   // should be set to 1 prior to initializing the threads.
568   asan_inited = 1;
569   asan_init_is_running = false;
570
571   if (flags()->atexit)
572     Atexit(asan_atexit);
573
574   InitializeCoverage(common_flags()->coverage, common_flags()->coverage_dir);
575
576   // Now that ASan runtime is (mostly) initialized, deactivate it if
577   // necessary, so that it can be re-activated when requested.
578   if (flags()->start_deactivated)
579     AsanDeactivate();
580
581   // interceptors
582   InitTlsSize();
583
584   // Create main thread.
585   AsanThread *main_thread = AsanThread::Create(
586       /* start_routine */ nullptr, /* arg */ nullptr, /* parent_tid */ 0,
587       /* stack */ nullptr, /* detached */ true);
588   CHECK_EQ(0, main_thread->tid());
589   SetCurrentThread(main_thread);
590   main_thread->ThreadStart(internal_getpid(),
591                            /* signal_thread_is_registered */ nullptr);
592   force_interface_symbols();  // no-op.
593   SanitizerInitializeUnwinder();
594
595   if (CAN_SANITIZE_LEAKS) {
596     __lsan::InitCommonLsan();
597     if (common_flags()->detect_leaks && common_flags()->leak_check_at_exit) {
598       Atexit(__lsan::DoLeakCheck);
599     }
600   }
601
602 #if CAN_SANITIZE_UB
603   __ubsan::InitAsPlugin();
604 #endif
605
606   InitializeSuppressions();
607
608   if (CAN_SANITIZE_LEAKS) {
609     // LateInitialize() calls dlsym, which can allocate an error string buffer
610     // in the TLS.  Let's ignore the allocation to avoid reporting a leak.
611     __lsan::ScopedInterceptorDisabler disabler;
612     Symbolizer::LateInitialize();
613   } else {
614     Symbolizer::LateInitialize();
615   }
616
617   VReport(1, "AddressSanitizer Init done\n");
618 }
619
620 // Initialize as requested from some part of ASan runtime library (interceptors,
621 // allocator, etc).
622 void AsanInitFromRtl() {
623   AsanInitInternal();
624 }
625
626 #if ASAN_DYNAMIC
627 // Initialize runtime in case it's LD_PRELOAD-ed into unsanitized executable
628 // (and thus normal initializers from .preinit_array or modules haven't run).
629
630 class AsanInitializer {
631 public:  // NOLINT
632   AsanInitializer() {
633     AsanInitFromRtl();
634   }
635 };
636
637 static AsanInitializer asan_initializer;
638 #endif  // ASAN_DYNAMIC
639
640 } // namespace __asan
641
642 // ---------------------- Interface ---------------- {{{1
643 using namespace __asan;  // NOLINT
644
645 void NOINLINE __asan_handle_no_return() {
646   if (asan_init_is_running)
647     return;
648
649   int local_stack;
650   AsanThread *curr_thread = GetCurrentThread();
651   uptr PageSize = GetPageSizeCached();
652   uptr top, bottom;
653   if (curr_thread) {
654     top = curr_thread->stack_top();
655     bottom = ((uptr)&local_stack - PageSize) & ~(PageSize - 1);
656   } else {
657     // If we haven't seen this thread, try asking the OS for stack bounds.
658     uptr tls_addr, tls_size, stack_size;
659     GetThreadStackAndTls(/*main=*/false, &bottom, &stack_size, &tls_addr,
660                          &tls_size);
661     top = bottom + stack_size;
662   }
663   static const uptr kMaxExpectedCleanupSize = 64 << 20;  // 64M
664   if (top - bottom > kMaxExpectedCleanupSize) {
665     static bool reported_warning = false;
666     if (reported_warning)
667       return;
668     reported_warning = true;
669     Report("WARNING: ASan is ignoring requested __asan_handle_no_return: "
670            "stack top: %p; bottom %p; size: %p (%zd)\n"
671            "False positive error reports may follow\n"
672            "For details see "
673            "https://github.com/google/sanitizers/issues/189\n",
674            top, bottom, top - bottom, top - bottom);
675     return;
676   }
677   PoisonShadow(bottom, top - bottom, 0);
678   if (curr_thread && curr_thread->has_fake_stack())
679     curr_thread->fake_stack()->HandleNoReturn();
680 }
681
682 void NOINLINE __asan_set_death_callback(void (*callback)(void)) {
683   SetUserDieCallback(callback);
684 }
685
686 // Initialize as requested from instrumented application code.
687 // We use this call as a trigger to wake up ASan from deactivated state.
688 void __asan_init() {
689   AsanActivate();
690   AsanInitInternal();
691 }
692
693 void __asan_version_mismatch_check() {
694   // Do nothing.
695 }