1 //===-- asan_rtl.cpp ------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file is a part of AddressSanitizer, an address sanity checker.
10 //
11 // Main file of the ASan run-time library.
12 //===----------------------------------------------------------------------===//
13 
14 #include "asan_activation.h"
15 #include "asan_allocator.h"
16 #include "asan_fake_stack.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 "lsan/lsan_common.h"
28 #include "sanitizer_common/sanitizer_atomic.h"
29 #include "sanitizer_common/sanitizer_flags.h"
30 #include "sanitizer_common/sanitizer_interface_internal.h"
31 #include "sanitizer_common/sanitizer_libc.h"
32 #include "sanitizer_common/sanitizer_symbolizer.h"
33 #include "ubsan/ubsan_init.h"
34 #include "ubsan/ubsan_platform.h"
35 
36 uptr __asan_shadow_memory_dynamic_address;  // Global interface symbol.
37 int __asan_option_detect_stack_use_after_return;  // Global interface symbol.
38 uptr *__asan_test_only_reported_buggy_pointer;  // Used only for testing asan.
39 
40 namespace __asan {
41 
42 uptr AsanMappingProfile[kAsanMappingProfileSize];
43 
44 static void AsanDie() {
45   static atomic_uint32_t num_calls;
46   if (atomic_fetch_add(&num_calls, 1, memory_order_relaxed) != 0) {
47     // Don't die twice - run a busy loop.
48     while (1) {
49       internal_sched_yield();
50     }
51   }
52   if (common_flags()->print_module_map >= 1)
53     DumpProcessMap();
54   if (flags()->sleep_before_dying) {
55     Report("Sleeping for %d second(s)\n", flags()->sleep_before_dying);
56     SleepForSeconds(flags()->sleep_before_dying);
57   }
58   if (flags()->unmap_shadow_on_exit) {
59     if (kMidMemBeg) {
60       UnmapOrDie((void*)kLowShadowBeg, kMidMemBeg - kLowShadowBeg);
61       UnmapOrDie((void*)kMidMemEnd, kHighShadowEnd - kMidMemEnd);
62     } else {
63       if (kHighShadowEnd)
64         UnmapOrDie((void*)kLowShadowBeg, kHighShadowEnd - kLowShadowBeg);
65     }
66   }
67 }
68 
69 static void CheckUnwind() {
70   GET_STACK_TRACE(kStackTraceMax, common_flags()->fast_unwind_on_check);
71   stack.Print();
72 }
73 
74 // -------------------------- Globals --------------------- {{{1
75 int asan_inited;
76 bool asan_init_is_running;
77 
78 #if !ASAN_FIXED_MAPPING
79 uptr kHighMemEnd, kMidMemBeg, kMidMemEnd;
80 #endif
81 
82 // -------------------------- Misc ---------------- {{{1
83 void ShowStatsAndAbort() {
84   __asan_print_accumulated_stats();
85   Die();
86 }
87 
88 NOINLINE
89 static void ReportGenericErrorWrapper(uptr addr, bool is_write, int size,
90                                       int exp_arg, bool fatal) {
91   GET_CALLER_PC_BP_SP;
92   ReportGenericError(pc, bp, sp, addr, is_write, size, exp_arg, fatal);
93 }
94 
95 // --------------- LowLevelAllocateCallbac ---------- {{{1
96 static void OnLowLevelAllocate(uptr ptr, uptr size) {
97   PoisonShadow(ptr, size, kAsanInternalHeapMagic);
98 }
99 
100 // -------------------------- Run-time entry ------------------- {{{1
101 // exported functions
102 #define ASAN_REPORT_ERROR(type, is_write, size)                     \
103 extern "C" NOINLINE INTERFACE_ATTRIBUTE                             \
104 void __asan_report_ ## type ## size(uptr addr) {                    \
105   GET_CALLER_PC_BP_SP;                                              \
106   ReportGenericError(pc, bp, sp, addr, is_write, size, 0, true);    \
107 }                                                                   \
108 extern "C" NOINLINE INTERFACE_ATTRIBUTE                             \
109 void __asan_report_exp_ ## type ## size(uptr addr, u32 exp) {       \
110   GET_CALLER_PC_BP_SP;                                              \
111   ReportGenericError(pc, bp, sp, addr, is_write, size, exp, true);  \
112 }                                                                   \
113 extern "C" NOINLINE INTERFACE_ATTRIBUTE                             \
114 void __asan_report_ ## type ## size ## _noabort(uptr addr) {        \
115   GET_CALLER_PC_BP_SP;                                              \
116   ReportGenericError(pc, bp, sp, addr, is_write, size, 0, false);   \
117 }                                                                   \
118 
119 ASAN_REPORT_ERROR(load, false, 1)
120 ASAN_REPORT_ERROR(load, false, 2)
121 ASAN_REPORT_ERROR(load, false, 4)
122 ASAN_REPORT_ERROR(load, false, 8)
123 ASAN_REPORT_ERROR(load, false, 16)
124 ASAN_REPORT_ERROR(store, true, 1)
125 ASAN_REPORT_ERROR(store, true, 2)
126 ASAN_REPORT_ERROR(store, true, 4)
127 ASAN_REPORT_ERROR(store, true, 8)
128 ASAN_REPORT_ERROR(store, true, 16)
129 
130 #define ASAN_REPORT_ERROR_N(type, is_write)                                 \
131 extern "C" NOINLINE INTERFACE_ATTRIBUTE                                     \
132 void __asan_report_ ## type ## _n(uptr addr, uptr size) {                   \
133   GET_CALLER_PC_BP_SP;                                                      \
134   ReportGenericError(pc, bp, sp, addr, is_write, size, 0, true);            \
135 }                                                                           \
136 extern "C" NOINLINE INTERFACE_ATTRIBUTE                                     \
137 void __asan_report_exp_ ## type ## _n(uptr addr, uptr size, u32 exp) {      \
138   GET_CALLER_PC_BP_SP;                                                      \
139   ReportGenericError(pc, bp, sp, addr, is_write, size, exp, true);          \
140 }                                                                           \
141 extern "C" NOINLINE INTERFACE_ATTRIBUTE                                     \
142 void __asan_report_ ## type ## _n_noabort(uptr addr, uptr size) {           \
143   GET_CALLER_PC_BP_SP;                                                      \
144   ReportGenericError(pc, bp, sp, addr, is_write, size, 0, false);           \
145 }                                                                           \
146 
147 ASAN_REPORT_ERROR_N(load, false)
148 ASAN_REPORT_ERROR_N(store, true)
149 
150 #define ASAN_MEMORY_ACCESS_CALLBACK_BODY(type, is_write, size, exp_arg, fatal) \
151   uptr sp = MEM_TO_SHADOW(addr);                                               \
152   uptr s = size <= ASAN_SHADOW_GRANULARITY ? *reinterpret_cast<u8 *>(sp)       \
153                                            : *reinterpret_cast<u16 *>(sp);     \
154   if (UNLIKELY(s)) {                                                           \
155     if (UNLIKELY(size >= ASAN_SHADOW_GRANULARITY ||                            \
156                  ((s8)((addr & (ASAN_SHADOW_GRANULARITY - 1)) + size - 1)) >=  \
157                      (s8)s)) {                                                 \
158       ReportGenericErrorWrapper(addr, is_write, size, exp_arg, fatal);         \
159     }                                                                          \
160   }
161 
162 #define ASAN_MEMORY_ACCESS_CALLBACK(type, is_write, size)                      \
163   extern "C" NOINLINE INTERFACE_ATTRIBUTE                                      \
164   void __asan_##type##size(uptr addr) {                                        \
165     ASAN_MEMORY_ACCESS_CALLBACK_BODY(type, is_write, size, 0, true)            \
166   }                                                                            \
167   extern "C" NOINLINE INTERFACE_ATTRIBUTE                                      \
168   void __asan_exp_##type##size(uptr addr, u32 exp) {                           \
169     ASAN_MEMORY_ACCESS_CALLBACK_BODY(type, is_write, size, exp, true)          \
170   }                                                                            \
171   extern "C" NOINLINE INTERFACE_ATTRIBUTE                                      \
172   void __asan_##type##size ## _noabort(uptr addr) {                            \
173     ASAN_MEMORY_ACCESS_CALLBACK_BODY(type, is_write, size, 0, false)           \
174   }                                                                            \
175 
176 ASAN_MEMORY_ACCESS_CALLBACK(load, false, 1)
177 ASAN_MEMORY_ACCESS_CALLBACK(load, false, 2)
178 ASAN_MEMORY_ACCESS_CALLBACK(load, false, 4)
179 ASAN_MEMORY_ACCESS_CALLBACK(load, false, 8)
180 ASAN_MEMORY_ACCESS_CALLBACK(load, false, 16)
181 ASAN_MEMORY_ACCESS_CALLBACK(store, true, 1)
182 ASAN_MEMORY_ACCESS_CALLBACK(store, true, 2)
183 ASAN_MEMORY_ACCESS_CALLBACK(store, true, 4)
184 ASAN_MEMORY_ACCESS_CALLBACK(store, true, 8)
185 ASAN_MEMORY_ACCESS_CALLBACK(store, true, 16)
186 
187 extern "C"
188 NOINLINE INTERFACE_ATTRIBUTE
189 void __asan_loadN(uptr addr, uptr size) {
190   if (__asan_region_is_poisoned(addr, size)) {
191     GET_CALLER_PC_BP_SP;
192     ReportGenericError(pc, bp, sp, addr, false, size, 0, true);
193   }
194 }
195 
196 extern "C"
197 NOINLINE INTERFACE_ATTRIBUTE
198 void __asan_exp_loadN(uptr addr, uptr size, u32 exp) {
199   if (__asan_region_is_poisoned(addr, size)) {
200     GET_CALLER_PC_BP_SP;
201     ReportGenericError(pc, bp, sp, addr, false, size, exp, true);
202   }
203 }
204 
205 extern "C"
206 NOINLINE INTERFACE_ATTRIBUTE
207 void __asan_loadN_noabort(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, false);
211   }
212 }
213 
214 extern "C"
215 NOINLINE INTERFACE_ATTRIBUTE
216 void __asan_storeN(uptr addr, uptr size) {
217   if (__asan_region_is_poisoned(addr, size)) {
218     GET_CALLER_PC_BP_SP;
219     ReportGenericError(pc, bp, sp, addr, true, size, 0, true);
220   }
221 }
222 
223 extern "C"
224 NOINLINE INTERFACE_ATTRIBUTE
225 void __asan_exp_storeN(uptr addr, uptr size, u32 exp) {
226   if (__asan_region_is_poisoned(addr, size)) {
227     GET_CALLER_PC_BP_SP;
228     ReportGenericError(pc, bp, sp, addr, true, size, exp, true);
229   }
230 }
231 
232 extern "C"
233 NOINLINE INTERFACE_ATTRIBUTE
234 void __asan_storeN_noabort(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, false);
238   }
239 }
240 
241 // Force the linker to keep the symbols for various ASan interface functions.
242 // We want to keep those in the executable in order to let the instrumented
243 // dynamic libraries access the symbol even if it is not used by the executable
244 // itself. This should help if the build system is removing dead code at link
245 // time.
246 static NOINLINE void force_interface_symbols() {
247   volatile int fake_condition = 0;  // prevent dead condition elimination.
248   // __asan_report_* functions are noreturn, so we need a switch to prevent
249   // the compiler from removing any of them.
250   // clang-format off
251   switch (fake_condition) {
252     case 1: __asan_report_load1(0); break;
253     case 2: __asan_report_load2(0); break;
254     case 3: __asan_report_load4(0); break;
255     case 4: __asan_report_load8(0); break;
256     case 5: __asan_report_load16(0); break;
257     case 6: __asan_report_load_n(0, 0); break;
258     case 7: __asan_report_store1(0); break;
259     case 8: __asan_report_store2(0); break;
260     case 9: __asan_report_store4(0); break;
261     case 10: __asan_report_store8(0); break;
262     case 11: __asan_report_store16(0); break;
263     case 12: __asan_report_store_n(0, 0); break;
264     case 13: __asan_report_exp_load1(0, 0); break;
265     case 14: __asan_report_exp_load2(0, 0); break;
266     case 15: __asan_report_exp_load4(0, 0); break;
267     case 16: __asan_report_exp_load8(0, 0); break;
268     case 17: __asan_report_exp_load16(0, 0); break;
269     case 18: __asan_report_exp_load_n(0, 0, 0); break;
270     case 19: __asan_report_exp_store1(0, 0); break;
271     case 20: __asan_report_exp_store2(0, 0); break;
272     case 21: __asan_report_exp_store4(0, 0); break;
273     case 22: __asan_report_exp_store8(0, 0); break;
274     case 23: __asan_report_exp_store16(0, 0); break;
275     case 24: __asan_report_exp_store_n(0, 0, 0); break;
276     case 25: __asan_register_globals(nullptr, 0); break;
277     case 26: __asan_unregister_globals(nullptr, 0); break;
278     case 27: __asan_set_death_callback(nullptr); break;
279     case 28: __asan_set_error_report_callback(nullptr); break;
280     case 29: __asan_handle_no_return(); break;
281     case 30: __asan_address_is_poisoned(nullptr); break;
282     case 31: __asan_poison_memory_region(nullptr, 0); break;
283     case 32: __asan_unpoison_memory_region(nullptr, 0); break;
284     case 34: __asan_before_dynamic_init(nullptr); break;
285     case 35: __asan_after_dynamic_init(); break;
286     case 36: __asan_poison_stack_memory(0, 0); break;
287     case 37: __asan_unpoison_stack_memory(0, 0); break;
288     case 38: __asan_region_is_poisoned(0, 0); break;
289     case 39: __asan_describe_address(0); break;
290     case 40: __asan_set_shadow_00(0, 0); break;
291     case 41: __asan_set_shadow_f1(0, 0); break;
292     case 42: __asan_set_shadow_f2(0, 0); break;
293     case 43: __asan_set_shadow_f3(0, 0); break;
294     case 44: __asan_set_shadow_f5(0, 0); break;
295     case 45: __asan_set_shadow_f8(0, 0); break;
296   }
297   // clang-format on
298 }
299 
300 static void asan_atexit() {
301   Printf("AddressSanitizer exit stats:\n");
302   __asan_print_accumulated_stats();
303   // Print AsanMappingProfile.
304   for (uptr i = 0; i < kAsanMappingProfileSize; i++) {
305     if (AsanMappingProfile[i] == 0) continue;
306     Printf("asan_mapping.h:%zd -- %zd\n", i, AsanMappingProfile[i]);
307   }
308 }
309 
310 static void InitializeHighMemEnd() {
311 #if !ASAN_FIXED_MAPPING
312   kHighMemEnd = GetMaxUserVirtualAddress();
313   // Increase kHighMemEnd to make sure it's properly
314   // aligned together with kHighMemBeg:
315   kHighMemEnd |= (GetMmapGranularity() << ASAN_SHADOW_SCALE) - 1;
316 #endif  // !ASAN_FIXED_MAPPING
317   CHECK_EQ((kHighMemBeg % GetMmapGranularity()), 0);
318 }
319 
320 void PrintAddressSpaceLayout() {
321   if (kHighMemBeg) {
322     Printf("|| `[%p, %p]` || HighMem    ||\n",
323            (void*)kHighMemBeg, (void*)kHighMemEnd);
324     Printf("|| `[%p, %p]` || HighShadow ||\n",
325            (void*)kHighShadowBeg, (void*)kHighShadowEnd);
326   }
327   if (kMidMemBeg) {
328     Printf("|| `[%p, %p]` || ShadowGap3 ||\n",
329            (void*)kShadowGap3Beg, (void*)kShadowGap3End);
330     Printf("|| `[%p, %p]` || MidMem     ||\n",
331            (void*)kMidMemBeg, (void*)kMidMemEnd);
332     Printf("|| `[%p, %p]` || ShadowGap2 ||\n",
333            (void*)kShadowGap2Beg, (void*)kShadowGap2End);
334     Printf("|| `[%p, %p]` || MidShadow  ||\n",
335            (void*)kMidShadowBeg, (void*)kMidShadowEnd);
336   }
337   Printf("|| `[%p, %p]` || ShadowGap  ||\n",
338          (void*)kShadowGapBeg, (void*)kShadowGapEnd);
339   if (kLowShadowBeg) {
340     Printf("|| `[%p, %p]` || LowShadow  ||\n",
341            (void*)kLowShadowBeg, (void*)kLowShadowEnd);
342     Printf("|| `[%p, %p]` || LowMem     ||\n",
343            (void*)kLowMemBeg, (void*)kLowMemEnd);
344   }
345   Printf("MemToShadow(shadow): %p %p",
346          (void*)MEM_TO_SHADOW(kLowShadowBeg),
347          (void*)MEM_TO_SHADOW(kLowShadowEnd));
348   if (kHighMemBeg) {
349     Printf(" %p %p",
350            (void*)MEM_TO_SHADOW(kHighShadowBeg),
351            (void*)MEM_TO_SHADOW(kHighShadowEnd));
352   }
353   if (kMidMemBeg) {
354     Printf(" %p %p",
355            (void*)MEM_TO_SHADOW(kMidShadowBeg),
356            (void*)MEM_TO_SHADOW(kMidShadowEnd));
357   }
358   Printf("\n");
359   Printf("redzone=%zu\n", (uptr)flags()->redzone);
360   Printf("max_redzone=%zu\n", (uptr)flags()->max_redzone);
361   Printf("quarantine_size_mb=%zuM\n", (uptr)flags()->quarantine_size_mb);
362   Printf("thread_local_quarantine_size_kb=%zuK\n",
363          (uptr)flags()->thread_local_quarantine_size_kb);
364   Printf("malloc_context_size=%zu\n",
365          (uptr)common_flags()->malloc_context_size);
366 
367   Printf("SHADOW_SCALE: %d\n", (int)ASAN_SHADOW_SCALE);
368   Printf("SHADOW_GRANULARITY: %d\n", (int)ASAN_SHADOW_GRANULARITY);
369   Printf("SHADOW_OFFSET: 0x%zx\n", (uptr)ASAN_SHADOW_OFFSET);
370   CHECK(ASAN_SHADOW_SCALE >= 3 && ASAN_SHADOW_SCALE <= 7);
371   if (kMidMemBeg)
372     CHECK(kMidShadowBeg > kLowShadowEnd &&
373           kMidMemBeg > kMidShadowEnd &&
374           kHighShadowBeg > kMidMemEnd);
375 }
376 
377 static void AsanInitInternal() {
378   if (LIKELY(asan_inited)) return;
379   SanitizerToolName = "AddressSanitizer";
380   CHECK(!asan_init_is_running && "ASan init calls itself!");
381   asan_init_is_running = true;
382 
383   CacheBinaryName();
384 
385   // Initialize flags. This must be done early, because most of the
386   // initialization steps look at flags().
387   InitializeFlags();
388 
389   // Stop performing init at this point if we are being loaded via
390   // dlopen() and the platform supports it.
391   if (SANITIZER_SUPPORTS_INIT_FOR_DLOPEN && UNLIKELY(HandleDlopenInit())) {
392     asan_init_is_running = false;
393     VReport(1, "AddressSanitizer init is being performed for dlopen().\n");
394     return;
395   }
396 
397   AsanCheckIncompatibleRT();
398   AsanCheckDynamicRTPrereqs();
399   AvoidCVE_2016_2143();
400 
401   SetCanPoisonMemory(flags()->poison_heap);
402   SetMallocContextSize(common_flags()->malloc_context_size);
403 
404   InitializePlatformExceptionHandlers();
405 
406   InitializeHighMemEnd();
407 
408   // Make sure we are not statically linked.
409   AsanDoesNotSupportStaticLinkage();
410 
411   // Install tool-specific callbacks in sanitizer_common.
412   AddDieCallback(AsanDie);
413   SetCheckUnwindCallback(CheckUnwind);
414   SetPrintfAndReportCallback(AppendToErrorMessageBuffer);
415 
416   __sanitizer_set_report_path(common_flags()->log_path);
417 
418   __asan_option_detect_stack_use_after_return =
419       flags()->detect_stack_use_after_return;
420 
421   __sanitizer::InitializePlatformEarly();
422 
423   // Re-exec ourselves if we need to set additional env or command line args.
424   MaybeReexec();
425 
426   // Setup internal allocator callback.
427   SetLowLevelAllocateMinAlignment(ASAN_SHADOW_GRANULARITY);
428   SetLowLevelAllocateCallback(OnLowLevelAllocate);
429 
430   InitializeAsanInterceptors();
431   CheckASLR();
432 
433   // Enable system log ("adb logcat") on Android.
434   // Doing this before interceptors are initialized crashes in:
435   // AsanInitInternal -> android_log_write -> __interceptor_strcmp
436   AndroidLogInit();
437 
438   ReplaceSystemMalloc();
439 
440   DisableCoreDumperIfNecessary();
441 
442   InitializeShadowMemory();
443 
444   AsanTSDInit(PlatformTSDDtor);
445   InstallDeadlySignalHandlers(AsanOnDeadlySignal);
446 
447   AllocatorOptions allocator_options;
448   allocator_options.SetFrom(flags(), common_flags());
449   InitializeAllocator(allocator_options);
450 
451   if (SANITIZER_START_BACKGROUND_THREAD_IN_ASAN_INTERNAL)
452     MaybeStartBackgroudThread();
453 
454   // On Linux AsanThread::ThreadStart() calls malloc() that's why asan_inited
455   // should be set to 1 prior to initializing the threads.
456   asan_inited = 1;
457   asan_init_is_running = false;
458 
459   if (flags()->atexit)
460     Atexit(asan_atexit);
461 
462   InitializeCoverage(common_flags()->coverage, common_flags()->coverage_dir);
463 
464   // Now that ASan runtime is (mostly) initialized, deactivate it if
465   // necessary, so that it can be re-activated when requested.
466   if (flags()->start_deactivated)
467     AsanDeactivate();
468 
469   // interceptors
470   InitTlsSize();
471 
472   // Create main thread.
473   AsanThread *main_thread = CreateMainThread();
474   CHECK_EQ(0, main_thread->tid());
475   force_interface_symbols();  // no-op.
476   SanitizerInitializeUnwinder();
477 
478   if (CAN_SANITIZE_LEAKS) {
479     __lsan::InitCommonLsan();
480     if (common_flags()->detect_leaks && common_flags()->leak_check_at_exit) {
481       if (flags()->halt_on_error)
482         Atexit(__lsan::DoLeakCheck);
483       else
484         Atexit(__lsan::DoRecoverableLeakCheckVoid);
485     }
486   }
487 
488 #if CAN_SANITIZE_UB
489   __ubsan::InitAsPlugin();
490 #endif
491 
492   InitializeSuppressions();
493 
494   if (CAN_SANITIZE_LEAKS) {
495     // LateInitialize() calls dlsym, which can allocate an error string buffer
496     // in the TLS.  Let's ignore the allocation to avoid reporting a leak.
497     __lsan::ScopedInterceptorDisabler disabler;
498     Symbolizer::LateInitialize();
499   } else {
500     Symbolizer::LateInitialize();
501   }
502 
503   VReport(1, "AddressSanitizer Init done\n");
504 
505   if (flags()->sleep_after_init) {
506     Report("Sleeping for %d second(s)\n", flags()->sleep_after_init);
507     SleepForSeconds(flags()->sleep_after_init);
508   }
509 }
510 
511 // Initialize as requested from some part of ASan runtime library (interceptors,
512 // allocator, etc).
513 void AsanInitFromRtl() {
514   AsanInitInternal();
515 }
516 
517 #if ASAN_DYNAMIC
518 // Initialize runtime in case it's LD_PRELOAD-ed into unsanitized executable
519 // (and thus normal initializers from .preinit_array or modules haven't run).
520 
521 class AsanInitializer {
522  public:
523   AsanInitializer() {
524     AsanInitFromRtl();
525   }
526 };
527 
528 static AsanInitializer asan_initializer;
529 #endif  // ASAN_DYNAMIC
530 
531 void UnpoisonStack(uptr bottom, uptr top, const char *type) {
532   static const uptr kMaxExpectedCleanupSize = 64 << 20;  // 64M
533   if (top - bottom > kMaxExpectedCleanupSize) {
534     static bool reported_warning = false;
535     if (reported_warning)
536       return;
537     reported_warning = true;
538     Report(
539         "WARNING: ASan is ignoring requested __asan_handle_no_return: "
540         "stack type: %s top: %p; bottom %p; size: %p (%zd)\n"
541         "False positive error reports may follow\n"
542         "For details see "
543         "https://github.com/google/sanitizers/issues/189\n",
544         type, (void *)top, (void *)bottom, (void *)(top - bottom),
545         top - bottom);
546     return;
547   }
548   PoisonShadow(bottom, RoundUpTo(top - bottom, ASAN_SHADOW_GRANULARITY), 0);
549 }
550 
551 static void UnpoisonDefaultStack() {
552   uptr bottom, top;
553 
554   if (AsanThread *curr_thread = GetCurrentThread()) {
555     int local_stack;
556     const uptr page_size = GetPageSizeCached();
557     top = curr_thread->stack_top();
558     bottom = ((uptr)&local_stack - page_size) & ~(page_size - 1);
559   } else {
560     CHECK(!SANITIZER_FUCHSIA);
561     // If we haven't seen this thread, try asking the OS for stack bounds.
562     uptr tls_addr, tls_size, stack_size;
563     GetThreadStackAndTls(/*main=*/false, &bottom, &stack_size, &tls_addr,
564                          &tls_size);
565     top = bottom + stack_size;
566   }
567 
568   UnpoisonStack(bottom, top, "default");
569 }
570 
571 static void UnpoisonFakeStack() {
572   AsanThread *curr_thread = GetCurrentThread();
573   if (!curr_thread)
574     return;
575   FakeStack *stack = curr_thread->get_fake_stack();
576   if (!stack)
577     return;
578   stack->HandleNoReturn();
579 }
580 
581 }  // namespace __asan
582 
583 // ---------------------- Interface ---------------- {{{1
584 using namespace __asan;
585 
586 void NOINLINE __asan_handle_no_return() {
587   if (asan_init_is_running)
588     return;
589 
590   if (!PlatformUnpoisonStacks())
591     UnpoisonDefaultStack();
592 
593   UnpoisonFakeStack();
594 }
595 
596 extern "C" void *__asan_extra_spill_area() {
597   AsanThread *t = GetCurrentThread();
598   CHECK(t);
599   return t->extra_spill_area();
600 }
601 
602 void __asan_handle_vfork(void *sp) {
603   AsanThread *t = GetCurrentThread();
604   CHECK(t);
605   uptr bottom = t->stack_bottom();
606   PoisonShadow(bottom, (uptr)sp - bottom, 0);
607 }
608 
609 void NOINLINE __asan_set_death_callback(void (*callback)(void)) {
610   SetUserDieCallback(callback);
611 }
612 
613 // Initialize as requested from instrumented application code.
614 // We use this call as a trigger to wake up ASan from deactivated state.
615 void __asan_init() {
616   AsanActivate();
617   AsanInitInternal();
618 }
619 
620 void __asan_version_mismatch_check() {
621   // Do nothing.
622 }
623