[libc-commits] [libc] [libc] support PIE relocations (PR #78993)

via libc-commits libc-commits at lists.llvm.org
Mon Jan 22 07:26:36 PST 2024


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-libc

Author: Schrodinger ZHU Yifan (SchrodingerZhu)

<details>
<summary>Changes</summary>

For some reasons, we are using `-fpie` (libc/cmake/modules/LLVMLibCObjectRules.cmake:31) without supporting it.
According to @<!-- -->lntue, some of the hermetic tests are broken without proper PIE support. This patch implements basic relocations support for PIE. 


---
Full diff: https://github.com/llvm/llvm-project/pull/78993.diff


1 Files Affected:

- (modified) libc/startup/linux/do_start.cpp (+19-8) 


``````````diff
diff --git a/libc/startup/linux/do_start.cpp b/libc/startup/linux/do_start.cpp
index 05dbd4488f58828..36f065e4f829a2d 100644
--- a/libc/startup/linux/do_start.cpp
+++ b/libc/startup/linux/do_start.cpp
@@ -29,6 +29,9 @@ extern uintptr_t __init_array_start[];
 extern uintptr_t __init_array_end[];
 extern uintptr_t __fini_array_start[];
 extern uintptr_t __fini_array_end[];
+// https://refspecs.linuxbase.org/elf/gabi4+/ch5.dynamic.html#dynamic_section
+[[gnu::weak,
+  gnu::visibility("hidden")]] extern const Elf64_Dyn _DYNAMIC[]; // NOLINT
 }
 
 namespace LIBC_NAMESPACE {
@@ -94,18 +97,26 @@ static ThreadAttributes main_thread_attrib;
     }
   }
 
+  ptrdiff_t base = 0;
   app.tls.size = 0;
+  Elf64_Phdr *tls_phdr = nullptr;
+
   for (uintptr_t i = 0; i < program_hdr_count; ++i) {
-    Elf64_Phdr *phdr = program_hdr_table + i;
-    if (phdr->p_type != PT_TLS)
-      continue;
-    // TODO: p_vaddr value has to be adjusted for static-pie executables.
-    app.tls.address = phdr->p_vaddr;
-    app.tls.size = phdr->p_memsz;
-    app.tls.init_size = phdr->p_filesz;
-    app.tls.align = phdr->p_align;
+    auto &phdr = program_hdr_table[i];
+    if (phdr.p_type == PT_PHDR)
+      base = reinterpret_cast<ptrdiff_t>(program_hdr_table) - phdr.p_vaddr;
+    if (phdr.p_type == PT_DYNAMIC && _DYNAMIC)
+      base = reinterpret_cast<ptrdiff_t>(_DYNAMIC) - phdr.p_vaddr;
+    if (phdr.p_type == PT_TLS)
+      tls_phdr = &phdr;
+    // TODO: adjust PT_GNU_STACK
   }
 
+  app.tls.address = tls_phdr->p_vaddr + base;
+  app.tls.size = tls_phdr->p_memsz;
+  app.tls.init_size = tls_phdr->p_filesz;
+  app.tls.align = tls_phdr->p_align;
+
   // This descriptor has to be static since its cleanup function cannot
   // capture the context.
   static TLSDescriptor tls;

``````````

</details>


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


More information about the libc-commits mailing list