[compiler-rt] [asan] Optimize initialization order checking (PR #101837)

Fangrui Song via llvm-commits llvm-commits at lists.llvm.org
Mon Aug 5 20:59:44 PDT 2024


================
@@ -520,6 +520,44 @@ void __asan_before_dynamic_init(const char *module_name) {
   current_dynamic_init_module_name = module_name;
 }
 
+// Maybe SANITIZER_CAN_USE_PREINIT_ARRAY is to conservative for `.init_array`,
+// however we should not make mistake here. If `AfterDynamicInit` was not
+// executed at all we will have false reports on globals.
+#if SANITIZER_CAN_USE_PREINIT_ARRAY
+// This is optimization. We will ignore all `__asan_after_dynamic_init`, but the
+// last `__asan_after_dynamic_init`. We don't need number of
+// `__asan_{before,after}_dynamic_init` matches, but we need that the last call
+// was to `__asan_after_dynamic_init`, as it will unpoison all global preparing
+// program for `main` execution. To run `__asan_after_dynamic_init` later, we
+// will register in `.init_array`.
+static bool allow_after_dynamic_init SANITIZER_GUARDED_BY(mu_for_globals) =
+    false;
+
+static void __attribute__((used)) AfterDynamicInit(void) {
+  {
+    Lock lock(&mu_for_globals);
+    if (allow_after_dynamic_init)
+      return;
+    allow_after_dynamic_init = true;
+  }
+  if (flags()->report_globals >= 3)
+    Printf("AfterDynamicInit\n");
+  __asan_after_dynamic_init();
+}
+
+// 65537 will make it run after constructors with default priority, but it
+// requires ld.lld. With ld.bfd it can be called to early, and fail the
+// optimization. However, correctness should not be affected, as after the first
+// call all subsequent `__asan_after_dynamic_init` will be allowed.
+__attribute__((section(".init_array.65537"), used)) static void (
+    *asan_after_init_array)(void) = AfterDynamicInit;
+#else
+// Allow all `__asan_after_dynamic_init` if `AfterDynamicInit` is not set.
----------------
MaskRay wrote:

Incremental poisoning is disabled.

https://github.com/llvm/llvm-project/pull/101837


More information about the llvm-commits mailing list