blob: 20301497a059eb2a45420ab09022cdaca817dec1 [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);
219 if (verstr.empty())
Rui Ueyama35fa6c52016-11-23 05:48:40220 return;
221
222 // Truncate the symbol name so that it doesn't include the version string.
Rui Ueyama3837f422019-07-10 05:00:37223 nameSize = pos;
Rui Ueyama35fa6c52016-11-23 05:48:40224
Rafael Espindola1d6d1b42017-01-17 16:08:06225 // If this is not in this DSO, it is not a definition.
Peter Collingbourneb472aa02017-11-06 04:39:07226 if (!isDefined())
Rafael Espindola2756e042017-01-06 22:30:35227 return;
228
Rui Ueyama35fa6c52016-11-23 05:48:40229 // '@@' in a symbol name means the default version.
230 // It is usually the most recent one.
Rui Ueyama3837f422019-07-10 05:00:37231 bool isDefault = (verstr[0] == '@');
232 if (isDefault)
233 verstr = verstr.substr(1);
Rui Ueyama35fa6c52016-11-23 05:48:40234
Fangrui Songe28a70d2019-08-05 14:31:39235 for (const VersionDefinition &ver : namedVersionDefs()) {
Rui Ueyama3837f422019-07-10 05:00:37236 if (ver.name != verstr)
Rui Ueyama35fa6c52016-11-23 05:48:40237 continue;
238
Rui Ueyama3837f422019-07-10 05:00:37239 if (isDefault)
240 versionId = ver.id;
Rui Ueyama35fa6c52016-11-23 05:48:40241 else
Rui Ueyama3837f422019-07-10 05:00:37242 versionId = ver.id | VERSYM_HIDDEN;
Rui Ueyama35fa6c52016-11-23 05:48:40243 return;
244 }
245
246 // It is an error if the specified version is not defined.
George Rimar4d2f97622017-07-04 13:19:13247 // Usually version script is not provided when linking executable,
248 // but we may still want to override a versioned symbol from DSO,
Peter Smith796fb992018-05-14 10:13:56249 // so we do not report error in this case. We also do not error
250 // if the symbol has a local version as it won't be in the dynamic
251 // symbol table.
Rui Ueyama3837f422019-07-10 05:00:37252 if (config->shared && versionId != VER_NDX_LOCAL)
253 error(toString(file) + ": symbol " + s + " has undefined version " +
254 verstr);
Rui Ueyama35fa6c52016-11-23 05:48:40255}
256
Fangrui Song09401df2021-11-26 18:58:50257void Symbol::extract() const {
Fangrui Song3a5fb572021-12-23 01:41:50258 if (auto *sym = dyn_cast<LazyArchive>(this)) {
Fangrui Song09401df2021-11-26 18:58:50259 cast<ArchiveFile>(sym->file)->extract(sym->sym);
Fangrui Song3a5fb572021-12-23 01:41:50260 } else if (file->lazy) {
261 file->lazy = false;
262 parseFile(file);
263 }
Rui Ueyama7d476192019-05-16 02:14:00264}
Rui Ueyamaf8baa662016-04-07 19:24:51265
Peter Collingbourne98930112018-08-08 23:48:12266MemoryBufferRef LazyArchive::getMemberBuffer() {
Nico Weber9c0716f2019-07-23 19:00:01267 Archive::Child c =
268 CHECK(sym.getMember(),
269 "could not get the member for symbol " + toELFString(sym));
Peter Collingbourne98930112018-08-08 23:48:12270
Rui Ueyama3837f422019-07-10 05:00:37271 return CHECK(c.getMemoryBufferRef(),
Peter Collingbourne98930112018-08-08 23:48:12272 "could not get the buffer for the member defining symbol " +
Nico Weber9c0716f2019-07-23 19:00:01273 toELFString(sym));
Peter Collingbourne98930112018-08-08 23:48:12274}
275
Rui Ueyamaf52496e2017-11-03 21:21:47276uint8_t Symbol::computeBinding() const {
Rui Ueyama3837f422019-07-10 05:00:37277 if (config->relocatable)
278 return binding;
Fangrui Songcfdd4582019-08-11 17:03:00279 if ((visibility != STV_DEFAULT && visibility != STV_PROTECTED) ||
Nathan Lanza2f651662021-03-16 08:33:50280 (versionId == VER_NDX_LOCAL && !isLazy()))
Rafael Espindolab7e2ee22017-01-10 17:08:13281 return STB_LOCAL;
Rui Ueyama3837f422019-07-10 05:00:37282 if (!config->gnuUnique && binding == STB_GNU_UNIQUE)
Rafael Espindolab7e2ee22017-01-10 17:08:13283 return STB_GLOBAL;
Rui Ueyama3837f422019-07-10 05:00:37284 return binding;
Rafael Espindolab7e2ee22017-01-10 17:08:13285}
286
Rui Ueyamaf52496e2017-11-03 21:21:47287bool Symbol::includeInDynsym() const {
Rui Ueyama3837f422019-07-10 05:00:37288 if (!config->hasDynSymTab)
Rafael Espindolae05e2f82017-09-15 18:05:02289 return false;
Rafael Espindolab7e2ee22017-01-10 17:08:13290 if (computeBinding() == STB_LOCAL)
Rafael Espindolaae605c12016-04-21 20:35:25291 return false;
Fangrui Song375371c2020-01-09 23:53:52292 if (!isDefined() && !isCommon())
Fangrui Song0fbf28f2020-01-23 19:52:03293 // This should unconditionally return true, unfortunately glibc -static-pie
294 // expects undefined weak symbols not to exist in .dynsym, e.g.
295 // __pthread_mutex_lock reference in _dl_add_to_namespace_list,
296 // __pthread_initialize_minimal reference in csu/libc-start.c.
297 return !(config->noDynamicLinker && isUndefWeak());
Rui Ueyamae63ae7f2019-06-25 06:58:07298
Fangrui Song375371c2020-01-09 23:53:52299 return exportDynamic || inDynamicList;
Rafael Espindolaae605c12016-04-21 20:35:25300}
Rui Ueyama69c778c2016-07-17 17:50:09301
302// Print out a log message for --trace-symbol.
Fangrui Song07837b82020-05-15 05:18:58303void elf::printTraceSymbol(const Symbol *sym) {
Rui Ueyama3837f422019-07-10 05:00:37304 std::string s;
305 if (sym->isUndefined())
306 s = ": reference to ";
307 else if (sym->isLazy())
308 s = ": lazy definition of ";
309 else if (sym->isShared())
310 s = ": shared definition of ";
311 else if (sym->isCommon())
312 s = ": common definition of ";
Rui Ueyama69c778c2016-07-17 17:50:09313 else
Rui Ueyama3837f422019-07-10 05:00:37314 s = ": definition of ";
Rui Ueyamae6e206d2017-02-21 23:22:56315
Rui Ueyama3837f422019-07-10 05:00:37316 message(toString(sym->file) + s + sym->getName());
Rui Ueyama69c778c2016-07-17 17:50:09317}
318
Fangrui Songa954bb12021-09-20 16:52:30319static void recordWhyExtract(const InputFile *reference,
320 const InputFile &extracted, const Symbol &sym) {
321 whyExtract.emplace_back(toString(reference), &extracted, sym);
322}
323
Fangrui Song07837b82020-05-15 05:18:58324void elf::maybeWarnUnorderableSymbol(const Symbol *sym) {
Rui Ueyama3837f422019-07-10 05:00:37325 if (!config->warnSymbolOrdering)
Michael J. Spencerb8427252018-04-17 23:30:05326 return;
Rui Ueyamab774c3c2018-04-26 01:38:29327
Fangrui Song11ca54f2018-10-10 22:48:57328 // If UnresolvedPolicy::Ignore is used, no "undefined symbol" error/warning
329 // is emitted. It makes sense to not warn on undefined symbols.
330 //
331 // Note, ld.bfd --symbol-ordering-file= does not warn on undefined symbols,
332 // but we don't have to be compatible here.
Rui Ueyama3837f422019-07-10 05:00:37333 if (sym->isUndefined() &&
334 config->unresolvedSymbols == UnresolvedPolicy::Ignore)
Fangrui Song11ca54f2018-10-10 22:48:57335 return;
336
Rui Ueyama3837f422019-07-10 05:00:37337 const InputFile *file = sym->file;
338 auto *d = dyn_cast<Defined>(sym);
Rui Ueyamab774c3c2018-04-26 01:38:29339
Rui Ueyama3837f422019-07-10 05:00:37340 auto report = [&](StringRef s) { warn(toString(file) + s + sym->getName()); };
Rui Ueyamab774c3c2018-04-26 01:38:29341
Rui Ueyama3837f422019-07-10 05:00:37342 if (sym->isUndefined())
343 report(": unable to order undefined symbol: ");
344 else if (sym->isShared())
345 report(": unable to order shared symbol: ");
346 else if (d && !d->section)
347 report(": unable to order absolute symbol: ");
348 else if (d && isa<OutputSection>(d->section))
349 report(": unable to order synthetic symbol: ");
Fangrui Songe1b6b5b2021-12-24 20:09:48350 else if (d && !d->section->isLive())
Rui Ueyama3837f422019-07-10 05:00:37351 report(": unable to order discarded symbol: ");
Michael J. Spencerb8427252018-04-17 23:30:05352}
353
Fangrui Songcd0ab242019-11-30 05:58:36354// Returns true if a symbol can be replaced at load-time by a symbol
355// with the same name defined in other ELF executable or DSO.
Fangrui Song07837b82020-05-15 05:18:58356bool elf::computeIsPreemptible(const Symbol &sym) {
Fangrui Songcd0ab242019-11-30 05:58:36357 assert(!sym.isLocal());
358
359 // Only symbols with default visibility that appear in dynsym can be
360 // preempted. Symbols with protected visibility cannot be preempted.
361 if (!sym.includeInDynsym() || sym.visibility != STV_DEFAULT)
362 return false;
363
364 // At this point copy relocations have not been created yet, so any
365 // symbol that is not defined locally is preemptible.
366 if (!sym.isDefined())
367 return true;
368
369 if (!config->shared)
370 return false;
371
Fangrui Song751f18e2020-06-01 18:27:53372 // If -Bsymbolic or --dynamic-list is specified, or -Bsymbolic-functions is
373 // specified and the symbol is STT_FUNC, the symbol is preemptible iff it is
Fangrui Songb06426d2021-07-29 21:46:53374 // in the dynamic list. -Bsymbolic-non-weak-functions is a non-weak subset of
375 // -Bsymbolic-functions.
376 if (config->symbolic ||
377 (config->bsymbolic == BsymbolicKind::Functions && sym.isFunc()) ||
378 (config->bsymbolic == BsymbolicKind::NonWeakFunctions && sym.isFunc() &&
379 sym.binding != STB_WEAK))
Fangrui Songcd0ab242019-11-30 05:58:36380 return sym.inDynamicList;
Fangrui Songcd0ab242019-11-30 05:58:36381 return true;
382}
383
Fangrui Song07837b82020-05-15 05:18:58384void elf::reportBackrefs() {
Fangrui Song03c825c2020-04-06 05:27:46385 for (auto &it : backwardReferences) {
386 const Symbol &sym = *it.first;
Fangrui Song3ba334222020-11-08 04:17:41387 std::string to = toString(it.second.second);
388 // Some libraries have known problems and can cause noise. Filter them out
389 // with --warn-backrefs-exclude=. to may look like *.o or *.a(*.o).
390 bool exclude = false;
391 for (const llvm::GlobPattern &pat : config->warnBackrefsExclude)
392 if (pat.match(to)) {
393 exclude = true;
394 break;
395 }
396 if (!exclude)
397 warn("backward reference detected: " + sym.getName() + " in " +
398 toString(it.second.first) + " refers to " + to);
Fangrui Song03c825c2020-04-06 05:27:46399 }
400}
401
Rui Ueyama3837f422019-07-10 05:00:37402static uint8_t getMinVisibility(uint8_t va, uint8_t vb) {
403 if (va == STV_DEFAULT)
404 return vb;
405 if (vb == STV_DEFAULT)
406 return va;
407 return std::min(va, vb);
Rui Ueyama7f7d2b22019-05-23 09:58:08408}
409
410// Merge symbol properties.
411//
412// When we have many symbols of the same name, we choose one of them,
413// and that's the result of symbol resolution. However, symbols that
414// were not chosen still affect some symbol properties.
Rui Ueyama3837f422019-07-10 05:00:37415void Symbol::mergeProperties(const Symbol &other) {
416 if (other.exportDynamic)
417 exportDynamic = true;
418 if (other.isUsedInRegularObj)
419 isUsedInRegularObj = true;
Rui Ueyama7f7d2b22019-05-23 09:58:08420
421 // DSO symbols do not affect visibility in the output.
Rui Ueyama3837f422019-07-10 05:00:37422 if (!other.isShared())
423 visibility = getMinVisibility(visibility, other.visibility);
Rui Ueyama7f7d2b22019-05-23 09:58:08424}
425
Rui Ueyama3837f422019-07-10 05:00:37426void Symbol::resolve(const Symbol &other) {
427 mergeProperties(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08428
429 if (isPlaceholder()) {
Rui Ueyama3837f422019-07-10 05:00:37430 replace(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08431 return;
432 }
433
Rui Ueyama3837f422019-07-10 05:00:37434 switch (other.kind()) {
Rui Ueyama7f7d2b22019-05-23 09:58:08435 case Symbol::UndefinedKind:
Rui Ueyama3837f422019-07-10 05:00:37436 resolveUndefined(cast<Undefined>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08437 break;
438 case Symbol::CommonKind:
Rui Ueyama3837f422019-07-10 05:00:37439 resolveCommon(cast<CommonSymbol>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08440 break;
441 case Symbol::DefinedKind:
Rui Ueyama3837f422019-07-10 05:00:37442 resolveDefined(cast<Defined>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08443 break;
444 case Symbol::LazyArchiveKind:
Rui Ueyama3837f422019-07-10 05:00:37445 resolveLazy(cast<LazyArchive>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08446 break;
447 case Symbol::LazyObjectKind:
Rui Ueyama3837f422019-07-10 05:00:37448 resolveLazy(cast<LazyObject>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08449 break;
450 case Symbol::SharedKind:
Rui Ueyama3837f422019-07-10 05:00:37451 resolveShared(cast<SharedSymbol>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08452 break;
453 case Symbol::PlaceholderKind:
454 llvm_unreachable("bad symbol kind");
455 }
456}
457
Rui Ueyama3837f422019-07-10 05:00:37458void Symbol::resolveUndefined(const Undefined &other) {
Rui Ueyama7f7d2b22019-05-23 09:58:08459 // An undefined symbol with non default visibility must be satisfied
460 // in the same DSO.
461 //
462 // If this is a non-weak defined symbol in a discarded section, override the
463 // existing undefined symbol for better error message later.
Rui Ueyama3837f422019-07-10 05:00:37464 if ((isShared() && other.visibility != STV_DEFAULT) ||
465 (isUndefined() && other.binding != STB_WEAK && other.discardedSecIdx)) {
466 replace(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08467 return;
468 }
469
Rui Ueyama3837f422019-07-10 05:00:37470 if (traced)
471 printTraceSymbol(&other);
Sam Clegg7991b682019-05-24 13:29:17472
Fangrui Songf3475412019-07-04 10:38:04473 if (isLazy()) {
Fangrui Song09401df2021-11-26 18:58:50474 // An undefined weak will not extract archive members. See comment on Lazy
475 // in Symbols.h for the details.
Rui Ueyama3837f422019-07-10 05:00:37476 if (other.binding == STB_WEAK) {
477 binding = STB_WEAK;
478 type = other.type;
Rui Ueyama7f7d2b22019-05-23 09:58:08479 return;
480 }
481
482 // Do extra check for --warn-backrefs.
483 //
484 // --warn-backrefs is an option to prevent an undefined reference from
Fangrui Song09401df2021-11-26 18:58:50485 // extracting an archive member written earlier in the command line. It can
486 // be used to keep compatibility with GNU linkers to some degree. I'll
487 // explain the feature and why you may find it useful in this comment.
Rui Ueyama7f7d2b22019-05-23 09:58:08488 //
489 // lld's symbol resolution semantics is more relaxed than traditional Unix
490 // linkers. For example,
491 //
492 // ld.lld foo.a bar.o
493 //
494 // succeeds even if bar.o contains an undefined symbol that has to be
495 // resolved by some object file in foo.a. Traditional Unix linkers don't
496 // allow this kind of backward reference, as they visit each file only once
497 // from left to right in the command line while resolving all undefined
498 // symbols at the moment of visiting.
499 //
500 // In the above case, since there's no undefined symbol when a linker visits
501 // foo.a, no files are pulled out from foo.a, and because the linker forgets
502 // about foo.a after visiting, it can't resolve undefined symbols in bar.o
503 // that could have been resolved otherwise.
504 //
505 // That lld accepts more relaxed form means that (besides it'd make more
506 // sense) you can accidentally write a command line or a build file that
507 // works only with lld, even if you have a plan to distribute it to wider
508 // users who may be using GNU linkers. With --warn-backrefs, you can detect
509 // a library order that doesn't work with other Unix linkers.
510 //
511 // The option is also useful to detect cyclic dependencies between static
512 // archives. Again, lld accepts
513 //
514 // ld.lld foo.a bar.a
515 //
516 // even if foo.a and bar.a depend on each other. With --warn-backrefs, it is
517 // handled as an error.
518 //
519 // Here is how the option works. We assign a group ID to each file. A file
520 // with a smaller group ID can pull out object files from an archive file
521 // with an equal or greater group ID. Otherwise, it is a reverse dependency
522 // and an error.
523 //
524 // A file outside --{start,end}-group gets a fresh ID when instantiated. All
525 // files within the same --{start,end}-group get the same group ID. E.g.
526 //
527 // ld.lld A B --start-group C D --end-group E
528 //
529 // A forms group 0. B form group 1. C and D (including their member object
530 // files) form group 2. E forms group 3. I think that you can see how this
531 // group assignment rule simulates the traditional linker's semantics.
Rui Ueyama3837f422019-07-10 05:00:37532 bool backref = config->warnBackrefs && other.file &&
533 file->groupId < other.file->groupId;
Fangrui Song09401df2021-11-26 18:58:50534 extract();
Rui Ueyama7f7d2b22019-05-23 09:58:08535
Fangrui Songa954bb12021-09-20 16:52:30536 if (!config->whyExtract.empty())
537 recordWhyExtract(other.file, *file, *this);
538
Rui Ueyama7f7d2b22019-05-23 09:58:08539 // We don't report backward references to weak symbols as they can be
540 // overridden later.
Fangrui Song03c825c2020-04-06 05:27:46541 //
542 // A traditional linker does not error for -ldef1 -lref -ldef2 (linking
543 // sandwich), where def2 may or may not be the same as def1. We don't want
544 // to warn for this case, so dismiss the warning if we see a subsequent lazy
Fangrui Songce3c5da2020-10-22 22:26:52545 // definition. this->file needs to be saved because in the case of LTO it
546 // may be reset to nullptr or be replaced with a file named lto.tmp.
Rui Ueyama3837f422019-07-10 05:00:37547 if (backref && !isWeak())
Fangrui Songce3c5da2020-10-22 22:26:52548 backwardReferences.try_emplace(this, std::make_pair(other.file, file));
Fangrui Songf3475412019-07-04 10:38:04549 return;
550 }
551
552 // Undefined symbols in a SharedFile do not change the binding.
Kazu Hirata62e48ed2021-12-25 05:22:27553 if (isa_and_nonnull<SharedFile>(other.file))
Fangrui Songf3475412019-07-04 10:38:04554 return;
555
Fangrui Songe49c4172019-08-06 14:03:45556 if (isUndefined() || isShared()) {
557 // The binding will be weak if there is at least one reference and all are
558 // weak. The binding has one opportunity to change to weak: if the first
559 // reference is weak.
560 if (other.binding != STB_WEAK || !referenced)
Rui Ueyama3837f422019-07-10 05:00:37561 binding = other.binding;
Rui Ueyama7f7d2b22019-05-23 09:58:08562 }
563}
564
Rui Ueyama7f7d2b22019-05-23 09:58:08565// Compare two symbols. Return 1 if the new symbol should win, -1 if
566// the new symbol should lose, or 0 if there is a conflict.
Rui Ueyama3837f422019-07-10 05:00:37567int Symbol::compare(const Symbol *other) const {
568 assert(other->isDefined() || other->isCommon());
Rui Ueyama7f7d2b22019-05-23 09:58:08569
570 if (!isDefined() && !isCommon())
571 return 1;
572
Fangrui Song2bdad162021-12-15 23:19:35573 // .symver foo,foo@@VER unfortunately creates two defined symbols: foo and
574 // foo@@VER. In GNU ld, if foo and foo@@VER are in the same file, foo is
575 // ignored. In our implementation, when this is foo, this->getName() may still
576 // contain @@, return 1 in this case as well.
577 if (file == other->file) {
578 if (other->getName().contains("@@"))
579 return 1;
580 if (getName().contains("@@"))
581 return -1;
582 }
Rui Ueyama7f7d2b22019-05-23 09:58:08583
Rui Ueyama3837f422019-07-10 05:00:37584 if (other->isWeak())
Rui Ueyama7f7d2b22019-05-23 09:58:08585 return -1;
586
587 if (isWeak())
588 return 1;
589
Rui Ueyama3837f422019-07-10 05:00:37590 if (isCommon() && other->isCommon()) {
591 if (config->warnCommon)
Rui Ueyama7f7d2b22019-05-23 09:58:08592 warn("multiple common of " + getName());
593 return 0;
594 }
595
596 if (isCommon()) {
Rui Ueyama3837f422019-07-10 05:00:37597 if (config->warnCommon)
Rui Ueyama7f7d2b22019-05-23 09:58:08598 warn("common " + getName() + " is overridden");
599 return 1;
600 }
601
Rui Ueyama3837f422019-07-10 05:00:37602 if (other->isCommon()) {
603 if (config->warnCommon)
Rui Ueyama7f7d2b22019-05-23 09:58:08604 warn("common " + getName() + " is overridden");
605 return -1;
606 }
607
Rui Ueyama3837f422019-07-10 05:00:37608 auto *oldSym = cast<Defined>(this);
609 auto *newSym = cast<Defined>(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08610
Kazu Hirata62e48ed2021-12-25 05:22:27611 if (isa_and_nonnull<BitcodeFile>(other->file))
Rui Ueyama7f7d2b22019-05-23 09:58:08612 return 0;
613
Rui Ueyama3837f422019-07-10 05:00:37614 if (!oldSym->section && !newSym->section && oldSym->value == newSym->value &&
615 newSym->binding == STB_GLOBAL)
Rui Ueyama7f7d2b22019-05-23 09:58:08616 return -1;
617
618 return 0;
619}
620
Rui Ueyama3837f422019-07-10 05:00:37621static void reportDuplicate(Symbol *sym, InputFile *newFile,
622 InputSectionBase *errSec, uint64_t errOffset) {
623 if (config->allowMultipleDefinition)
Rui Ueyama7f7d2b22019-05-23 09:58:08624 return;
625
Rui Ueyama3837f422019-07-10 05:00:37626 Defined *d = cast<Defined>(sym);
627 if (!d->section || !errSec) {
628 error("duplicate symbol: " + toString(*sym) + "\n>>> defined in " +
629 toString(sym->file) + "\n>>> defined in " + toString(newFile));
Rui Ueyama7f7d2b22019-05-23 09:58:08630 return;
631 }
632
633 // Construct and print an error message in the form of:
634 //
635 // ld.lld: error: duplicate symbol: foo
636 // >>> defined at bar.c:30
637 // >>> bar.o (/home/alice/src/bar.o)
638 // >>> defined at baz.c:563
639 // >>> baz.o in archive libbaz.a
Rui Ueyama3837f422019-07-10 05:00:37640 auto *sec1 = cast<InputSectionBase>(d->section);
641 std::string src1 = sec1->getSrcMsg(*sym, d->value);
642 std::string obj1 = sec1->getObjMsg(d->value);
643 std::string src2 = errSec->getSrcMsg(*sym, errOffset);
644 std::string obj2 = errSec->getObjMsg(errOffset);
Rui Ueyama7f7d2b22019-05-23 09:58:08645
Rui Ueyama3837f422019-07-10 05:00:37646 std::string msg = "duplicate symbol: " + toString(*sym) + "\n>>> defined at ";
647 if (!src1.empty())
648 msg += src1 + "\n>>> ";
649 msg += obj1 + "\n>>> defined at ";
650 if (!src2.empty())
651 msg += src2 + "\n>>> ";
652 msg += obj2;
653 error(msg);
Rui Ueyama7f7d2b22019-05-23 09:58:08654}
655
Rui Ueyama3837f422019-07-10 05:00:37656void Symbol::resolveCommon(const CommonSymbol &other) {
657 int cmp = compare(&other);
658 if (cmp < 0)
Rui Ueyama7f7d2b22019-05-23 09:58:08659 return;
660
Rui Ueyama3837f422019-07-10 05:00:37661 if (cmp > 0) {
Fangrui Song69d10d22019-12-07 05:18:31662 if (auto *s = dyn_cast<SharedSymbol>(this)) {
663 // Increase st_size if the shared symbol has a larger st_size. The shared
664 // symbol may be created from common symbols. The fact that some object
665 // files were linked into a shared object first should not change the
666 // regular rule that picks the largest st_size.
667 uint64_t size = s->size;
668 replace(other);
669 if (size > cast<CommonSymbol>(this)->size)
670 cast<CommonSymbol>(this)->size = size;
671 } else {
672 replace(other);
673 }
Rui Ueyama7f7d2b22019-05-23 09:58:08674 return;
675 }
676
Rui Ueyama3837f422019-07-10 05:00:37677 CommonSymbol *oldSym = cast<CommonSymbol>(this);
Rui Ueyama7f7d2b22019-05-23 09:58:08678
Rui Ueyama3837f422019-07-10 05:00:37679 oldSym->alignment = std::max(oldSym->alignment, other.alignment);
680 if (oldSym->size < other.size) {
681 oldSym->file = other.file;
682 oldSym->size = other.size;
Rui Ueyama7f7d2b22019-05-23 09:58:08683 }
684}
685
Rui Ueyama3837f422019-07-10 05:00:37686void Symbol::resolveDefined(const Defined &other) {
687 int cmp = compare(&other);
688 if (cmp > 0)
689 replace(other);
690 else if (cmp == 0)
691 reportDuplicate(this, other.file,
692 dyn_cast_or_null<InputSectionBase>(other.section),
693 other.value);
Rui Ueyama7f7d2b22019-05-23 09:58:08694}
695
Sean Fertile8f91f382020-12-07 14:28:17696template <class LazyT>
697static void replaceCommon(Symbol &oldSym, const LazyT &newSym) {
698 backwardReferences.erase(&oldSym);
699 oldSym.replace(newSym);
Fangrui Song09401df2021-11-26 18:58:50700 newSym.extract();
Sean Fertile8f91f382020-12-07 14:28:17701}
702
Rui Ueyama3837f422019-07-10 05:00:37703template <class LazyT> void Symbol::resolveLazy(const LazyT &other) {
Sean Fertile8f91f382020-12-07 14:28:17704 // For common objects, we want to look for global or weak definitions that
Fangrui Song09401df2021-11-26 18:58:50705 // should be extracted as the canonical definition instead.
Sean Fertile8f91f382020-12-07 14:28:17706 if (isCommon() && elf::config->fortranCommon) {
707 if (auto *laSym = dyn_cast<LazyArchive>(&other)) {
708 ArchiveFile *archive = cast<ArchiveFile>(laSym->file);
709 const Archive::Symbol &archiveSym = laSym->sym;
Fangrui Song09401df2021-11-26 18:58:50710 if (archive->shouldExtractForCommon(archiveSym)) {
Sean Fertile8f91f382020-12-07 14:28:17711 replaceCommon(*this, other);
712 return;
713 }
714 } else if (auto *loSym = dyn_cast<LazyObject>(&other)) {
Fangrui Song3a5fb572021-12-23 01:41:50715 if (loSym->file->shouldExtractForCommon(loSym->getName())) {
Sean Fertile8f91f382020-12-07 14:28:17716 replaceCommon(*this, other);
717 return;
718 }
719 }
720 }
721
Fangrui Song03c825c2020-04-06 05:27:46722 if (!isUndefined()) {
723 // See the comment in resolveUndefined().
724 if (isDefined())
725 backwardReferences.erase(this);
Rui Ueyama7f7d2b22019-05-23 09:58:08726 return;
Fangrui Song03c825c2020-04-06 05:27:46727 }
Rui Ueyama7f7d2b22019-05-23 09:58:08728
Fangrui Song09401df2021-11-26 18:58:50729 // An undefined weak will not extract archive members. See comment on Lazy in
Rui Ueyama7f7d2b22019-05-23 09:58:08730 // Symbols.h for the details.
731 if (isWeak()) {
Rui Ueyama3837f422019-07-10 05:00:37732 uint8_t ty = type;
733 replace(other);
734 type = ty;
735 binding = STB_WEAK;
Rui Ueyama7f7d2b22019-05-23 09:58:08736 return;
737 }
738
Fangrui Songa954bb12021-09-20 16:52:30739 const InputFile *oldFile = file;
Fangrui Song09401df2021-11-26 18:58:50740 other.extract();
Fangrui Songa954bb12021-09-20 16:52:30741 if (!config->whyExtract.empty())
742 recordWhyExtract(oldFile, *file, *this);
Rui Ueyama7f7d2b22019-05-23 09:58:08743}
744
Rui Ueyama3837f422019-07-10 05:00:37745void Symbol::resolveShared(const SharedSymbol &other) {
Fangrui Song69d10d22019-12-07 05:18:31746 if (isCommon()) {
747 // See the comment in resolveCommon() above.
748 if (other.size > cast<CommonSymbol>(this)->size)
749 cast<CommonSymbol>(this)->size = other.size;
750 return;
751 }
Rui Ueyama3837f422019-07-10 05:00:37752 if (visibility == STV_DEFAULT && (isUndefined() || isLazy())) {
Rui Ueyama7f7d2b22019-05-23 09:58:08753 // An undefined symbol with non default visibility must be satisfied
754 // in the same DSO.
Rui Ueyama3837f422019-07-10 05:00:37755 uint8_t bind = binding;
756 replace(other);
757 binding = bind;
Fangrui Song64676492020-05-18 17:15:59758 } else if (traced)
759 printTraceSymbol(&other);
Rui Ueyama7f7d2b22019-05-23 09:58:08760}