asan_rtl.cpp 22 KB

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