blob: fe1c2cacd310c4d5bcd4f015aa09b2d392c6e606 [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"
Eugene Leviantc958d8d2016-10-12 08:19:3019#include "llvm/Support/Path.h"
Rui Ueyamac72ba3a2016-11-23 04:57:2520#include <cstring>
Michael J. Spencer1b348a62015-09-04 22:28:1021
22using namespace llvm;
Michael J. Spencer84487f12015-07-24 21:03:0723using namespace llvm::object;
Rafael Espindola78471f02015-09-01 23:12:5224using namespace llvm::ELF;
Michael J. Spencer84487f12015-07-24 21:03:0725
Fangrui Songbd8cfe62019-10-07 08:31:1826namespace lld {
27// Returns a symbol for an error message.
28static std::string demangle(StringRef symName) {
29 if (elf::config->demangle)
30 return demangleItanium(symName);
Benjamin Krameradcd0262020-01-28 19:23:4631 return std::string(symName);
Fangrui Songbd8cfe62019-10-07 08:31:1832}
Michael J. Spencer84487f12015-07-24 21:03:0733
Fangrui Songf2036a12020-03-28 22:48:3834std::string toString(const elf::Symbol &sym) {
35 StringRef name = sym.getName();
36 std::string ret = demangle(name);
37
38 // If sym has a non-default version, its name may have been truncated at '@'
39 // by Symbol::parseSymbolVersion(). Add the trailing part. This check is safe
40 // because every symbol name ends with '\0'.
41 if (name.data()[name.size()] == '@')
42 ret += name.data() + name.size();
43 return ret;
44}
45
Fangrui Songbd8cfe62019-10-07 08:31:1846std::string toELFString(const Archive::Symbol &b) {
47 return demangle(b.getName());
48}
49
50namespace elf {
Rui Ueyama3837f422019-07-10 05:00:3751Defined *ElfSym::bss;
52Defined *ElfSym::etext1;
53Defined *ElfSym::etext2;
54Defined *ElfSym::edata1;
55Defined *ElfSym::edata2;
56Defined *ElfSym::end1;
57Defined *ElfSym::end2;
58Defined *ElfSym::globalOffsetTable;
59Defined *ElfSym::mipsGp;
60Defined *ElfSym::mipsGpDisp;
61Defined *ElfSym::mipsLocalGp;
62Defined *ElfSym::relaIpltStart;
63Defined *ElfSym::relaIpltEnd;
64Defined *ElfSym::riscvGlobalPointer;
65Defined *ElfSym::tlsModuleBase;
Fangrui Song03c825c2020-04-06 05:27:4666DenseMap<const Symbol *, const InputFile *> backwardReferences;
Rui Ueyama80474a22017-02-28 19:29:5567
Rui Ueyama3837f422019-07-10 05:00:3768static uint64_t getSymVA(const Symbol &sym, int64_t &addend) {
69 switch (sym.kind()) {
Peter Collingbournee9a9e0a2017-11-06 04:35:3170 case Symbol::DefinedKind: {
Rui Ueyama3837f422019-07-10 05:00:3771 auto &d = cast<Defined>(sym);
72 SectionBase *isec = d.section;
Rui Ueyamab5a69702016-02-01 21:00:3573
74 // This is an absolute symbol.
Rui Ueyama3837f422019-07-10 05:00:3775 if (!isec)
76 return d.value;
Rui Ueyamab5a69702016-02-01 21:00:3577
Rui Ueyama3837f422019-07-10 05:00:3778 assert(isec != &InputSection::discarded);
79 isec = isec->repl;
Rafael Espindolaf4d6e8c2018-04-19 17:26:5080
Rui Ueyama3837f422019-07-10 05:00:3781 uint64_t offset = d.value;
Sean Silvaa9ba4502017-02-28 08:32:5682
83 // An object in an SHF_MERGE section might be referenced via a
84 // section symbol (as a hack for reducing the number of local
85 // symbols).
Sean Silvad4e60622017-03-01 04:44:0486 // Depending on the addend, the reference via a section symbol
87 // refers to a different object in the merge section.
88 // Since the objects in the merge section are not necessarily
89 // contiguous in the output, the addend can thus affect the final
90 // VA in a non-linear way.
91 // To make this work, we incorporate the addend into the section
92 // offset (and zero out the addend for later processing) so that
93 // we find the right object in the section.
Rui Ueyama3837f422019-07-10 05:00:3794 if (d.isSection()) {
95 offset += addend;
96 addend = 0;
Rafael Espindola1f5b70f2016-03-11 14:21:3797 }
Sean Silvaa9ba4502017-02-28 08:32:5698
Sean Silva6ab39262017-02-28 09:01:5899 // In the typical case, this is actually very simple and boils
100 // down to adding together 3 numbers:
101 // 1. The address of the output section.
102 // 2. The offset of the input section within the output section.
103 // 3. The offset within the input section (this addition happens
104 // inside InputSection::getOffset).
105 //
106 // If you understand the data structures involved with this next
107 // line (and how they get built), then you have a pretty good
108 // understanding of the linker.
Rui Ueyama3837f422019-07-10 05:00:37109 uint64_t va = isec->getVA(offset);
Sean Silva6ab39262017-02-28 09:01:58110
Simon Atanasyanfae2a5092019-02-19 10:36:58111 // MIPS relocatable files can mix regular and microMIPS code.
112 // Linker needs to distinguish such code. To do so microMIPS
113 // symbols has the `STO_MIPS_MICROMIPS` flag in the `st_other`
Fangrui Songdeb58192020-01-23 05:39:16114 // field. Unfortunately, the `MIPS::relocate()` method has
Simon Atanasyanfae2a5092019-02-19 10:36:58115 // a symbol value only. To pass type of the symbol (regular/microMIPS)
116 // to that routine as well as other places where we write
117 // a symbol value as-is (.dynamic section, `Elf_Ehdr::e_entry`
118 // field etc) do the same trick as compiler uses to mark microMIPS
119 // for CPU - set the less-significant bit.
Rui Ueyama3837f422019-07-10 05:00:37120 if (config->emachine == EM_MIPS && isMicroMips() &&
121 ((sym.stOther & STO_MIPS_MICROMIPS) || sym.needsPltAddr))
122 va |= 1;
Simon Atanasyanfae2a5092019-02-19 10:36:58123
Rui Ueyama3837f422019-07-10 05:00:37124 if (d.isTls() && !config->relocatable) {
Ryan Prichard1c33d142018-09-18 00:24:48125 // Use the address of the TLS segment's first section rather than the
126 // segment's address, because segment addresses aren't initialized until
127 // after sections are finalized. (e.g. Measuring the size of .rela.dyn
128 // for Android relocation packing requires knowing TLS symbol addresses
129 // during section finalization.)
Rui Ueyama3837f422019-07-10 05:00:37130 if (!Out::tlsPhdr || !Out::tlsPhdr->firstSec)
131 fatal(toString(d.file) +
Peter Collingbourne3e2abde2017-07-14 00:22:46132 " has an STT_TLS symbol but doesn't have an SHF_TLS section");
Rui Ueyama3837f422019-07-10 05:00:37133 return va - Out::tlsPhdr->firstSec->addr;
George Rimar6a3b1542016-10-04 08:52:51134 }
Rui Ueyama3837f422019-07-10 05:00:37135 return va;
Rui Ueyamab5a69702016-02-01 21:00:35136 }
Rafael Espindolaab0cce52018-04-26 17:58:58137 case Symbol::SharedKind:
Rui Ueyamaf52496e2017-11-03 21:21:47138 case Symbol::UndefinedKind:
Rui Ueyamab5a69702016-02-01 21:00:35139 return 0;
Rui Ueyamaf52496e2017-11-03 21:21:47140 case Symbol::LazyArchiveKind:
141 case Symbol::LazyObjectKind:
Rui Ueyama3837f422019-07-10 05:00:37142 assert(sym.isUsedInRegularObj && "lazy symbol reached writer");
Chih-Hung Hsieh73e04842018-09-11 23:00:36143 return 0;
Rui Ueyama5c073a92019-05-16 03:29:03144 case Symbol::CommonKind:
145 llvm_unreachable("common symbol reached writer");
Rui Ueyamaf3fad552018-10-12 18:29:18146 case Symbol::PlaceholderKind:
147 llvm_unreachable("placeholder symbol reached writer");
Rui Ueyamab5a69702016-02-01 21:00:35148 }
George Rimar777f9632016-03-12 08:31:34149 llvm_unreachable("invalid symbol kind");
Rui Ueyamab5a69702016-02-01 21:00:35150}
151
Rui Ueyama3837f422019-07-10 05:00:37152uint64_t Symbol::getVA(int64_t addend) const {
153 uint64_t outVA = getSymVA(*this, addend);
154 return outVA + 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
Rui Ueyama3837f422019-07-10 05:00:37163uint64_t Symbol::getGotOffset() const { return gotIndex * config->wordsize; }
Rui Ueyamab5a69702016-02-01 21:00:35164
Rui Ueyamaf52496e2017-11-03 21:21:47165uint64_t Symbol::getGotPltVA() const {
Rui Ueyama3837f422019-07-10 05:00:37166 if (isInIplt)
167 return in.igotPlt->getVA() + getGotPltOffset();
168 return in.gotPlt->getVA() + getGotPltOffset();
Rafael Espindola74031ba2016-04-07 15:20:56169}
170
Rui Ueyamaf52496e2017-11-03 21:21:47171uint64_t Symbol::getGotPltOffset() const {
Rui Ueyama3837f422019-07-10 05:00:37172 if (isInIplt)
173 return pltIndex * config->wordsize;
174 return (pltIndex + target->gotPltHeaderEntriesNum) * config->wordsize;
Rui Ueyamab5a69702016-02-01 21:00:35175}
176
Rui Ueyamaf52496e2017-11-03 21:21:47177uint64_t Symbol::getPltVA() const {
Fangrui Song891a8652019-12-14 22:17:35178 uint64_t outVA = isInIplt
179 ? in.iplt->getVA() + pltIndex * target->ipltEntrySize
180 : in.plt->getVA() + in.plt->headerSize +
181 pltIndex * target->pltEntrySize;
182
Simon Atanasyanfae2a5092019-02-19 10:36:58183 // While linking microMIPS code PLT code are always microMIPS
184 // code. Set the less-significant bit to track that fact.
185 // See detailed comment in the `getSymVA` function.
Rui Ueyama3837f422019-07-10 05:00:37186 if (config->emachine == EM_MIPS && isMicroMips())
187 outVA |= 1;
188 return outVA;
Rafael Espindolaab0cce52018-04-26 17:58:58189}
190
Rui Ueyamaf52496e2017-11-03 21:21:47191uint64_t Symbol::getSize() const {
Rui Ueyama3837f422019-07-10 05:00:37192 if (const auto *dr = dyn_cast<Defined>(this))
193 return dr->size;
194 return cast<SharedSymbol>(this)->size;
Rui Ueyama512c61d2016-02-03 00:12:24195}
196
Rui Ueyamaf52496e2017-11-03 21:21:47197OutputSection *Symbol::getOutputSection() const {
Rui Ueyama3837f422019-07-10 05:00:37198 if (auto *s = dyn_cast<Defined>(this)) {
199 if (auto *sec = s->section)
200 return sec->repl->getOutputSection();
Rui Ueyama968db482017-02-28 04:02:42201 return nullptr;
202 }
Rui Ueyama968db482017-02-28 04:02:42203 return nullptr;
204}
205
Rui Ueyama35fa6c52016-11-23 05:48:40206// If a symbol name contains '@', the characters after that is
207// a symbol version name. This function parses that.
Rui Ueyamaf52496e2017-11-03 21:21:47208void Symbol::parseSymbolVersion() {
Rui Ueyama3837f422019-07-10 05:00:37209 StringRef s = getName();
210 size_t pos = s.find('@');
211 if (pos == 0 || pos == StringRef::npos)
Rui Ueyama35fa6c52016-11-23 05:48:40212 return;
Rui Ueyama3837f422019-07-10 05:00:37213 StringRef verstr = s.substr(pos + 1);
214 if (verstr.empty())
Rui Ueyama35fa6c52016-11-23 05:48:40215 return;
216
217 // Truncate the symbol name so that it doesn't include the version string.
Rui Ueyama3837f422019-07-10 05:00:37218 nameSize = pos;
Rui Ueyama35fa6c52016-11-23 05:48:40219
Rafael Espindola1d6d1b42017-01-17 16:08:06220 // If this is not in this DSO, it is not a definition.
Peter Collingbourneb472aa02017-11-06 04:39:07221 if (!isDefined())
Rafael Espindola2756e042017-01-06 22:30:35222 return;
223
Rui Ueyama35fa6c52016-11-23 05:48:40224 // '@@' in a symbol name means the default version.
225 // It is usually the most recent one.
Rui Ueyama3837f422019-07-10 05:00:37226 bool isDefault = (verstr[0] == '@');
227 if (isDefault)
228 verstr = verstr.substr(1);
Rui Ueyama35fa6c52016-11-23 05:48:40229
Fangrui Songe28a70d2019-08-05 14:31:39230 for (const VersionDefinition &ver : namedVersionDefs()) {
Rui Ueyama3837f422019-07-10 05:00:37231 if (ver.name != verstr)
Rui Ueyama35fa6c52016-11-23 05:48:40232 continue;
233
Rui Ueyama3837f422019-07-10 05:00:37234 if (isDefault)
235 versionId = ver.id;
Rui Ueyama35fa6c52016-11-23 05:48:40236 else
Rui Ueyama3837f422019-07-10 05:00:37237 versionId = ver.id | VERSYM_HIDDEN;
Rui Ueyama35fa6c52016-11-23 05:48:40238 return;
239 }
240
241 // It is an error if the specified version is not defined.
George Rimar4d2f97622017-07-04 13:19:13242 // Usually version script is not provided when linking executable,
243 // but we may still want to override a versioned symbol from DSO,
Peter Smith796fb992018-05-14 10:13:56244 // so we do not report error in this case. We also do not error
245 // if the symbol has a local version as it won't be in the dynamic
246 // symbol table.
Rui Ueyama3837f422019-07-10 05:00:37247 if (config->shared && versionId != VER_NDX_LOCAL)
248 error(toString(file) + ": symbol " + s + " has undefined version " +
249 verstr);
Rui Ueyama35fa6c52016-11-23 05:48:40250}
251
Rui Ueyama7f7d2b22019-05-23 09:58:08252void Symbol::fetch() const {
Rui Ueyama3837f422019-07-10 05:00:37253 if (auto *sym = dyn_cast<LazyArchive>(this)) {
254 cast<ArchiveFile>(sym->file)->fetch(sym->sym);
Rui Ueyama7f7d2b22019-05-23 09:58:08255 return;
256 }
257
Rui Ueyama3837f422019-07-10 05:00:37258 if (auto *sym = dyn_cast<LazyObject>(this)) {
259 dyn_cast<LazyObjFile>(sym->file)->fetch();
Rui Ueyama7f7d2b22019-05-23 09:58:08260 return;
261 }
262
263 llvm_unreachable("Symbol::fetch() is called on a non-lazy symbol");
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) ||
Fangrui Songc1c679e2020-04-01 23:11:31280 (versionId == VER_NDX_LOCAL && isDefined()))
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 Songbd8cfe62019-10-07 08:31:18303void 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 Songbd8cfe62019-10-07 08:31:18319void maybeWarnUnorderableSymbol(const Symbol *sym) {
Rui Ueyama3837f422019-07-10 05:00:37320 if (!config->warnSymbolOrdering)
Michael J. Spencerb8427252018-04-17 23:30:05321 return;
Rui Ueyamab774c3c2018-04-26 01:38:29322
Fangrui Song11ca54f2018-10-10 22:48:57323 // If UnresolvedPolicy::Ignore is used, no "undefined symbol" error/warning
324 // is emitted. It makes sense to not warn on undefined symbols.
325 //
326 // Note, ld.bfd --symbol-ordering-file= does not warn on undefined symbols,
327 // but we don't have to be compatible here.
Rui Ueyama3837f422019-07-10 05:00:37328 if (sym->isUndefined() &&
329 config->unresolvedSymbols == UnresolvedPolicy::Ignore)
Fangrui Song11ca54f2018-10-10 22:48:57330 return;
331
Rui Ueyama3837f422019-07-10 05:00:37332 const InputFile *file = sym->file;
333 auto *d = dyn_cast<Defined>(sym);
Rui Ueyamab774c3c2018-04-26 01:38:29334
Rui Ueyama3837f422019-07-10 05:00:37335 auto report = [&](StringRef s) { warn(toString(file) + s + sym->getName()); };
Rui Ueyamab774c3c2018-04-26 01:38:29336
Rui Ueyama3837f422019-07-10 05:00:37337 if (sym->isUndefined())
338 report(": unable to order undefined symbol: ");
339 else if (sym->isShared())
340 report(": unable to order shared symbol: ");
341 else if (d && !d->section)
342 report(": unable to order absolute symbol: ");
343 else if (d && isa<OutputSection>(d->section))
344 report(": unable to order synthetic symbol: ");
345 else if (d && !d->section->repl->isLive())
346 report(": unable to order discarded symbol: ");
Michael J. Spencerb8427252018-04-17 23:30:05347}
348
Fangrui Songcd0ab242019-11-30 05:58:36349// Returns true if a symbol can be replaced at load-time by a symbol
350// with the same name defined in other ELF executable or DSO.
351bool computeIsPreemptible(const Symbol &sym) {
352 assert(!sym.isLocal());
353
354 // Only symbols with default visibility that appear in dynsym can be
355 // preempted. Symbols with protected visibility cannot be preempted.
356 if (!sym.includeInDynsym() || sym.visibility != STV_DEFAULT)
357 return false;
358
359 // At this point copy relocations have not been created yet, so any
360 // symbol that is not defined locally is preemptible.
361 if (!sym.isDefined())
362 return true;
363
364 if (!config->shared)
365 return false;
366
367 // If the dynamic list is present, it specifies preemptable symbols in a DSO.
368 if (config->hasDynamicList)
369 return sym.inDynamicList;
370
371 // -Bsymbolic means that definitions are not preempted.
372 if (config->bsymbolic || (config->bsymbolicFunctions && sym.isFunc()))
373 return false;
374 return true;
375}
376
Fangrui Song03c825c2020-04-06 05:27:46377void reportBackrefs() {
378 for (auto &it : backwardReferences) {
379 const Symbol &sym = *it.first;
380 warn("backward reference detected: " + sym.getName() + " in " +
381 toString(it.second) + " refers to " + toString(sym.file));
382 }
383}
384
Rui Ueyama3837f422019-07-10 05:00:37385static uint8_t getMinVisibility(uint8_t va, uint8_t vb) {
386 if (va == STV_DEFAULT)
387 return vb;
388 if (vb == STV_DEFAULT)
389 return va;
390 return std::min(va, vb);
Rui Ueyama7f7d2b22019-05-23 09:58:08391}
392
393// Merge symbol properties.
394//
395// When we have many symbols of the same name, we choose one of them,
396// and that's the result of symbol resolution. However, symbols that
397// were not chosen still affect some symbol properties.
Rui Ueyama3837f422019-07-10 05:00:37398void Symbol::mergeProperties(const Symbol &other) {
399 if (other.exportDynamic)
400 exportDynamic = true;
401 if (other.isUsedInRegularObj)
402 isUsedInRegularObj = true;
Rui Ueyama7f7d2b22019-05-23 09:58:08403
404 // DSO symbols do not affect visibility in the output.
Rui Ueyama3837f422019-07-10 05:00:37405 if (!other.isShared())
406 visibility = getMinVisibility(visibility, other.visibility);
Rui Ueyama7f7d2b22019-05-23 09:58:08407}
408
Rui Ueyama3837f422019-07-10 05:00:37409void Symbol::resolve(const Symbol &other) {
410 mergeProperties(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08411
412 if (isPlaceholder()) {
Rui Ueyama3837f422019-07-10 05:00:37413 replace(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08414 return;
415 }
416
Rui Ueyama3837f422019-07-10 05:00:37417 switch (other.kind()) {
Rui Ueyama7f7d2b22019-05-23 09:58:08418 case Symbol::UndefinedKind:
Rui Ueyama3837f422019-07-10 05:00:37419 resolveUndefined(cast<Undefined>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08420 break;
421 case Symbol::CommonKind:
Rui Ueyama3837f422019-07-10 05:00:37422 resolveCommon(cast<CommonSymbol>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08423 break;
424 case Symbol::DefinedKind:
Rui Ueyama3837f422019-07-10 05:00:37425 resolveDefined(cast<Defined>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08426 break;
427 case Symbol::LazyArchiveKind:
Rui Ueyama3837f422019-07-10 05:00:37428 resolveLazy(cast<LazyArchive>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08429 break;
430 case Symbol::LazyObjectKind:
Rui Ueyama3837f422019-07-10 05:00:37431 resolveLazy(cast<LazyObject>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08432 break;
433 case Symbol::SharedKind:
Rui Ueyama3837f422019-07-10 05:00:37434 resolveShared(cast<SharedSymbol>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08435 break;
436 case Symbol::PlaceholderKind:
437 llvm_unreachable("bad symbol kind");
438 }
439}
440
Rui Ueyama3837f422019-07-10 05:00:37441void Symbol::resolveUndefined(const Undefined &other) {
Rui Ueyama7f7d2b22019-05-23 09:58:08442 // An undefined symbol with non default visibility must be satisfied
443 // in the same DSO.
444 //
445 // If this is a non-weak defined symbol in a discarded section, override the
446 // existing undefined symbol for better error message later.
Rui Ueyama3837f422019-07-10 05:00:37447 if ((isShared() && other.visibility != STV_DEFAULT) ||
448 (isUndefined() && other.binding != STB_WEAK && other.discardedSecIdx)) {
449 replace(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08450 return;
451 }
452
Rui Ueyama3837f422019-07-10 05:00:37453 if (traced)
454 printTraceSymbol(&other);
Sam Clegg7991b682019-05-24 13:29:17455
Fangrui Songf3475412019-07-04 10:38:04456 if (isLazy()) {
Rui Ueyama7f7d2b22019-05-23 09:58:08457 // An undefined weak will not fetch archive members. See comment on Lazy in
458 // Symbols.h for the details.
Rui Ueyama3837f422019-07-10 05:00:37459 if (other.binding == STB_WEAK) {
460 binding = STB_WEAK;
461 type = other.type;
Rui Ueyama7f7d2b22019-05-23 09:58:08462 return;
463 }
464
465 // Do extra check for --warn-backrefs.
466 //
467 // --warn-backrefs is an option to prevent an undefined reference from
468 // fetching an archive member written earlier in the command line. It can be
469 // used to keep compatibility with GNU linkers to some degree.
470 // I'll explain the feature and why you may find it useful in this comment.
471 //
472 // lld's symbol resolution semantics is more relaxed than traditional Unix
473 // linkers. For example,
474 //
475 // ld.lld foo.a bar.o
476 //
477 // succeeds even if bar.o contains an undefined symbol that has to be
478 // resolved by some object file in foo.a. Traditional Unix linkers don't
479 // allow this kind of backward reference, as they visit each file only once
480 // from left to right in the command line while resolving all undefined
481 // symbols at the moment of visiting.
482 //
483 // In the above case, since there's no undefined symbol when a linker visits
484 // foo.a, no files are pulled out from foo.a, and because the linker forgets
485 // about foo.a after visiting, it can't resolve undefined symbols in bar.o
486 // that could have been resolved otherwise.
487 //
488 // That lld accepts more relaxed form means that (besides it'd make more
489 // sense) you can accidentally write a command line or a build file that
490 // works only with lld, even if you have a plan to distribute it to wider
491 // users who may be using GNU linkers. With --warn-backrefs, you can detect
492 // a library order that doesn't work with other Unix linkers.
493 //
494 // The option is also useful to detect cyclic dependencies between static
495 // archives. Again, lld accepts
496 //
497 // ld.lld foo.a bar.a
498 //
499 // even if foo.a and bar.a depend on each other. With --warn-backrefs, it is
500 // handled as an error.
501 //
502 // Here is how the option works. We assign a group ID to each file. A file
503 // with a smaller group ID can pull out object files from an archive file
504 // with an equal or greater group ID. Otherwise, it is a reverse dependency
505 // and an error.
506 //
507 // A file outside --{start,end}-group gets a fresh ID when instantiated. All
508 // files within the same --{start,end}-group get the same group ID. E.g.
509 //
510 // ld.lld A B --start-group C D --end-group E
511 //
512 // A forms group 0. B form group 1. C and D (including their member object
513 // files) form group 2. E forms group 3. I think that you can see how this
514 // group assignment rule simulates the traditional linker's semantics.
Rui Ueyama3837f422019-07-10 05:00:37515 bool backref = config->warnBackrefs && other.file &&
516 file->groupId < other.file->groupId;
Rui Ueyama7f7d2b22019-05-23 09:58:08517 fetch();
518
519 // We don't report backward references to weak symbols as they can be
520 // overridden later.
Fangrui Song03c825c2020-04-06 05:27:46521 //
522 // A traditional linker does not error for -ldef1 -lref -ldef2 (linking
523 // sandwich), where def2 may or may not be the same as def1. We don't want
524 // to warn for this case, so dismiss the warning if we see a subsequent lazy
525 // definition.
Rui Ueyama3837f422019-07-10 05:00:37526 if (backref && !isWeak())
Fangrui Song03c825c2020-04-06 05:27:46527 backwardReferences.try_emplace(this, other.file);
Fangrui Songf3475412019-07-04 10:38:04528 return;
529 }
530
531 // Undefined symbols in a SharedFile do not change the binding.
Rui Ueyama3837f422019-07-10 05:00:37532 if (dyn_cast_or_null<SharedFile>(other.file))
Fangrui Songf3475412019-07-04 10:38:04533 return;
534
Fangrui Songe49c4172019-08-06 14:03:45535 if (isUndefined() || isShared()) {
536 // The binding will be weak if there is at least one reference and all are
537 // weak. The binding has one opportunity to change to weak: if the first
538 // reference is weak.
539 if (other.binding != STB_WEAK || !referenced)
Rui Ueyama3837f422019-07-10 05:00:37540 binding = other.binding;
Rui Ueyama7f7d2b22019-05-23 09:58:08541 }
542}
543
544// Using .symver foo,foo@@VER unfortunately creates two symbols: foo and
545// foo@@VER. We want to effectively ignore foo, so give precedence to
546// foo@@VER.
547// FIXME: If users can transition to using
548// .symver foo,foo@@@VER
549// we can delete this hack.
Rui Ueyama3837f422019-07-10 05:00:37550static int compareVersion(StringRef a, StringRef b) {
551 bool x = a.contains("@@");
552 bool y = b.contains("@@");
553 if (!x && y)
Rui Ueyama7f7d2b22019-05-23 09:58:08554 return 1;
Rui Ueyama3837f422019-07-10 05:00:37555 if (x && !y)
Rui Ueyama7f7d2b22019-05-23 09:58:08556 return -1;
557 return 0;
558}
559
560// Compare two symbols. Return 1 if the new symbol should win, -1 if
561// the new symbol should lose, or 0 if there is a conflict.
Rui Ueyama3837f422019-07-10 05:00:37562int Symbol::compare(const Symbol *other) const {
563 assert(other->isDefined() || other->isCommon());
Rui Ueyama7f7d2b22019-05-23 09:58:08564
565 if (!isDefined() && !isCommon())
566 return 1;
567
Rui Ueyama3837f422019-07-10 05:00:37568 if (int cmp = compareVersion(getName(), other->getName()))
569 return cmp;
Rui Ueyama7f7d2b22019-05-23 09:58:08570
Rui Ueyama3837f422019-07-10 05:00:37571 if (other->isWeak())
Rui Ueyama7f7d2b22019-05-23 09:58:08572 return -1;
573
574 if (isWeak())
575 return 1;
576
Rui Ueyama3837f422019-07-10 05:00:37577 if (isCommon() && other->isCommon()) {
578 if (config->warnCommon)
Rui Ueyama7f7d2b22019-05-23 09:58:08579 warn("multiple common of " + getName());
580 return 0;
581 }
582
583 if (isCommon()) {
Rui Ueyama3837f422019-07-10 05:00:37584 if (config->warnCommon)
Rui Ueyama7f7d2b22019-05-23 09:58:08585 warn("common " + getName() + " is overridden");
586 return 1;
587 }
588
Rui Ueyama3837f422019-07-10 05:00:37589 if (other->isCommon()) {
590 if (config->warnCommon)
Rui Ueyama7f7d2b22019-05-23 09:58:08591 warn("common " + getName() + " is overridden");
592 return -1;
593 }
594
Rui Ueyama3837f422019-07-10 05:00:37595 auto *oldSym = cast<Defined>(this);
596 auto *newSym = cast<Defined>(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08597
Fangrui Songd6c44822019-07-26 16:29:15598 if (dyn_cast_or_null<BitcodeFile>(other->file))
Rui Ueyama7f7d2b22019-05-23 09:58:08599 return 0;
600
Rui Ueyama3837f422019-07-10 05:00:37601 if (!oldSym->section && !newSym->section && oldSym->value == newSym->value &&
602 newSym->binding == STB_GLOBAL)
Rui Ueyama7f7d2b22019-05-23 09:58:08603 return -1;
604
605 return 0;
606}
607
Rui Ueyama3837f422019-07-10 05:00:37608static void reportDuplicate(Symbol *sym, InputFile *newFile,
609 InputSectionBase *errSec, uint64_t errOffset) {
610 if (config->allowMultipleDefinition)
Rui Ueyama7f7d2b22019-05-23 09:58:08611 return;
612
Rui Ueyama3837f422019-07-10 05:00:37613 Defined *d = cast<Defined>(sym);
614 if (!d->section || !errSec) {
615 error("duplicate symbol: " + toString(*sym) + "\n>>> defined in " +
616 toString(sym->file) + "\n>>> defined in " + toString(newFile));
Rui Ueyama7f7d2b22019-05-23 09:58:08617 return;
618 }
619
620 // Construct and print an error message in the form of:
621 //
622 // ld.lld: error: duplicate symbol: foo
623 // >>> defined at bar.c:30
624 // >>> bar.o (/home/alice/src/bar.o)
625 // >>> defined at baz.c:563
626 // >>> baz.o in archive libbaz.a
Rui Ueyama3837f422019-07-10 05:00:37627 auto *sec1 = cast<InputSectionBase>(d->section);
628 std::string src1 = sec1->getSrcMsg(*sym, d->value);
629 std::string obj1 = sec1->getObjMsg(d->value);
630 std::string src2 = errSec->getSrcMsg(*sym, errOffset);
631 std::string obj2 = errSec->getObjMsg(errOffset);
Rui Ueyama7f7d2b22019-05-23 09:58:08632
Rui Ueyama3837f422019-07-10 05:00:37633 std::string msg = "duplicate symbol: " + toString(*sym) + "\n>>> defined at ";
634 if (!src1.empty())
635 msg += src1 + "\n>>> ";
636 msg += obj1 + "\n>>> defined at ";
637 if (!src2.empty())
638 msg += src2 + "\n>>> ";
639 msg += obj2;
640 error(msg);
Rui Ueyama7f7d2b22019-05-23 09:58:08641}
642
Rui Ueyama3837f422019-07-10 05:00:37643void Symbol::resolveCommon(const CommonSymbol &other) {
644 int cmp = compare(&other);
645 if (cmp < 0)
Rui Ueyama7f7d2b22019-05-23 09:58:08646 return;
647
Rui Ueyama3837f422019-07-10 05:00:37648 if (cmp > 0) {
Fangrui Song69d10d22019-12-07 05:18:31649 if (auto *s = dyn_cast<SharedSymbol>(this)) {
650 // Increase st_size if the shared symbol has a larger st_size. The shared
651 // symbol may be created from common symbols. The fact that some object
652 // files were linked into a shared object first should not change the
653 // regular rule that picks the largest st_size.
654 uint64_t size = s->size;
655 replace(other);
656 if (size > cast<CommonSymbol>(this)->size)
657 cast<CommonSymbol>(this)->size = size;
658 } else {
659 replace(other);
660 }
Rui Ueyama7f7d2b22019-05-23 09:58:08661 return;
662 }
663
Rui Ueyama3837f422019-07-10 05:00:37664 CommonSymbol *oldSym = cast<CommonSymbol>(this);
Rui Ueyama7f7d2b22019-05-23 09:58:08665
Rui Ueyama3837f422019-07-10 05:00:37666 oldSym->alignment = std::max(oldSym->alignment, other.alignment);
667 if (oldSym->size < other.size) {
668 oldSym->file = other.file;
669 oldSym->size = other.size;
Rui Ueyama7f7d2b22019-05-23 09:58:08670 }
671}
672
Rui Ueyama3837f422019-07-10 05:00:37673void Symbol::resolveDefined(const Defined &other) {
674 int cmp = compare(&other);
675 if (cmp > 0)
676 replace(other);
677 else if (cmp == 0)
678 reportDuplicate(this, other.file,
679 dyn_cast_or_null<InputSectionBase>(other.section),
680 other.value);
Rui Ueyama7f7d2b22019-05-23 09:58:08681}
682
Rui Ueyama3837f422019-07-10 05:00:37683template <class LazyT> void Symbol::resolveLazy(const LazyT &other) {
Fangrui Song03c825c2020-04-06 05:27:46684 if (!isUndefined()) {
685 // See the comment in resolveUndefined().
686 if (isDefined())
687 backwardReferences.erase(this);
Rui Ueyama7f7d2b22019-05-23 09:58:08688 return;
Fangrui Song03c825c2020-04-06 05:27:46689 }
Rui Ueyama7f7d2b22019-05-23 09:58:08690
691 // An undefined weak will not fetch archive members. See comment on Lazy in
692 // Symbols.h for the details.
693 if (isWeak()) {
Rui Ueyama3837f422019-07-10 05:00:37694 uint8_t ty = type;
695 replace(other);
696 type = ty;
697 binding = STB_WEAK;
Rui Ueyama7f7d2b22019-05-23 09:58:08698 return;
699 }
700
Rui Ueyama3837f422019-07-10 05:00:37701 other.fetch();
Rui Ueyama7f7d2b22019-05-23 09:58:08702}
703
Rui Ueyama3837f422019-07-10 05:00:37704void Symbol::resolveShared(const SharedSymbol &other) {
Fangrui Song69d10d22019-12-07 05:18:31705 if (isCommon()) {
706 // See the comment in resolveCommon() above.
707 if (other.size > cast<CommonSymbol>(this)->size)
708 cast<CommonSymbol>(this)->size = other.size;
709 return;
710 }
Rui Ueyama3837f422019-07-10 05:00:37711 if (visibility == STV_DEFAULT && (isUndefined() || isLazy())) {
Rui Ueyama7f7d2b22019-05-23 09:58:08712 // An undefined symbol with non default visibility must be satisfied
713 // in the same DSO.
Rui Ueyama3837f422019-07-10 05:00:37714 uint8_t bind = binding;
715 replace(other);
716 binding = bind;
Rui Ueyama7f7d2b22019-05-23 09:58:08717 }
718}
Fangrui Songbd8cfe62019-10-07 08:31:18719
720} // namespace elf
721} // namespace lld