[lld] [LLD][COFF] Handle imported weak aliases consistently (PR #109105)

via llvm-commits llvm-commits at lists.llvm.org
Wed Sep 18 02:03:12 PDT 2024


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-lld

Author: Mike Hommey (glandium)

<details>
<summary>Changes</summary>

symTab being a DenseMap, the order in which a symbol and its corresponding import symbol are processed is not guaranteed, and when the latter comes first, it is left undefined.

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


2 Files Affected:

- (modified) lld/COFF/SymbolTable.cpp (+8) 
- (added) lld/test/COFF/import_weak_alias.test (+25) 


``````````diff
diff --git a/lld/COFF/SymbolTable.cpp b/lld/COFF/SymbolTable.cpp
index efea16ccbbfea0..6b96d8bbda789c 100644
--- a/lld/COFF/SymbolTable.cpp
+++ b/lld/COFF/SymbolTable.cpp
@@ -502,6 +502,14 @@ void SymbolTable::resolveRemainingUndefines() {
     // This odd rule is for compatibility with MSVC linker.
     if (name.starts_with("__imp_")) {
       Symbol *imp = find(name.substr(strlen("__imp_")));
+      if (imp) {
+         // The unprefixed symbol might come later in symMap, so handle it now
+	 // so that the condition below can be appropriately applied.
+         auto *undef = dyn_cast<Undefined>(imp);
+         if (undef) {
+            undef->resolveWeakAlias();
+         }
+      }
       if (imp && isa<Defined>(imp)) {
         auto *d = cast<Defined>(imp);
         replaceSymbol<DefinedLocalImport>(sym, ctx, name, d);
diff --git a/lld/test/COFF/import_weak_alias.test b/lld/test/COFF/import_weak_alias.test
new file mode 100644
index 00000000000000..63df565d5dbc9d
--- /dev/null
+++ b/lld/test/COFF/import_weak_alias.test
@@ -0,0 +1,25 @@
+# REQUIRES: x86
+
+# RUN: split-file %s %t.dir
+# RUN: llc --filetype=obj -o %t.foo.obj %t.dir/foo.ll
+# RUN: llvm-mc --filetype=obj -triple=x86_64-windows-msvc %t.dir/qux.s -o %t.qux.obj
+# RUN: lld-link %t.qux.obj %t.foo.obj -out:%t.dll -dll 2>&1 | FileCheck %s
+#
+# CHECK-NOT: lld-link: error: undefined symbol: __declspec(dllimport) foo
+
+#--- foo.ll
+target datalayout = "e-m:w-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-pc-windows-msvc"
+
+ at foo = weak alias void(), ptr @bar
+
+define void @bar() {
+  ret void
+}
+
+#--- qux.s
+.text
+.global _DllMainCRTStartup
+_DllMainCRTStartup:
+  call __imp_foo
+  ret

``````````

</details>


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


More information about the llvm-commits mailing list