diff --git a/lld/ELF/Config.h b/lld/ELF/Config.h index 06ba88a83dd412..ef1edbcd199240 100644 --- a/lld/ELF/Config.h +++ b/lld/ELF/Config.h @@ -169,6 +169,7 @@ struct Configuration { bool mipsN32Abi = false; bool mmapOutputFile; bool nmagic; + bool noDynamicLinker = false; bool noinhibitExec; bool nostdlib; bool oFormatBinary; diff --git a/lld/ELF/Driver.cpp b/lld/ELF/Driver.cpp index 23da749d307859..25330832339cfd 100644 --- a/lld/ELF/Driver.cpp +++ b/lld/ELF/Driver.cpp @@ -602,8 +602,13 @@ static DiscardPolicy getDiscard(opt::InputArgList &args) { static StringRef getDynamicLinker(opt::InputArgList &args) { auto *arg = args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker); - if (!arg || arg->getOption().getID() == OPT_no_dynamic_linker) + if (!arg) + return ""; + if (arg->getOption().getID() == OPT_no_dynamic_linker) { + // --no-dynamic-linker suppresses undefined weak symbols in .dynsym + config->noDynamicLinker = true; return ""; + } return arg->getValue(); } diff --git a/lld/ELF/Symbols.cpp b/lld/ELF/Symbols.cpp index f0f6121009a539..0dcf34722d33ac 100644 --- a/lld/ELF/Symbols.cpp +++ b/lld/ELF/Symbols.cpp @@ -278,7 +278,11 @@ bool Symbol::includeInDynsym() const { if (computeBinding() == STB_LOCAL) return false; if (!isDefined() && !isCommon()) - return true; + // This should unconditionally return true, unfortunately glibc -static-pie + // expects undefined weak symbols not to exist in .dynsym, e.g. + // __pthread_mutex_lock reference in _dl_add_to_namespace_list, + // __pthread_initialize_minimal reference in csu/libc-start.c. + return !(config->noDynamicLinker && isUndefWeak()); return exportDynamic || inDynamicList; } diff --git a/lld/test/ELF/weak-undef-no-dynamic-linker.s b/lld/test/ELF/weak-undef-no-dynamic-linker.s new file mode 100644 index 00000000000000..fa6936e1ef393f --- /dev/null +++ b/lld/test/ELF/weak-undef-no-dynamic-linker.s @@ -0,0 +1,15 @@ +# REQUIRES: x86 +# RUN: llvm-mc -filetype=obj -triple=x86_64 %s -o %t.o +# RUN: ld.lld -pie %t.o -o %t +# RUN: llvm-readobj --dyn-syms %t | FileCheck %s +# RUN: ld.lld -pie --no-dynamic-linker %t.o -o %t +# RUN: llvm-readobj --dyn-syms %t | FileCheck --check-prefix=NO %s + +## With --no-dynamic-linker, don't emit undefined weak symbols to .dynsym . +## This will suppress a relocation. +# CHECK: Name: foo +# NO-NOT: Name: foo + +.weak foo +cmpq $0, foo@GOTPCREL(%rip) +callq foo