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