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_interceptors.h"
17 #include "asan_interface_internal.h"
18 #include "asan_internal.h"
19 #include "asan_mapping.h"
20 #include "asan_poisoning.h"
21 #include "asan_report.h"
22 #include "asan_stack.h"
23 #include "asan_stats.h"
24 #include "asan_suppressions.h"
25 #include "asan_thread.h"
26 #include "sanitizer_common/sanitizer_atomic.h"
27 #include "sanitizer_common/sanitizer_flags.h"
28 #include "sanitizer_common/sanitizer_libc.h"
29 #include "sanitizer_common/sanitizer_symbolizer.h"
30 #include "lsan/lsan_common.h"
31 #include "ubsan/ubsan_init.h"
32 #include "ubsan/ubsan_platform.h"
33 
34 uptr __asan_shadow_memory_dynamic_address;  // Global interface symbol.
35 int __asan_option_detect_stack_use_after_return;  // Global interface symbol.
36 uptr *__asan_test_only_reported_buggy_pointer;  // Used only for testing asan.
37 
38 namespace __asan {
39 
40 uptr AsanMappingProfile[kAsanMappingProfileSize];
41 
42 static void AsanDie() {
43   static atomic_uint32_t num_calls;
44   if (atomic_fetch_add(&num_calls, 1, memory_order_relaxed) != 0) {
45     // Don't die twice - run a busy loop.
46     while (1) { }
47   }
48   if (common_flags()->print_module_map >= 1)
49     DumpProcessMap();
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       if (kHighShadowEnd)
60         UnmapOrDie((void*)kLowShadowBeg, kHighShadowEnd - kLowShadowBeg);
61     }
62   }
63 }
64 
65 static void CheckUnwind() {
66   GET_STACK_TRACE(kStackTraceMax, common_flags()->fast_unwind_on_check);
67   stack.Print();
68 }
69 
70 // -------------------------- Globals --------------------- {{{1
71 int asan_inited;
72 bool asan_init_is_running;
73 
74 #if !ASAN_FIXED_MAPPING
75 uptr kHighMemEnd, kMidMemBeg, kMidMemEnd;
76 #endif
77 
78 // -------------------------- Misc ---------------- {{{1
79 void ShowStatsAndAbort() {
80   __asan_print_accumulated_stats();
81   Die();
82 }
83 
84 // --------------- LowLevelAllocateCallbac ---------- {{{1
85 static void OnLowLevelAllocate(uptr ptr, uptr size) {
86   PoisonShadow(ptr, size, kAsanInternalHeapMagic);
87 }
88 
89 // -------------------------- Run-time entry ------------------- {{{1
90 // exported functions
91 #define ASAN_REPORT_ERROR(type, is_write, size)                     \
92 extern "C" NOINLINE INTERFACE_ATTRIBUTE                             \
93 void __asan_report_ ## type ## size(uptr addr) {                    \
94   GET_CALLER_PC_BP_SP;                                              \
95   ReportGenericError(pc, bp, sp, addr, is_write, size, 0, true);    \
96 }                                                                   \
97 extern "C" NOINLINE INTERFACE_ATTRIBUTE                             \
98 void __asan_report_exp_ ## type ## size(uptr addr, u32 exp) {       \
99   GET_CALLER_PC_BP_SP;                                              \
100   ReportGenericError(pc, bp, sp, addr, is_write, size, exp, true);  \
101 }                                                                   \
102 extern "C" NOINLINE INTERFACE_ATTRIBUTE                             \
103 void __asan_report_ ## type ## size ## _noabort(uptr addr) {        \
104   GET_CALLER_PC_BP_SP;                                              \
105   ReportGenericError(pc, bp, sp, addr, is_write, size, 0, false);   \
106 }                                                                   \
107 
108 ASAN_REPORT_ERROR(load, false, 1)
109 ASAN_REPORT_ERROR(load, false, 2)
110 ASAN_REPORT_ERROR(load, false, 4)
111 ASAN_REPORT_ERROR(load, false, 8)
112 ASAN_REPORT_ERROR(load, false, 16)
113 ASAN_REPORT_ERROR(store, true, 1)
114 ASAN_REPORT_ERROR(store, true, 2)
115 ASAN_REPORT_ERROR(store, true, 4)
116 ASAN_REPORT_ERROR(store, true, 8)
117 ASAN_REPORT_ERROR(store, true, 16)
118 
119 #define ASAN_REPORT_ERROR_N(type, is_write)                                 \
120 extern "C" NOINLINE INTERFACE_ATTRIBUTE                                     \
121 void __asan_report_ ## type ## _n(uptr addr, uptr size) {                   \
122   GET_CALLER_PC_BP_SP;                                                      \
123   ReportGenericError(pc, bp, sp, addr, is_write, size, 0, true);            \
124 }                                                                           \
125 extern "C" NOINLINE INTERFACE_ATTRIBUTE                                     \
126 void __asan_report_exp_ ## type ## _n(uptr addr, uptr size, u32 exp) {      \
127   GET_CALLER_PC_BP_SP;                                                      \
128   ReportGenericError(pc, bp, sp, addr, is_write, size, exp, true);          \
129 }                                                                           \
130 extern "C" NOINLINE INTERFACE_ATTRIBUTE                                     \
131 void __asan_report_ ## type ## _n_noabort(uptr addr, uptr size) {           \
132   GET_CALLER_PC_BP_SP;                                                      \
133   ReportGenericError(pc, bp, sp, addr, is_write, size, 0, false);           \
134 }                                                                           \
135 
136 ASAN_REPORT_ERROR_N(load, false)
137 ASAN_REPORT_ERROR_N(store, true)
138 
139 #define ASAN_MEMORY_ACCESS_CALLBACK_BODY(type, is_write, size, exp_arg, fatal) \
140     if (SANITIZER_MYRIAD2 && !AddrIsInMem(addr) && !AddrIsInShadow(addr))      \
141       return;                                                                  \
142     uptr sp = MEM_TO_SHADOW(addr);                                             \
143     uptr s = size <= SHADOW_GRANULARITY ? *reinterpret_cast<u8 *>(sp)          \
144                                         : *reinterpret_cast<u16 *>(sp);        \
145     if (UNLIKELY(s)) {                                                         \
146       if (UNLIKELY(size >= SHADOW_GRANULARITY ||                               \
147                    ((s8)((addr & (SHADOW_GRANULARITY - 1)) + size - 1)) >=     \
148                        (s8)s)) {                                               \
149         if (__asan_test_only_reported_buggy_pointer) {                         \
150           *__asan_test_only_reported_buggy_pointer = addr;                     \
151         } else {                                                               \
152           GET_CALLER_PC_BP_SP;                                                 \
153           ReportGenericError(pc, bp, sp, addr, is_write, size, exp_arg,        \
154                               fatal);                                          \
155         }                                                                      \
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 !SANITIZER_MYRIAD2
309 #if !ASAN_FIXED_MAPPING
310   kHighMemEnd = GetMaxUserVirtualAddress();
311   // Increase kHighMemEnd to make sure it's properly
312   // aligned together with kHighMemBeg:
313   kHighMemEnd |= (GetMmapGranularity() << SHADOW_SCALE) - 1;
314 #endif  // !ASAN_FIXED_MAPPING
315   CHECK_EQ((kHighMemBeg % GetMmapGranularity()), 0);
316 #endif  // !SANITIZER_MYRIAD2
317 }
318 
319 void PrintAddressSpaceLayout() {
320   if (kHighMemBeg) {
321     Printf("|| `[%p, %p]` || HighMem    ||\n",
322            (void*)kHighMemBeg, (void*)kHighMemEnd);
323     Printf("|| `[%p, %p]` || HighShadow ||\n",
324            (void*)kHighShadowBeg, (void*)kHighShadowEnd);
325   }
326   if (kMidMemBeg) {
327     Printf("|| `[%p, %p]` || ShadowGap3 ||\n",
328            (void*)kShadowGap3Beg, (void*)kShadowGap3End);
329     Printf("|| `[%p, %p]` || MidMem     ||\n",
330            (void*)kMidMemBeg, (void*)kMidMemEnd);
331     Printf("|| `[%p, %p]` || ShadowGap2 ||\n",
332            (void*)kShadowGap2Beg, (void*)kShadowGap2End);
333     Printf("|| `[%p, %p]` || MidShadow  ||\n",
334            (void*)kMidShadowBeg, (void*)kMidShadowEnd);
335   }
336   Printf("|| `[%p, %p]` || ShadowGap  ||\n",
337          (void*)kShadowGapBeg, (void*)kShadowGapEnd);
338   if (kLowShadowBeg) {
339     Printf("|| `[%p, %p]` || LowShadow  ||\n",
340            (void*)kLowShadowBeg, (void*)kLowShadowEnd);
341     Printf("|| `[%p, %p]` || LowMem     ||\n",
342            (void*)kLowMemBeg, (void*)kLowMemEnd);
343   }
344   Printf("MemToShadow(shadow): %p %p",
345          (void*)MEM_TO_SHADOW(kLowShadowBeg),
346          (void*)MEM_TO_SHADOW(kLowShadowEnd));
347   if (kHighMemBeg) {
348     Printf(" %p %p",
349            (void*)MEM_TO_SHADOW(kHighShadowBeg),
350            (void*)MEM_TO_SHADOW(kHighShadowEnd));
351   }
352   if (kMidMemBeg) {
353     Printf(" %p %p",
354            (void*)MEM_TO_SHADOW(kMidShadowBeg),
355            (void*)MEM_TO_SHADOW(kMidShadowEnd));
356   }
357   Printf("\n");
358   Printf("redzone=%zu\n", (uptr)flags()->redzone);
359   Printf("max_redzone=%zu\n", (uptr)flags()->max_redzone);
360   Printf("quarantine_size_mb=%zuM\n", (uptr)flags()->quarantine_size_mb);
361   Printf("thread_local_quarantine_size_kb=%zuK\n",
362          (uptr)flags()->thread_local_quarantine_size_kb);
363   Printf("malloc_context_size=%zu\n",
364          (uptr)common_flags()->malloc_context_size);
365 
366   Printf("SHADOW_SCALE: %d\n", (int)SHADOW_SCALE);
367   Printf("SHADOW_GRANULARITY: %d\n", (int)SHADOW_GRANULARITY);
368   Printf("SHADOW_OFFSET: 0x%zx\n", (uptr)SHADOW_OFFSET);
369   CHECK(SHADOW_SCALE >= 3 && SHADOW_SCALE <= 7);
370   if (kMidMemBeg)
371     CHECK(kMidShadowBeg > kLowShadowEnd &&
372           kMidMemBeg > kMidShadowEnd &&
373           kHighShadowBeg > kMidMemEnd);
374 }
375 
376 #if defined(__thumb__) && defined(__linux__)
377 #define START_BACKGROUND_THREAD_IN_ASAN_INTERNAL
378 #endif
379 
380 #ifndef START_BACKGROUND_THREAD_IN_ASAN_INTERNAL
381 static bool UNUSED __local_asan_dyninit = [] {
382   MaybeStartBackgroudThread();
383   SetSoftRssLimitExceededCallback(AsanSoftRssLimitExceededCallback);
384 
385   return false;
386 }();
387 #endif
388 
389 static void AsanInitInternal() {
390   if (LIKELY(asan_inited)) return;
391   SanitizerToolName = "AddressSanitizer";
392   CHECK(!asan_init_is_running && "ASan init calls itself!");
393   asan_init_is_running = true;
394 
395   CacheBinaryName();
396 
397   // Initialize flags. This must be done early, because most of the
398   // initialization steps look at flags().
399   InitializeFlags();
400 
401   // Stop performing init at this point if we are being loaded via
402   // dlopen() and the platform supports it.
403   if (SANITIZER_SUPPORTS_INIT_FOR_DLOPEN && UNLIKELY(HandleDlopenInit())) {
404     asan_init_is_running = false;
405     VReport(1, "AddressSanitizer init is being performed for dlopen().\n");
406     return;
407   }
408 
409   AsanCheckIncompatibleRT();
410   AsanCheckDynamicRTPrereqs();
411   AvoidCVE_2016_2143();
412 
413   SetCanPoisonMemory(flags()->poison_heap);
414   SetMallocContextSize(common_flags()->malloc_context_size);
415 
416   InitializePlatformExceptionHandlers();
417 
418   InitializeHighMemEnd();
419 
420   // Make sure we are not statically linked.
421   AsanDoesNotSupportStaticLinkage();
422 
423   // Install tool-specific callbacks in sanitizer_common.
424   AddDieCallback(AsanDie);
425   SetCheckUnwindCallback(CheckUnwind);
426   SetPrintfAndReportCallback(AppendToErrorMessageBuffer);
427 
428   __sanitizer_set_report_path(common_flags()->log_path);
429 
430   __asan_option_detect_stack_use_after_return =
431       flags()->detect_stack_use_after_return;
432 
433   __sanitizer::InitializePlatformEarly();
434 
435   // Re-exec ourselves if we need to set additional env or command line args.
436   MaybeReexec();
437 
438   // Setup internal allocator callback.
439   SetLowLevelAllocateMinAlignment(SHADOW_GRANULARITY);
440   SetLowLevelAllocateCallback(OnLowLevelAllocate);
441 
442   InitializeAsanInterceptors();
443   CheckASLR();
444 
445   // Enable system log ("adb logcat") on Android.
446   // Doing this before interceptors are initialized crashes in:
447   // AsanInitInternal -> android_log_write -> __interceptor_strcmp
448   AndroidLogInit();
449 
450   ReplaceSystemMalloc();
451 
452   DisableCoreDumperIfNecessary();
453 
454   InitializeShadowMemory();
455 
456   AsanTSDInit(PlatformTSDDtor);
457   InstallDeadlySignalHandlers(AsanOnDeadlySignal);
458 
459   AllocatorOptions allocator_options;
460   allocator_options.SetFrom(flags(), common_flags());
461   InitializeAllocator(allocator_options);
462 
463 #ifdef START_BACKGROUND_THREAD_IN_ASAN_INTERNAL
464   MaybeStartBackgroudThread();
465   SetSoftRssLimitExceededCallback(AsanSoftRssLimitExceededCallback);
466 #endif
467 
468   // On Linux AsanThread::ThreadStart() calls malloc() that's why asan_inited
469   // should be set to 1 prior to initializing the threads.
470   asan_inited = 1;
471   asan_init_is_running = false;
472 
473   if (flags()->atexit)
474     Atexit(asan_atexit);
475 
476   InitializeCoverage(common_flags()->coverage, common_flags()->coverage_dir);
477 
478   // Now that ASan runtime is (mostly) initialized, deactivate it if
479   // necessary, so that it can be re-activated when requested.
480   if (flags()->start_deactivated)
481     AsanDeactivate();
482 
483   // interceptors
484   InitTlsSize();
485 
486   // Create main thread.
487   AsanThread *main_thread = CreateMainThread();
488   CHECK_EQ(0, main_thread->tid());
489   force_interface_symbols();  // no-op.
490   SanitizerInitializeUnwinder();
491 
492   if (CAN_SANITIZE_LEAKS) {
493     __lsan::InitCommonLsan();
494     if (common_flags()->detect_leaks && common_flags()->leak_check_at_exit) {
495       if (flags()->halt_on_error)
496         Atexit(__lsan::DoLeakCheck);
497       else
498         Atexit(__lsan::DoRecoverableLeakCheckVoid);
499     }
500   }
501 
502 #if CAN_SANITIZE_UB
503   __ubsan::InitAsPlugin();
504 #endif
505 
506   InitializeSuppressions();
507 
508   if (CAN_SANITIZE_LEAKS) {
509     // LateInitialize() calls dlsym, which can allocate an error string buffer
510     // in the TLS.  Let's ignore the allocation to avoid reporting a leak.
511     __lsan::ScopedInterceptorDisabler disabler;
512     Symbolizer::LateInitialize();
513   } else {
514     Symbolizer::LateInitialize();
515   }
516 
517   VReport(1, "AddressSanitizer Init done\n");
518 
519   if (flags()->sleep_after_init) {
520     Report("Sleeping for %d second(s)\n", flags()->sleep_after_init);
521     SleepForSeconds(flags()->sleep_after_init);
522   }
523 }
524 
525 // Initialize as requested from some part of ASan runtime library (interceptors,
526 // allocator, etc).
527 void AsanInitFromRtl() {
528   AsanInitInternal();
529 }
530 
531 #if ASAN_DYNAMIC
532 // Initialize runtime in case it's LD_PRELOAD-ed into unsanitized executable
533 // (and thus normal initializers from .preinit_array or modules haven't run).
534 
535 class AsanInitializer {
536  public:
537   AsanInitializer() {
538     AsanInitFromRtl();
539   }
540 };
541 
542 static AsanInitializer asan_initializer;
543 #endif  // ASAN_DYNAMIC
544 
545 void UnpoisonStack(uptr bottom, uptr top, const char *type) {
546   static const uptr kMaxExpectedCleanupSize = 64 << 20;  // 64M
547   if (top - bottom > kMaxExpectedCleanupSize) {
548     static bool reported_warning = false;
549     if (reported_warning)
550       return;
551     reported_warning = true;
552     Report(
553         "WARNING: ASan is ignoring requested __asan_handle_no_return: "
554         "stack type: %s top: %p; bottom %p; size: %p (%zd)\n"
555         "False positive error reports may follow\n"
556         "For details see "
557         "https://github.com/google/sanitizers/issues/189\n",
558         type, top, bottom, top - bottom, top - bottom);
559     return;
560   }
561   PoisonShadow(bottom, RoundUpTo(top - bottom, SHADOW_GRANULARITY), 0);
562 }
563 
564 static void UnpoisonDefaultStack() {
565   uptr bottom, top;
566 
567   if (AsanThread *curr_thread = GetCurrentThread()) {
568     int local_stack;
569     const uptr page_size = GetPageSizeCached();
570     top = curr_thread->stack_top();
571     bottom = ((uptr)&local_stack - page_size) & ~(page_size - 1);
572   } else if (SANITIZER_RTEMS) {
573     // Give up On RTEMS.
574     return;
575   } else {
576     CHECK(!SANITIZER_FUCHSIA);
577     // If we haven't seen this thread, try asking the OS for stack bounds.
578     uptr tls_addr, tls_size, stack_size;
579     GetThreadStackAndTls(/*main=*/false, &bottom, &stack_size, &tls_addr,
580                          &tls_size);
581     top = bottom + stack_size;
582   }
583 
584   UnpoisonStack(bottom, top, "default");
585 }
586 
587 static void UnpoisonFakeStack() {
588   AsanThread *curr_thread = GetCurrentThread();
589   if (curr_thread && curr_thread->has_fake_stack())
590     curr_thread->fake_stack()->HandleNoReturn();
591 }
592 
593 }  // namespace __asan
594 
595 // ---------------------- Interface ---------------- {{{1
596 using namespace __asan;
597 
598 void NOINLINE __asan_handle_no_return() {
599   if (asan_init_is_running)
600     return;
601 
602   if (!PlatformUnpoisonStacks())
603     UnpoisonDefaultStack();
604 
605   UnpoisonFakeStack();
606 }
607 
608 extern "C" void *__asan_extra_spill_area() {
609   AsanThread *t = GetCurrentThread();
610   CHECK(t);
611   return t->extra_spill_area();
612 }
613 
614 void __asan_handle_vfork(void *sp) {
615   AsanThread *t = GetCurrentThread();
616   CHECK(t);
617   uptr bottom = t->stack_bottom();
618   PoisonShadow(bottom, (uptr)sp - bottom, 0);
619 }
620 
621 void NOINLINE __asan_set_death_callback(void (*callback)(void)) {
622   SetUserDieCallback(callback);
623 }
624 
625 // Initialize as requested from instrumented application code.
626 // We use this call as a trigger to wake up ASan from deactivated state.
627 void __asan_init() {
628   AsanActivate();
629   AsanInitInternal();
630 }
631 
632 void __asan_version_mismatch_check() {
633   // Do nothing.
634 }
635