blob: 90ce5048ea720767a8b6e347d24bd87430375160 [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"
Rui Ueyama53fe4692017-11-28 02:15:2618#include "lld/Common/Strings.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
Fangrui Song07837b82020-05-15 05:18:5846std::string lld::toString(const elf::Symbol &sym) {
Fangrui Songf2036a12020-03-28 22:48:3847 StringRef name = sym.getName();
Luís Ferreira10e40a42022-01-05 03:05:1048 std::string ret = demangle(name, config->demangle);
Fangrui Songf2036a12020-03-28 22:48:3849
Fangrui Song941e9332020-12-01 16:54:0150 const char *suffix = sym.getVersionSuffix();
51 if (*suffix == '@')
52 ret += suffix;
Fangrui Songf2036a12020-03-28 22:48:3853 return ret;
54}
55
Rui Ueyama3837f422019-07-10 05:00:3756Defined *ElfSym::bss;
57Defined *ElfSym::etext1;
58Defined *ElfSym::etext2;
59Defined *ElfSym::edata1;
60Defined *ElfSym::edata2;
61Defined *ElfSym::end1;
62Defined *ElfSym::end2;
63Defined *ElfSym::globalOffsetTable;
64Defined *ElfSym::mipsGp;
65Defined *ElfSym::mipsGpDisp;
66Defined *ElfSym::mipsLocalGp;
67Defined *ElfSym::relaIpltStart;
68Defined *ElfSym::relaIpltEnd;
69Defined *ElfSym::riscvGlobalPointer;
70Defined *ElfSym::tlsModuleBase;
Fangrui Song5d3bd7f2022-01-09 21:43:2671SmallVector<SymbolAux, 0> elf::symAux;
Rui Ueyama80474a22017-02-28 19:29:5572
Fangrui Songa8024df2021-12-13 03:12:0173static uint64_t getSymVA(const Symbol &sym, int64_t addend) {
Rui Ueyama3837f422019-07-10 05:00:3774 switch (sym.kind()) {
Peter Collingbournee9a9e0a2017-11-06 04:35:3175 case Symbol::DefinedKind: {
Rui Ueyama3837f422019-07-10 05:00:3776 auto &d = cast<Defined>(sym);
77 SectionBase *isec = d.section;
Rui Ueyamab5a69702016-02-01 21:00:3578
79 // This is an absolute symbol.
Rui Ueyama3837f422019-07-10 05:00:3780 if (!isec)
81 return d.value;
Rui Ueyamab5a69702016-02-01 21:00:3582
Rui Ueyama3837f422019-07-10 05:00:3783 assert(isec != &InputSection::discarded);
Rafael Espindolaf4d6e8c2018-04-19 17:26:5084
Rui Ueyama3837f422019-07-10 05:00:3785 uint64_t offset = d.value;
Sean Silvaa9ba4502017-02-28 08:32:5686
87 // An object in an SHF_MERGE section might be referenced via a
88 // section symbol (as a hack for reducing the number of local
89 // symbols).
Sean Silvad4e60622017-03-01 04:44:0490 // Depending on the addend, the reference via a section symbol
91 // refers to a different object in the merge section.
92 // Since the objects in the merge section are not necessarily
93 // contiguous in the output, the addend can thus affect the final
94 // VA in a non-linear way.
95 // To make this work, we incorporate the addend into the section
96 // offset (and zero out the addend for later processing) so that
97 // we find the right object in the section.
Fangrui Songa8024df2021-12-13 03:12:0198 if (d.isSection())
Rui Ueyama3837f422019-07-10 05:00:3799 offset += addend;
Sean Silvaa9ba4502017-02-28 08:32:56100
Sean Silva6ab39262017-02-28 09:01:58101 // In the typical case, this is actually very simple and boils
102 // down to adding together 3 numbers:
103 // 1. The address of the output section.
104 // 2. The offset of the input section within the output section.
105 // 3. The offset within the input section (this addition happens
106 // inside InputSection::getOffset).
107 //
108 // If you understand the data structures involved with this next
109 // line (and how they get built), then you have a pretty good
110 // understanding of the linker.
Rui Ueyama3837f422019-07-10 05:00:37111 uint64_t va = isec->getVA(offset);
Fangrui Songa8024df2021-12-13 03:12:01112 if (d.isSection())
113 va -= addend;
Sean Silva6ab39262017-02-28 09:01:58114
Simon Atanasyanfae2a5092019-02-19 10:36:58115 // MIPS relocatable files can mix regular and microMIPS code.
116 // Linker needs to distinguish such code. To do so microMIPS
117 // symbols has the `STO_MIPS_MICROMIPS` flag in the `st_other`
Fangrui Songdeb58192020-01-23 05:39:16118 // field. Unfortunately, the `MIPS::relocate()` method has
Simon Atanasyanfae2a5092019-02-19 10:36:58119 // a symbol value only. To pass type of the symbol (regular/microMIPS)
120 // to that routine as well as other places where we write
121 // a symbol value as-is (.dynamic section, `Elf_Ehdr::e_entry`
122 // field etc) do the same trick as compiler uses to mark microMIPS
123 // for CPU - set the less-significant bit.
Rui Ueyama3837f422019-07-10 05:00:37124 if (config->emachine == EM_MIPS && isMicroMips() &&
Fangrui Songbd16ffb32022-09-09 21:37:18125 ((sym.stOther & STO_MIPS_MICROMIPS) || sym.hasFlag(NEEDS_COPY)))
Rui Ueyama3837f422019-07-10 05:00:37126 va |= 1;
Simon Atanasyanfae2a5092019-02-19 10:36:58127
Rui Ueyama3837f422019-07-10 05:00:37128 if (d.isTls() && !config->relocatable) {
Ryan Prichard1c33d142018-09-18 00:24:48129 // Use the address of the TLS segment's first section rather than the
130 // segment's address, because segment addresses aren't initialized until
131 // after sections are finalized. (e.g. Measuring the size of .rela.dyn
132 // for Android relocation packing requires knowing TLS symbol addresses
133 // during section finalization.)
Rui Ueyama3837f422019-07-10 05:00:37134 if (!Out::tlsPhdr || !Out::tlsPhdr->firstSec)
135 fatal(toString(d.file) +
Peter Collingbourne3e2abde2017-07-14 00:22:46136 " has an STT_TLS symbol but doesn't have an SHF_TLS section");
Rui Ueyama3837f422019-07-10 05:00:37137 return va - Out::tlsPhdr->firstSec->addr;
George Rimar6a3b1542016-10-04 08:52:51138 }
Rui Ueyama3837f422019-07-10 05:00:37139 return va;
Rui Ueyamab5a69702016-02-01 21:00:35140 }
Rafael Espindolaab0cce52018-04-26 17:58:58141 case Symbol::SharedKind:
Rui Ueyamaf52496e2017-11-03 21:21:47142 case Symbol::UndefinedKind:
Rui Ueyamab5a69702016-02-01 21:00:35143 return 0;
Rui Ueyamaf52496e2017-11-03 21:21:47144 case Symbol::LazyObjectKind:
Fangrui Song935229f2022-01-05 08:46:48145 llvm_unreachable("lazy symbol reached writer");
Rui Ueyama5c073a92019-05-16 03:29:03146 case Symbol::CommonKind:
147 llvm_unreachable("common symbol reached writer");
Rui Ueyamaf3fad552018-10-12 18:29:18148 case Symbol::PlaceholderKind:
149 llvm_unreachable("placeholder symbol reached writer");
Rui Ueyamab5a69702016-02-01 21:00:35150 }
George Rimar777f9632016-03-12 08:31:34151 llvm_unreachable("invalid symbol kind");
Rui Ueyamab5a69702016-02-01 21:00:35152}
153
Rui Ueyama3837f422019-07-10 05:00:37154uint64_t Symbol::getVA(int64_t addend) const {
Fangrui Songa8024df2021-12-13 03:12:01155 return getSymVA(*this, addend) + addend;
Rafael Espindola87d9f102016-03-11 12:19:05156}
157
Peter Collingbourne8331f612019-02-13 21:49:55158uint64_t Symbol::getGotVA() const {
Rui Ueyama3837f422019-07-10 05:00:37159 if (gotInIgot)
160 return in.igotPlt->getVA() + getGotPltOffset();
161 return in.got->getVA() + getGotOffset();
Peter Collingbourne8331f612019-02-13 21:49:55162}
Rafael Espindola74031ba2016-04-07 15:20:56163
Harald van Dijkd6241342021-05-16 23:13:00164uint64_t Symbol::getGotOffset() const {
Fangrui Song5d3bd7f2022-01-09 21:43:26165 return getGotIdx() * target->gotEntrySize;
Harald van Dijkd6241342021-05-16 23:13:00166}
Rui Ueyamab5a69702016-02-01 21:00:35167
Rui Ueyamaf52496e2017-11-03 21:21:47168uint64_t Symbol::getGotPltVA() const {
Rui Ueyama3837f422019-07-10 05:00:37169 if (isInIplt)
170 return in.igotPlt->getVA() + getGotPltOffset();
171 return in.gotPlt->getVA() + getGotPltOffset();
Rafael Espindola74031ba2016-04-07 15:20:56172}
173
Rui Ueyamaf52496e2017-11-03 21:21:47174uint64_t Symbol::getGotPltOffset() const {
Rui Ueyama3837f422019-07-10 05:00:37175 if (isInIplt)
Fangrui Song5d3bd7f2022-01-09 21:43:26176 return getPltIdx() * target->gotEntrySize;
177 return (getPltIdx() + target->gotPltHeaderEntriesNum) * target->gotEntrySize;
Rui Ueyamab5a69702016-02-01 21:00:35178}
179
Rui Ueyamaf52496e2017-11-03 21:21:47180uint64_t Symbol::getPltVA() const {
Fangrui Song891a8652019-12-14 22:17:35181 uint64_t outVA = isInIplt
Fangrui Song5d3bd7f2022-01-09 21:43:26182 ? in.iplt->getVA() + getPltIdx() * target->ipltEntrySize
Fangrui Song891a8652019-12-14 22:17:35183 : in.plt->getVA() + in.plt->headerSize +
Fangrui Song5d3bd7f2022-01-09 21:43:26184 getPltIdx() * target->pltEntrySize;
Fangrui Song891a8652019-12-14 22:17:35185
Simon Atanasyanfae2a5092019-02-19 10:36:58186 // While linking microMIPS code PLT code are always microMIPS
187 // code. Set the less-significant bit to track that fact.
188 // See detailed comment in the `getSymVA` function.
Rui Ueyama3837f422019-07-10 05:00:37189 if (config->emachine == EM_MIPS && isMicroMips())
190 outVA |= 1;
191 return outVA;
Rafael Espindolaab0cce52018-04-26 17:58:58192}
193
Rui Ueyamaf52496e2017-11-03 21:21:47194uint64_t Symbol::getSize() const {
Rui Ueyama3837f422019-07-10 05:00:37195 if (const auto *dr = dyn_cast<Defined>(this))
196 return dr->size;
197 return cast<SharedSymbol>(this)->size;
Rui Ueyama512c61d2016-02-03 00:12:24198}
199
Rui Ueyamaf52496e2017-11-03 21:21:47200OutputSection *Symbol::getOutputSection() const {
Rui Ueyama3837f422019-07-10 05:00:37201 if (auto *s = dyn_cast<Defined>(this)) {
202 if (auto *sec = s->section)
Fangrui Songc2f2bb02021-12-21 08:39:16203 return sec->getOutputSection();
Rui Ueyama968db482017-02-28 04:02:42204 return nullptr;
205 }
Rui Ueyama968db482017-02-28 04:02:42206 return nullptr;
207}
208
Rui Ueyama35fa6c52016-11-23 05:48:40209// If a symbol name contains '@', the characters after that is
210// a symbol version name. This function parses that.
Rui Ueyamaf52496e2017-11-03 21:21:47211void Symbol::parseSymbolVersion() {
Fangrui Song00809c82021-08-05 06:52:55212 // Return if localized by a local: pattern in a version script.
213 if (versionId == VER_NDX_LOCAL)
214 return;
Rui Ueyama3837f422019-07-10 05:00:37215 StringRef s = getName();
216 size_t pos = s.find('@');
Fangrui Song101407b2021-12-16 07:59:55217 if (pos == StringRef::npos)
Rui Ueyama35fa6c52016-11-23 05:48:40218 return;
Rui Ueyama3837f422019-07-10 05:00:37219 StringRef verstr = s.substr(pos + 1);
Rui Ueyama35fa6c52016-11-23 05:48:40220
221 // Truncate the symbol name so that it doesn't include the version string.
Rui Ueyama3837f422019-07-10 05:00:37222 nameSize = pos;
Rui Ueyama35fa6c52016-11-23 05:48:40223
Fangrui Song7924b382021-12-27 01:25:54224 if (verstr.empty())
225 return;
226
Rafael Espindola1d6d1b42017-01-17 16:08:06227 // If this is not in this DSO, it is not a definition.
Peter Collingbourneb472aa02017-11-06 04:39:07228 if (!isDefined())
Rafael Espindola2756e042017-01-06 22:30:35229 return;
230
Rui Ueyama35fa6c52016-11-23 05:48:40231 // '@@' in a symbol name means the default version.
232 // It is usually the most recent one.
Rui Ueyama3837f422019-07-10 05:00:37233 bool isDefault = (verstr[0] == '@');
234 if (isDefault)
235 verstr = verstr.substr(1);
Rui Ueyama35fa6c52016-11-23 05:48:40236
Fangrui Songe28a70d2019-08-05 14:31:39237 for (const VersionDefinition &ver : namedVersionDefs()) {
Rui Ueyama3837f422019-07-10 05:00:37238 if (ver.name != verstr)
Rui Ueyama35fa6c52016-11-23 05:48:40239 continue;
240
Rui Ueyama3837f422019-07-10 05:00:37241 if (isDefault)
242 versionId = ver.id;
Rui Ueyama35fa6c52016-11-23 05:48:40243 else
Rui Ueyama3837f422019-07-10 05:00:37244 versionId = ver.id | VERSYM_HIDDEN;
Rui Ueyama35fa6c52016-11-23 05:48:40245 return;
246 }
247
248 // It is an error if the specified version is not defined.
George Rimar4d2f97622017-07-04 13:19:13249 // Usually version script is not provided when linking executable,
250 // but we may still want to override a versioned symbol from DSO,
Peter Smith796fb992018-05-14 10:13:56251 // so we do not report error in this case. We also do not error
252 // if the symbol has a local version as it won't be in the dynamic
253 // symbol table.
Rui Ueyama3837f422019-07-10 05:00:37254 if (config->shared && versionId != VER_NDX_LOCAL)
255 error(toString(file) + ": symbol " + s + " has undefined version " +
256 verstr);
Rui Ueyama35fa6c52016-11-23 05:48:40257}
258
Fangrui Song09401df2021-11-26 18:58:50259void Symbol::extract() const {
Fangrui Song3d854242022-02-15 17:38:00260 if (file->lazy) {
Fangrui Song3a5fb572021-12-23 01:41:50261 file->lazy = false;
262 parseFile(file);
263 }
Rui Ueyama7d476192019-05-16 02:14:00264}
Rui Ueyamaf8baa662016-04-07 19:24:51265
Rui Ueyamaf52496e2017-11-03 21:21:47266uint8_t Symbol::computeBinding() const {
Fangrui Song82ed93ea2022-09-05 00:27:35267 auto v = visibility();
268 if ((v != STV_DEFAULT && v != STV_PROTECTED) || versionId == VER_NDX_LOCAL)
Rafael Espindolab7e2ee22017-01-10 17:08:13269 return STB_LOCAL;
Fangrui Songb3cc4702022-01-16 07:40:43270 if (binding == STB_GNU_UNIQUE && !config->gnuUnique)
Rafael Espindolab7e2ee22017-01-10 17:08:13271 return STB_GLOBAL;
Rui Ueyama3837f422019-07-10 05:00:37272 return binding;
Rafael Espindolab7e2ee22017-01-10 17:08:13273}
274
Rui Ueyamaf52496e2017-11-03 21:21:47275bool Symbol::includeInDynsym() const {
Rafael Espindolab7e2ee22017-01-10 17:08:13276 if (computeBinding() == STB_LOCAL)
Rafael Espindolaae605c12016-04-21 20:35:25277 return false;
Fangrui Song375371c2020-01-09 23:53:52278 if (!isDefined() && !isCommon())
Fangrui Song0fbf28f2020-01-23 19:52:03279 // This should unconditionally return true, unfortunately glibc -static-pie
280 // expects undefined weak symbols not to exist in .dynsym, e.g.
281 // __pthread_mutex_lock reference in _dl_add_to_namespace_list,
282 // __pthread_initialize_minimal reference in csu/libc-start.c.
Fangrui Song01a51622022-01-16 07:32:48283 return !(isUndefWeak() && config->noDynamicLinker);
Rui Ueyamae63ae7f2019-06-25 06:58:07284
Fangrui Song375371c2020-01-09 23:53:52285 return exportDynamic || inDynamicList;
Rafael Espindolaae605c12016-04-21 20:35:25286}
Rui Ueyama69c778c2016-07-17 17:50:09287
288// Print out a log message for --trace-symbol.
Fangrui Song977a1a52022-02-06 00:34:02289void elf::printTraceSymbol(const Symbol &sym, StringRef name) {
Rui Ueyama3837f422019-07-10 05:00:37290 std::string s;
Fangrui Song977a1a52022-02-06 00:34:02291 if (sym.isUndefined())
Rui Ueyama3837f422019-07-10 05:00:37292 s = ": reference to ";
Fangrui Song977a1a52022-02-06 00:34:02293 else if (sym.isLazy())
Rui Ueyama3837f422019-07-10 05:00:37294 s = ": lazy definition of ";
Fangrui Song977a1a52022-02-06 00:34:02295 else if (sym.isShared())
Rui Ueyama3837f422019-07-10 05:00:37296 s = ": shared definition of ";
Fangrui Song977a1a52022-02-06 00:34:02297 else if (sym.isCommon())
Rui Ueyama3837f422019-07-10 05:00:37298 s = ": common definition of ";
Rui Ueyama69c778c2016-07-17 17:50:09299 else
Rui Ueyama3837f422019-07-10 05:00:37300 s = ": definition of ";
Rui Ueyamae6e206d2017-02-21 23:22:56301
Fangrui Song977a1a52022-02-06 00:34:02302 message(toString(sym.file) + s + name);
Rui Ueyama69c778c2016-07-17 17:50:09303}
304
Fangrui Songa954bb12021-09-20 16:52:30305static void recordWhyExtract(const InputFile *reference,
306 const InputFile &extracted, const Symbol &sym) {
Fangrui Songe980f162022-06-30 00:34:30307 ctx->whyExtractRecords.emplace_back(toString(reference), &extracted, sym);
Fangrui Songa954bb12021-09-20 16:52:30308}
309
Fangrui Song07837b82020-05-15 05:18:58310void elf::maybeWarnUnorderableSymbol(const Symbol *sym) {
Rui Ueyama3837f422019-07-10 05:00:37311 if (!config->warnSymbolOrdering)
Michael J. Spencerb8427252018-04-17 23:30:05312 return;
Rui Ueyamab774c3c2018-04-26 01:38:29313
Fangrui Song11ca54f2018-10-10 22:48:57314 // If UnresolvedPolicy::Ignore is used, no "undefined symbol" error/warning
315 // is emitted. It makes sense to not warn on undefined symbols.
316 //
317 // Note, ld.bfd --symbol-ordering-file= does not warn on undefined symbols,
318 // but we don't have to be compatible here.
Rui Ueyama3837f422019-07-10 05:00:37319 if (sym->isUndefined() &&
320 config->unresolvedSymbols == UnresolvedPolicy::Ignore)
Fangrui Song11ca54f2018-10-10 22:48:57321 return;
322
Rui Ueyama3837f422019-07-10 05:00:37323 const InputFile *file = sym->file;
324 auto *d = dyn_cast<Defined>(sym);
Rui Ueyamab774c3c2018-04-26 01:38:29325
Rui Ueyama3837f422019-07-10 05:00:37326 auto report = [&](StringRef s) { warn(toString(file) + s + sym->getName()); };
Rui Ueyamab774c3c2018-04-26 01:38:29327
Rui Ueyama3837f422019-07-10 05:00:37328 if (sym->isUndefined())
329 report(": unable to order undefined symbol: ");
330 else if (sym->isShared())
331 report(": unable to order shared symbol: ");
332 else if (d && !d->section)
333 report(": unable to order absolute symbol: ");
334 else if (d && isa<OutputSection>(d->section))
335 report(": unable to order synthetic symbol: ");
Fangrui Songe1b6b5b2021-12-24 20:09:48336 else if (d && !d->section->isLive())
Rui Ueyama3837f422019-07-10 05:00:37337 report(": unable to order discarded symbol: ");
Michael J. Spencerb8427252018-04-17 23:30:05338}
339
Fangrui Songcd0ab242019-11-30 05:58:36340// Returns true if a symbol can be replaced at load-time by a symbol
341// with the same name defined in other ELF executable or DSO.
Fangrui Song07837b82020-05-15 05:18:58342bool elf::computeIsPreemptible(const Symbol &sym) {
Fangrui Songe9262ed2021-12-27 02:11:45343 assert(!sym.isLocal() || sym.isPlaceholder());
Fangrui Songcd0ab242019-11-30 05:58:36344
345 // Only symbols with default visibility that appear in dynsym can be
346 // preempted. Symbols with protected visibility cannot be preempted.
Fangrui Song82ed93ea2022-09-05 00:27:35347 if (!sym.includeInDynsym() || sym.visibility() != STV_DEFAULT)
Fangrui Songcd0ab242019-11-30 05:58:36348 return false;
349
350 // At this point copy relocations have not been created yet, so any
351 // symbol that is not defined locally is preemptible.
352 if (!sym.isDefined())
353 return true;
354
355 if (!config->shared)
356 return false;
357
Fangrui Song751f18e2020-06-01 18:27:53358 // If -Bsymbolic or --dynamic-list is specified, or -Bsymbolic-functions is
359 // specified and the symbol is STT_FUNC, the symbol is preemptible iff it is
Fangrui Songb06426d2021-07-29 21:46:53360 // in the dynamic list. -Bsymbolic-non-weak-functions is a non-weak subset of
361 // -Bsymbolic-functions.
362 if (config->symbolic ||
363 (config->bsymbolic == BsymbolicKind::Functions && sym.isFunc()) ||
364 (config->bsymbolic == BsymbolicKind::NonWeakFunctions && sym.isFunc() &&
365 sym.binding != STB_WEAK))
Fangrui Songcd0ab242019-11-30 05:58:36366 return sym.inDynamicList;
Fangrui Songcd0ab242019-11-30 05:58:36367 return true;
368}
369
Rui Ueyama7f7d2b22019-05-23 09:58:08370// Merge symbol properties.
371//
372// When we have many symbols of the same name, we choose one of them,
373// and that's the result of symbol resolution. However, symbols that
374// were not chosen still affect some symbol properties.
Rui Ueyama3837f422019-07-10 05:00:37375void Symbol::mergeProperties(const Symbol &other) {
376 if (other.exportDynamic)
377 exportDynamic = true;
Rui Ueyama7f7d2b22019-05-23 09:58:08378
379 // DSO symbols do not affect visibility in the output.
Fangrui Song82ed93ea2022-09-05 00:27:35380 if (!other.isShared() && other.visibility() != STV_DEFAULT) {
381 uint8_t v = visibility(), ov = other.visibility();
382 setVisibility(v == STV_DEFAULT ? ov : std::min(v, ov));
383 }
Rui Ueyama7f7d2b22019-05-23 09:58:08384}
385
Fangrui Song9e6840c2022-09-29 03:01:41386void Symbol::resolve(const Undefined &other) {
387 if (other.visibility() != STV_DEFAULT) {
388 uint8_t v = visibility(), ov = other.visibility();
389 setVisibility(v == STV_DEFAULT ? ov : std::min(v, ov));
Rui Ueyama7f7d2b22019-05-23 09:58:08390 }
Rui Ueyama7f7d2b22019-05-23 09:58:08391 // An undefined symbol with non default visibility must be satisfied
392 // in the same DSO.
393 //
394 // If this is a non-weak defined symbol in a discarded section, override the
395 // existing undefined symbol for better error message later.
Fangrui Songdf6803d2022-09-28 17:39:31396 if (isPlaceholder() || (isShared() && other.visibility() != STV_DEFAULT) ||
Rui Ueyama3837f422019-07-10 05:00:37397 (isUndefined() && other.binding != STB_WEAK && other.discardedSecIdx)) {
Fangrui Song7a58dd12022-09-28 20:11:31398 other.overwrite(*this);
Rui Ueyama7f7d2b22019-05-23 09:58:08399 return;
400 }
401
Rui Ueyama3837f422019-07-10 05:00:37402 if (traced)
Fangrui Song977a1a52022-02-06 00:34:02403 printTraceSymbol(other, getName());
Sam Clegg7991b682019-05-24 13:29:17404
Fangrui Songf3475412019-07-04 10:38:04405 if (isLazy()) {
Fangrui Song09401df2021-11-26 18:58:50406 // An undefined weak will not extract archive members. See comment on Lazy
407 // in Symbols.h for the details.
Rui Ueyama3837f422019-07-10 05:00:37408 if (other.binding == STB_WEAK) {
409 binding = STB_WEAK;
410 type = other.type;
Rui Ueyama7f7d2b22019-05-23 09:58:08411 return;
412 }
413
414 // Do extra check for --warn-backrefs.
415 //
416 // --warn-backrefs is an option to prevent an undefined reference from
Fangrui Song09401df2021-11-26 18:58:50417 // extracting an archive member written earlier in the command line. It can
418 // be used to keep compatibility with GNU linkers to some degree. I'll
419 // explain the feature and why you may find it useful in this comment.
Rui Ueyama7f7d2b22019-05-23 09:58:08420 //
421 // lld's symbol resolution semantics is more relaxed than traditional Unix
422 // linkers. For example,
423 //
424 // ld.lld foo.a bar.o
425 //
426 // succeeds even if bar.o contains an undefined symbol that has to be
427 // resolved by some object file in foo.a. Traditional Unix linkers don't
428 // allow this kind of backward reference, as they visit each file only once
429 // from left to right in the command line while resolving all undefined
430 // symbols at the moment of visiting.
431 //
432 // In the above case, since there's no undefined symbol when a linker visits
433 // foo.a, no files are pulled out from foo.a, and because the linker forgets
434 // about foo.a after visiting, it can't resolve undefined symbols in bar.o
435 // that could have been resolved otherwise.
436 //
437 // That lld accepts more relaxed form means that (besides it'd make more
438 // sense) you can accidentally write a command line or a build file that
439 // works only with lld, even if you have a plan to distribute it to wider
440 // users who may be using GNU linkers. With --warn-backrefs, you can detect
441 // a library order that doesn't work with other Unix linkers.
442 //
443 // The option is also useful to detect cyclic dependencies between static
444 // archives. Again, lld accepts
445 //
446 // ld.lld foo.a bar.a
447 //
448 // even if foo.a and bar.a depend on each other. With --warn-backrefs, it is
449 // handled as an error.
450 //
451 // Here is how the option works. We assign a group ID to each file. A file
452 // with a smaller group ID can pull out object files from an archive file
453 // with an equal or greater group ID. Otherwise, it is a reverse dependency
454 // and an error.
455 //
456 // A file outside --{start,end}-group gets a fresh ID when instantiated. All
457 // files within the same --{start,end}-group get the same group ID. E.g.
458 //
459 // ld.lld A B --start-group C D --end-group E
460 //
461 // A forms group 0. B form group 1. C and D (including their member object
462 // files) form group 2. E forms group 3. I think that you can see how this
463 // group assignment rule simulates the traditional linker's semantics.
Rui Ueyama3837f422019-07-10 05:00:37464 bool backref = config->warnBackrefs && other.file &&
465 file->groupId < other.file->groupId;
Fangrui Song09401df2021-11-26 18:58:50466 extract();
Rui Ueyama7f7d2b22019-05-23 09:58:08467
Fangrui Songa954bb12021-09-20 16:52:30468 if (!config->whyExtract.empty())
469 recordWhyExtract(other.file, *file, *this);
470
Rui Ueyama7f7d2b22019-05-23 09:58:08471 // We don't report backward references to weak symbols as they can be
472 // overridden later.
Fangrui Song03c825c2020-04-06 05:27:46473 //
474 // A traditional linker does not error for -ldef1 -lref -ldef2 (linking
475 // sandwich), where def2 may or may not be the same as def1. We don't want
476 // to warn for this case, so dismiss the warning if we see a subsequent lazy
Fangrui Songce3c5da2020-10-22 22:26:52477 // definition. this->file needs to be saved because in the case of LTO it
478 // may be reset to nullptr or be replaced with a file named lto.tmp.
Rui Ueyama3837f422019-07-10 05:00:37479 if (backref && !isWeak())
Fangrui Songe980f162022-06-30 00:34:30480 ctx->backwardReferences.try_emplace(this,
481 std::make_pair(other.file, file));
Fangrui Songf3475412019-07-04 10:38:04482 return;
483 }
484
485 // Undefined symbols in a SharedFile do not change the binding.
Kazu Hirata62e48ed2021-12-25 05:22:27486 if (isa_and_nonnull<SharedFile>(other.file))
Fangrui Songf3475412019-07-04 10:38:04487 return;
488
Fangrui Songe49c4172019-08-06 14:03:45489 if (isUndefined() || isShared()) {
490 // The binding will be weak if there is at least one reference and all are
491 // weak. The binding has one opportunity to change to weak: if the first
492 // reference is weak.
493 if (other.binding != STB_WEAK || !referenced)
Rui Ueyama3837f422019-07-10 05:00:37494 binding = other.binding;
Rui Ueyama7f7d2b22019-05-23 09:58:08495 }
496}
497
Fangrui Song19e37a72022-02-24 22:09:00498// Compare two symbols. Return true if the new symbol should win.
Fangrui Songb07ef4d2022-02-28 18:25:21499bool Symbol::shouldReplace(const Defined &other) const {
Fangrui Song6d943402022-02-24 22:08:06500 if (LLVM_UNLIKELY(isCommon())) {
501 if (config->warnCommon)
502 warn("common " + getName() + " is overridden");
503 return !other.isWeak();
504 }
505 if (!isDefined())
506 return true;
Rui Ueyama7f7d2b22019-05-23 09:58:08507
Fangrui Songc7cf9602022-03-14 19:00:15508 // Incoming STB_GLOBAL overrides STB_WEAK/STB_GNU_UNIQUE. -fgnu-unique changes
509 // some vague linkage data in COMDAT from STB_WEAK to STB_GNU_UNIQUE. Treat
510 // STB_GNU_UNIQUE like STB_WEAK so that we prefer the first among all
511 // STB_WEAK/STB_GNU_UNIQUE copies. If we prefer an incoming STB_GNU_UNIQUE to
512 // an existing STB_WEAK, there may be discarded section errors because the
513 // selected copy may be in a non-prevailing COMDAT.
514 return !isGlobal() && other.isGlobal();
Rui Ueyama7f7d2b22019-05-23 09:58:08515}
516
Fangrui Song7c7702b2022-03-16 02:24:41517void elf::reportDuplicate(const Symbol &sym, const InputFile *newFile,
Fangrui Song88d66f62022-02-22 18:07:58518 InputSectionBase *errSec, uint64_t errOffset) {
Rui Ueyama3837f422019-07-10 05:00:37519 if (config->allowMultipleDefinition)
Rui Ueyama7f7d2b22019-05-23 09:58:08520 return;
Fangrui Song7c7702b2022-03-16 02:24:41521 // In glibc<2.32, crti.o has .gnu.linkonce.t.__x86.get_pc_thunk.bx, which
522 // is sort of proto-comdat. There is actually no duplicate if we have
523 // full support for .gnu.linkonce.
524 const Defined *d = dyn_cast<Defined>(&sym);
525 if (!d || d->getName() == "__x86.get_pc_thunk.bx")
526 return;
527 // Allow absolute symbols with the same value for GNU ld compatibility.
528 if (!d->section && !errSec && errOffset && d->value == errOffset)
529 return;
Rui Ueyama3837f422019-07-10 05:00:37530 if (!d->section || !errSec) {
Fangrui Song467e1b32022-02-15 19:18:31531 error("duplicate symbol: " + toString(sym) + "\n>>> defined in " +
532 toString(sym.file) + "\n>>> defined in " + toString(newFile));
Rui Ueyama7f7d2b22019-05-23 09:58:08533 return;
534 }
535
536 // Construct and print an error message in the form of:
537 //
538 // ld.lld: error: duplicate symbol: foo
539 // >>> defined at bar.c:30
540 // >>> bar.o (/home/alice/src/bar.o)
541 // >>> defined at baz.c:563
542 // >>> baz.o in archive libbaz.a
Rui Ueyama3837f422019-07-10 05:00:37543 auto *sec1 = cast<InputSectionBase>(d->section);
Fangrui Song467e1b32022-02-15 19:18:31544 std::string src1 = sec1->getSrcMsg(sym, d->value);
Rui Ueyama3837f422019-07-10 05:00:37545 std::string obj1 = sec1->getObjMsg(d->value);
Fangrui Song467e1b32022-02-15 19:18:31546 std::string src2 = errSec->getSrcMsg(sym, errOffset);
Rui Ueyama3837f422019-07-10 05:00:37547 std::string obj2 = errSec->getObjMsg(errOffset);
Rui Ueyama7f7d2b22019-05-23 09:58:08548
Fangrui Song467e1b32022-02-15 19:18:31549 std::string msg = "duplicate symbol: " + toString(sym) + "\n>>> defined at ";
Rui Ueyama3837f422019-07-10 05:00:37550 if (!src1.empty())
551 msg += src1 + "\n>>> ";
552 msg += obj1 + "\n>>> defined at ";
553 if (!src2.empty())
554 msg += src2 + "\n>>> ";
555 msg += obj2;
556 error(msg);
Rui Ueyama7f7d2b22019-05-23 09:58:08557}
558
Fangrui Song88d66f62022-02-22 18:07:58559void Symbol::checkDuplicate(const Defined &other) const {
Fangrui Song6d943402022-02-24 22:08:06560 if (isDefined() && !isWeak() && !other.isWeak())
Fangrui Song88d66f62022-02-22 18:07:58561 reportDuplicate(*this, other.file,
562 dyn_cast_or_null<InputSectionBase>(other.section),
563 other.value);
564}
565
Fangrui Song9e6840c2022-09-29 03:01:41566void Symbol::resolve(const CommonSymbol &other) {
567 if (other.exportDynamic)
568 exportDynamic = true;
569 if (other.visibility() != STV_DEFAULT) {
570 uint8_t v = visibility(), ov = other.visibility();
571 setVisibility(v == STV_DEFAULT ? ov : std::min(v, ov));
572 }
Fangrui Song6d943402022-02-24 22:08:06573 if (isDefined() && !isWeak()) {
574 if (config->warnCommon)
575 warn("common " + getName() + " is overridden");
Rui Ueyama7f7d2b22019-05-23 09:58:08576 return;
Fangrui Song6d943402022-02-24 22:08:06577 }
Rui Ueyama7f7d2b22019-05-23 09:58:08578
Fangrui Song6d943402022-02-24 22:08:06579 if (CommonSymbol *oldSym = dyn_cast<CommonSymbol>(this)) {
580 if (config->warnCommon)
581 warn("multiple common of " + getName());
582 oldSym->alignment = std::max(oldSym->alignment, other.alignment);
583 if (oldSym->size < other.size) {
584 oldSym->file = other.file;
585 oldSym->size = other.size;
Fangrui Song69d10d22019-12-07 05:18:31586 }
Rui Ueyama7f7d2b22019-05-23 09:58:08587 return;
588 }
589
Fangrui Song6d943402022-02-24 22:08:06590 if (auto *s = dyn_cast<SharedSymbol>(this)) {
591 // Increase st_size if the shared symbol has a larger st_size. The shared
592 // symbol may be created from common symbols. The fact that some object
593 // files were linked into a shared object first should not change the
594 // regular rule that picks the largest st_size.
595 uint64_t size = s->size;
Fangrui Song7a58dd12022-09-28 20:11:31596 other.overwrite(*this);
Fangrui Song6d943402022-02-24 22:08:06597 if (size > cast<CommonSymbol>(this)->size)
598 cast<CommonSymbol>(this)->size = size;
599 } else {
Fangrui Song7a58dd12022-09-28 20:11:31600 other.overwrite(*this);
Rui Ueyama7f7d2b22019-05-23 09:58:08601 }
602}
603
Fangrui Song9e6840c2022-09-29 03:01:41604void Symbol::resolve(const Defined &other) {
605 if (other.exportDynamic)
606 exportDynamic = true;
607 if (other.visibility() != STV_DEFAULT) {
608 uint8_t v = visibility(), ov = other.visibility();
609 setVisibility(v == STV_DEFAULT ? ov : std::min(v, ov));
610 }
Fangrui Songb07ef4d2022-02-28 18:25:21611 if (shouldReplace(other))
Fangrui Song7a58dd12022-09-28 20:11:31612 other.overwrite(*this);
Rui Ueyama7f7d2b22019-05-23 09:58:08613}
614
Fangrui Song9e6840c2022-09-29 03:01:41615void Symbol::resolve(const LazyObject &other) {
Fangrui Songdf6803d2022-09-28 17:39:31616 if (isPlaceholder()) {
Fangrui Song7a58dd12022-09-28 20:11:31617 other.overwrite(*this);
Fangrui Songdf6803d2022-09-28 17:39:31618 return;
619 }
620
Sean Fertile8f91f382020-12-07 14:28:17621 // For common objects, we want to look for global or weak definitions that
Fangrui Song09401df2021-11-26 18:58:50622 // should be extracted as the canonical definition instead.
Fangrui Song15617cd2022-02-24 20:21:40623 if (LLVM_UNLIKELY(isCommon()) && elf::config->fortranCommon &&
624 other.file->shouldExtractForCommon(getName())) {
Fangrui Songe980f162022-06-30 00:34:30625 ctx->backwardReferences.erase(this);
Fangrui Song7a58dd12022-09-28 20:11:31626 other.overwrite(*this);
Fangrui Song15617cd2022-02-24 20:21:40627 other.extract();
628 return;
Sean Fertile8f91f382020-12-07 14:28:17629 }
630
Fangrui Song03c825c2020-04-06 05:27:46631 if (!isUndefined()) {
632 // See the comment in resolveUndefined().
633 if (isDefined())
Fangrui Songe980f162022-06-30 00:34:30634 ctx->backwardReferences.erase(this);
Rui Ueyama7f7d2b22019-05-23 09:58:08635 return;
Fangrui Song03c825c2020-04-06 05:27:46636 }
Rui Ueyama7f7d2b22019-05-23 09:58:08637
Fangrui Song09401df2021-11-26 18:58:50638 // An undefined weak will not extract archive members. See comment on Lazy in
Rui Ueyama7f7d2b22019-05-23 09:58:08639 // Symbols.h for the details.
640 if (isWeak()) {
Rui Ueyama3837f422019-07-10 05:00:37641 uint8_t ty = type;
Fangrui Song7a58dd12022-09-28 20:11:31642 other.overwrite(*this);
Rui Ueyama3837f422019-07-10 05:00:37643 type = ty;
644 binding = STB_WEAK;
Rui Ueyama7f7d2b22019-05-23 09:58:08645 return;
646 }
647
Fangrui Songa954bb12021-09-20 16:52:30648 const InputFile *oldFile = file;
Fangrui Song09401df2021-11-26 18:58:50649 other.extract();
Fangrui Songa954bb12021-09-20 16:52:30650 if (!config->whyExtract.empty())
651 recordWhyExtract(oldFile, *file, *this);
Rui Ueyama7f7d2b22019-05-23 09:58:08652}
653
Fangrui Song9e6840c2022-09-29 03:01:41654void Symbol::resolve(const SharedSymbol &other) {
655 exportDynamic = true;
Fangrui Songdf6803d2022-09-28 17:39:31656 if (isPlaceholder()) {
Fangrui Song7a58dd12022-09-28 20:11:31657 other.overwrite(*this);
Fangrui Songdf6803d2022-09-28 17:39:31658 return;
659 }
Fangrui Song69d10d22019-12-07 05:18:31660 if (isCommon()) {
661 // See the comment in resolveCommon() above.
662 if (other.size > cast<CommonSymbol>(this)->size)
663 cast<CommonSymbol>(this)->size = other.size;
664 return;
665 }
Fangrui Song82ed93ea2022-09-05 00:27:35666 if (visibility() == STV_DEFAULT && (isUndefined() || isLazy())) {
Rui Ueyama7f7d2b22019-05-23 09:58:08667 // An undefined symbol with non default visibility must be satisfied
668 // in the same DSO.
Rui Ueyama3837f422019-07-10 05:00:37669 uint8_t bind = binding;
Fangrui Song7a58dd12022-09-28 20:11:31670 other.overwrite(*this);
Rui Ueyama3837f422019-07-10 05:00:37671 binding = bind;
Fangrui Song64676492020-05-18 17:15:59672 } else if (traced)
Fangrui Song977a1a52022-02-06 00:34:02673 printTraceSymbol(other, getName());
Rui Ueyama7f7d2b22019-05-23 09:58:08674}