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