blob: 8f2f55418df5f94e98825f3bfe6fb995422ceb0e [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
40 // If sym has a non-default version, its name may have been truncated at '@'
41 // by Symbol::parseSymbolVersion(). Add the trailing part. This check is safe
42 // because every symbol name ends with '\0'.
43 if (name.data()[name.size()] == '@')
44 ret += name.data() + name.size();
45 return ret;
46}
47
Fangrui Song07837b82020-05-15 05:18:5848std::string lld::toELFString(const Archive::Symbol &b) {
Fangrui Songbd8cfe62019-10-07 08:31:1849 return demangle(b.getName());
50}
51
Rui Ueyama3837f422019-07-10 05:00:3752Defined *ElfSym::bss;
53Defined *ElfSym::etext1;
54Defined *ElfSym::etext2;
55Defined *ElfSym::edata1;
56Defined *ElfSym::edata2;
57Defined *ElfSym::end1;
58Defined *ElfSym::end2;
59Defined *ElfSym::globalOffsetTable;
60Defined *ElfSym::mipsGp;
61Defined *ElfSym::mipsGpDisp;
62Defined *ElfSym::mipsLocalGp;
63Defined *ElfSym::relaIpltStart;
64Defined *ElfSym::relaIpltEnd;
65Defined *ElfSym::riscvGlobalPointer;
66Defined *ElfSym::tlsModuleBase;
Fangrui Song07837b82020-05-15 05:18:5867DenseMap<const Symbol *, const InputFile *> elf::backwardReferences;
Rui Ueyama80474a22017-02-28 19:29:5568
Rui Ueyama3837f422019-07-10 05:00:3769static uint64_t getSymVA(const Symbol &sym, int64_t &addend) {
70 switch (sym.kind()) {
Peter Collingbournee9a9e0a2017-11-06 04:35:3171 case Symbol::DefinedKind: {
Rui Ueyama3837f422019-07-10 05:00:3772 auto &d = cast<Defined>(sym);
73 SectionBase *isec = d.section;
Rui Ueyamab5a69702016-02-01 21:00:3574
75 // This is an absolute symbol.
Rui Ueyama3837f422019-07-10 05:00:3776 if (!isec)
77 return d.value;
Rui Ueyamab5a69702016-02-01 21:00:3578
Rui Ueyama3837f422019-07-10 05:00:3779 assert(isec != &InputSection::discarded);
80 isec = isec->repl;
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.
Rui Ueyama3837f422019-07-10 05:00:3795 if (d.isSection()) {
96 offset += addend;
97 addend = 0;
Rafael Espindola1f5b70f2016-03-11 14:21:3798 }
Sean Silvaa9ba4502017-02-28 08:32:5699
Sean Silva6ab39262017-02-28 09:01:58100 // In the typical case, this is actually very simple and boils
101 // down to adding together 3 numbers:
102 // 1. The address of the output section.
103 // 2. The offset of the input section within the output section.
104 // 3. The offset within the input section (this addition happens
105 // inside InputSection::getOffset).
106 //
107 // If you understand the data structures involved with this next
108 // line (and how they get built), then you have a pretty good
109 // understanding of the linker.
Rui Ueyama3837f422019-07-10 05:00:37110 uint64_t va = isec->getVA(offset);
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() &&
122 ((sym.stOther & STO_MIPS_MICROMIPS) || sym.needsPltAddr))
123 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 {
154 uint64_t outVA = getSymVA(*this, addend);
155 return outVA + 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
Rui Ueyama3837f422019-07-10 05:00:37164uint64_t Symbol::getGotOffset() const { return gotIndex * config->wordsize; }
Rui Ueyamab5a69702016-02-01 21:00:35165
Rui Ueyamaf52496e2017-11-03 21:21:47166uint64_t Symbol::getGotPltVA() const {
Rui Ueyama3837f422019-07-10 05:00:37167 if (isInIplt)
168 return in.igotPlt->getVA() + getGotPltOffset();
169 return in.gotPlt->getVA() + getGotPltOffset();
Rafael Espindola74031ba2016-04-07 15:20:56170}
171
Rui Ueyamaf52496e2017-11-03 21:21:47172uint64_t Symbol::getGotPltOffset() const {
Rui Ueyama3837f422019-07-10 05:00:37173 if (isInIplt)
174 return pltIndex * config->wordsize;
175 return (pltIndex + target->gotPltHeaderEntriesNum) * config->wordsize;
Rui Ueyamab5a69702016-02-01 21:00:35176}
177
Rui Ueyamaf52496e2017-11-03 21:21:47178uint64_t Symbol::getPltVA() const {
Fangrui Song891a8652019-12-14 22:17:35179 uint64_t outVA = isInIplt
180 ? in.iplt->getVA() + pltIndex * target->ipltEntrySize
181 : in.plt->getVA() + in.plt->headerSize +
182 pltIndex * target->pltEntrySize;
183
Simon Atanasyanfae2a5092019-02-19 10:36:58184 // While linking microMIPS code PLT code are always microMIPS
185 // code. Set the less-significant bit to track that fact.
186 // See detailed comment in the `getSymVA` function.
Rui Ueyama3837f422019-07-10 05:00:37187 if (config->emachine == EM_MIPS && isMicroMips())
188 outVA |= 1;
189 return outVA;
Rafael Espindolaab0cce52018-04-26 17:58:58190}
191
Rui Ueyamaf52496e2017-11-03 21:21:47192uint64_t Symbol::getSize() const {
Rui Ueyama3837f422019-07-10 05:00:37193 if (const auto *dr = dyn_cast<Defined>(this))
194 return dr->size;
195 return cast<SharedSymbol>(this)->size;
Rui Ueyama512c61d2016-02-03 00:12:24196}
197
Rui Ueyamaf52496e2017-11-03 21:21:47198OutputSection *Symbol::getOutputSection() const {
Rui Ueyama3837f422019-07-10 05:00:37199 if (auto *s = dyn_cast<Defined>(this)) {
200 if (auto *sec = s->section)
201 return sec->repl->getOutputSection();
Rui Ueyama968db482017-02-28 04:02:42202 return nullptr;
203 }
Rui Ueyama968db482017-02-28 04:02:42204 return nullptr;
205}
206
Rui Ueyama35fa6c52016-11-23 05:48:40207// If a symbol name contains '@', the characters after that is
208// a symbol version name. This function parses that.
Rui Ueyamaf52496e2017-11-03 21:21:47209void Symbol::parseSymbolVersion() {
Rui Ueyama3837f422019-07-10 05:00:37210 StringRef s = getName();
211 size_t pos = s.find('@');
212 if (pos == 0 || pos == StringRef::npos)
Rui Ueyama35fa6c52016-11-23 05:48:40213 return;
Rui Ueyama3837f422019-07-10 05:00:37214 StringRef verstr = s.substr(pos + 1);
215 if (verstr.empty())
Rui Ueyama35fa6c52016-11-23 05:48:40216 return;
217
218 // Truncate the symbol name so that it doesn't include the version string.
Rui Ueyama3837f422019-07-10 05:00:37219 nameSize = pos;
Rui Ueyama35fa6c52016-11-23 05:48:40220
Rafael Espindola1d6d1b42017-01-17 16:08:06221 // If this is not in this DSO, it is not a definition.
Peter Collingbourneb472aa02017-11-06 04:39:07222 if (!isDefined())
Rafael Espindola2756e042017-01-06 22:30:35223 return;
224
Rui Ueyama35fa6c52016-11-23 05:48:40225 // '@@' in a symbol name means the default version.
226 // It is usually the most recent one.
Rui Ueyama3837f422019-07-10 05:00:37227 bool isDefault = (verstr[0] == '@');
228 if (isDefault)
229 verstr = verstr.substr(1);
Rui Ueyama35fa6c52016-11-23 05:48:40230
Fangrui Songe28a70d2019-08-05 14:31:39231 for (const VersionDefinition &ver : namedVersionDefs()) {
Rui Ueyama3837f422019-07-10 05:00:37232 if (ver.name != verstr)
Rui Ueyama35fa6c52016-11-23 05:48:40233 continue;
234
Rui Ueyama3837f422019-07-10 05:00:37235 if (isDefault)
236 versionId = ver.id;
Rui Ueyama35fa6c52016-11-23 05:48:40237 else
Rui Ueyama3837f422019-07-10 05:00:37238 versionId = ver.id | VERSYM_HIDDEN;
Rui Ueyama35fa6c52016-11-23 05:48:40239 return;
240 }
241
242 // It is an error if the specified version is not defined.
George Rimar4d2f97622017-07-04 13:19:13243 // Usually version script is not provided when linking executable,
244 // but we may still want to override a versioned symbol from DSO,
Peter Smith796fb992018-05-14 10:13:56245 // so we do not report error in this case. We also do not error
246 // if the symbol has a local version as it won't be in the dynamic
247 // symbol table.
Rui Ueyama3837f422019-07-10 05:00:37248 if (config->shared && versionId != VER_NDX_LOCAL)
249 error(toString(file) + ": symbol " + s + " has undefined version " +
250 verstr);
Rui Ueyama35fa6c52016-11-23 05:48:40251}
252
Rui Ueyama7f7d2b22019-05-23 09:58:08253void Symbol::fetch() const {
Rui Ueyama3837f422019-07-10 05:00:37254 if (auto *sym = dyn_cast<LazyArchive>(this)) {
255 cast<ArchiveFile>(sym->file)->fetch(sym->sym);
Rui Ueyama7f7d2b22019-05-23 09:58:08256 return;
257 }
258
Rui Ueyama3837f422019-07-10 05:00:37259 if (auto *sym = dyn_cast<LazyObject>(this)) {
260 dyn_cast<LazyObjFile>(sym->file)->fetch();
Rui Ueyama7f7d2b22019-05-23 09:58:08261 return;
262 }
263
264 llvm_unreachable("Symbol::fetch() is called on a non-lazy symbol");
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) ||
Fangrui Songc1c679e2020-04-01 23:11:31281 (versionId == VER_NDX_LOCAL && isDefined()))
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 Song07837b82020-05-15 05:18:58320void elf::maybeWarnUnorderableSymbol(const Symbol *sym) {
Rui Ueyama3837f422019-07-10 05:00:37321 if (!config->warnSymbolOrdering)
Michael J. Spencerb8427252018-04-17 23:30:05322 return;
Rui Ueyamab774c3c2018-04-26 01:38:29323
Fangrui Song11ca54f2018-10-10 22:48:57324 // If UnresolvedPolicy::Ignore is used, no "undefined symbol" error/warning
325 // is emitted. It makes sense to not warn on undefined symbols.
326 //
327 // Note, ld.bfd --symbol-ordering-file= does not warn on undefined symbols,
328 // but we don't have to be compatible here.
Rui Ueyama3837f422019-07-10 05:00:37329 if (sym->isUndefined() &&
330 config->unresolvedSymbols == UnresolvedPolicy::Ignore)
Fangrui Song11ca54f2018-10-10 22:48:57331 return;
332
Rui Ueyama3837f422019-07-10 05:00:37333 const InputFile *file = sym->file;
334 auto *d = dyn_cast<Defined>(sym);
Rui Ueyamab774c3c2018-04-26 01:38:29335
Rui Ueyama3837f422019-07-10 05:00:37336 auto report = [&](StringRef s) { warn(toString(file) + s + sym->getName()); };
Rui Ueyamab774c3c2018-04-26 01:38:29337
Rui Ueyama3837f422019-07-10 05:00:37338 if (sym->isUndefined())
339 report(": unable to order undefined symbol: ");
340 else if (sym->isShared())
341 report(": unable to order shared symbol: ");
342 else if (d && !d->section)
343 report(": unable to order absolute symbol: ");
344 else if (d && isa<OutputSection>(d->section))
345 report(": unable to order synthetic symbol: ");
346 else if (d && !d->section->repl->isLive())
347 report(": unable to order discarded symbol: ");
Michael J. Spencerb8427252018-04-17 23:30:05348}
349
Fangrui Songcd0ab242019-11-30 05:58:36350// Returns true if a symbol can be replaced at load-time by a symbol
351// with the same name defined in other ELF executable or DSO.
Fangrui Song07837b82020-05-15 05:18:58352bool elf::computeIsPreemptible(const Symbol &sym) {
Fangrui Songcd0ab242019-11-30 05:58:36353 assert(!sym.isLocal());
354
355 // Only symbols with default visibility that appear in dynsym can be
356 // preempted. Symbols with protected visibility cannot be preempted.
357 if (!sym.includeInDynsym() || sym.visibility != STV_DEFAULT)
358 return false;
359
360 // At this point copy relocations have not been created yet, so any
361 // symbol that is not defined locally is preemptible.
362 if (!sym.isDefined())
363 return true;
364
365 if (!config->shared)
366 return false;
367
Fangrui Song751f18e2020-06-01 18:27:53368 // If -Bsymbolic or --dynamic-list is specified, or -Bsymbolic-functions is
369 // specified and the symbol is STT_FUNC, the symbol is preemptible iff it is
370 // in the dynamic list.
371 if (config->symbolic || (config->bsymbolicFunctions && sym.isFunc()))
Fangrui Songcd0ab242019-11-30 05:58:36372 return sym.inDynamicList;
Fangrui Songcd0ab242019-11-30 05:58:36373 return true;
374}
375
Fangrui Song07837b82020-05-15 05:18:58376void elf::reportBackrefs() {
Fangrui Song03c825c2020-04-06 05:27:46377 for (auto &it : backwardReferences) {
378 const Symbol &sym = *it.first;
379 warn("backward reference detected: " + sym.getName() + " in " +
380 toString(it.second) + " refers to " + toString(sym.file));
381 }
382}
383
Rui Ueyama3837f422019-07-10 05:00:37384static uint8_t getMinVisibility(uint8_t va, uint8_t vb) {
385 if (va == STV_DEFAULT)
386 return vb;
387 if (vb == STV_DEFAULT)
388 return va;
389 return std::min(va, vb);
Rui Ueyama7f7d2b22019-05-23 09:58:08390}
391
392// Merge symbol properties.
393//
394// When we have many symbols of the same name, we choose one of them,
395// and that's the result of symbol resolution. However, symbols that
396// were not chosen still affect some symbol properties.
Rui Ueyama3837f422019-07-10 05:00:37397void Symbol::mergeProperties(const Symbol &other) {
398 if (other.exportDynamic)
399 exportDynamic = true;
400 if (other.isUsedInRegularObj)
401 isUsedInRegularObj = true;
Rui Ueyama7f7d2b22019-05-23 09:58:08402
403 // DSO symbols do not affect visibility in the output.
Rui Ueyama3837f422019-07-10 05:00:37404 if (!other.isShared())
405 visibility = getMinVisibility(visibility, other.visibility);
Rui Ueyama7f7d2b22019-05-23 09:58:08406}
407
Rui Ueyama3837f422019-07-10 05:00:37408void Symbol::resolve(const Symbol &other) {
409 mergeProperties(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08410
411 if (isPlaceholder()) {
Rui Ueyama3837f422019-07-10 05:00:37412 replace(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08413 return;
414 }
415
Rui Ueyama3837f422019-07-10 05:00:37416 switch (other.kind()) {
Rui Ueyama7f7d2b22019-05-23 09:58:08417 case Symbol::UndefinedKind:
Rui Ueyama3837f422019-07-10 05:00:37418 resolveUndefined(cast<Undefined>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08419 break;
420 case Symbol::CommonKind:
Rui Ueyama3837f422019-07-10 05:00:37421 resolveCommon(cast<CommonSymbol>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08422 break;
423 case Symbol::DefinedKind:
Rui Ueyama3837f422019-07-10 05:00:37424 resolveDefined(cast<Defined>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08425 break;
426 case Symbol::LazyArchiveKind:
Rui Ueyama3837f422019-07-10 05:00:37427 resolveLazy(cast<LazyArchive>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08428 break;
429 case Symbol::LazyObjectKind:
Rui Ueyama3837f422019-07-10 05:00:37430 resolveLazy(cast<LazyObject>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08431 break;
432 case Symbol::SharedKind:
Rui Ueyama3837f422019-07-10 05:00:37433 resolveShared(cast<SharedSymbol>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08434 break;
435 case Symbol::PlaceholderKind:
436 llvm_unreachable("bad symbol kind");
437 }
438}
439
Rui Ueyama3837f422019-07-10 05:00:37440void Symbol::resolveUndefined(const Undefined &other) {
Rui Ueyama7f7d2b22019-05-23 09:58:08441 // An undefined symbol with non default visibility must be satisfied
442 // in the same DSO.
443 //
444 // If this is a non-weak defined symbol in a discarded section, override the
445 // existing undefined symbol for better error message later.
Rui Ueyama3837f422019-07-10 05:00:37446 if ((isShared() && other.visibility != STV_DEFAULT) ||
447 (isUndefined() && other.binding != STB_WEAK && other.discardedSecIdx)) {
448 replace(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08449 return;
450 }
451
Rui Ueyama3837f422019-07-10 05:00:37452 if (traced)
453 printTraceSymbol(&other);
Sam Clegg7991b682019-05-24 13:29:17454
Fangrui Songf3475412019-07-04 10:38:04455 if (isLazy()) {
Rui Ueyama7f7d2b22019-05-23 09:58:08456 // An undefined weak will not fetch archive members. See comment on Lazy in
457 // Symbols.h for the details.
Rui Ueyama3837f422019-07-10 05:00:37458 if (other.binding == STB_WEAK) {
459 binding = STB_WEAK;
460 type = other.type;
Rui Ueyama7f7d2b22019-05-23 09:58:08461 return;
462 }
463
464 // Do extra check for --warn-backrefs.
465 //
466 // --warn-backrefs is an option to prevent an undefined reference from
467 // fetching an archive member written earlier in the command line. It can be
468 // used to keep compatibility with GNU linkers to some degree.
469 // I'll explain the feature and why you may find it useful in this comment.
470 //
471 // lld's symbol resolution semantics is more relaxed than traditional Unix
472 // linkers. For example,
473 //
474 // ld.lld foo.a bar.o
475 //
476 // succeeds even if bar.o contains an undefined symbol that has to be
477 // resolved by some object file in foo.a. Traditional Unix linkers don't
478 // allow this kind of backward reference, as they visit each file only once
479 // from left to right in the command line while resolving all undefined
480 // symbols at the moment of visiting.
481 //
482 // In the above case, since there's no undefined symbol when a linker visits
483 // foo.a, no files are pulled out from foo.a, and because the linker forgets
484 // about foo.a after visiting, it can't resolve undefined symbols in bar.o
485 // that could have been resolved otherwise.
486 //
487 // That lld accepts more relaxed form means that (besides it'd make more
488 // sense) you can accidentally write a command line or a build file that
489 // works only with lld, even if you have a plan to distribute it to wider
490 // users who may be using GNU linkers. With --warn-backrefs, you can detect
491 // a library order that doesn't work with other Unix linkers.
492 //
493 // The option is also useful to detect cyclic dependencies between static
494 // archives. Again, lld accepts
495 //
496 // ld.lld foo.a bar.a
497 //
498 // even if foo.a and bar.a depend on each other. With --warn-backrefs, it is
499 // handled as an error.
500 //
501 // Here is how the option works. We assign a group ID to each file. A file
502 // with a smaller group ID can pull out object files from an archive file
503 // with an equal or greater group ID. Otherwise, it is a reverse dependency
504 // and an error.
505 //
506 // A file outside --{start,end}-group gets a fresh ID when instantiated. All
507 // files within the same --{start,end}-group get the same group ID. E.g.
508 //
509 // ld.lld A B --start-group C D --end-group E
510 //
511 // A forms group 0. B form group 1. C and D (including their member object
512 // files) form group 2. E forms group 3. I think that you can see how this
513 // group assignment rule simulates the traditional linker's semantics.
Rui Ueyama3837f422019-07-10 05:00:37514 bool backref = config->warnBackrefs && other.file &&
515 file->groupId < other.file->groupId;
Fangrui Song23257882020-04-05 04:31:36516 if (backref) {
517 // Some libraries have known problems and can cause noise. Filter them out
518 // with --warn-backrefs-exclude=.
519 StringRef name =
520 !file->archiveName.empty() ? file->archiveName : file->getName();
521 for (const llvm::GlobPattern &pat : config->warnBackrefsExclude)
522 if (pat.match(name)) {
523 backref = false;
524 break;
525 }
526 }
Rui Ueyama7f7d2b22019-05-23 09:58:08527 fetch();
528
529 // We don't report backward references to weak symbols as they can be
530 // overridden later.
Fangrui Song03c825c2020-04-06 05:27:46531 //
532 // A traditional linker does not error for -ldef1 -lref -ldef2 (linking
533 // sandwich), where def2 may or may not be the same as def1. We don't want
534 // to warn for this case, so dismiss the warning if we see a subsequent lazy
535 // definition.
Rui Ueyama3837f422019-07-10 05:00:37536 if (backref && !isWeak())
Fangrui Song03c825c2020-04-06 05:27:46537 backwardReferences.try_emplace(this, other.file);
Fangrui Songf3475412019-07-04 10:38:04538 return;
539 }
540
541 // Undefined symbols in a SharedFile do not change the binding.
Rui Ueyama3837f422019-07-10 05:00:37542 if (dyn_cast_or_null<SharedFile>(other.file))
Fangrui Songf3475412019-07-04 10:38:04543 return;
544
Fangrui Songe49c4172019-08-06 14:03:45545 if (isUndefined() || isShared()) {
546 // The binding will be weak if there is at least one reference and all are
547 // weak. The binding has one opportunity to change to weak: if the first
548 // reference is weak.
549 if (other.binding != STB_WEAK || !referenced)
Rui Ueyama3837f422019-07-10 05:00:37550 binding = other.binding;
Rui Ueyama7f7d2b22019-05-23 09:58:08551 }
552}
553
554// Using .symver foo,foo@@VER unfortunately creates two symbols: foo and
555// foo@@VER. We want to effectively ignore foo, so give precedence to
556// foo@@VER.
557// FIXME: If users can transition to using
558// .symver foo,foo@@@VER
559// we can delete this hack.
Rui Ueyama3837f422019-07-10 05:00:37560static int compareVersion(StringRef a, StringRef b) {
561 bool x = a.contains("@@");
562 bool y = b.contains("@@");
563 if (!x && y)
Rui Ueyama7f7d2b22019-05-23 09:58:08564 return 1;
Rui Ueyama3837f422019-07-10 05:00:37565 if (x && !y)
Rui Ueyama7f7d2b22019-05-23 09:58:08566 return -1;
567 return 0;
568}
569
570// Compare two symbols. Return 1 if the new symbol should win, -1 if
571// the new symbol should lose, or 0 if there is a conflict.
Rui Ueyama3837f422019-07-10 05:00:37572int Symbol::compare(const Symbol *other) const {
573 assert(other->isDefined() || other->isCommon());
Rui Ueyama7f7d2b22019-05-23 09:58:08574
575 if (!isDefined() && !isCommon())
576 return 1;
577
Rui Ueyama3837f422019-07-10 05:00:37578 if (int cmp = compareVersion(getName(), other->getName()))
579 return cmp;
Rui Ueyama7f7d2b22019-05-23 09:58:08580
Rui Ueyama3837f422019-07-10 05:00:37581 if (other->isWeak())
Rui Ueyama7f7d2b22019-05-23 09:58:08582 return -1;
583
584 if (isWeak())
585 return 1;
586
Rui Ueyama3837f422019-07-10 05:00:37587 if (isCommon() && other->isCommon()) {
588 if (config->warnCommon)
Rui Ueyama7f7d2b22019-05-23 09:58:08589 warn("multiple common of " + getName());
590 return 0;
591 }
592
593 if (isCommon()) {
Rui Ueyama3837f422019-07-10 05:00:37594 if (config->warnCommon)
Rui Ueyama7f7d2b22019-05-23 09:58:08595 warn("common " + getName() + " is overridden");
596 return 1;
597 }
598
Rui Ueyama3837f422019-07-10 05:00:37599 if (other->isCommon()) {
600 if (config->warnCommon)
Rui Ueyama7f7d2b22019-05-23 09:58:08601 warn("common " + getName() + " is overridden");
602 return -1;
603 }
604
Rui Ueyama3837f422019-07-10 05:00:37605 auto *oldSym = cast<Defined>(this);
606 auto *newSym = cast<Defined>(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08607
Fangrui Songd6c44822019-07-26 16:29:15608 if (dyn_cast_or_null<BitcodeFile>(other->file))
Rui Ueyama7f7d2b22019-05-23 09:58:08609 return 0;
610
Rui Ueyama3837f422019-07-10 05:00:37611 if (!oldSym->section && !newSym->section && oldSym->value == newSym->value &&
612 newSym->binding == STB_GLOBAL)
Rui Ueyama7f7d2b22019-05-23 09:58:08613 return -1;
614
615 return 0;
616}
617
Rui Ueyama3837f422019-07-10 05:00:37618static void reportDuplicate(Symbol *sym, InputFile *newFile,
619 InputSectionBase *errSec, uint64_t errOffset) {
620 if (config->allowMultipleDefinition)
Rui Ueyama7f7d2b22019-05-23 09:58:08621 return;
622
Rui Ueyama3837f422019-07-10 05:00:37623 Defined *d = cast<Defined>(sym);
624 if (!d->section || !errSec) {
625 error("duplicate symbol: " + toString(*sym) + "\n>>> defined in " +
626 toString(sym->file) + "\n>>> defined in " + toString(newFile));
Rui Ueyama7f7d2b22019-05-23 09:58:08627 return;
628 }
629
630 // Construct and print an error message in the form of:
631 //
632 // ld.lld: error: duplicate symbol: foo
633 // >>> defined at bar.c:30
634 // >>> bar.o (/home/alice/src/bar.o)
635 // >>> defined at baz.c:563
636 // >>> baz.o in archive libbaz.a
Rui Ueyama3837f422019-07-10 05:00:37637 auto *sec1 = cast<InputSectionBase>(d->section);
638 std::string src1 = sec1->getSrcMsg(*sym, d->value);
639 std::string obj1 = sec1->getObjMsg(d->value);
640 std::string src2 = errSec->getSrcMsg(*sym, errOffset);
641 std::string obj2 = errSec->getObjMsg(errOffset);
Rui Ueyama7f7d2b22019-05-23 09:58:08642
Rui Ueyama3837f422019-07-10 05:00:37643 std::string msg = "duplicate symbol: " + toString(*sym) + "\n>>> defined at ";
644 if (!src1.empty())
645 msg += src1 + "\n>>> ";
646 msg += obj1 + "\n>>> defined at ";
647 if (!src2.empty())
648 msg += src2 + "\n>>> ";
649 msg += obj2;
650 error(msg);
Rui Ueyama7f7d2b22019-05-23 09:58:08651}
652
Rui Ueyama3837f422019-07-10 05:00:37653void Symbol::resolveCommon(const CommonSymbol &other) {
654 int cmp = compare(&other);
655 if (cmp < 0)
Rui Ueyama7f7d2b22019-05-23 09:58:08656 return;
657
Rui Ueyama3837f422019-07-10 05:00:37658 if (cmp > 0) {
Fangrui Song69d10d22019-12-07 05:18:31659 if (auto *s = dyn_cast<SharedSymbol>(this)) {
660 // Increase st_size if the shared symbol has a larger st_size. The shared
661 // symbol may be created from common symbols. The fact that some object
662 // files were linked into a shared object first should not change the
663 // regular rule that picks the largest st_size.
664 uint64_t size = s->size;
665 replace(other);
666 if (size > cast<CommonSymbol>(this)->size)
667 cast<CommonSymbol>(this)->size = size;
668 } else {
669 replace(other);
670 }
Rui Ueyama7f7d2b22019-05-23 09:58:08671 return;
672 }
673
Rui Ueyama3837f422019-07-10 05:00:37674 CommonSymbol *oldSym = cast<CommonSymbol>(this);
Rui Ueyama7f7d2b22019-05-23 09:58:08675
Rui Ueyama3837f422019-07-10 05:00:37676 oldSym->alignment = std::max(oldSym->alignment, other.alignment);
677 if (oldSym->size < other.size) {
678 oldSym->file = other.file;
679 oldSym->size = other.size;
Rui Ueyama7f7d2b22019-05-23 09:58:08680 }
681}
682
Rui Ueyama3837f422019-07-10 05:00:37683void Symbol::resolveDefined(const Defined &other) {
684 int cmp = compare(&other);
685 if (cmp > 0)
686 replace(other);
687 else if (cmp == 0)
688 reportDuplicate(this, other.file,
689 dyn_cast_or_null<InputSectionBase>(other.section),
690 other.value);
Rui Ueyama7f7d2b22019-05-23 09:58:08691}
692
Rui Ueyama3837f422019-07-10 05:00:37693template <class LazyT> void Symbol::resolveLazy(const LazyT &other) {
Fangrui Song03c825c2020-04-06 05:27:46694 if (!isUndefined()) {
695 // See the comment in resolveUndefined().
696 if (isDefined())
697 backwardReferences.erase(this);
Rui Ueyama7f7d2b22019-05-23 09:58:08698 return;
Fangrui Song03c825c2020-04-06 05:27:46699 }
Rui Ueyama7f7d2b22019-05-23 09:58:08700
701 // An undefined weak will not fetch archive members. See comment on Lazy in
702 // Symbols.h for the details.
703 if (isWeak()) {
Rui Ueyama3837f422019-07-10 05:00:37704 uint8_t ty = type;
705 replace(other);
706 type = ty;
707 binding = STB_WEAK;
Rui Ueyama7f7d2b22019-05-23 09:58:08708 return;
709 }
710
Rui Ueyama3837f422019-07-10 05:00:37711 other.fetch();
Rui Ueyama7f7d2b22019-05-23 09:58:08712}
713
Rui Ueyama3837f422019-07-10 05:00:37714void Symbol::resolveShared(const SharedSymbol &other) {
Fangrui Song69d10d22019-12-07 05:18:31715 if (isCommon()) {
716 // See the comment in resolveCommon() above.
717 if (other.size > cast<CommonSymbol>(this)->size)
718 cast<CommonSymbol>(this)->size = other.size;
719 return;
720 }
Rui Ueyama3837f422019-07-10 05:00:37721 if (visibility == STV_DEFAULT && (isUndefined() || isLazy())) {
Rui Ueyama7f7d2b22019-05-23 09:58:08722 // An undefined symbol with non default visibility must be satisfied
723 // in the same DSO.
Rui Ueyama3837f422019-07-10 05:00:37724 uint8_t bind = binding;
725 replace(other);
726 binding = bind;
Fangrui Song64676492020-05-18 17:15:59727 } else if (traced)
728 printTraceSymbol(&other);
Rui Ueyama7f7d2b22019-05-23 09:58:08729}