[lld] [LLD][ELF] Do not emit __start/__stop for empty sections (PR #96213)

via llvm-commits llvm-commits at lists.llvm.org
Thu Jun 20 09:41:25 PDT 2024


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-lld-elf

Author: Andrew Ng (nga888)

<details>
<summary>Changes</summary>

For empty sections that are not emitted, do not emit the corresponding __start/__stop section symbols. This behavior now matches GNU ld.

Previously, the emission of these symbols for empty sections could also result in references to invalid sections.

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


2 Files Affected:

- (modified) lld/ELF/Writer.cpp (+4) 
- (added) lld/test/ELF/linkerscript/empty-section-start-stop.test (+36) 


``````````diff
diff --git a/lld/ELF/Writer.cpp b/lld/ELF/Writer.cpp
index 640cb2a445f7d..4404faf217fcf 100644
--- a/lld/ELF/Writer.cpp
+++ b/lld/ELF/Writer.cpp
@@ -1803,6 +1803,8 @@ template <class ELFT> void Writer<ELFT>::finalizeSections() {
         continue;
       if (!config->relocatable)
         sym->binding = sym->computeBinding();
+      if (sym->isLocal() && sym->isUndefined())
+        continue;
       if (in.symTab)
         in.symTab->addSymbol(sym);
 
@@ -2073,6 +2075,8 @@ template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
 // gold provide the feature, and used by many programs.
 template <class ELFT>
 void Writer<ELFT>::addStartStopSymbols(OutputSection &osec) {
+  if (script->isDiscarded(&osec))
+    return;
   StringRef s = osec.name;
   if (!isValidCIdentifier(s))
     return;
diff --git a/lld/test/ELF/linkerscript/empty-section-start-stop.test b/lld/test/ELF/linkerscript/empty-section-start-stop.test
new file mode 100644
index 0000000000000..de917366952a5
--- /dev/null
+++ b/lld/test/ELF/linkerscript/empty-section-start-stop.test
@@ -0,0 +1,36 @@
+# REQUIRES: x86
+# RUN: rm -rf %t && split-file %s %t
+# RUN: llvm-mc -filetype=obj -triple=x86_64 %t/test.s -o %t.o
+
+## Check that __start/__stop symbols are not emitted for an empty section.
+# RUN: ld.lld -T %t/ldscript -o %t.out %t.o
+# RUN: llvm-readelf -s %t.out | FileCheck %s
+
+# CHECK-NOT: __start_empty
+# CHECK-NOT: __stop_empty
+
+#--- ldscript
+SECTIONS {
+  .text : { *(.text .text.*) }
+
+  # The following ".pad" sections are used to increase the section index which
+  # would have resulted in the emission of __start_empty & __stop_empty symbols
+  # with out of range section indices.
+  .pad0 : {}
+  .pad1 : {}
+  .pad2 : {}
+  .pad3 : {}
+  .pad4 : {}
+  .pad5 : {}
+
+  empty : { *(empty empty.*) }
+}
+
+#--- test.s
+.weak __start_empty,__stop_empty
+.hidden __start_empty,__stop_empty
+
+.globl _start
+_start:
+  movq __start_empty at GOTPCREL(%rip),%rax
+  movq __stop_empty at GOTPCREL(%rip),%rax

``````````

</details>


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


More information about the llvm-commits mailing list