blob: 93653def328f8224b5e1b3e8d11e30423f5f561f [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>();
Fangrui Song7071a252024-01-20 00:15:5243 AssertSymbol<LazySymbol>();
Shoaib Meenaib862bcb2022-04-19 20:42:0544}
45
Jez Ng32647c82022-10-14 19:28:1946// Returns a symbol for an error message.
47static std::string maybeDemangleSymbol(StringRef symName) {
Nick Desaulniers8abbc172023-06-05 21:59:4648 return elf::config->demangle ? demangle(symName.str()) : symName.str();
Jez Ng32647c82022-10-14 19:28:1949}
50
Fangrui Song07837b82020-05-15 05:18:5851std::string lld::toString(const elf::Symbol &sym) {
Fangrui Songf2036a12020-03-28 22:48:3852 StringRef name = sym.getName();
Jez Ng32647c82022-10-14 19:28:1953 std::string ret = maybeDemangleSymbol(name);
Fangrui Songf2036a12020-03-28 22:48:3854
Fangrui Song941e9332020-12-01 16:54:0155 const char *suffix = sym.getVersionSuffix();
56 if (*suffix == '@')
57 ret += suffix;
Fangrui Songf2036a12020-03-28 22:48:3858 return ret;
59}
60
Rui Ueyama3837f422019-07-10 05:00:3761Defined *ElfSym::bss;
62Defined *ElfSym::etext1;
63Defined *ElfSym::etext2;
64Defined *ElfSym::edata1;
65Defined *ElfSym::edata2;
66Defined *ElfSym::end1;
67Defined *ElfSym::end2;
68Defined *ElfSym::globalOffsetTable;
69Defined *ElfSym::mipsGp;
70Defined *ElfSym::mipsGpDisp;
71Defined *ElfSym::mipsLocalGp;
Craig Topper85444792023-04-13 17:39:4772Defined *ElfSym::riscvGlobalPointer;
Rui Ueyama3837f422019-07-10 05:00:3773Defined *ElfSym::relaIpltStart;
74Defined *ElfSym::relaIpltEnd;
Rui Ueyama3837f422019-07-10 05:00:3775Defined *ElfSym::tlsModuleBase;
Fangrui Song5d3bd7f2022-01-09 21:43:2676SmallVector<SymbolAux, 0> elf::symAux;
Rui Ueyama80474a22017-02-28 19:29:5577
Fangrui Songa8024df2021-12-13 03:12:0178static uint64_t getSymVA(const Symbol &sym, int64_t addend) {
Rui Ueyama3837f422019-07-10 05:00:3779 switch (sym.kind()) {
Peter Collingbournee9a9e0a2017-11-06 04:35:3180 case Symbol::DefinedKind: {
Rui Ueyama3837f422019-07-10 05:00:3781 auto &d = cast<Defined>(sym);
82 SectionBase *isec = d.section;
Rui Ueyamab5a69702016-02-01 21:00:3583
84 // This is an absolute symbol.
Rui Ueyama3837f422019-07-10 05:00:3785 if (!isec)
86 return d.value;
Rui Ueyamab5a69702016-02-01 21:00:3587
Rui Ueyama3837f422019-07-10 05:00:3788 assert(isec != &InputSection::discarded);
Rafael Espindolaf4d6e8c2018-04-19 17:26:5089
Rui Ueyama3837f422019-07-10 05:00:3790 uint64_t offset = d.value;
Sean Silvaa9ba4502017-02-28 08:32:5691
92 // An object in an SHF_MERGE section might be referenced via a
93 // section symbol (as a hack for reducing the number of local
94 // symbols).
Sean Silvad4e60622017-03-01 04:44:0495 // Depending on the addend, the reference via a section symbol
96 // refers to a different object in the merge section.
97 // Since the objects in the merge section are not necessarily
98 // contiguous in the output, the addend can thus affect the final
99 // VA in a non-linear way.
100 // To make this work, we incorporate the addend into the section
101 // offset (and zero out the addend for later processing) so that
102 // we find the right object in the section.
Fangrui Songa8024df2021-12-13 03:12:01103 if (d.isSection())
Rui Ueyama3837f422019-07-10 05:00:37104 offset += addend;
Sean Silvaa9ba4502017-02-28 08:32:56105
Sean Silva6ab39262017-02-28 09:01:58106 // In the typical case, this is actually very simple and boils
107 // down to adding together 3 numbers:
108 // 1. The address of the output section.
109 // 2. The offset of the input section within the output section.
110 // 3. The offset within the input section (this addition happens
111 // inside InputSection::getOffset).
112 //
113 // If you understand the data structures involved with this next
114 // line (and how they get built), then you have a pretty good
115 // understanding of the linker.
Rui Ueyama3837f422019-07-10 05:00:37116 uint64_t va = isec->getVA(offset);
Fangrui Songa8024df2021-12-13 03:12:01117 if (d.isSection())
118 va -= addend;
Sean Silva6ab39262017-02-28 09:01:58119
Simon Atanasyanfae2a5092019-02-19 10:36:58120 // MIPS relocatable files can mix regular and microMIPS code.
121 // Linker needs to distinguish such code. To do so microMIPS
122 // symbols has the `STO_MIPS_MICROMIPS` flag in the `st_other`
Fangrui Songdeb58192020-01-23 05:39:16123 // field. Unfortunately, the `MIPS::relocate()` method has
Simon Atanasyanfae2a5092019-02-19 10:36:58124 // a symbol value only. To pass type of the symbol (regular/microMIPS)
125 // to that routine as well as other places where we write
126 // a symbol value as-is (.dynamic section, `Elf_Ehdr::e_entry`
127 // field etc) do the same trick as compiler uses to mark microMIPS
128 // for CPU - set the less-significant bit.
Rui Ueyama3837f422019-07-10 05:00:37129 if (config->emachine == EM_MIPS && isMicroMips() &&
Fangrui Songbd16ffb32022-09-09 21:37:18130 ((sym.stOther & STO_MIPS_MICROMIPS) || sym.hasFlag(NEEDS_COPY)))
Rui Ueyama3837f422019-07-10 05:00:37131 va |= 1;
Simon Atanasyanfae2a5092019-02-19 10:36:58132
Rui Ueyama3837f422019-07-10 05:00:37133 if (d.isTls() && !config->relocatable) {
Ryan Prichard1c33d142018-09-18 00:24:48134 // Use the address of the TLS segment's first section rather than the
135 // segment's address, because segment addresses aren't initialized until
136 // after sections are finalized. (e.g. Measuring the size of .rela.dyn
137 // for Android relocation packing requires knowing TLS symbol addresses
138 // during section finalization.)
Rui Ueyama3837f422019-07-10 05:00:37139 if (!Out::tlsPhdr || !Out::tlsPhdr->firstSec)
140 fatal(toString(d.file) +
Peter Collingbourne3e2abde2017-07-14 00:22:46141 " has an STT_TLS symbol but doesn't have an SHF_TLS section");
Rui Ueyama3837f422019-07-10 05:00:37142 return va - Out::tlsPhdr->firstSec->addr;
George Rimar6a3b1542016-10-04 08:52:51143 }
Rui Ueyama3837f422019-07-10 05:00:37144 return va;
Rui Ueyamab5a69702016-02-01 21:00:35145 }
Rafael Espindolaab0cce52018-04-26 17:58:58146 case Symbol::SharedKind:
Rui Ueyamaf52496e2017-11-03 21:21:47147 case Symbol::UndefinedKind:
Rui Ueyamab5a69702016-02-01 21:00:35148 return 0;
Fangrui Song7071a252024-01-20 00:15:52149 case Symbol::LazyKind:
Fangrui Song935229f2022-01-05 08:46:48150 llvm_unreachable("lazy symbol reached writer");
Rui Ueyama5c073a92019-05-16 03:29:03151 case Symbol::CommonKind:
152 llvm_unreachable("common symbol reached writer");
Rui Ueyamaf3fad552018-10-12 18:29:18153 case Symbol::PlaceholderKind:
154 llvm_unreachable("placeholder symbol reached writer");
Rui Ueyamab5a69702016-02-01 21:00:35155 }
George Rimar777f9632016-03-12 08:31:34156 llvm_unreachable("invalid symbol kind");
Rui Ueyamab5a69702016-02-01 21:00:35157}
158
Rui Ueyama3837f422019-07-10 05:00:37159uint64_t Symbol::getVA(int64_t addend) const {
Fangrui Songa8024df2021-12-13 03:12:01160 return getSymVA(*this, addend) + addend;
Rafael Espindola87d9f102016-03-11 12:19:05161}
162
Peter Collingbourne8331f612019-02-13 21:49:55163uint64_t Symbol::getGotVA() const {
Rui Ueyama3837f422019-07-10 05:00:37164 if (gotInIgot)
165 return in.igotPlt->getVA() + getGotPltOffset();
166 return in.got->getVA() + getGotOffset();
Peter Collingbourne8331f612019-02-13 21:49:55167}
Rafael Espindola74031ba2016-04-07 15:20:56168
Harald van Dijkd6241342021-05-16 23:13:00169uint64_t Symbol::getGotOffset() const {
Fangrui Song5d3bd7f2022-01-09 21:43:26170 return getGotIdx() * target->gotEntrySize;
Harald van Dijkd6241342021-05-16 23:13:00171}
Rui Ueyamab5a69702016-02-01 21:00:35172
Rui Ueyamaf52496e2017-11-03 21:21:47173uint64_t Symbol::getGotPltVA() const {
Rui Ueyama3837f422019-07-10 05:00:37174 if (isInIplt)
175 return in.igotPlt->getVA() + getGotPltOffset();
176 return in.gotPlt->getVA() + getGotPltOffset();
Rafael Espindola74031ba2016-04-07 15:20:56177}
178
Rui Ueyamaf52496e2017-11-03 21:21:47179uint64_t Symbol::getGotPltOffset() const {
Rui Ueyama3837f422019-07-10 05:00:37180 if (isInIplt)
Fangrui Song5d3bd7f2022-01-09 21:43:26181 return getPltIdx() * target->gotEntrySize;
182 return (getPltIdx() + target->gotPltHeaderEntriesNum) * target->gotEntrySize;
Rui Ueyamab5a69702016-02-01 21:00:35183}
184
Rui Ueyamaf52496e2017-11-03 21:21:47185uint64_t Symbol::getPltVA() const {
Fangrui Song891a8652019-12-14 22:17:35186 uint64_t outVA = isInIplt
Fangrui Song5d3bd7f2022-01-09 21:43:26187 ? in.iplt->getVA() + getPltIdx() * target->ipltEntrySize
Fangrui Song891a8652019-12-14 22:17:35188 : in.plt->getVA() + in.plt->headerSize +
Fangrui Song5d3bd7f2022-01-09 21:43:26189 getPltIdx() * target->pltEntrySize;
Fangrui Song891a8652019-12-14 22:17:35190
Simon Atanasyanfae2a5092019-02-19 10:36:58191 // While linking microMIPS code PLT code are always microMIPS
192 // code. Set the less-significant bit to track that fact.
193 // See detailed comment in the `getSymVA` function.
Rui Ueyama3837f422019-07-10 05:00:37194 if (config->emachine == EM_MIPS && isMicroMips())
195 outVA |= 1;
196 return outVA;
Rafael Espindolaab0cce52018-04-26 17:58:58197}
198
Rui Ueyamaf52496e2017-11-03 21:21:47199uint64_t Symbol::getSize() const {
Rui Ueyama3837f422019-07-10 05:00:37200 if (const auto *dr = dyn_cast<Defined>(this))
201 return dr->size;
202 return cast<SharedSymbol>(this)->size;
Rui Ueyama512c61d2016-02-03 00:12:24203}
204
Rui Ueyamaf52496e2017-11-03 21:21:47205OutputSection *Symbol::getOutputSection() const {
Rui Ueyama3837f422019-07-10 05:00:37206 if (auto *s = dyn_cast<Defined>(this)) {
207 if (auto *sec = s->section)
Fangrui Songc2f2bb02021-12-21 08:39:16208 return sec->getOutputSection();
Rui Ueyama968db482017-02-28 04:02:42209 return nullptr;
210 }
Rui Ueyama968db482017-02-28 04:02:42211 return nullptr;
212}
213
Rui Ueyama35fa6c52016-11-23 05:48:40214// If a symbol name contains '@', the characters after that is
215// a symbol version name. This function parses that.
Rui Ueyamaf52496e2017-11-03 21:21:47216void Symbol::parseSymbolVersion() {
Fangrui Song00809c82021-08-05 06:52:55217 // Return if localized by a local: pattern in a version script.
218 if (versionId == VER_NDX_LOCAL)
219 return;
Rui Ueyama3837f422019-07-10 05:00:37220 StringRef s = getName();
221 size_t pos = s.find('@');
Fangrui Song101407b2021-12-16 07:59:55222 if (pos == StringRef::npos)
Rui Ueyama35fa6c52016-11-23 05:48:40223 return;
Rui Ueyama3837f422019-07-10 05:00:37224 StringRef verstr = s.substr(pos + 1);
Rui Ueyama35fa6c52016-11-23 05:48:40225
226 // Truncate the symbol name so that it doesn't include the version string.
Rui Ueyama3837f422019-07-10 05:00:37227 nameSize = pos;
Rui Ueyama35fa6c52016-11-23 05:48:40228
Fangrui Song7924b382021-12-27 01:25:54229 if (verstr.empty())
230 return;
231
Rafael Espindola1d6d1b42017-01-17 16:08:06232 // If this is not in this DSO, it is not a definition.
Peter Collingbourneb472aa02017-11-06 04:39:07233 if (!isDefined())
Rafael Espindola2756e042017-01-06 22:30:35234 return;
235
Rui Ueyama35fa6c52016-11-23 05:48:40236 // '@@' in a symbol name means the default version.
237 // It is usually the most recent one.
Rui Ueyama3837f422019-07-10 05:00:37238 bool isDefault = (verstr[0] == '@');
239 if (isDefault)
240 verstr = verstr.substr(1);
Rui Ueyama35fa6c52016-11-23 05:48:40241
Fangrui Songe28a70d2019-08-05 14:31:39242 for (const VersionDefinition &ver : namedVersionDefs()) {
Rui Ueyama3837f422019-07-10 05:00:37243 if (ver.name != verstr)
Rui Ueyama35fa6c52016-11-23 05:48:40244 continue;
245
Rui Ueyama3837f422019-07-10 05:00:37246 if (isDefault)
247 versionId = ver.id;
Rui Ueyama35fa6c52016-11-23 05:48:40248 else
Rui Ueyama3837f422019-07-10 05:00:37249 versionId = ver.id | VERSYM_HIDDEN;
Rui Ueyama35fa6c52016-11-23 05:48:40250 return;
251 }
252
253 // It is an error if the specified version is not defined.
George Rimar4d2f97622017-07-04 13:19:13254 // Usually version script is not provided when linking executable,
255 // but we may still want to override a versioned symbol from DSO,
Peter Smith796fb992018-05-14 10:13:56256 // so we do not report error in this case. We also do not error
257 // if the symbol has a local version as it won't be in the dynamic
258 // symbol table.
Rui Ueyama3837f422019-07-10 05:00:37259 if (config->shared && versionId != VER_NDX_LOCAL)
260 error(toString(file) + ": symbol " + s + " has undefined version " +
261 verstr);
Rui Ueyama35fa6c52016-11-23 05:48:40262}
263
Fangrui Song09401df2021-11-26 18:58:50264void Symbol::extract() const {
Fangrui Song3d854242022-02-15 17:38:00265 if (file->lazy) {
Fangrui Song3a5fb572021-12-23 01:41:50266 file->lazy = false;
267 parseFile(file);
268 }
Rui Ueyama7d476192019-05-16 02:14:00269}
Rui Ueyamaf8baa662016-04-07 19:24:51270
Rui Ueyamaf52496e2017-11-03 21:21:47271uint8_t Symbol::computeBinding() const {
Fangrui Song82ed93ea2022-09-05 00:27:35272 auto v = visibility();
273 if ((v != STV_DEFAULT && v != STV_PROTECTED) || versionId == VER_NDX_LOCAL)
Rafael Espindolab7e2ee22017-01-10 17:08:13274 return STB_LOCAL;
Fangrui Songb3cc4702022-01-16 07:40:43275 if (binding == STB_GNU_UNIQUE && !config->gnuUnique)
Rafael Espindolab7e2ee22017-01-10 17:08:13276 return STB_GLOBAL;
Rui Ueyama3837f422019-07-10 05:00:37277 return binding;
Rafael Espindolab7e2ee22017-01-10 17:08:13278}
279
Rui Ueyamaf52496e2017-11-03 21:21:47280bool Symbol::includeInDynsym() const {
Rafael Espindolab7e2ee22017-01-10 17:08:13281 if (computeBinding() == STB_LOCAL)
Rafael Espindolaae605c12016-04-21 20:35:25282 return false;
Fangrui Song375371c2020-01-09 23:53:52283 if (!isDefined() && !isCommon())
Fangrui Song0fbf28f2020-01-23 19:52:03284 // This should unconditionally return true, unfortunately glibc -static-pie
285 // expects undefined weak symbols not to exist in .dynsym, e.g.
286 // __pthread_mutex_lock reference in _dl_add_to_namespace_list,
287 // __pthread_initialize_minimal reference in csu/libc-start.c.
Fangrui Song01a51622022-01-16 07:32:48288 return !(isUndefWeak() && config->noDynamicLinker);
Rui Ueyamae63ae7f2019-06-25 06:58:07289
Fangrui Song375371c2020-01-09 23:53:52290 return exportDynamic || inDynamicList;
Rafael Espindolaae605c12016-04-21 20:35:25291}
Rui Ueyama69c778c2016-07-17 17:50:09292
293// Print out a log message for --trace-symbol.
Fangrui Song977a1a52022-02-06 00:34:02294void elf::printTraceSymbol(const Symbol &sym, StringRef name) {
Rui Ueyama3837f422019-07-10 05:00:37295 std::string s;
Fangrui Song977a1a52022-02-06 00:34:02296 if (sym.isUndefined())
Rui Ueyama3837f422019-07-10 05:00:37297 s = ": reference to ";
Fangrui Song977a1a52022-02-06 00:34:02298 else if (sym.isLazy())
Rui Ueyama3837f422019-07-10 05:00:37299 s = ": lazy definition of ";
Fangrui Song977a1a52022-02-06 00:34:02300 else if (sym.isShared())
Rui Ueyama3837f422019-07-10 05:00:37301 s = ": shared definition of ";
Fangrui Song977a1a52022-02-06 00:34:02302 else if (sym.isCommon())
Rui Ueyama3837f422019-07-10 05:00:37303 s = ": common definition of ";
Rui Ueyama69c778c2016-07-17 17:50:09304 else
Rui Ueyama3837f422019-07-10 05:00:37305 s = ": definition of ";
Rui Ueyamae6e206d2017-02-21 23:22:56306
Fangrui Song977a1a52022-02-06 00:34:02307 message(toString(sym.file) + s + name);
Rui Ueyama69c778c2016-07-17 17:50:09308}
309
Fangrui Songa954bb12021-09-20 16:52:30310static void recordWhyExtract(const InputFile *reference,
311 const InputFile &extracted, const Symbol &sym) {
Fangrui Song34fa8602022-10-01 19:06:33312 ctx.whyExtractRecords.emplace_back(toString(reference), &extracted, sym);
Fangrui Songa954bb12021-09-20 16:52:30313}
314
Fangrui Song07837b82020-05-15 05:18:58315void elf::maybeWarnUnorderableSymbol(const Symbol *sym) {
Rui Ueyama3837f422019-07-10 05:00:37316 if (!config->warnSymbolOrdering)
Michael J. Spencerb8427252018-04-17 23:30:05317 return;
Rui Ueyamab774c3c2018-04-26 01:38:29318
Fangrui Song1981b1b2023-10-17 21:10:52319 // If UnresolvedPolicy::Ignore is used, no "undefined symbol" error/warning is
320 // emitted. It makes sense to not warn on undefined symbols (excluding those
321 // demoted by demoteSymbols).
Fangrui Song11ca54f2018-10-10 22:48:57322 //
323 // Note, ld.bfd --symbol-ordering-file= does not warn on undefined symbols,
324 // but we don't have to be compatible here.
Fangrui Song1981b1b2023-10-17 21:10:52325 if (sym->isUndefined() && !cast<Undefined>(sym)->discardedSecIdx &&
Rui Ueyama3837f422019-07-10 05:00:37326 config->unresolvedSymbols == UnresolvedPolicy::Ignore)
Fangrui Song11ca54f2018-10-10 22:48:57327 return;
328
Rui Ueyama3837f422019-07-10 05:00:37329 const InputFile *file = sym->file;
330 auto *d = dyn_cast<Defined>(sym);
Rui Ueyamab774c3c2018-04-26 01:38:29331
Rui Ueyama3837f422019-07-10 05:00:37332 auto report = [&](StringRef s) { warn(toString(file) + s + sym->getName()); };
Rui Ueyamab774c3c2018-04-26 01:38:29333
Fangrui Song1981b1b2023-10-17 21:10:52334 if (sym->isUndefined()) {
335 if (cast<Undefined>(sym)->discardedSecIdx)
336 report(": unable to order discarded symbol: ");
337 else
338 report(": unable to order undefined symbol: ");
339 } else if (sym->isShared())
Rui Ueyama3837f422019-07-10 05:00:37340 report(": unable to order shared symbol: ");
341 else if (d && !d->section)
342 report(": unable to order absolute symbol: ");
343 else if (d && isa<OutputSection>(d->section))
344 report(": unable to order synthetic symbol: ");
Fangrui Songe1b6b5b2021-12-24 20:09:48345 else if (d && !d->section->isLive())
Rui Ueyama3837f422019-07-10 05:00:37346 report(": unable to order discarded symbol: ");
Michael J. Spencerb8427252018-04-17 23:30:05347}
348
Fangrui Songcd0ab242019-11-30 05:58:36349// Returns true if a symbol can be replaced at load-time by a symbol
350// with the same name defined in other ELF executable or DSO.
Fangrui Song07837b82020-05-15 05:18:58351bool elf::computeIsPreemptible(const Symbol &sym) {
Fangrui Songe9262ed2021-12-27 02:11:45352 assert(!sym.isLocal() || sym.isPlaceholder());
Fangrui Songcd0ab242019-11-30 05:58:36353
354 // Only symbols with default visibility that appear in dynsym can be
355 // preempted. Symbols with protected visibility cannot be preempted.
Fangrui Song82ed93ea2022-09-05 00:27:35356 if (!sym.includeInDynsym() || sym.visibility() != STV_DEFAULT)
Fangrui Songcd0ab242019-11-30 05:58:36357 return false;
358
359 // At this point copy relocations have not been created yet, so any
360 // symbol that is not defined locally is preemptible.
361 if (!sym.isDefined())
362 return true;
363
364 if (!config->shared)
365 return false;
366
Fangrui Song751f18e2020-06-01 18:27:53367 // If -Bsymbolic or --dynamic-list is specified, or -Bsymbolic-functions is
368 // specified and the symbol is STT_FUNC, the symbol is preemptible iff it is
Fangrui Songb06426d2021-07-29 21:46:53369 // in the dynamic list. -Bsymbolic-non-weak-functions is a non-weak subset of
370 // -Bsymbolic-functions.
371 if (config->symbolic ||
Shoaib Meenai97e39f92023-08-18 22:37:35372 (config->bsymbolic == BsymbolicKind::NonWeak &&
373 sym.binding != STB_WEAK) ||
Fangrui Songb06426d2021-07-29 21:46:53374 (config->bsymbolic == BsymbolicKind::Functions && sym.isFunc()) ||
375 (config->bsymbolic == BsymbolicKind::NonWeakFunctions && sym.isFunc() &&
376 sym.binding != STB_WEAK))
Fangrui Songcd0ab242019-11-30 05:58:36377 return sym.inDynamicList;
Fangrui Songcd0ab242019-11-30 05:58:36378 return true;
379}
380
Rui Ueyama7f7d2b22019-05-23 09:58:08381// Merge symbol properties.
382//
383// When we have many symbols of the same name, we choose one of them,
384// and that's the result of symbol resolution. However, symbols that
385// were not chosen still affect some symbol properties.
Rui Ueyama3837f422019-07-10 05:00:37386void Symbol::mergeProperties(const Symbol &other) {
387 if (other.exportDynamic)
388 exportDynamic = true;
Rui Ueyama7f7d2b22019-05-23 09:58:08389
390 // DSO symbols do not affect visibility in the output.
Fangrui Song82ed93ea2022-09-05 00:27:35391 if (!other.isShared() && other.visibility() != STV_DEFAULT) {
392 uint8_t v = visibility(), ov = other.visibility();
393 setVisibility(v == STV_DEFAULT ? ov : std::min(v, ov));
394 }
Rui Ueyama7f7d2b22019-05-23 09:58:08395}
396
Fangrui Song9e6840c2022-09-29 03:01:41397void Symbol::resolve(const Undefined &other) {
398 if (other.visibility() != STV_DEFAULT) {
399 uint8_t v = visibility(), ov = other.visibility();
400 setVisibility(v == STV_DEFAULT ? ov : std::min(v, ov));
Rui Ueyama7f7d2b22019-05-23 09:58:08401 }
Rui Ueyama7f7d2b22019-05-23 09:58:08402 // An undefined symbol with non default visibility must be satisfied
403 // in the same DSO.
404 //
405 // If this is a non-weak defined symbol in a discarded section, override the
406 // existing undefined symbol for better error message later.
Fangrui Songdf6803d2022-09-28 17:39:31407 if (isPlaceholder() || (isShared() && other.visibility() != STV_DEFAULT) ||
Rui Ueyama3837f422019-07-10 05:00:37408 (isUndefined() && other.binding != STB_WEAK && other.discardedSecIdx)) {
Fangrui Song7a58dd12022-09-28 20:11:31409 other.overwrite(*this);
Rui Ueyama7f7d2b22019-05-23 09:58:08410 return;
411 }
412
Rui Ueyama3837f422019-07-10 05:00:37413 if (traced)
Fangrui Song977a1a52022-02-06 00:34:02414 printTraceSymbol(other, getName());
Sam Clegg7991b682019-05-24 13:29:17415
Fangrui Songf3475412019-07-04 10:38:04416 if (isLazy()) {
Fangrui Song09401df2021-11-26 18:58:50417 // An undefined weak will not extract archive members. See comment on Lazy
418 // in Symbols.h for the details.
Rui Ueyama3837f422019-07-10 05:00:37419 if (other.binding == STB_WEAK) {
420 binding = STB_WEAK;
421 type = other.type;
Rui Ueyama7f7d2b22019-05-23 09:58:08422 return;
423 }
424
425 // Do extra check for --warn-backrefs.
426 //
427 // --warn-backrefs is an option to prevent an undefined reference from
Fangrui Song09401df2021-11-26 18:58:50428 // extracting an archive member written earlier in the command line. It can
429 // be used to keep compatibility with GNU linkers to some degree. I'll
430 // explain the feature and why you may find it useful in this comment.
Rui Ueyama7f7d2b22019-05-23 09:58:08431 //
432 // lld's symbol resolution semantics is more relaxed than traditional Unix
433 // linkers. For example,
434 //
435 // ld.lld foo.a bar.o
436 //
437 // succeeds even if bar.o contains an undefined symbol that has to be
438 // resolved by some object file in foo.a. Traditional Unix linkers don't
439 // allow this kind of backward reference, as they visit each file only once
440 // from left to right in the command line while resolving all undefined
441 // symbols at the moment of visiting.
442 //
443 // In the above case, since there's no undefined symbol when a linker visits
444 // foo.a, no files are pulled out from foo.a, and because the linker forgets
445 // about foo.a after visiting, it can't resolve undefined symbols in bar.o
446 // that could have been resolved otherwise.
447 //
448 // That lld accepts more relaxed form means that (besides it'd make more
449 // sense) you can accidentally write a command line or a build file that
450 // works only with lld, even if you have a plan to distribute it to wider
451 // users who may be using GNU linkers. With --warn-backrefs, you can detect
452 // a library order that doesn't work with other Unix linkers.
453 //
454 // The option is also useful to detect cyclic dependencies between static
455 // archives. Again, lld accepts
456 //
457 // ld.lld foo.a bar.a
458 //
459 // even if foo.a and bar.a depend on each other. With --warn-backrefs, it is
460 // handled as an error.
461 //
462 // Here is how the option works. We assign a group ID to each file. A file
463 // with a smaller group ID can pull out object files from an archive file
464 // with an equal or greater group ID. Otherwise, it is a reverse dependency
465 // and an error.
466 //
467 // A file outside --{start,end}-group gets a fresh ID when instantiated. All
468 // files within the same --{start,end}-group get the same group ID. E.g.
469 //
470 // ld.lld A B --start-group C D --end-group E
471 //
472 // A forms group 0. B form group 1. C and D (including their member object
473 // files) form group 2. E forms group 3. I think that you can see how this
474 // group assignment rule simulates the traditional linker's semantics.
Rui Ueyama3837f422019-07-10 05:00:37475 bool backref = config->warnBackrefs && other.file &&
476 file->groupId < other.file->groupId;
Fangrui Song09401df2021-11-26 18:58:50477 extract();
Rui Ueyama7f7d2b22019-05-23 09:58:08478
Fangrui Songa954bb12021-09-20 16:52:30479 if (!config->whyExtract.empty())
480 recordWhyExtract(other.file, *file, *this);
481
Rui Ueyama7f7d2b22019-05-23 09:58:08482 // We don't report backward references to weak symbols as they can be
483 // overridden later.
Fangrui Song03c825c2020-04-06 05:27:46484 //
485 // A traditional linker does not error for -ldef1 -lref -ldef2 (linking
486 // sandwich), where def2 may or may not be the same as def1. We don't want
487 // to warn for this case, so dismiss the warning if we see a subsequent lazy
Fangrui Songce3c5da2020-10-22 22:26:52488 // definition. this->file needs to be saved because in the case of LTO it
489 // may be reset to nullptr or be replaced with a file named lto.tmp.
Rui Ueyama3837f422019-07-10 05:00:37490 if (backref && !isWeak())
Fangrui Song34fa8602022-10-01 19:06:33491 ctx.backwardReferences.try_emplace(this,
492 std::make_pair(other.file, file));
Fangrui Songf3475412019-07-04 10:38:04493 return;
494 }
495
496 // Undefined symbols in a SharedFile do not change the binding.
Kazu Hirata62e48ed2021-12-25 05:22:27497 if (isa_and_nonnull<SharedFile>(other.file))
Fangrui Songf3475412019-07-04 10:38:04498 return;
499
Fangrui Songe49c4172019-08-06 14:03:45500 if (isUndefined() || isShared()) {
501 // The binding will be weak if there is at least one reference and all are
502 // weak. The binding has one opportunity to change to weak: if the first
503 // reference is weak.
504 if (other.binding != STB_WEAK || !referenced)
Rui Ueyama3837f422019-07-10 05:00:37505 binding = other.binding;
Rui Ueyama7f7d2b22019-05-23 09:58:08506 }
507}
508
Fangrui Song19e37a72022-02-24 22:09:00509// Compare two symbols. Return true if the new symbol should win.
Fangrui Songb07ef4d2022-02-28 18:25:21510bool Symbol::shouldReplace(const Defined &other) const {
Fangrui Song6d943402022-02-24 22:08:06511 if (LLVM_UNLIKELY(isCommon())) {
512 if (config->warnCommon)
513 warn("common " + getName() + " is overridden");
514 return !other.isWeak();
515 }
516 if (!isDefined())
517 return true;
Rui Ueyama7f7d2b22019-05-23 09:58:08518
Fangrui Songc7cf9602022-03-14 19:00:15519 // Incoming STB_GLOBAL overrides STB_WEAK/STB_GNU_UNIQUE. -fgnu-unique changes
520 // some vague linkage data in COMDAT from STB_WEAK to STB_GNU_UNIQUE. Treat
521 // STB_GNU_UNIQUE like STB_WEAK so that we prefer the first among all
522 // STB_WEAK/STB_GNU_UNIQUE copies. If we prefer an incoming STB_GNU_UNIQUE to
523 // an existing STB_WEAK, there may be discarded section errors because the
524 // selected copy may be in a non-prevailing COMDAT.
525 return !isGlobal() && other.isGlobal();
Rui Ueyama7f7d2b22019-05-23 09:58:08526}
527
Fangrui Song7c7702b2022-03-16 02:24:41528void elf::reportDuplicate(const Symbol &sym, const InputFile *newFile,
Fangrui Song88d66f62022-02-22 18:07:58529 InputSectionBase *errSec, uint64_t errOffset) {
Rui Ueyama3837f422019-07-10 05:00:37530 if (config->allowMultipleDefinition)
Rui Ueyama7f7d2b22019-05-23 09:58:08531 return;
Fangrui Song7c7702b2022-03-16 02:24:41532 // In glibc<2.32, crti.o has .gnu.linkonce.t.__x86.get_pc_thunk.bx, which
533 // is sort of proto-comdat. There is actually no duplicate if we have
534 // full support for .gnu.linkonce.
535 const Defined *d = dyn_cast<Defined>(&sym);
536 if (!d || d->getName() == "__x86.get_pc_thunk.bx")
537 return;
538 // Allow absolute symbols with the same value for GNU ld compatibility.
539 if (!d->section && !errSec && errOffset && d->value == errOffset)
540 return;
Rui Ueyama3837f422019-07-10 05:00:37541 if (!d->section || !errSec) {
Fangrui Songacdba092024-03-27 21:08:59542 errorOrWarn("duplicate symbol: " + toString(sym) + "\n>>> defined in " +
543 toString(sym.file) + "\n>>> defined in " + toString(newFile));
Rui Ueyama7f7d2b22019-05-23 09:58:08544 return;
545 }
546
547 // Construct and print an error message in the form of:
548 //
549 // ld.lld: error: duplicate symbol: foo
550 // >>> defined at bar.c:30
551 // >>> bar.o (/home/alice/src/bar.o)
552 // >>> defined at baz.c:563
553 // >>> baz.o in archive libbaz.a
Rui Ueyama3837f422019-07-10 05:00:37554 auto *sec1 = cast<InputSectionBase>(d->section);
Fangrui Song467e1b32022-02-15 19:18:31555 std::string src1 = sec1->getSrcMsg(sym, d->value);
Rui Ueyama3837f422019-07-10 05:00:37556 std::string obj1 = sec1->getObjMsg(d->value);
Fangrui Song467e1b32022-02-15 19:18:31557 std::string src2 = errSec->getSrcMsg(sym, errOffset);
Rui Ueyama3837f422019-07-10 05:00:37558 std::string obj2 = errSec->getObjMsg(errOffset);
Rui Ueyama7f7d2b22019-05-23 09:58:08559
Fangrui Song467e1b32022-02-15 19:18:31560 std::string msg = "duplicate symbol: " + toString(sym) + "\n>>> defined at ";
Rui Ueyama3837f422019-07-10 05:00:37561 if (!src1.empty())
562 msg += src1 + "\n>>> ";
563 msg += obj1 + "\n>>> defined at ";
564 if (!src2.empty())
565 msg += src2 + "\n>>> ";
566 msg += obj2;
Fangrui Songacdba092024-03-27 21:08:59567 errorOrWarn(msg);
Rui Ueyama7f7d2b22019-05-23 09:58:08568}
569
Fangrui Song88d66f62022-02-22 18:07:58570void Symbol::checkDuplicate(const Defined &other) const {
Fangrui Song6d943402022-02-24 22:08:06571 if (isDefined() && !isWeak() && !other.isWeak())
Fangrui Song88d66f62022-02-22 18:07:58572 reportDuplicate(*this, other.file,
573 dyn_cast_or_null<InputSectionBase>(other.section),
574 other.value);
575}
576
Fangrui Song9e6840c2022-09-29 03:01:41577void Symbol::resolve(const CommonSymbol &other) {
578 if (other.exportDynamic)
579 exportDynamic = true;
580 if (other.visibility() != STV_DEFAULT) {
581 uint8_t v = visibility(), ov = other.visibility();
582 setVisibility(v == STV_DEFAULT ? ov : std::min(v, ov));
583 }
Fangrui Song6d943402022-02-24 22:08:06584 if (isDefined() && !isWeak()) {
585 if (config->warnCommon)
586 warn("common " + getName() + " is overridden");
Rui Ueyama7f7d2b22019-05-23 09:58:08587 return;
Fangrui Song6d943402022-02-24 22:08:06588 }
Rui Ueyama7f7d2b22019-05-23 09:58:08589
Fangrui Song6d943402022-02-24 22:08:06590 if (CommonSymbol *oldSym = dyn_cast<CommonSymbol>(this)) {
591 if (config->warnCommon)
592 warn("multiple common of " + getName());
593 oldSym->alignment = std::max(oldSym->alignment, other.alignment);
594 if (oldSym->size < other.size) {
595 oldSym->file = other.file;
596 oldSym->size = other.size;
Fangrui Song69d10d22019-12-07 05:18:31597 }
Rui Ueyama7f7d2b22019-05-23 09:58:08598 return;
599 }
600
Fangrui Song6d943402022-02-24 22:08:06601 if (auto *s = dyn_cast<SharedSymbol>(this)) {
602 // Increase st_size if the shared symbol has a larger st_size. The shared
603 // symbol may be created from common symbols. The fact that some object
604 // files were linked into a shared object first should not change the
605 // regular rule that picks the largest st_size.
606 uint64_t size = s->size;
Fangrui Song7a58dd12022-09-28 20:11:31607 other.overwrite(*this);
Fangrui Song6d943402022-02-24 22:08:06608 if (size > cast<CommonSymbol>(this)->size)
609 cast<CommonSymbol>(this)->size = size;
610 } else {
Fangrui Song7a58dd12022-09-28 20:11:31611 other.overwrite(*this);
Rui Ueyama7f7d2b22019-05-23 09:58:08612 }
613}
614
Fangrui Song9e6840c2022-09-29 03:01:41615void Symbol::resolve(const Defined &other) {
616 if (other.exportDynamic)
617 exportDynamic = true;
618 if (other.visibility() != STV_DEFAULT) {
619 uint8_t v = visibility(), ov = other.visibility();
620 setVisibility(v == STV_DEFAULT ? ov : std::min(v, ov));
621 }
Fangrui Songb07ef4d2022-02-28 18:25:21622 if (shouldReplace(other))
Fangrui Song7a58dd12022-09-28 20:11:31623 other.overwrite(*this);
Rui Ueyama7f7d2b22019-05-23 09:58:08624}
625
Fangrui Song7071a252024-01-20 00:15:52626void Symbol::resolve(const LazySymbol &other) {
Fangrui Songdf6803d2022-09-28 17:39:31627 if (isPlaceholder()) {
Fangrui Song7a58dd12022-09-28 20:11:31628 other.overwrite(*this);
Fangrui Songdf6803d2022-09-28 17:39:31629 return;
630 }
631
Sean Fertile8f91f382020-12-07 14:28:17632 // For common objects, we want to look for global or weak definitions that
Fangrui Song09401df2021-11-26 18:58:50633 // should be extracted as the canonical definition instead.
Fangrui Song15617cd2022-02-24 20:21:40634 if (LLVM_UNLIKELY(isCommon()) && elf::config->fortranCommon &&
635 other.file->shouldExtractForCommon(getName())) {
Fangrui Song34fa8602022-10-01 19:06:33636 ctx.backwardReferences.erase(this);
Fangrui Song7a58dd12022-09-28 20:11:31637 other.overwrite(*this);
Fangrui Song15617cd2022-02-24 20:21:40638 other.extract();
639 return;
Sean Fertile8f91f382020-12-07 14:28:17640 }
641
Fangrui Song03c825c2020-04-06 05:27:46642 if (!isUndefined()) {
643 // See the comment in resolveUndefined().
644 if (isDefined())
Fangrui Song34fa8602022-10-01 19:06:33645 ctx.backwardReferences.erase(this);
Rui Ueyama7f7d2b22019-05-23 09:58:08646 return;
Fangrui Song03c825c2020-04-06 05:27:46647 }
Rui Ueyama7f7d2b22019-05-23 09:58:08648
Fangrui Song09401df2021-11-26 18:58:50649 // An undefined weak will not extract archive members. See comment on Lazy in
Rui Ueyama7f7d2b22019-05-23 09:58:08650 // Symbols.h for the details.
651 if (isWeak()) {
Rui Ueyama3837f422019-07-10 05:00:37652 uint8_t ty = type;
Fangrui Song7a58dd12022-09-28 20:11:31653 other.overwrite(*this);
Rui Ueyama3837f422019-07-10 05:00:37654 type = ty;
655 binding = STB_WEAK;
Rui Ueyama7f7d2b22019-05-23 09:58:08656 return;
657 }
658
Fangrui Songa954bb12021-09-20 16:52:30659 const InputFile *oldFile = file;
Fangrui Song09401df2021-11-26 18:58:50660 other.extract();
Fangrui Songa954bb12021-09-20 16:52:30661 if (!config->whyExtract.empty())
662 recordWhyExtract(oldFile, *file, *this);
Rui Ueyama7f7d2b22019-05-23 09:58:08663}
664
Fangrui Song9e6840c2022-09-29 03:01:41665void Symbol::resolve(const SharedSymbol &other) {
666 exportDynamic = true;
Fangrui Songdf6803d2022-09-28 17:39:31667 if (isPlaceholder()) {
Fangrui Song7a58dd12022-09-28 20:11:31668 other.overwrite(*this);
Fangrui Songdf6803d2022-09-28 17:39:31669 return;
670 }
Fangrui Song69d10d22019-12-07 05:18:31671 if (isCommon()) {
672 // See the comment in resolveCommon() above.
673 if (other.size > cast<CommonSymbol>(this)->size)
674 cast<CommonSymbol>(this)->size = other.size;
675 return;
676 }
Fangrui Song82ed93ea2022-09-05 00:27:35677 if (visibility() == STV_DEFAULT && (isUndefined() || isLazy())) {
Rui Ueyama7f7d2b22019-05-23 09:58:08678 // An undefined symbol with non default visibility must be satisfied
679 // in the same DSO.
Rui Ueyama3837f422019-07-10 05:00:37680 uint8_t bind = binding;
Fangrui Song7a58dd12022-09-28 20:11:31681 other.overwrite(*this);
Rui Ueyama3837f422019-07-10 05:00:37682 binding = bind;
Fangrui Song64676492020-05-18 17:15:59683 } else if (traced)
Fangrui Song977a1a52022-02-06 00:34:02684 printTraceSymbol(other, getName());
Rui Ueyama7f7d2b22019-05-23 09:58:08685}
Fangrui Song255ea482023-11-16 09:03:52686
687void Defined::overwrite(Symbol &sym) const {
688 if (isa_and_nonnull<SharedFile>(sym.file))
689 sym.versionId = VER_NDX_GLOBAL;
690 Symbol::overwrite(sym, DefinedKind);
691 auto &s = static_cast<Defined &>(sym);
692 s.value = value;
693 s.size = size;
694 s.section = section;
695}