[lld] [lld][ELF] Fix wrap when __real_X is weak to avoid undefined symbol #98294 (PR #98297)

via llvm-commits llvm-commits at lists.llvm.org
Wed Jul 10 03:27:30 PDT 2024


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-lld-elf

Author: Alexander Qi (xdqi)

<details>
<summary>Changes</summary>

When you specify --wrap=foo, sometimes foo is undefined in any context. If you declare __real_foo as weak, GNU ld will not attempt to find the strong symbol foo, instead, it generates a weak undefined symbol.

This pull request imitates this behavior by copying the binding attribute from __real_foo to foo.

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


2 Files Affected:

- (modified) lld/ELF/Driver.cpp (+5-1) 
- (added) lld/test/ELF/wrap-weak.s (+23) 


``````````diff
diff --git a/lld/ELF/Driver.cpp b/lld/ELF/Driver.cpp
index a4863d6717efb..8c9196fe4047b 100644
--- a/lld/ELF/Driver.cpp
+++ b/lld/ELF/Driver.cpp
@@ -2551,8 +2551,12 @@ static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) {
     // If __real_ is referenced, pull in the symbol if it is lazy. Do this after
     // processing __wrap_ as that may have referenced __real_.
     StringRef realName = saver().save("__real_" + name);
-    if (symtab.find(realName))
+    if (Symbol *real = symtab.find(realName)) {
       symtab.addUnusedUndefined(name, sym->binding);
+      // update sym's binding to __real_'s binding, as sym will replacing
+      // __real_ later in SymbolTable::wrap().
+      sym->binding = real->binding;
+    }
 
     Symbol *real = symtab.addUnusedUndefined(realName);
     v.push_back({sym, real, wrap});
diff --git a/lld/test/ELF/wrap-weak.s b/lld/test/ELF/wrap-weak.s
new file mode 100644
index 0000000000000..e06304f39daa8
--- /dev/null
+++ b/lld/test/ELF/wrap-weak.s
@@ -0,0 +1,23 @@
+# REQUIRES: x86
+# RUN: llvm-mc -filetype=obj -triple=x86_64-pc-linux %s -o %t.o
+# RUN: ld.lld -shared -o %t.so %t.o -wrap foo
+
+# RUN: llvm-readelf --dyn-syms %t.so | FileCheck %s --check-prefix=CHECK
+
+# CHECK:      Symbol table '.dynsym' contains 4 entries:
+# CHECK:      NOTYPE  LOCAL  DEFAULT   UND
+# CHECK-NEXT: NOTYPE  WEAK   DEFAULT   UND foo
+# CHECK-NEXT: NOTYPE  GLOBAL DEFAULT [[#]] __wrap_foo
+# CHECK-NEXT: NOTYPE  GLOBAL DEFAULT [[#]] _start
+
+.global foo
+.weak __real_foo
+
+.global __wrap_foo
+__wrap_foo:
+  movq __real_foo at gotpcrel(%rip), %rax
+  call __real_foo at plt
+
+.global _start
+_start:
+  call foo at plt

``````````

</details>


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


More information about the llvm-commits mailing list