blob: 62a8a3c30664e3b51751c3d33871720f8c6a4035 [file] [log] [blame]
Michael J. Spencer84487f12015-07-24 21:03:071//===- Symbols.cpp --------------------------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:563// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Michael J. Spencer84487f12015-07-24 21:03:076//
7//===----------------------------------------------------------------------===//
8
9#include "Symbols.h"
Fangrui Song7fd38492022-02-27 20:23:0910#include "Driver.h"
Michael J. Spencercdae0a42015-07-28 22:58:2511#include "InputFiles.h"
Rui Ueyamab5a69702016-02-01 21:00:3512#include "InputSection.h"
13#include "OutputSections.h"
Rui Ueyamae8a61022016-11-05 23:05:4714#include "SyntheticSections.h"
Rui Ueyamab5a69702016-02-01 21:00:3515#include "Target.h"
Rafael Espindola17cb7c02016-12-19 17:01:0116#include "Writer.h"
Bob Haarmanb8a59c82017-10-25 22:28:3817#include "lld/Common/ErrorHandler.h"
Jez Ng32647c82022-10-14 19:28:1918#include "llvm/Demangle/Demangle.h"
Shoaib Meenaib862bcb2022-04-19 20:42:0519#include "llvm/Support/Compiler.h"
Rui Ueyamac72ba3a2016-11-23 04:57:2520#include <cstring>
Michael J. Spencer1b348a62015-09-04 22:28:1021
22using namespace llvm;
Michael J. Spencer84487f12015-07-24 21:03:0723using namespace llvm::object;
Rafael Espindola78471f02015-09-01 23:12:5224using namespace llvm::ELF;
Fangrui Song07837b82020-05-15 05:18:5825using namespace lld;
26using namespace lld::elf;
Michael J. Spencer84487f12015-07-24 21:03:0727
Shoaib Meenaib862bcb2022-04-19 20:42:0528static_assert(sizeof(SymbolUnion) <= 64, "SymbolUnion too large");
29
30template <typename T> struct AssertSymbol {
31 static_assert(std::is_trivially_destructible<T>(),
32 "Symbol types must be trivially destructible");
33 static_assert(sizeof(T) <= sizeof(SymbolUnion), "SymbolUnion too small");
34 static_assert(alignof(T) <= alignof(SymbolUnion),
35 "SymbolUnion not aligned enough");
36};
37
38LLVM_ATTRIBUTE_UNUSED static inline void assertSymbols() {
39 AssertSymbol<Defined>();
40 AssertSymbol<CommonSymbol>();
41 AssertSymbol<Undefined>();
42 AssertSymbol<SharedSymbol>();
43 AssertSymbol<LazyObject>();
44}
45
Jez Ng32647c82022-10-14 19:28:1946// Returns a symbol for an error message.
47static std::string maybeDemangleSymbol(StringRef symName) {
48 if (elf::config->demangle)
49 return demangle(symName.str());
50 return symName.str();
51}
52
Fangrui Song07837b82020-05-15 05:18:5853std::string lld::toString(const elf::Symbol &sym) {
Fangrui Songf2036a12020-03-28 22:48:3854 StringRef name = sym.getName();
Jez Ng32647c82022-10-14 19:28:1955 std::string ret = maybeDemangleSymbol(name);
Fangrui Songf2036a12020-03-28 22:48:3856
Fangrui Song941e9332020-12-01 16:54:0157 const char *suffix = sym.getVersionSuffix();
58 if (*suffix == '@')
59 ret += suffix;
Fangrui Songf2036a12020-03-28 22:48:3860 return ret;
61}
62
Rui Ueyama3837f422019-07-10 05:00:3763Defined *ElfSym::bss;
64Defined *ElfSym::etext1;
65Defined *ElfSym::etext2;
66Defined *ElfSym::edata1;
67Defined *ElfSym::edata2;
68Defined *ElfSym::end1;
69Defined *ElfSym::end2;
70Defined *ElfSym::globalOffsetTable;
71Defined *ElfSym::mipsGp;
72Defined *ElfSym::mipsGpDisp;
73Defined *ElfSym::mipsLocalGp;
Craig Topper85444792023-04-13 17:39:4774Defined *ElfSym::riscvGlobalPointer;
Rui Ueyama3837f422019-07-10 05:00:3775Defined *ElfSym::relaIpltStart;
76Defined *ElfSym::relaIpltEnd;
Rui Ueyama3837f422019-07-10 05:00:3777Defined *ElfSym::tlsModuleBase;
Fangrui Song5d3bd7f2022-01-09 21:43:2678SmallVector<SymbolAux, 0> elf::symAux;
Rui Ueyama80474a22017-02-28 19:29:5579
Fangrui Songa8024df2021-12-13 03:12:0180static uint64_t getSymVA(const Symbol &sym, int64_t addend) {
Rui Ueyama3837f422019-07-10 05:00:3781 switch (sym.kind()) {
Peter Collingbournee9a9e0a2017-11-06 04:35:3182 case Symbol::DefinedKind: {
Rui Ueyama3837f422019-07-10 05:00:3783 auto &d = cast<Defined>(sym);
84 SectionBase *isec = d.section;
Rui Ueyamab5a69702016-02-01 21:00:3585
86 // This is an absolute symbol.
Rui Ueyama3837f422019-07-10 05:00:3787 if (!isec)
88 return d.value;
Rui Ueyamab5a69702016-02-01 21:00:3589
Rui Ueyama3837f422019-07-10 05:00:3790 assert(isec != &InputSection::discarded);
Rafael Espindolaf4d6e8c2018-04-19 17:26:5091
Rui Ueyama3837f422019-07-10 05:00:3792 uint64_t offset = d.value;
Sean Silvaa9ba4502017-02-28 08:32:5693
94 // An object in an SHF_MERGE section might be referenced via a
95 // section symbol (as a hack for reducing the number of local
96 // symbols).
Sean Silvad4e60622017-03-01 04:44:0497 // Depending on the addend, the reference via a section symbol
98 // refers to a different object in the merge section.
99 // Since the objects in the merge section are not necessarily
100 // contiguous in the output, the addend can thus affect the final
101 // VA in a non-linear way.
102 // To make this work, we incorporate the addend into the section
103 // offset (and zero out the addend for later processing) so that
104 // we find the right object in the section.
Fangrui Songa8024df2021-12-13 03:12:01105 if (d.isSection())
Rui Ueyama3837f422019-07-10 05:00:37106 offset += addend;
Sean Silvaa9ba4502017-02-28 08:32:56107
Sean Silva6ab39262017-02-28 09:01:58108 // In the typical case, this is actually very simple and boils
109 // down to adding together 3 numbers:
110 // 1. The address of the output section.
111 // 2. The offset of the input section within the output section.
112 // 3. The offset within the input section (this addition happens
113 // inside InputSection::getOffset).
114 //
115 // If you understand the data structures involved with this next
116 // line (and how they get built), then you have a pretty good
117 // understanding of the linker.
Rui Ueyama3837f422019-07-10 05:00:37118 uint64_t va = isec->getVA(offset);
Fangrui Songa8024df2021-12-13 03:12:01119 if (d.isSection())
120 va -= addend;
Sean Silva6ab39262017-02-28 09:01:58121
Simon Atanasyanfae2a5092019-02-19 10:36:58122 // MIPS relocatable files can mix regular and microMIPS code.
123 // Linker needs to distinguish such code. To do so microMIPS
124 // symbols has the `STO_MIPS_MICROMIPS` flag in the `st_other`
Fangrui Songdeb58192020-01-23 05:39:16125 // field. Unfortunately, the `MIPS::relocate()` method has
Simon Atanasyanfae2a5092019-02-19 10:36:58126 // a symbol value only. To pass type of the symbol (regular/microMIPS)
127 // to that routine as well as other places where we write
128 // a symbol value as-is (.dynamic section, `Elf_Ehdr::e_entry`
129 // field etc) do the same trick as compiler uses to mark microMIPS
130 // for CPU - set the less-significant bit.
Rui Ueyama3837f422019-07-10 05:00:37131 if (config->emachine == EM_MIPS && isMicroMips() &&
Fangrui Songbd16ffb32022-09-09 21:37:18132 ((sym.stOther & STO_MIPS_MICROMIPS) || sym.hasFlag(NEEDS_COPY)))
Rui Ueyama3837f422019-07-10 05:00:37133 va |= 1;
Simon Atanasyanfae2a5092019-02-19 10:36:58134
Rui Ueyama3837f422019-07-10 05:00:37135 if (d.isTls() && !config->relocatable) {
Ryan Prichard1c33d142018-09-18 00:24:48136 // Use the address of the TLS segment's first section rather than the
137 // segment's address, because segment addresses aren't initialized until
138 // after sections are finalized. (e.g. Measuring the size of .rela.dyn
139 // for Android relocation packing requires knowing TLS symbol addresses
140 // during section finalization.)
Rui Ueyama3837f422019-07-10 05:00:37141 if (!Out::tlsPhdr || !Out::tlsPhdr->firstSec)
142 fatal(toString(d.file) +
Peter Collingbourne3e2abde2017-07-14 00:22:46143 " has an STT_TLS symbol but doesn't have an SHF_TLS section");
Rui Ueyama3837f422019-07-10 05:00:37144 return va - Out::tlsPhdr->firstSec->addr;
George Rimar6a3b1542016-10-04 08:52:51145 }
Rui Ueyama3837f422019-07-10 05:00:37146 return va;
Rui Ueyamab5a69702016-02-01 21:00:35147 }
Rafael Espindolaab0cce52018-04-26 17:58:58148 case Symbol::SharedKind:
Rui Ueyamaf52496e2017-11-03 21:21:47149 case Symbol::UndefinedKind:
Rui Ueyamab5a69702016-02-01 21:00:35150 return 0;
Rui Ueyamaf52496e2017-11-03 21:21:47151 case Symbol::LazyObjectKind:
Fangrui Song935229f2022-01-05 08:46:48152 llvm_unreachable("lazy symbol reached writer");
Rui Ueyama5c073a92019-05-16 03:29:03153 case Symbol::CommonKind:
154 llvm_unreachable("common symbol reached writer");
Rui Ueyamaf3fad552018-10-12 18:29:18155 case Symbol::PlaceholderKind:
156 llvm_unreachable("placeholder symbol reached writer");
Rui Ueyamab5a69702016-02-01 21:00:35157 }
George Rimar777f9632016-03-12 08:31:34158 llvm_unreachable("invalid symbol kind");
Rui Ueyamab5a69702016-02-01 21:00:35159}
160
Rui Ueyama3837f422019-07-10 05:00:37161uint64_t Symbol::getVA(int64_t addend) const {
Fangrui Songa8024df2021-12-13 03:12:01162 return getSymVA(*this, addend) + addend;
Rafael Espindola87d9f102016-03-11 12:19:05163}
164
Peter Collingbourne8331f612019-02-13 21:49:55165uint64_t Symbol::getGotVA() const {
Rui Ueyama3837f422019-07-10 05:00:37166 if (gotInIgot)
167 return in.igotPlt->getVA() + getGotPltOffset();
168 return in.got->getVA() + getGotOffset();
Peter Collingbourne8331f612019-02-13 21:49:55169}
Rafael Espindola74031ba2016-04-07 15:20:56170
Harald van Dijkd6241342021-05-16 23:13:00171uint64_t Symbol::getGotOffset() const {
Fangrui Song5d3bd7f2022-01-09 21:43:26172 return getGotIdx() * target->gotEntrySize;
Harald van Dijkd6241342021-05-16 23:13:00173}
Rui Ueyamab5a69702016-02-01 21:00:35174
Rui Ueyamaf52496e2017-11-03 21:21:47175uint64_t Symbol::getGotPltVA() const {
Rui Ueyama3837f422019-07-10 05:00:37176 if (isInIplt)
177 return in.igotPlt->getVA() + getGotPltOffset();
178 return in.gotPlt->getVA() + getGotPltOffset();
Rafael Espindola74031ba2016-04-07 15:20:56179}
180
Rui Ueyamaf52496e2017-11-03 21:21:47181uint64_t Symbol::getGotPltOffset() const {
Rui Ueyama3837f422019-07-10 05:00:37182 if (isInIplt)
Fangrui Song5d3bd7f2022-01-09 21:43:26183 return getPltIdx() * target->gotEntrySize;
184 return (getPltIdx() + target->gotPltHeaderEntriesNum) * target->gotEntrySize;
Rui Ueyamab5a69702016-02-01 21:00:35185}
186
Rui Ueyamaf52496e2017-11-03 21:21:47187uint64_t Symbol::getPltVA() const {
Fangrui Song891a8652019-12-14 22:17:35188 uint64_t outVA = isInIplt
Fangrui Song5d3bd7f2022-01-09 21:43:26189 ? in.iplt->getVA() + getPltIdx() * target->ipltEntrySize
Fangrui Song891a8652019-12-14 22:17:35190 : in.plt->getVA() + in.plt->headerSize +
Fangrui Song5d3bd7f2022-01-09 21:43:26191 getPltIdx() * target->pltEntrySize;
Fangrui Song891a8652019-12-14 22:17:35192
Simon Atanasyanfae2a5092019-02-19 10:36:58193 // While linking microMIPS code PLT code are always microMIPS
194 // code. Set the less-significant bit to track that fact.
195 // See detailed comment in the `getSymVA` function.
Rui Ueyama3837f422019-07-10 05:00:37196 if (config->emachine == EM_MIPS && isMicroMips())
197 outVA |= 1;
198 return outVA;
Rafael Espindolaab0cce52018-04-26 17:58:58199}
200
Rui Ueyamaf52496e2017-11-03 21:21:47201uint64_t Symbol::getSize() const {
Rui Ueyama3837f422019-07-10 05:00:37202 if (const auto *dr = dyn_cast<Defined>(this))
203 return dr->size;
204 return cast<SharedSymbol>(this)->size;
Rui Ueyama512c61d2016-02-03 00:12:24205}
206
Rui Ueyamaf52496e2017-11-03 21:21:47207OutputSection *Symbol::getOutputSection() const {
Rui Ueyama3837f422019-07-10 05:00:37208 if (auto *s = dyn_cast<Defined>(this)) {
209 if (auto *sec = s->section)
Fangrui Songc2f2bb02021-12-21 08:39:16210 return sec->getOutputSection();
Rui Ueyama968db482017-02-28 04:02:42211 return nullptr;
212 }
Rui Ueyama968db482017-02-28 04:02:42213 return nullptr;
214}
215
Rui Ueyama35fa6c52016-11-23 05:48:40216// If a symbol name contains '@', the characters after that is
217// a symbol version name. This function parses that.
Rui Ueyamaf52496e2017-11-03 21:21:47218void Symbol::parseSymbolVersion() {
Fangrui Song00809c82021-08-05 06:52:55219 // Return if localized by a local: pattern in a version script.
220 if (versionId == VER_NDX_LOCAL)
221 return;
Rui Ueyama3837f422019-07-10 05:00:37222 StringRef s = getName();
223 size_t pos = s.find('@');
Fangrui Song101407b2021-12-16 07:59:55224 if (pos == StringRef::npos)
Rui Ueyama35fa6c52016-11-23 05:48:40225 return;
Rui Ueyama3837f422019-07-10 05:00:37226 StringRef verstr = s.substr(pos + 1);
Rui Ueyama35fa6c52016-11-23 05:48:40227
228 // Truncate the symbol name so that it doesn't include the version string.
Rui Ueyama3837f422019-07-10 05:00:37229 nameSize = pos;
Rui Ueyama35fa6c52016-11-23 05:48:40230
Fangrui Song7924b382021-12-27 01:25:54231 if (verstr.empty())
232 return;
233
Rafael Espindola1d6d1b42017-01-17 16:08:06234 // If this is not in this DSO, it is not a definition.
Peter Collingbourneb472aa02017-11-06 04:39:07235 if (!isDefined())
Rafael Espindola2756e042017-01-06 22:30:35236 return;
237
Rui Ueyama35fa6c52016-11-23 05:48:40238 // '@@' in a symbol name means the default version.
239 // It is usually the most recent one.
Rui Ueyama3837f422019-07-10 05:00:37240 bool isDefault = (verstr[0] == '@');
241 if (isDefault)
242 verstr = verstr.substr(1);
Rui Ueyama35fa6c52016-11-23 05:48:40243
Fangrui Songe28a70d2019-08-05 14:31:39244 for (const VersionDefinition &ver : namedVersionDefs()) {
Rui Ueyama3837f422019-07-10 05:00:37245 if (ver.name != verstr)
Rui Ueyama35fa6c52016-11-23 05:48:40246 continue;
247
Rui Ueyama3837f422019-07-10 05:00:37248 if (isDefault)
249 versionId = ver.id;
Rui Ueyama35fa6c52016-11-23 05:48:40250 else
Rui Ueyama3837f422019-07-10 05:00:37251 versionId = ver.id | VERSYM_HIDDEN;
Rui Ueyama35fa6c52016-11-23 05:48:40252 return;
253 }
254
255 // It is an error if the specified version is not defined.
George Rimar4d2f97622017-07-04 13:19:13256 // Usually version script is not provided when linking executable,
257 // but we may still want to override a versioned symbol from DSO,
Peter Smith796fb992018-05-14 10:13:56258 // so we do not report error in this case. We also do not error
259 // if the symbol has a local version as it won't be in the dynamic
260 // symbol table.
Rui Ueyama3837f422019-07-10 05:00:37261 if (config->shared && versionId != VER_NDX_LOCAL)
262 error(toString(file) + ": symbol " + s + " has undefined version " +
263 verstr);
Rui Ueyama35fa6c52016-11-23 05:48:40264}
265
Fangrui Song09401df2021-11-26 18:58:50266void Symbol::extract() const {
Fangrui Song3d854242022-02-15 17:38:00267 if (file->lazy) {
Fangrui Song3a5fb572021-12-23 01:41:50268 file->lazy = false;
269 parseFile(file);
270 }
Rui Ueyama7d476192019-05-16 02:14:00271}
Rui Ueyamaf8baa662016-04-07 19:24:51272
Rui Ueyamaf52496e2017-11-03 21:21:47273uint8_t Symbol::computeBinding() const {
Fangrui Song82ed93ea2022-09-05 00:27:35274 auto v = visibility();
275 if ((v != STV_DEFAULT && v != STV_PROTECTED) || versionId == VER_NDX_LOCAL)
Rafael Espindolab7e2ee22017-01-10 17:08:13276 return STB_LOCAL;
Fangrui Songb3cc4702022-01-16 07:40:43277 if (binding == STB_GNU_UNIQUE && !config->gnuUnique)
Rafael Espindolab7e2ee22017-01-10 17:08:13278 return STB_GLOBAL;
Rui Ueyama3837f422019-07-10 05:00:37279 return binding;
Rafael Espindolab7e2ee22017-01-10 17:08:13280}
281
Rui Ueyamaf52496e2017-11-03 21:21:47282bool Symbol::includeInDynsym() const {
Rafael Espindolab7e2ee22017-01-10 17:08:13283 if (computeBinding() == STB_LOCAL)
Rafael Espindolaae605c12016-04-21 20:35:25284 return false;
Fangrui Song375371c2020-01-09 23:53:52285 if (!isDefined() && !isCommon())
Fangrui Song0fbf28f2020-01-23 19:52:03286 // This should unconditionally return true, unfortunately glibc -static-pie
287 // expects undefined weak symbols not to exist in .dynsym, e.g.
288 // __pthread_mutex_lock reference in _dl_add_to_namespace_list,
289 // __pthread_initialize_minimal reference in csu/libc-start.c.
Fangrui Song01a51622022-01-16 07:32:48290 return !(isUndefWeak() && config->noDynamicLinker);
Rui Ueyamae63ae7f2019-06-25 06:58:07291
Fangrui Song375371c2020-01-09 23:53:52292 return exportDynamic || inDynamicList;
Rafael Espindolaae605c12016-04-21 20:35:25293}
Rui Ueyama69c778c2016-07-17 17:50:09294
295// Print out a log message for --trace-symbol.
Fangrui Song977a1a52022-02-06 00:34:02296void elf::printTraceSymbol(const Symbol &sym, StringRef name) {
Rui Ueyama3837f422019-07-10 05:00:37297 std::string s;
Fangrui Song977a1a52022-02-06 00:34:02298 if (sym.isUndefined())
Rui Ueyama3837f422019-07-10 05:00:37299 s = ": reference to ";
Fangrui Song977a1a52022-02-06 00:34:02300 else if (sym.isLazy())
Rui Ueyama3837f422019-07-10 05:00:37301 s = ": lazy definition of ";
Fangrui Song977a1a52022-02-06 00:34:02302 else if (sym.isShared())
Rui Ueyama3837f422019-07-10 05:00:37303 s = ": shared definition of ";
Fangrui Song977a1a52022-02-06 00:34:02304 else if (sym.isCommon())
Rui Ueyama3837f422019-07-10 05:00:37305 s = ": common definition of ";
Rui Ueyama69c778c2016-07-17 17:50:09306 else
Rui Ueyama3837f422019-07-10 05:00:37307 s = ": definition of ";
Rui Ueyamae6e206d2017-02-21 23:22:56308
Fangrui Song977a1a52022-02-06 00:34:02309 message(toString(sym.file) + s + name);
Rui Ueyama69c778c2016-07-17 17:50:09310}
311
Fangrui Songa954bb12021-09-20 16:52:30312static void recordWhyExtract(const InputFile *reference,
313 const InputFile &extracted, const Symbol &sym) {
Fangrui Song34fa8602022-10-01 19:06:33314 ctx.whyExtractRecords.emplace_back(toString(reference), &extracted, sym);
Fangrui Songa954bb12021-09-20 16:52:30315}
316
Fangrui Song07837b82020-05-15 05:18:58317void elf::maybeWarnUnorderableSymbol(const Symbol *sym) {
Rui Ueyama3837f422019-07-10 05:00:37318 if (!config->warnSymbolOrdering)
Michael J. Spencerb8427252018-04-17 23:30:05319 return;
Rui Ueyamab774c3c2018-04-26 01:38:29320
Fangrui Song11ca54f2018-10-10 22:48:57321 // If UnresolvedPolicy::Ignore is used, no "undefined symbol" error/warning
322 // is emitted. It makes sense to not warn on undefined symbols.
323 //
324 // Note, ld.bfd --symbol-ordering-file= does not warn on undefined symbols,
325 // but we don't have to be compatible here.
Rui Ueyama3837f422019-07-10 05:00:37326 if (sym->isUndefined() &&
327 config->unresolvedSymbols == UnresolvedPolicy::Ignore)
Fangrui Song11ca54f2018-10-10 22:48:57328 return;
329
Rui Ueyama3837f422019-07-10 05:00:37330 const InputFile *file = sym->file;
331 auto *d = dyn_cast<Defined>(sym);
Rui Ueyamab774c3c2018-04-26 01:38:29332
Rui Ueyama3837f422019-07-10 05:00:37333 auto report = [&](StringRef s) { warn(toString(file) + s + sym->getName()); };
Rui Ueyamab774c3c2018-04-26 01:38:29334
Rui Ueyama3837f422019-07-10 05:00:37335 if (sym->isUndefined())
336 report(": unable to order undefined symbol: ");
337 else if (sym->isShared())
338 report(": unable to order shared symbol: ");
339 else if (d && !d->section)
340 report(": unable to order absolute symbol: ");
341 else if (d && isa<OutputSection>(d->section))
342 report(": unable to order synthetic symbol: ");
Fangrui Songe1b6b5b2021-12-24 20:09:48343 else if (d && !d->section->isLive())
Rui Ueyama3837f422019-07-10 05:00:37344 report(": unable to order discarded symbol: ");
Michael J. Spencerb8427252018-04-17 23:30:05345}
346
Fangrui Songcd0ab242019-11-30 05:58:36347// Returns true if a symbol can be replaced at load-time by a symbol
348// with the same name defined in other ELF executable or DSO.
Fangrui Song07837b82020-05-15 05:18:58349bool elf::computeIsPreemptible(const Symbol &sym) {
Fangrui Songe9262ed2021-12-27 02:11:45350 assert(!sym.isLocal() || sym.isPlaceholder());
Fangrui Songcd0ab242019-11-30 05:58:36351
352 // Only symbols with default visibility that appear in dynsym can be
353 // preempted. Symbols with protected visibility cannot be preempted.
Fangrui Song82ed93ea2022-09-05 00:27:35354 if (!sym.includeInDynsym() || sym.visibility() != STV_DEFAULT)
Fangrui Songcd0ab242019-11-30 05:58:36355 return false;
356
357 // At this point copy relocations have not been created yet, so any
358 // symbol that is not defined locally is preemptible.
359 if (!sym.isDefined())
360 return true;
361
362 if (!config->shared)
363 return false;
364
Fangrui Song751f18e2020-06-01 18:27:53365 // If -Bsymbolic or --dynamic-list is specified, or -Bsymbolic-functions is
366 // specified and the symbol is STT_FUNC, the symbol is preemptible iff it is
Fangrui Songb06426d2021-07-29 21:46:53367 // in the dynamic list. -Bsymbolic-non-weak-functions is a non-weak subset of
368 // -Bsymbolic-functions.
369 if (config->symbolic ||
370 (config->bsymbolic == BsymbolicKind::Functions && sym.isFunc()) ||
371 (config->bsymbolic == BsymbolicKind::NonWeakFunctions && sym.isFunc() &&
372 sym.binding != STB_WEAK))
Fangrui Songcd0ab242019-11-30 05:58:36373 return sym.inDynamicList;
Fangrui Songcd0ab242019-11-30 05:58:36374 return true;
375}
376
Rui Ueyama7f7d2b22019-05-23 09:58:08377// Merge symbol properties.
378//
379// When we have many symbols of the same name, we choose one of them,
380// and that's the result of symbol resolution. However, symbols that
381// were not chosen still affect some symbol properties.
Rui Ueyama3837f422019-07-10 05:00:37382void Symbol::mergeProperties(const Symbol &other) {
383 if (other.exportDynamic)
384 exportDynamic = true;
Rui Ueyama7f7d2b22019-05-23 09:58:08385
386 // DSO symbols do not affect visibility in the output.
Fangrui Song82ed93ea2022-09-05 00:27:35387 if (!other.isShared() && other.visibility() != STV_DEFAULT) {
388 uint8_t v = visibility(), ov = other.visibility();
389 setVisibility(v == STV_DEFAULT ? ov : std::min(v, ov));
390 }
Rui Ueyama7f7d2b22019-05-23 09:58:08391}
392
Fangrui Song9e6840c2022-09-29 03:01:41393void Symbol::resolve(const Undefined &other) {
394 if (other.visibility() != STV_DEFAULT) {
395 uint8_t v = visibility(), ov = other.visibility();
396 setVisibility(v == STV_DEFAULT ? ov : std::min(v, ov));
Rui Ueyama7f7d2b22019-05-23 09:58:08397 }
Rui Ueyama7f7d2b22019-05-23 09:58:08398 // An undefined symbol with non default visibility must be satisfied
399 // in the same DSO.
400 //
401 // If this is a non-weak defined symbol in a discarded section, override the
402 // existing undefined symbol for better error message later.
Fangrui Songdf6803d2022-09-28 17:39:31403 if (isPlaceholder() || (isShared() && other.visibility() != STV_DEFAULT) ||
Rui Ueyama3837f422019-07-10 05:00:37404 (isUndefined() && other.binding != STB_WEAK && other.discardedSecIdx)) {
Fangrui Song7a58dd12022-09-28 20:11:31405 other.overwrite(*this);
Rui Ueyama7f7d2b22019-05-23 09:58:08406 return;
407 }
408
Rui Ueyama3837f422019-07-10 05:00:37409 if (traced)
Fangrui Song977a1a52022-02-06 00:34:02410 printTraceSymbol(other, getName());
Sam Clegg7991b682019-05-24 13:29:17411
Fangrui Songf3475412019-07-04 10:38:04412 if (isLazy()) {
Fangrui Song09401df2021-11-26 18:58:50413 // An undefined weak will not extract archive members. See comment on Lazy
414 // in Symbols.h for the details.
Rui Ueyama3837f422019-07-10 05:00:37415 if (other.binding == STB_WEAK) {
416 binding = STB_WEAK;
417 type = other.type;
Rui Ueyama7f7d2b22019-05-23 09:58:08418 return;
419 }
420
421 // Do extra check for --warn-backrefs.
422 //
423 // --warn-backrefs is an option to prevent an undefined reference from
Fangrui Song09401df2021-11-26 18:58:50424 // extracting an archive member written earlier in the command line. It can
425 // be used to keep compatibility with GNU linkers to some degree. I'll
426 // explain the feature and why you may find it useful in this comment.
Rui Ueyama7f7d2b22019-05-23 09:58:08427 //
428 // lld's symbol resolution semantics is more relaxed than traditional Unix
429 // linkers. For example,
430 //
431 // ld.lld foo.a bar.o
432 //
433 // succeeds even if bar.o contains an undefined symbol that has to be
434 // resolved by some object file in foo.a. Traditional Unix linkers don't
435 // allow this kind of backward reference, as they visit each file only once
436 // from left to right in the command line while resolving all undefined
437 // symbols at the moment of visiting.
438 //
439 // In the above case, since there's no undefined symbol when a linker visits
440 // foo.a, no files are pulled out from foo.a, and because the linker forgets
441 // about foo.a after visiting, it can't resolve undefined symbols in bar.o
442 // that could have been resolved otherwise.
443 //
444 // That lld accepts more relaxed form means that (besides it'd make more
445 // sense) you can accidentally write a command line or a build file that
446 // works only with lld, even if you have a plan to distribute it to wider
447 // users who may be using GNU linkers. With --warn-backrefs, you can detect
448 // a library order that doesn't work with other Unix linkers.
449 //
450 // The option is also useful to detect cyclic dependencies between static
451 // archives. Again, lld accepts
452 //
453 // ld.lld foo.a bar.a
454 //
455 // even if foo.a and bar.a depend on each other. With --warn-backrefs, it is
456 // handled as an error.
457 //
458 // Here is how the option works. We assign a group ID to each file. A file
459 // with a smaller group ID can pull out object files from an archive file
460 // with an equal or greater group ID. Otherwise, it is a reverse dependency
461 // and an error.
462 //
463 // A file outside --{start,end}-group gets a fresh ID when instantiated. All
464 // files within the same --{start,end}-group get the same group ID. E.g.
465 //
466 // ld.lld A B --start-group C D --end-group E
467 //
468 // A forms group 0. B form group 1. C and D (including their member object
469 // files) form group 2. E forms group 3. I think that you can see how this
470 // group assignment rule simulates the traditional linker's semantics.
Rui Ueyama3837f422019-07-10 05:00:37471 bool backref = config->warnBackrefs && other.file &&
472 file->groupId < other.file->groupId;
Fangrui Song09401df2021-11-26 18:58:50473 extract();
Rui Ueyama7f7d2b22019-05-23 09:58:08474
Fangrui Songa954bb12021-09-20 16:52:30475 if (!config->whyExtract.empty())
476 recordWhyExtract(other.file, *file, *this);
477
Rui Ueyama7f7d2b22019-05-23 09:58:08478 // We don't report backward references to weak symbols as they can be
479 // overridden later.
Fangrui Song03c825c2020-04-06 05:27:46480 //
481 // A traditional linker does not error for -ldef1 -lref -ldef2 (linking
482 // sandwich), where def2 may or may not be the same as def1. We don't want
483 // to warn for this case, so dismiss the warning if we see a subsequent lazy
Fangrui Songce3c5da2020-10-22 22:26:52484 // definition. this->file needs to be saved because in the case of LTO it
485 // may be reset to nullptr or be replaced with a file named lto.tmp.
Rui Ueyama3837f422019-07-10 05:00:37486 if (backref && !isWeak())
Fangrui Song34fa8602022-10-01 19:06:33487 ctx.backwardReferences.try_emplace(this,
488 std::make_pair(other.file, file));
Fangrui Songf3475412019-07-04 10:38:04489 return;
490 }
491
492 // Undefined symbols in a SharedFile do not change the binding.
Kazu Hirata62e48ed2021-12-25 05:22:27493 if (isa_and_nonnull<SharedFile>(other.file))
Fangrui Songf3475412019-07-04 10:38:04494 return;
495
Fangrui Songe49c4172019-08-06 14:03:45496 if (isUndefined() || isShared()) {
497 // The binding will be weak if there is at least one reference and all are
498 // weak. The binding has one opportunity to change to weak: if the first
499 // reference is weak.
500 if (other.binding != STB_WEAK || !referenced)
Rui Ueyama3837f422019-07-10 05:00:37501 binding = other.binding;
Rui Ueyama7f7d2b22019-05-23 09:58:08502 }
503}
504
Fangrui Song19e37a72022-02-24 22:09:00505// Compare two symbols. Return true if the new symbol should win.
Fangrui Songb07ef4d2022-02-28 18:25:21506bool Symbol::shouldReplace(const Defined &other) const {
Fangrui Song6d943402022-02-24 22:08:06507 if (LLVM_UNLIKELY(isCommon())) {
508 if (config->warnCommon)
509 warn("common " + getName() + " is overridden");
510 return !other.isWeak();
511 }
512 if (!isDefined())
513 return true;
Rui Ueyama7f7d2b22019-05-23 09:58:08514
Fangrui Songc7cf9602022-03-14 19:00:15515 // Incoming STB_GLOBAL overrides STB_WEAK/STB_GNU_UNIQUE. -fgnu-unique changes
516 // some vague linkage data in COMDAT from STB_WEAK to STB_GNU_UNIQUE. Treat
517 // STB_GNU_UNIQUE like STB_WEAK so that we prefer the first among all
518 // STB_WEAK/STB_GNU_UNIQUE copies. If we prefer an incoming STB_GNU_UNIQUE to
519 // an existing STB_WEAK, there may be discarded section errors because the
520 // selected copy may be in a non-prevailing COMDAT.
521 return !isGlobal() && other.isGlobal();
Rui Ueyama7f7d2b22019-05-23 09:58:08522}
523
Fangrui Song7c7702b2022-03-16 02:24:41524void elf::reportDuplicate(const Symbol &sym, const InputFile *newFile,
Fangrui Song88d66f62022-02-22 18:07:58525 InputSectionBase *errSec, uint64_t errOffset) {
Rui Ueyama3837f422019-07-10 05:00:37526 if (config->allowMultipleDefinition)
Rui Ueyama7f7d2b22019-05-23 09:58:08527 return;
Fangrui Song7c7702b2022-03-16 02:24:41528 // In glibc<2.32, crti.o has .gnu.linkonce.t.__x86.get_pc_thunk.bx, which
529 // is sort of proto-comdat. There is actually no duplicate if we have
530 // full support for .gnu.linkonce.
531 const Defined *d = dyn_cast<Defined>(&sym);
532 if (!d || d->getName() == "__x86.get_pc_thunk.bx")
533 return;
534 // Allow absolute symbols with the same value for GNU ld compatibility.
535 if (!d->section && !errSec && errOffset && d->value == errOffset)
536 return;
Rui Ueyama3837f422019-07-10 05:00:37537 if (!d->section || !errSec) {
Fangrui Song467e1b32022-02-15 19:18:31538 error("duplicate symbol: " + toString(sym) + "\n>>> defined in " +
539 toString(sym.file) + "\n>>> defined in " + toString(newFile));
Rui Ueyama7f7d2b22019-05-23 09:58:08540 return;
541 }
542
543 // Construct and print an error message in the form of:
544 //
545 // ld.lld: error: duplicate symbol: foo
546 // >>> defined at bar.c:30
547 // >>> bar.o (/home/alice/src/bar.o)
548 // >>> defined at baz.c:563
549 // >>> baz.o in archive libbaz.a
Rui Ueyama3837f422019-07-10 05:00:37550 auto *sec1 = cast<InputSectionBase>(d->section);
Fangrui Song467e1b32022-02-15 19:18:31551 std::string src1 = sec1->getSrcMsg(sym, d->value);
Rui Ueyama3837f422019-07-10 05:00:37552 std::string obj1 = sec1->getObjMsg(d->value);
Fangrui Song467e1b32022-02-15 19:18:31553 std::string src2 = errSec->getSrcMsg(sym, errOffset);
Rui Ueyama3837f422019-07-10 05:00:37554 std::string obj2 = errSec->getObjMsg(errOffset);
Rui Ueyama7f7d2b22019-05-23 09:58:08555
Fangrui Song467e1b32022-02-15 19:18:31556 std::string msg = "duplicate symbol: " + toString(sym) + "\n>>> defined at ";
Rui Ueyama3837f422019-07-10 05:00:37557 if (!src1.empty())
558 msg += src1 + "\n>>> ";
559 msg += obj1 + "\n>>> defined at ";
560 if (!src2.empty())
561 msg += src2 + "\n>>> ";
562 msg += obj2;
563 error(msg);
Rui Ueyama7f7d2b22019-05-23 09:58:08564}
565
Fangrui Song88d66f62022-02-22 18:07:58566void Symbol::checkDuplicate(const Defined &other) const {
Fangrui Song6d943402022-02-24 22:08:06567 if (isDefined() && !isWeak() && !other.isWeak())
Fangrui Song88d66f62022-02-22 18:07:58568 reportDuplicate(*this, other.file,
569 dyn_cast_or_null<InputSectionBase>(other.section),
570 other.value);
571}
572
Fangrui Song9e6840c2022-09-29 03:01:41573void Symbol::resolve(const CommonSymbol &other) {
574 if (other.exportDynamic)
575 exportDynamic = true;
576 if (other.visibility() != STV_DEFAULT) {
577 uint8_t v = visibility(), ov = other.visibility();
578 setVisibility(v == STV_DEFAULT ? ov : std::min(v, ov));
579 }
Fangrui Song6d943402022-02-24 22:08:06580 if (isDefined() && !isWeak()) {
581 if (config->warnCommon)
582 warn("common " + getName() + " is overridden");
Rui Ueyama7f7d2b22019-05-23 09:58:08583 return;
Fangrui Song6d943402022-02-24 22:08:06584 }
Rui Ueyama7f7d2b22019-05-23 09:58:08585
Fangrui Song6d943402022-02-24 22:08:06586 if (CommonSymbol *oldSym = dyn_cast<CommonSymbol>(this)) {
587 if (config->warnCommon)
588 warn("multiple common of " + getName());
589 oldSym->alignment = std::max(oldSym->alignment, other.alignment);
590 if (oldSym->size < other.size) {
591 oldSym->file = other.file;
592 oldSym->size = other.size;
Fangrui Song69d10d22019-12-07 05:18:31593 }
Rui Ueyama7f7d2b22019-05-23 09:58:08594 return;
595 }
596
Fangrui Song6d943402022-02-24 22:08:06597 if (auto *s = dyn_cast<SharedSymbol>(this)) {
598 // Increase st_size if the shared symbol has a larger st_size. The shared
599 // symbol may be created from common symbols. The fact that some object
600 // files were linked into a shared object first should not change the
601 // regular rule that picks the largest st_size.
602 uint64_t size = s->size;
Fangrui Song7a58dd12022-09-28 20:11:31603 other.overwrite(*this);
Fangrui Song6d943402022-02-24 22:08:06604 if (size > cast<CommonSymbol>(this)->size)
605 cast<CommonSymbol>(this)->size = size;
606 } else {
Fangrui Song7a58dd12022-09-28 20:11:31607 other.overwrite(*this);
Rui Ueyama7f7d2b22019-05-23 09:58:08608 }
609}
610
Fangrui Song9e6840c2022-09-29 03:01:41611void Symbol::resolve(const Defined &other) {
612 if (other.exportDynamic)
613 exportDynamic = true;
614 if (other.visibility() != STV_DEFAULT) {
615 uint8_t v = visibility(), ov = other.visibility();
616 setVisibility(v == STV_DEFAULT ? ov : std::min(v, ov));
617 }
Fangrui Songb07ef4d2022-02-28 18:25:21618 if (shouldReplace(other))
Fangrui Song7a58dd12022-09-28 20:11:31619 other.overwrite(*this);
Rui Ueyama7f7d2b22019-05-23 09:58:08620}
621
Fangrui Song9e6840c2022-09-29 03:01:41622void Symbol::resolve(const LazyObject &other) {
Fangrui Songdf6803d2022-09-28 17:39:31623 if (isPlaceholder()) {
Fangrui Song7a58dd12022-09-28 20:11:31624 other.overwrite(*this);
Fangrui Songdf6803d2022-09-28 17:39:31625 return;
626 }
627
Sean Fertile8f91f382020-12-07 14:28:17628 // For common objects, we want to look for global or weak definitions that
Fangrui Song09401df2021-11-26 18:58:50629 // should be extracted as the canonical definition instead.
Fangrui Song15617cd2022-02-24 20:21:40630 if (LLVM_UNLIKELY(isCommon()) && elf::config->fortranCommon &&
631 other.file->shouldExtractForCommon(getName())) {
Fangrui Song34fa8602022-10-01 19:06:33632 ctx.backwardReferences.erase(this);
Fangrui Song7a58dd12022-09-28 20:11:31633 other.overwrite(*this);
Fangrui Song15617cd2022-02-24 20:21:40634 other.extract();
635 return;
Sean Fertile8f91f382020-12-07 14:28:17636 }
637
Fangrui Song03c825c2020-04-06 05:27:46638 if (!isUndefined()) {
639 // See the comment in resolveUndefined().
640 if (isDefined())
Fangrui Song34fa8602022-10-01 19:06:33641 ctx.backwardReferences.erase(this);
Rui Ueyama7f7d2b22019-05-23 09:58:08642 return;
Fangrui Song03c825c2020-04-06 05:27:46643 }
Rui Ueyama7f7d2b22019-05-23 09:58:08644
Fangrui Song09401df2021-11-26 18:58:50645 // An undefined weak will not extract archive members. See comment on Lazy in
Rui Ueyama7f7d2b22019-05-23 09:58:08646 // Symbols.h for the details.
647 if (isWeak()) {
Rui Ueyama3837f422019-07-10 05:00:37648 uint8_t ty = type;
Fangrui Song7a58dd12022-09-28 20:11:31649 other.overwrite(*this);
Rui Ueyama3837f422019-07-10 05:00:37650 type = ty;
651 binding = STB_WEAK;
Rui Ueyama7f7d2b22019-05-23 09:58:08652 return;
653 }
654
Fangrui Songa954bb12021-09-20 16:52:30655 const InputFile *oldFile = file;
Fangrui Song09401df2021-11-26 18:58:50656 other.extract();
Fangrui Songa954bb12021-09-20 16:52:30657 if (!config->whyExtract.empty())
658 recordWhyExtract(oldFile, *file, *this);
Rui Ueyama7f7d2b22019-05-23 09:58:08659}
660
Fangrui Song9e6840c2022-09-29 03:01:41661void Symbol::resolve(const SharedSymbol &other) {
662 exportDynamic = true;
Fangrui Songdf6803d2022-09-28 17:39:31663 if (isPlaceholder()) {
Fangrui Song7a58dd12022-09-28 20:11:31664 other.overwrite(*this);
Fangrui Songdf6803d2022-09-28 17:39:31665 return;
666 }
Fangrui Song69d10d22019-12-07 05:18:31667 if (isCommon()) {
668 // See the comment in resolveCommon() above.
669 if (other.size > cast<CommonSymbol>(this)->size)
670 cast<CommonSymbol>(this)->size = other.size;
671 return;
672 }
Fangrui Song82ed93ea2022-09-05 00:27:35673 if (visibility() == STV_DEFAULT && (isUndefined() || isLazy())) {
Rui Ueyama7f7d2b22019-05-23 09:58:08674 // An undefined symbol with non default visibility must be satisfied
675 // in the same DSO.
Rui Ueyama3837f422019-07-10 05:00:37676 uint8_t bind = binding;
Fangrui Song7a58dd12022-09-28 20:11:31677 other.overwrite(*this);
Rui Ueyama3837f422019-07-10 05:00:37678 binding = bind;
Fangrui Song64676492020-05-18 17:15:59679 } else if (traced)
Fangrui Song977a1a52022-02-06 00:34:02680 printTraceSymbol(other, getName());
Rui Ueyama7f7d2b22019-05-23 09:58:08681}