blob: 9d8ff8aa4c19977c5791a75ca661030d72ec60fe [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"
Michael J. Spencercdae0a42015-07-28 22:58:2510#include "InputFiles.h"
Rui Ueyamab5a69702016-02-01 21:00:3511#include "InputSection.h"
12#include "OutputSections.h"
Rui Ueyamae8a61022016-11-05 23:05:4713#include "SyntheticSections.h"
Rui Ueyamab5a69702016-02-01 21:00:3514#include "Target.h"
Rafael Espindola17cb7c02016-12-19 17:01:0115#include "Writer.h"
Bob Haarmanb8a59c82017-10-25 22:28:3816#include "lld/Common/ErrorHandler.h"
Rui Ueyama53fe4692017-11-28 02:15:2617#include "lld/Common/Strings.h"
Michael J. Spencer1b348a62015-09-04 22:28:1018#include "llvm/ADT/STLExtras.h"
Fangrui Song23257882020-04-05 04:31:3619#include "llvm/Support/FileSystem.h"
Eugene Leviantc958d8d2016-10-12 08:19:3020#include "llvm/Support/Path.h"
Rui Ueyamac72ba3a2016-11-23 04:57:2521#include <cstring>
Michael J. Spencer1b348a62015-09-04 22:28:1022
23using namespace llvm;
Michael J. Spencer84487f12015-07-24 21:03:0724using namespace llvm::object;
Rafael Espindola78471f02015-09-01 23:12:5225using namespace llvm::ELF;
Fangrui Song07837b82020-05-15 05:18:5826using namespace lld;
27using namespace lld::elf;
Michael J. Spencer84487f12015-07-24 21:03:0728
Fangrui Songbd8cfe62019-10-07 08:31:1829// Returns a symbol for an error message.
30static std::string demangle(StringRef symName) {
31 if (elf::config->demangle)
32 return demangleItanium(symName);
Benjamin Krameradcd0262020-01-28 19:23:4633 return std::string(symName);
Fangrui Songbd8cfe62019-10-07 08:31:1834}
Michael J. Spencer84487f12015-07-24 21:03:0735
Fangrui Song07837b82020-05-15 05:18:5836std::string lld::toString(const elf::Symbol &sym) {
Fangrui Songf2036a12020-03-28 22:48:3837 StringRef name = sym.getName();
38 std::string ret = demangle(name);
39
Fangrui Song941e9332020-12-01 16:54:0140 const char *suffix = sym.getVersionSuffix();
41 if (*suffix == '@')
42 ret += suffix;
Fangrui Songf2036a12020-03-28 22:48:3843 return ret;
44}
45
Fangrui Song07837b82020-05-15 05:18:5846std::string lld::toELFString(const Archive::Symbol &b) {
Fangrui Songbd8cfe62019-10-07 08:31:1847 return demangle(b.getName());
48}
49
Rui Ueyama3837f422019-07-10 05:00:3750Defined *ElfSym::bss;
51Defined *ElfSym::etext1;
52Defined *ElfSym::etext2;
53Defined *ElfSym::edata1;
54Defined *ElfSym::edata2;
55Defined *ElfSym::end1;
56Defined *ElfSym::end2;
57Defined *ElfSym::globalOffsetTable;
58Defined *ElfSym::mipsGp;
59Defined *ElfSym::mipsGpDisp;
60Defined *ElfSym::mipsLocalGp;
61Defined *ElfSym::relaIpltStart;
62Defined *ElfSym::relaIpltEnd;
63Defined *ElfSym::riscvGlobalPointer;
64Defined *ElfSym::tlsModuleBase;
Fangrui Songce3c5da2020-10-22 22:26:5265DenseMap<const Symbol *, std::pair<const InputFile *, const InputFile *>>
66 elf::backwardReferences;
Fangrui Songa954bb12021-09-20 16:52:3067SmallVector<std::tuple<std::string, const InputFile *, const Symbol &>, 0>
68 elf::whyExtract;
Rui Ueyama80474a22017-02-28 19:29:5569
Fangrui Songa8024df2021-12-13 03:12:0170static uint64_t getSymVA(const Symbol &sym, int64_t addend) {
Rui Ueyama3837f422019-07-10 05:00:3771 switch (sym.kind()) {
Peter Collingbournee9a9e0a2017-11-06 04:35:3172 case Symbol::DefinedKind: {
Rui Ueyama3837f422019-07-10 05:00:3773 auto &d = cast<Defined>(sym);
74 SectionBase *isec = d.section;
Rui Ueyamab5a69702016-02-01 21:00:3575
76 // This is an absolute symbol.
Rui Ueyama3837f422019-07-10 05:00:3777 if (!isec)
78 return d.value;
Rui Ueyamab5a69702016-02-01 21:00:3579
Rui Ueyama3837f422019-07-10 05:00:3780 assert(isec != &InputSection::discarded);
Rafael Espindolaf4d6e8c2018-04-19 17:26:5081
Rui Ueyama3837f422019-07-10 05:00:3782 uint64_t offset = d.value;
Sean Silvaa9ba4502017-02-28 08:32:5683
84 // An object in an SHF_MERGE section might be referenced via a
85 // section symbol (as a hack for reducing the number of local
86 // symbols).
Sean Silvad4e60622017-03-01 04:44:0487 // Depending on the addend, the reference via a section symbol
88 // refers to a different object in the merge section.
89 // Since the objects in the merge section are not necessarily
90 // contiguous in the output, the addend can thus affect the final
91 // VA in a non-linear way.
92 // To make this work, we incorporate the addend into the section
93 // offset (and zero out the addend for later processing) so that
94 // we find the right object in the section.
Fangrui Songa8024df2021-12-13 03:12:0195 if (d.isSection())
Rui Ueyama3837f422019-07-10 05:00:3796 offset += addend;
Sean Silvaa9ba4502017-02-28 08:32:5697
Sean Silva6ab39262017-02-28 09:01:5898 // In the typical case, this is actually very simple and boils
99 // down to adding together 3 numbers:
100 // 1. The address of the output section.
101 // 2. The offset of the input section within the output section.
102 // 3. The offset within the input section (this addition happens
103 // inside InputSection::getOffset).
104 //
105 // If you understand the data structures involved with this next
106 // line (and how they get built), then you have a pretty good
107 // understanding of the linker.
Rui Ueyama3837f422019-07-10 05:00:37108 uint64_t va = isec->getVA(offset);
Fangrui Songa8024df2021-12-13 03:12:01109 if (d.isSection())
110 va -= addend;
Sean Silva6ab39262017-02-28 09:01:58111
Simon Atanasyanfae2a5092019-02-19 10:36:58112 // MIPS relocatable files can mix regular and microMIPS code.
113 // Linker needs to distinguish such code. To do so microMIPS
114 // symbols has the `STO_MIPS_MICROMIPS` flag in the `st_other`
Fangrui Songdeb58192020-01-23 05:39:16115 // field. Unfortunately, the `MIPS::relocate()` method has
Simon Atanasyanfae2a5092019-02-19 10:36:58116 // a symbol value only. To pass type of the symbol (regular/microMIPS)
117 // to that routine as well as other places where we write
118 // a symbol value as-is (.dynamic section, `Elf_Ehdr::e_entry`
119 // field etc) do the same trick as compiler uses to mark microMIPS
120 // for CPU - set the less-significant bit.
Rui Ueyama3837f422019-07-10 05:00:37121 if (config->emachine == EM_MIPS && isMicroMips() &&
Fangrui Songcf783be2021-12-15 00:28:41122 ((sym.stOther & STO_MIPS_MICROMIPS) || sym.needsCopy))
Rui Ueyama3837f422019-07-10 05:00:37123 va |= 1;
Simon Atanasyanfae2a5092019-02-19 10:36:58124
Rui Ueyama3837f422019-07-10 05:00:37125 if (d.isTls() && !config->relocatable) {
Ryan Prichard1c33d142018-09-18 00:24:48126 // Use the address of the TLS segment's first section rather than the
127 // segment's address, because segment addresses aren't initialized until
128 // after sections are finalized. (e.g. Measuring the size of .rela.dyn
129 // for Android relocation packing requires knowing TLS symbol addresses
130 // during section finalization.)
Rui Ueyama3837f422019-07-10 05:00:37131 if (!Out::tlsPhdr || !Out::tlsPhdr->firstSec)
132 fatal(toString(d.file) +
Peter Collingbourne3e2abde2017-07-14 00:22:46133 " has an STT_TLS symbol but doesn't have an SHF_TLS section");
Rui Ueyama3837f422019-07-10 05:00:37134 return va - Out::tlsPhdr->firstSec->addr;
George Rimar6a3b1542016-10-04 08:52:51135 }
Rui Ueyama3837f422019-07-10 05:00:37136 return va;
Rui Ueyamab5a69702016-02-01 21:00:35137 }
Rafael Espindolaab0cce52018-04-26 17:58:58138 case Symbol::SharedKind:
Rui Ueyamaf52496e2017-11-03 21:21:47139 case Symbol::UndefinedKind:
Rui Ueyamab5a69702016-02-01 21:00:35140 return 0;
Rui Ueyamaf52496e2017-11-03 21:21:47141 case Symbol::LazyArchiveKind:
142 case Symbol::LazyObjectKind:
Rui Ueyama3837f422019-07-10 05:00:37143 assert(sym.isUsedInRegularObj && "lazy symbol reached writer");
Chih-Hung Hsieh73e04842018-09-11 23:00:36144 return 0;
Rui Ueyama5c073a92019-05-16 03:29:03145 case Symbol::CommonKind:
146 llvm_unreachable("common symbol reached writer");
Rui Ueyamaf3fad552018-10-12 18:29:18147 case Symbol::PlaceholderKind:
148 llvm_unreachable("placeholder symbol reached writer");
Rui Ueyamab5a69702016-02-01 21:00:35149 }
George Rimar777f9632016-03-12 08:31:34150 llvm_unreachable("invalid symbol kind");
Rui Ueyamab5a69702016-02-01 21:00:35151}
152
Rui Ueyama3837f422019-07-10 05:00:37153uint64_t Symbol::getVA(int64_t addend) const {
Fangrui Songa8024df2021-12-13 03:12:01154 return getSymVA(*this, addend) + addend;
Rafael Espindola87d9f102016-03-11 12:19:05155}
156
Peter Collingbourne8331f612019-02-13 21:49:55157uint64_t Symbol::getGotVA() const {
Rui Ueyama3837f422019-07-10 05:00:37158 if (gotInIgot)
159 return in.igotPlt->getVA() + getGotPltOffset();
160 return in.got->getVA() + getGotOffset();
Peter Collingbourne8331f612019-02-13 21:49:55161}
Rafael Espindola74031ba2016-04-07 15:20:56162
Harald van Dijkd6241342021-05-16 23:13:00163uint64_t Symbol::getGotOffset() const {
164 return gotIndex * target->gotEntrySize;
165}
Rui Ueyamab5a69702016-02-01 21:00:35166
Rui Ueyamaf52496e2017-11-03 21:21:47167uint64_t Symbol::getGotPltVA() const {
Rui Ueyama3837f422019-07-10 05:00:37168 if (isInIplt)
169 return in.igotPlt->getVA() + getGotPltOffset();
170 return in.gotPlt->getVA() + getGotPltOffset();
Rafael Espindola74031ba2016-04-07 15:20:56171}
172
Rui Ueyamaf52496e2017-11-03 21:21:47173uint64_t Symbol::getGotPltOffset() const {
Rui Ueyama3837f422019-07-10 05:00:37174 if (isInIplt)
Harald van Dijkd6241342021-05-16 23:13:00175 return pltIndex * target->gotEntrySize;
176 return (pltIndex + target->gotPltHeaderEntriesNum) * target->gotEntrySize;
Rui Ueyamab5a69702016-02-01 21:00:35177}
178
Rui Ueyamaf52496e2017-11-03 21:21:47179uint64_t Symbol::getPltVA() const {
Fangrui Song891a8652019-12-14 22:17:35180 uint64_t outVA = isInIplt
181 ? in.iplt->getVA() + pltIndex * target->ipltEntrySize
182 : in.plt->getVA() + in.plt->headerSize +
183 pltIndex * target->pltEntrySize;
184
Simon Atanasyanfae2a5092019-02-19 10:36:58185 // While linking microMIPS code PLT code are always microMIPS
186 // code. Set the less-significant bit to track that fact.
187 // See detailed comment in the `getSymVA` function.
Rui Ueyama3837f422019-07-10 05:00:37188 if (config->emachine == EM_MIPS && isMicroMips())
189 outVA |= 1;
190 return outVA;
Rafael Espindolaab0cce52018-04-26 17:58:58191}
192
Rui Ueyamaf52496e2017-11-03 21:21:47193uint64_t Symbol::getSize() const {
Rui Ueyama3837f422019-07-10 05:00:37194 if (const auto *dr = dyn_cast<Defined>(this))
195 return dr->size;
196 return cast<SharedSymbol>(this)->size;
Rui Ueyama512c61d2016-02-03 00:12:24197}
198
Rui Ueyamaf52496e2017-11-03 21:21:47199OutputSection *Symbol::getOutputSection() const {
Rui Ueyama3837f422019-07-10 05:00:37200 if (auto *s = dyn_cast<Defined>(this)) {
201 if (auto *sec = s->section)
Fangrui Songc2f2bb02021-12-21 08:39:16202 return sec->getOutputSection();
Rui Ueyama968db482017-02-28 04:02:42203 return nullptr;
204 }
Rui Ueyama968db482017-02-28 04:02:42205 return nullptr;
206}
207
Rui Ueyama35fa6c52016-11-23 05:48:40208// If a symbol name contains '@', the characters after that is
209// a symbol version name. This function parses that.
Rui Ueyamaf52496e2017-11-03 21:21:47210void Symbol::parseSymbolVersion() {
Fangrui Song00809c82021-08-05 06:52:55211 // Return if localized by a local: pattern in a version script.
212 if (versionId == VER_NDX_LOCAL)
213 return;
Rui Ueyama3837f422019-07-10 05:00:37214 StringRef s = getName();
215 size_t pos = s.find('@');
Fangrui Song101407b2021-12-16 07:59:55216 if (pos == StringRef::npos)
Rui Ueyama35fa6c52016-11-23 05:48:40217 return;
Rui Ueyama3837f422019-07-10 05:00:37218 StringRef verstr = s.substr(pos + 1);
Rui Ueyama35fa6c52016-11-23 05:48:40219
220 // Truncate the symbol name so that it doesn't include the version string.
Rui Ueyama3837f422019-07-10 05:00:37221 nameSize = pos;
Rui Ueyama35fa6c52016-11-23 05:48:40222
Fangrui Song7924b382021-12-27 01:25:54223 if (verstr.empty())
224 return;
225
Rafael Espindola1d6d1b42017-01-17 16:08:06226 // If this is not in this DSO, it is not a definition.
Peter Collingbourneb472aa02017-11-06 04:39:07227 if (!isDefined())
Rafael Espindola2756e042017-01-06 22:30:35228 return;
229
Rui Ueyama35fa6c52016-11-23 05:48:40230 // '@@' in a symbol name means the default version.
231 // It is usually the most recent one.
Rui Ueyama3837f422019-07-10 05:00:37232 bool isDefault = (verstr[0] == '@');
233 if (isDefault)
234 verstr = verstr.substr(1);
Rui Ueyama35fa6c52016-11-23 05:48:40235
Fangrui Songe28a70d2019-08-05 14:31:39236 for (const VersionDefinition &ver : namedVersionDefs()) {
Rui Ueyama3837f422019-07-10 05:00:37237 if (ver.name != verstr)
Rui Ueyama35fa6c52016-11-23 05:48:40238 continue;
239
Rui Ueyama3837f422019-07-10 05:00:37240 if (isDefault)
241 versionId = ver.id;
Rui Ueyama35fa6c52016-11-23 05:48:40242 else
Rui Ueyama3837f422019-07-10 05:00:37243 versionId = ver.id | VERSYM_HIDDEN;
Rui Ueyama35fa6c52016-11-23 05:48:40244 return;
245 }
246
247 // It is an error if the specified version is not defined.
George Rimar4d2f97622017-07-04 13:19:13248 // Usually version script is not provided when linking executable,
249 // but we may still want to override a versioned symbol from DSO,
Peter Smith796fb992018-05-14 10:13:56250 // so we do not report error in this case. We also do not error
251 // if the symbol has a local version as it won't be in the dynamic
252 // symbol table.
Rui Ueyama3837f422019-07-10 05:00:37253 if (config->shared && versionId != VER_NDX_LOCAL)
254 error(toString(file) + ": symbol " + s + " has undefined version " +
255 verstr);
Rui Ueyama35fa6c52016-11-23 05:48:40256}
257
Fangrui Song09401df2021-11-26 18:58:50258void Symbol::extract() const {
Fangrui Song3a5fb572021-12-23 01:41:50259 if (auto *sym = dyn_cast<LazyArchive>(this)) {
Fangrui Song09401df2021-11-26 18:58:50260 cast<ArchiveFile>(sym->file)->extract(sym->sym);
Fangrui Song3a5fb572021-12-23 01:41:50261 } else if (file->lazy) {
262 file->lazy = false;
263 parseFile(file);
264 }
Rui Ueyama7d476192019-05-16 02:14:00265}
Rui Ueyamaf8baa662016-04-07 19:24:51266
Peter Collingbourne98930112018-08-08 23:48:12267MemoryBufferRef LazyArchive::getMemberBuffer() {
Nico Weber9c0716f2019-07-23 19:00:01268 Archive::Child c =
269 CHECK(sym.getMember(),
270 "could not get the member for symbol " + toELFString(sym));
Peter Collingbourne98930112018-08-08 23:48:12271
Rui Ueyama3837f422019-07-10 05:00:37272 return CHECK(c.getMemoryBufferRef(),
Peter Collingbourne98930112018-08-08 23:48:12273 "could not get the buffer for the member defining symbol " +
Nico Weber9c0716f2019-07-23 19:00:01274 toELFString(sym));
Peter Collingbourne98930112018-08-08 23:48:12275}
276
Rui Ueyamaf52496e2017-11-03 21:21:47277uint8_t Symbol::computeBinding() const {
Rui Ueyama3837f422019-07-10 05:00:37278 if (config->relocatable)
279 return binding;
Fangrui Songcfdd4582019-08-11 17:03:00280 if ((visibility != STV_DEFAULT && visibility != STV_PROTECTED) ||
Nathan Lanza2f651662021-03-16 08:33:50281 (versionId == VER_NDX_LOCAL && !isLazy()))
Rafael Espindolab7e2ee22017-01-10 17:08:13282 return STB_LOCAL;
Rui Ueyama3837f422019-07-10 05:00:37283 if (!config->gnuUnique && binding == STB_GNU_UNIQUE)
Rafael Espindolab7e2ee22017-01-10 17:08:13284 return STB_GLOBAL;
Rui Ueyama3837f422019-07-10 05:00:37285 return binding;
Rafael Espindolab7e2ee22017-01-10 17:08:13286}
287
Rui Ueyamaf52496e2017-11-03 21:21:47288bool Symbol::includeInDynsym() const {
Rui Ueyama3837f422019-07-10 05:00:37289 if (!config->hasDynSymTab)
Rafael Espindolae05e2f82017-09-15 18:05:02290 return false;
Rafael Espindolab7e2ee22017-01-10 17:08:13291 if (computeBinding() == STB_LOCAL)
Rafael Espindolaae605c12016-04-21 20:35:25292 return false;
Fangrui Song375371c2020-01-09 23:53:52293 if (!isDefined() && !isCommon())
Fangrui Song0fbf28f2020-01-23 19:52:03294 // This should unconditionally return true, unfortunately glibc -static-pie
295 // expects undefined weak symbols not to exist in .dynsym, e.g.
296 // __pthread_mutex_lock reference in _dl_add_to_namespace_list,
297 // __pthread_initialize_minimal reference in csu/libc-start.c.
298 return !(config->noDynamicLinker && isUndefWeak());
Rui Ueyamae63ae7f2019-06-25 06:58:07299
Fangrui Song375371c2020-01-09 23:53:52300 return exportDynamic || inDynamicList;
Rafael Espindolaae605c12016-04-21 20:35:25301}
Rui Ueyama69c778c2016-07-17 17:50:09302
303// Print out a log message for --trace-symbol.
Fangrui Song07837b82020-05-15 05:18:58304void elf::printTraceSymbol(const Symbol *sym) {
Rui Ueyama3837f422019-07-10 05:00:37305 std::string s;
306 if (sym->isUndefined())
307 s = ": reference to ";
308 else if (sym->isLazy())
309 s = ": lazy definition of ";
310 else if (sym->isShared())
311 s = ": shared definition of ";
312 else if (sym->isCommon())
313 s = ": common definition of ";
Rui Ueyama69c778c2016-07-17 17:50:09314 else
Rui Ueyama3837f422019-07-10 05:00:37315 s = ": definition of ";
Rui Ueyamae6e206d2017-02-21 23:22:56316
Rui Ueyama3837f422019-07-10 05:00:37317 message(toString(sym->file) + s + sym->getName());
Rui Ueyama69c778c2016-07-17 17:50:09318}
319
Fangrui Songa954bb12021-09-20 16:52:30320static void recordWhyExtract(const InputFile *reference,
321 const InputFile &extracted, const Symbol &sym) {
322 whyExtract.emplace_back(toString(reference), &extracted, sym);
323}
324
Fangrui Song07837b82020-05-15 05:18:58325void elf::maybeWarnUnorderableSymbol(const Symbol *sym) {
Rui Ueyama3837f422019-07-10 05:00:37326 if (!config->warnSymbolOrdering)
Michael J. Spencerb8427252018-04-17 23:30:05327 return;
Rui Ueyamab774c3c2018-04-26 01:38:29328
Fangrui Song11ca54f2018-10-10 22:48:57329 // If UnresolvedPolicy::Ignore is used, no "undefined symbol" error/warning
330 // is emitted. It makes sense to not warn on undefined symbols.
331 //
332 // Note, ld.bfd --symbol-ordering-file= does not warn on undefined symbols,
333 // but we don't have to be compatible here.
Rui Ueyama3837f422019-07-10 05:00:37334 if (sym->isUndefined() &&
335 config->unresolvedSymbols == UnresolvedPolicy::Ignore)
Fangrui Song11ca54f2018-10-10 22:48:57336 return;
337
Rui Ueyama3837f422019-07-10 05:00:37338 const InputFile *file = sym->file;
339 auto *d = dyn_cast<Defined>(sym);
Rui Ueyamab774c3c2018-04-26 01:38:29340
Rui Ueyama3837f422019-07-10 05:00:37341 auto report = [&](StringRef s) { warn(toString(file) + s + sym->getName()); };
Rui Ueyamab774c3c2018-04-26 01:38:29342
Rui Ueyama3837f422019-07-10 05:00:37343 if (sym->isUndefined())
344 report(": unable to order undefined symbol: ");
345 else if (sym->isShared())
346 report(": unable to order shared symbol: ");
347 else if (d && !d->section)
348 report(": unable to order absolute symbol: ");
349 else if (d && isa<OutputSection>(d->section))
350 report(": unable to order synthetic symbol: ");
Fangrui Songe1b6b5b2021-12-24 20:09:48351 else if (d && !d->section->isLive())
Rui Ueyama3837f422019-07-10 05:00:37352 report(": unable to order discarded symbol: ");
Michael J. Spencerb8427252018-04-17 23:30:05353}
354
Fangrui Songcd0ab242019-11-30 05:58:36355// Returns true if a symbol can be replaced at load-time by a symbol
356// with the same name defined in other ELF executable or DSO.
Fangrui Song07837b82020-05-15 05:18:58357bool elf::computeIsPreemptible(const Symbol &sym) {
Fangrui Songcd0ab242019-11-30 05:58:36358 assert(!sym.isLocal());
359
360 // Only symbols with default visibility that appear in dynsym can be
361 // preempted. Symbols with protected visibility cannot be preempted.
362 if (!sym.includeInDynsym() || sym.visibility != STV_DEFAULT)
363 return false;
364
365 // At this point copy relocations have not been created yet, so any
366 // symbol that is not defined locally is preemptible.
367 if (!sym.isDefined())
368 return true;
369
370 if (!config->shared)
371 return false;
372
Fangrui Song751f18e2020-06-01 18:27:53373 // If -Bsymbolic or --dynamic-list is specified, or -Bsymbolic-functions is
374 // specified and the symbol is STT_FUNC, the symbol is preemptible iff it is
Fangrui Songb06426d2021-07-29 21:46:53375 // in the dynamic list. -Bsymbolic-non-weak-functions is a non-weak subset of
376 // -Bsymbolic-functions.
377 if (config->symbolic ||
378 (config->bsymbolic == BsymbolicKind::Functions && sym.isFunc()) ||
379 (config->bsymbolic == BsymbolicKind::NonWeakFunctions && sym.isFunc() &&
380 sym.binding != STB_WEAK))
Fangrui Songcd0ab242019-11-30 05:58:36381 return sym.inDynamicList;
Fangrui Songcd0ab242019-11-30 05:58:36382 return true;
383}
384
Fangrui Song07837b82020-05-15 05:18:58385void elf::reportBackrefs() {
Fangrui Song03c825c2020-04-06 05:27:46386 for (auto &it : backwardReferences) {
387 const Symbol &sym = *it.first;
Fangrui Song3ba334222020-11-08 04:17:41388 std::string to = toString(it.second.second);
389 // Some libraries have known problems and can cause noise. Filter them out
390 // with --warn-backrefs-exclude=. to may look like *.o or *.a(*.o).
391 bool exclude = false;
392 for (const llvm::GlobPattern &pat : config->warnBackrefsExclude)
393 if (pat.match(to)) {
394 exclude = true;
395 break;
396 }
397 if (!exclude)
398 warn("backward reference detected: " + sym.getName() + " in " +
399 toString(it.second.first) + " refers to " + to);
Fangrui Song03c825c2020-04-06 05:27:46400 }
401}
402
Rui Ueyama3837f422019-07-10 05:00:37403static uint8_t getMinVisibility(uint8_t va, uint8_t vb) {
404 if (va == STV_DEFAULT)
405 return vb;
406 if (vb == STV_DEFAULT)
407 return va;
408 return std::min(va, vb);
Rui Ueyama7f7d2b22019-05-23 09:58:08409}
410
411// Merge symbol properties.
412//
413// When we have many symbols of the same name, we choose one of them,
414// and that's the result of symbol resolution. However, symbols that
415// were not chosen still affect some symbol properties.
Rui Ueyama3837f422019-07-10 05:00:37416void Symbol::mergeProperties(const Symbol &other) {
417 if (other.exportDynamic)
418 exportDynamic = true;
419 if (other.isUsedInRegularObj)
420 isUsedInRegularObj = true;
Rui Ueyama7f7d2b22019-05-23 09:58:08421
422 // DSO symbols do not affect visibility in the output.
Rui Ueyama3837f422019-07-10 05:00:37423 if (!other.isShared())
424 visibility = getMinVisibility(visibility, other.visibility);
Rui Ueyama7f7d2b22019-05-23 09:58:08425}
426
Rui Ueyama3837f422019-07-10 05:00:37427void Symbol::resolve(const Symbol &other) {
428 mergeProperties(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08429
430 if (isPlaceholder()) {
Rui Ueyama3837f422019-07-10 05:00:37431 replace(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08432 return;
433 }
434
Rui Ueyama3837f422019-07-10 05:00:37435 switch (other.kind()) {
Rui Ueyama7f7d2b22019-05-23 09:58:08436 case Symbol::UndefinedKind:
Rui Ueyama3837f422019-07-10 05:00:37437 resolveUndefined(cast<Undefined>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08438 break;
439 case Symbol::CommonKind:
Rui Ueyama3837f422019-07-10 05:00:37440 resolveCommon(cast<CommonSymbol>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08441 break;
442 case Symbol::DefinedKind:
Rui Ueyama3837f422019-07-10 05:00:37443 resolveDefined(cast<Defined>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08444 break;
445 case Symbol::LazyArchiveKind:
Rui Ueyama3837f422019-07-10 05:00:37446 resolveLazy(cast<LazyArchive>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08447 break;
448 case Symbol::LazyObjectKind:
Rui Ueyama3837f422019-07-10 05:00:37449 resolveLazy(cast<LazyObject>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08450 break;
451 case Symbol::SharedKind:
Rui Ueyama3837f422019-07-10 05:00:37452 resolveShared(cast<SharedSymbol>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08453 break;
454 case Symbol::PlaceholderKind:
455 llvm_unreachable("bad symbol kind");
456 }
457}
458
Rui Ueyama3837f422019-07-10 05:00:37459void Symbol::resolveUndefined(const Undefined &other) {
Rui Ueyama7f7d2b22019-05-23 09:58:08460 // An undefined symbol with non default visibility must be satisfied
461 // in the same DSO.
462 //
463 // If this is a non-weak defined symbol in a discarded section, override the
464 // existing undefined symbol for better error message later.
Rui Ueyama3837f422019-07-10 05:00:37465 if ((isShared() && other.visibility != STV_DEFAULT) ||
466 (isUndefined() && other.binding != STB_WEAK && other.discardedSecIdx)) {
467 replace(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08468 return;
469 }
470
Rui Ueyama3837f422019-07-10 05:00:37471 if (traced)
472 printTraceSymbol(&other);
Sam Clegg7991b682019-05-24 13:29:17473
Fangrui Songf3475412019-07-04 10:38:04474 if (isLazy()) {
Fangrui Song09401df2021-11-26 18:58:50475 // An undefined weak will not extract archive members. See comment on Lazy
476 // in Symbols.h for the details.
Rui Ueyama3837f422019-07-10 05:00:37477 if (other.binding == STB_WEAK) {
478 binding = STB_WEAK;
479 type = other.type;
Rui Ueyama7f7d2b22019-05-23 09:58:08480 return;
481 }
482
483 // Do extra check for --warn-backrefs.
484 //
485 // --warn-backrefs is an option to prevent an undefined reference from
Fangrui Song09401df2021-11-26 18:58:50486 // extracting an archive member written earlier in the command line. It can
487 // be used to keep compatibility with GNU linkers to some degree. I'll
488 // explain the feature and why you may find it useful in this comment.
Rui Ueyama7f7d2b22019-05-23 09:58:08489 //
490 // lld's symbol resolution semantics is more relaxed than traditional Unix
491 // linkers. For example,
492 //
493 // ld.lld foo.a bar.o
494 //
495 // succeeds even if bar.o contains an undefined symbol that has to be
496 // resolved by some object file in foo.a. Traditional Unix linkers don't
497 // allow this kind of backward reference, as they visit each file only once
498 // from left to right in the command line while resolving all undefined
499 // symbols at the moment of visiting.
500 //
501 // In the above case, since there's no undefined symbol when a linker visits
502 // foo.a, no files are pulled out from foo.a, and because the linker forgets
503 // about foo.a after visiting, it can't resolve undefined symbols in bar.o
504 // that could have been resolved otherwise.
505 //
506 // That lld accepts more relaxed form means that (besides it'd make more
507 // sense) you can accidentally write a command line or a build file that
508 // works only with lld, even if you have a plan to distribute it to wider
509 // users who may be using GNU linkers. With --warn-backrefs, you can detect
510 // a library order that doesn't work with other Unix linkers.
511 //
512 // The option is also useful to detect cyclic dependencies between static
513 // archives. Again, lld accepts
514 //
515 // ld.lld foo.a bar.a
516 //
517 // even if foo.a and bar.a depend on each other. With --warn-backrefs, it is
518 // handled as an error.
519 //
520 // Here is how the option works. We assign a group ID to each file. A file
521 // with a smaller group ID can pull out object files from an archive file
522 // with an equal or greater group ID. Otherwise, it is a reverse dependency
523 // and an error.
524 //
525 // A file outside --{start,end}-group gets a fresh ID when instantiated. All
526 // files within the same --{start,end}-group get the same group ID. E.g.
527 //
528 // ld.lld A B --start-group C D --end-group E
529 //
530 // A forms group 0. B form group 1. C and D (including their member object
531 // files) form group 2. E forms group 3. I think that you can see how this
532 // group assignment rule simulates the traditional linker's semantics.
Rui Ueyama3837f422019-07-10 05:00:37533 bool backref = config->warnBackrefs && other.file &&
534 file->groupId < other.file->groupId;
Fangrui Song09401df2021-11-26 18:58:50535 extract();
Rui Ueyama7f7d2b22019-05-23 09:58:08536
Fangrui Songa954bb12021-09-20 16:52:30537 if (!config->whyExtract.empty())
538 recordWhyExtract(other.file, *file, *this);
539
Rui Ueyama7f7d2b22019-05-23 09:58:08540 // We don't report backward references to weak symbols as they can be
541 // overridden later.
Fangrui Song03c825c2020-04-06 05:27:46542 //
543 // A traditional linker does not error for -ldef1 -lref -ldef2 (linking
544 // sandwich), where def2 may or may not be the same as def1. We don't want
545 // to warn for this case, so dismiss the warning if we see a subsequent lazy
Fangrui Songce3c5da2020-10-22 22:26:52546 // definition. this->file needs to be saved because in the case of LTO it
547 // may be reset to nullptr or be replaced with a file named lto.tmp.
Rui Ueyama3837f422019-07-10 05:00:37548 if (backref && !isWeak())
Fangrui Songce3c5da2020-10-22 22:26:52549 backwardReferences.try_emplace(this, std::make_pair(other.file, file));
Fangrui Songf3475412019-07-04 10:38:04550 return;
551 }
552
553 // Undefined symbols in a SharedFile do not change the binding.
Kazu Hirata62e48ed2021-12-25 05:22:27554 if (isa_and_nonnull<SharedFile>(other.file))
Fangrui Songf3475412019-07-04 10:38:04555 return;
556
Fangrui Songe49c4172019-08-06 14:03:45557 if (isUndefined() || isShared()) {
558 // The binding will be weak if there is at least one reference and all are
559 // weak. The binding has one opportunity to change to weak: if the first
560 // reference is weak.
561 if (other.binding != STB_WEAK || !referenced)
Rui Ueyama3837f422019-07-10 05:00:37562 binding = other.binding;
Rui Ueyama7f7d2b22019-05-23 09:58:08563 }
564}
565
Rui Ueyama7f7d2b22019-05-23 09:58:08566// Compare two symbols. Return 1 if the new symbol should win, -1 if
567// the new symbol should lose, or 0 if there is a conflict.
Rui Ueyama3837f422019-07-10 05:00:37568int Symbol::compare(const Symbol *other) const {
569 assert(other->isDefined() || other->isCommon());
Rui Ueyama7f7d2b22019-05-23 09:58:08570
571 if (!isDefined() && !isCommon())
572 return 1;
573
Fangrui Song2bdad162021-12-15 23:19:35574 // .symver foo,foo@@VER unfortunately creates two defined symbols: foo and
575 // foo@@VER. In GNU ld, if foo and foo@@VER are in the same file, foo is
576 // ignored. In our implementation, when this is foo, this->getName() may still
577 // contain @@, return 1 in this case as well.
578 if (file == other->file) {
579 if (other->getName().contains("@@"))
580 return 1;
581 if (getName().contains("@@"))
582 return -1;
583 }
Rui Ueyama7f7d2b22019-05-23 09:58:08584
Rui Ueyama3837f422019-07-10 05:00:37585 if (other->isWeak())
Rui Ueyama7f7d2b22019-05-23 09:58:08586 return -1;
587
588 if (isWeak())
589 return 1;
590
Rui Ueyama3837f422019-07-10 05:00:37591 if (isCommon() && other->isCommon()) {
592 if (config->warnCommon)
Rui Ueyama7f7d2b22019-05-23 09:58:08593 warn("multiple common of " + getName());
594 return 0;
595 }
596
597 if (isCommon()) {
Rui Ueyama3837f422019-07-10 05:00:37598 if (config->warnCommon)
Rui Ueyama7f7d2b22019-05-23 09:58:08599 warn("common " + getName() + " is overridden");
600 return 1;
601 }
602
Rui Ueyama3837f422019-07-10 05:00:37603 if (other->isCommon()) {
604 if (config->warnCommon)
Rui Ueyama7f7d2b22019-05-23 09:58:08605 warn("common " + getName() + " is overridden");
606 return -1;
607 }
608
Rui Ueyama3837f422019-07-10 05:00:37609 auto *oldSym = cast<Defined>(this);
610 auto *newSym = cast<Defined>(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08611
Kazu Hirata62e48ed2021-12-25 05:22:27612 if (isa_and_nonnull<BitcodeFile>(other->file))
Rui Ueyama7f7d2b22019-05-23 09:58:08613 return 0;
614
Rui Ueyama3837f422019-07-10 05:00:37615 if (!oldSym->section && !newSym->section && oldSym->value == newSym->value &&
616 newSym->binding == STB_GLOBAL)
Rui Ueyama7f7d2b22019-05-23 09:58:08617 return -1;
618
619 return 0;
620}
621
Rui Ueyama3837f422019-07-10 05:00:37622static void reportDuplicate(Symbol *sym, InputFile *newFile,
623 InputSectionBase *errSec, uint64_t errOffset) {
624 if (config->allowMultipleDefinition)
Rui Ueyama7f7d2b22019-05-23 09:58:08625 return;
626
Rui Ueyama3837f422019-07-10 05:00:37627 Defined *d = cast<Defined>(sym);
628 if (!d->section || !errSec) {
629 error("duplicate symbol: " + toString(*sym) + "\n>>> defined in " +
630 toString(sym->file) + "\n>>> defined in " + toString(newFile));
Rui Ueyama7f7d2b22019-05-23 09:58:08631 return;
632 }
633
634 // Construct and print an error message in the form of:
635 //
636 // ld.lld: error: duplicate symbol: foo
637 // >>> defined at bar.c:30
638 // >>> bar.o (/home/alice/src/bar.o)
639 // >>> defined at baz.c:563
640 // >>> baz.o in archive libbaz.a
Rui Ueyama3837f422019-07-10 05:00:37641 auto *sec1 = cast<InputSectionBase>(d->section);
642 std::string src1 = sec1->getSrcMsg(*sym, d->value);
643 std::string obj1 = sec1->getObjMsg(d->value);
644 std::string src2 = errSec->getSrcMsg(*sym, errOffset);
645 std::string obj2 = errSec->getObjMsg(errOffset);
Rui Ueyama7f7d2b22019-05-23 09:58:08646
Rui Ueyama3837f422019-07-10 05:00:37647 std::string msg = "duplicate symbol: " + toString(*sym) + "\n>>> defined at ";
648 if (!src1.empty())
649 msg += src1 + "\n>>> ";
650 msg += obj1 + "\n>>> defined at ";
651 if (!src2.empty())
652 msg += src2 + "\n>>> ";
653 msg += obj2;
654 error(msg);
Rui Ueyama7f7d2b22019-05-23 09:58:08655}
656
Rui Ueyama3837f422019-07-10 05:00:37657void Symbol::resolveCommon(const CommonSymbol &other) {
658 int cmp = compare(&other);
659 if (cmp < 0)
Rui Ueyama7f7d2b22019-05-23 09:58:08660 return;
661
Rui Ueyama3837f422019-07-10 05:00:37662 if (cmp > 0) {
Fangrui Song69d10d22019-12-07 05:18:31663 if (auto *s = dyn_cast<SharedSymbol>(this)) {
664 // Increase st_size if the shared symbol has a larger st_size. The shared
665 // symbol may be created from common symbols. The fact that some object
666 // files were linked into a shared object first should not change the
667 // regular rule that picks the largest st_size.
668 uint64_t size = s->size;
669 replace(other);
670 if (size > cast<CommonSymbol>(this)->size)
671 cast<CommonSymbol>(this)->size = size;
672 } else {
673 replace(other);
674 }
Rui Ueyama7f7d2b22019-05-23 09:58:08675 return;
676 }
677
Rui Ueyama3837f422019-07-10 05:00:37678 CommonSymbol *oldSym = cast<CommonSymbol>(this);
Rui Ueyama7f7d2b22019-05-23 09:58:08679
Rui Ueyama3837f422019-07-10 05:00:37680 oldSym->alignment = std::max(oldSym->alignment, other.alignment);
681 if (oldSym->size < other.size) {
682 oldSym->file = other.file;
683 oldSym->size = other.size;
Rui Ueyama7f7d2b22019-05-23 09:58:08684 }
685}
686
Rui Ueyama3837f422019-07-10 05:00:37687void Symbol::resolveDefined(const Defined &other) {
688 int cmp = compare(&other);
689 if (cmp > 0)
690 replace(other);
691 else if (cmp == 0)
692 reportDuplicate(this, other.file,
693 dyn_cast_or_null<InputSectionBase>(other.section),
694 other.value);
Rui Ueyama7f7d2b22019-05-23 09:58:08695}
696
Sean Fertile8f91f382020-12-07 14:28:17697template <class LazyT>
698static void replaceCommon(Symbol &oldSym, const LazyT &newSym) {
699 backwardReferences.erase(&oldSym);
700 oldSym.replace(newSym);
Fangrui Song09401df2021-11-26 18:58:50701 newSym.extract();
Sean Fertile8f91f382020-12-07 14:28:17702}
703
Rui Ueyama3837f422019-07-10 05:00:37704template <class LazyT> void Symbol::resolveLazy(const LazyT &other) {
Sean Fertile8f91f382020-12-07 14:28:17705 // For common objects, we want to look for global or weak definitions that
Fangrui Song09401df2021-11-26 18:58:50706 // should be extracted as the canonical definition instead.
Sean Fertile8f91f382020-12-07 14:28:17707 if (isCommon() && elf::config->fortranCommon) {
708 if (auto *laSym = dyn_cast<LazyArchive>(&other)) {
709 ArchiveFile *archive = cast<ArchiveFile>(laSym->file);
710 const Archive::Symbol &archiveSym = laSym->sym;
Fangrui Song09401df2021-11-26 18:58:50711 if (archive->shouldExtractForCommon(archiveSym)) {
Sean Fertile8f91f382020-12-07 14:28:17712 replaceCommon(*this, other);
713 return;
714 }
715 } else if (auto *loSym = dyn_cast<LazyObject>(&other)) {
Fangrui Song3a5fb572021-12-23 01:41:50716 if (loSym->file->shouldExtractForCommon(loSym->getName())) {
Sean Fertile8f91f382020-12-07 14:28:17717 replaceCommon(*this, other);
718 return;
719 }
720 }
721 }
722
Fangrui Song03c825c2020-04-06 05:27:46723 if (!isUndefined()) {
724 // See the comment in resolveUndefined().
725 if (isDefined())
726 backwardReferences.erase(this);
Rui Ueyama7f7d2b22019-05-23 09:58:08727 return;
Fangrui Song03c825c2020-04-06 05:27:46728 }
Rui Ueyama7f7d2b22019-05-23 09:58:08729
Fangrui Song09401df2021-11-26 18:58:50730 // An undefined weak will not extract archive members. See comment on Lazy in
Rui Ueyama7f7d2b22019-05-23 09:58:08731 // Symbols.h for the details.
732 if (isWeak()) {
Rui Ueyama3837f422019-07-10 05:00:37733 uint8_t ty = type;
734 replace(other);
735 type = ty;
736 binding = STB_WEAK;
Rui Ueyama7f7d2b22019-05-23 09:58:08737 return;
738 }
739
Fangrui Songa954bb12021-09-20 16:52:30740 const InputFile *oldFile = file;
Fangrui Song09401df2021-11-26 18:58:50741 other.extract();
Fangrui Songa954bb12021-09-20 16:52:30742 if (!config->whyExtract.empty())
743 recordWhyExtract(oldFile, *file, *this);
Rui Ueyama7f7d2b22019-05-23 09:58:08744}
745
Rui Ueyama3837f422019-07-10 05:00:37746void Symbol::resolveShared(const SharedSymbol &other) {
Fangrui Song69d10d22019-12-07 05:18:31747 if (isCommon()) {
748 // See the comment in resolveCommon() above.
749 if (other.size > cast<CommonSymbol>(this)->size)
750 cast<CommonSymbol>(this)->size = other.size;
751 return;
752 }
Rui Ueyama3837f422019-07-10 05:00:37753 if (visibility == STV_DEFAULT && (isUndefined() || isLazy())) {
Rui Ueyama7f7d2b22019-05-23 09:58:08754 // An undefined symbol with non default visibility must be satisfied
755 // in the same DSO.
Rui Ueyama3837f422019-07-10 05:00:37756 uint8_t bind = binding;
757 replace(other);
758 binding = bind;
Fangrui Song64676492020-05-18 17:15:59759 } else if (traced)
760 printTraceSymbol(&other);
Rui Ueyama7f7d2b22019-05-23 09:58:08761}