[llvm] [BOLT] Support instrumentation hook via DT_FINI_ARRAY (PR #67348)

Job Noorman via llvm-commits llvm-commits at lists.llvm.org
Wed Sep 27 06:19:51 PDT 2023


================
@@ -1276,6 +1280,60 @@ void RewriteInstance::discoverFileObjects() {
   registerFragments();
 }
 
+Error RewriteInstance::discoverFiniAddress() {
+  // If FiniFunctionAddress is already set, we got if from DT_FINI. We use
+  // DT_FINI instead of DT_FINI_ARRAY if it's available.
+  if (BC->FiniFunctionAddress)
+    return Error::success();
+
+  if (BC->IsStaticExecutable)
+    return Error::success();
+
+  if (!BC->FiniArrayAddress || !BC->FiniArraySize) {
+    return createStringError(
+        std::errc::not_supported,
+        "Instrumentation needs either DT_FINI or DT_FINI_ARRAY");
+  }
+
+  if (*BC->FiniArraySize < BC->AsmInfo->getCodePointerSize()) {
+    return createStringError(std::errc::not_supported,
+                             "Need at least 1 DT_FINI_ARRAY slot");
+  }
+
+  ErrorOr<BinarySection &> FiniArraySection =
+      BC->getSectionForAddress(*BC->FiniArrayAddress);
+  if (auto EC = FiniArraySection.getError())
+    return errorCodeToError(EC);
+
+  BC->FiniArraySection = &*FiniArraySection;
+  const Relocation *FiniFunctionReloc =
+      FiniArraySection->getDynamicRelocationAt(0);
+
+  if (!FiniFunctionReloc) {
+    return createStringError(std::errc::not_supported,
----------------
mtvec wrote:

I think I found an elegant way to do this: add a *pending* relocation for the static relocation we want to patch. Since pending relocations are already flushed while rewriting the file, patching the fini address happens automatically.

Note that although I think it's possible to test this on AArch64, I haven't been able to get AArch64 instrumentation working on my x86 machine so I'm not able to verify this. I'll try to fix this later and add tests.

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


More information about the llvm-commits mailing list