blob: 235ebe4560ff739fe02cd0cf0e975f80b8ae139b [file] [log] [blame]
Michael J. Spencer84487f12015-07-24 21:03:07 +00001//===- Symbols.cpp --------------------------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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:07 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "Symbols.h"
Michael J. Spencercdae0a42015-07-28 22:58:25 +000010#include "InputFiles.h"
Rui Ueyamab5a69702016-02-01 21:00:35 +000011#include "InputSection.h"
12#include "OutputSections.h"
Rui Ueyamae8a61022016-11-05 23:05:47 +000013#include "SyntheticSections.h"
Rui Ueyamab5a69702016-02-01 21:00:35 +000014#include "Target.h"
Rafael Espindola17cb7c02016-12-19 17:01:01 +000015#include "Writer.h"
Bob Haarmanb8a59c82017-10-25 22:28:38 +000016#include "lld/Common/ErrorHandler.h"
Rui Ueyama53fe4692017-11-28 02:15:26 +000017#include "lld/Common/Strings.h"
Michael J. Spencer1b348a62015-09-04 22:28:10 +000018#include "llvm/ADT/STLExtras.h"
Fangrui Song23257882020-04-04 21:31:36 -070019#include "llvm/Support/FileSystem.h"
Eugene Leviantc958d8d2016-10-12 08:19:30 +000020#include "llvm/Support/Path.h"
Rui Ueyamac72ba3a2016-11-23 04:57:25 +000021#include <cstring>
Michael J. Spencer1b348a62015-09-04 22:28:10 +000022
23using namespace llvm;
Michael J. Spencer84487f12015-07-24 21:03:07 +000024using namespace llvm::object;
Rafael Espindola78471f02015-09-01 23:12:52 +000025using namespace llvm::ELF;
Michael J. Spencer84487f12015-07-24 21:03:07 +000026
Fangrui Songbd8cfe62019-10-07 08:31:18 +000027namespace lld {
28// Returns a symbol for an error message.
29static std::string demangle(StringRef symName) {
30 if (elf::config->demangle)
31 return demangleItanium(symName);
Benjamin Krameradcd0262020-01-28 20:23:46 +010032 return std::string(symName);
Fangrui Songbd8cfe62019-10-07 08:31:18 +000033}
Michael J. Spencer84487f12015-07-24 21:03:07 +000034
Fangrui Songf2036a12020-03-28 15:48:38 -070035std::string toString(const elf::Symbol &sym) {
36 StringRef name = sym.getName();
37 std::string ret = demangle(name);
38
39 // If sym has a non-default version, its name may have been truncated at '@'
40 // by Symbol::parseSymbolVersion(). Add the trailing part. This check is safe
41 // because every symbol name ends with '\0'.
42 if (name.data()[name.size()] == '@')
43 ret += name.data() + name.size();
44 return ret;
45}
46
Fangrui Songbd8cfe62019-10-07 08:31:18 +000047std::string toELFString(const Archive::Symbol &b) {
48 return demangle(b.getName());
49}
50
51namespace elf {
Rui Ueyama3837f422019-07-10 05:00:37 +000052Defined *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 Song03c825c2020-04-05 22:27:46 -070067DenseMap<const Symbol *, const InputFile *> backwardReferences;
Rui Ueyama80474a22017-02-28 19:29:55 +000068
Rui Ueyama3837f422019-07-10 05:00:37 +000069static uint64_t getSymVA(const Symbol &sym, int64_t &addend) {
70 switch (sym.kind()) {
Peter Collingbournee9a9e0a2017-11-06 04:35:31 +000071 case Symbol::DefinedKind: {
Rui Ueyama3837f422019-07-10 05:00:37 +000072 auto &d = cast<Defined>(sym);
73 SectionBase *isec = d.section;
Rui Ueyamab5a69702016-02-01 21:00:35 +000074
75 // This is an absolute symbol.
Rui Ueyama3837f422019-07-10 05:00:37 +000076 if (!isec)
77 return d.value;
Rui Ueyamab5a69702016-02-01 21:00:35 +000078
Rui Ueyama3837f422019-07-10 05:00:37 +000079 assert(isec != &InputSection::discarded);
80 isec = isec->repl;
Rafael Espindolaf4d6e8c2018-04-19 17:26:50 +000081
Rui Ueyama3837f422019-07-10 05:00:37 +000082 uint64_t offset = d.value;
Sean Silvaa9ba4502017-02-28 08:32:56 +000083
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:04 +000087 // 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:37 +000095 if (d.isSection()) {
96 offset += addend;
97 addend = 0;
Rafael Espindola1f5b70f2016-03-11 14:21:37 +000098 }
Sean Silvaa9ba4502017-02-28 08:32:56 +000099
Sean Silva6ab39262017-02-28 09:01:58 +0000100 // 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:37 +0000110 uint64_t va = isec->getVA(offset);
Sean Silva6ab39262017-02-28 09:01:58 +0000111
Simon Atanasyanfae2a5092019-02-19 10:36:58 +0000112 // 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-22 21:39:16 -0800115 // field. Unfortunately, the `MIPS::relocate()` method has
Simon Atanasyanfae2a5092019-02-19 10:36:58 +0000116 // 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:37 +0000121 if (config->emachine == EM_MIPS && isMicroMips() &&
122 ((sym.stOther & STO_MIPS_MICROMIPS) || sym.needsPltAddr))
123 va |= 1;
Simon Atanasyanfae2a5092019-02-19 10:36:58 +0000124
Rui Ueyama3837f422019-07-10 05:00:37 +0000125 if (d.isTls() && !config->relocatable) {
Ryan Prichard1c33d142018-09-18 00:24:48 +0000126 // 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:37 +0000131 if (!Out::tlsPhdr || !Out::tlsPhdr->firstSec)
132 fatal(toString(d.file) +
Peter Collingbourne3e2abde2017-07-14 00:22:46 +0000133 " has an STT_TLS symbol but doesn't have an SHF_TLS section");
Rui Ueyama3837f422019-07-10 05:00:37 +0000134 return va - Out::tlsPhdr->firstSec->addr;
George Rimar6a3b1542016-10-04 08:52:51 +0000135 }
Rui Ueyama3837f422019-07-10 05:00:37 +0000136 return va;
Rui Ueyamab5a69702016-02-01 21:00:35 +0000137 }
Rafael Espindolaab0cce52018-04-26 17:58:58 +0000138 case Symbol::SharedKind:
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000139 case Symbol::UndefinedKind:
Rui Ueyamab5a69702016-02-01 21:00:35 +0000140 return 0;
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000141 case Symbol::LazyArchiveKind:
142 case Symbol::LazyObjectKind:
Rui Ueyama3837f422019-07-10 05:00:37 +0000143 assert(sym.isUsedInRegularObj && "lazy symbol reached writer");
Chih-Hung Hsieh73e04842018-09-11 23:00:36 +0000144 return 0;
Rui Ueyama5c073a92019-05-16 03:29:03 +0000145 case Symbol::CommonKind:
146 llvm_unreachable("common symbol reached writer");
Rui Ueyamaf3fad552018-10-12 18:29:18 +0000147 case Symbol::PlaceholderKind:
148 llvm_unreachable("placeholder symbol reached writer");
Rui Ueyamab5a69702016-02-01 21:00:35 +0000149 }
George Rimar777f9632016-03-12 08:31:34 +0000150 llvm_unreachable("invalid symbol kind");
Rui Ueyamab5a69702016-02-01 21:00:35 +0000151}
152
Rui Ueyama3837f422019-07-10 05:00:37 +0000153uint64_t Symbol::getVA(int64_t addend) const {
154 uint64_t outVA = getSymVA(*this, addend);
155 return outVA + addend;
Rafael Espindola87d9f102016-03-11 12:19:05 +0000156}
157
Peter Collingbourne8331f612019-02-13 21:49:55 +0000158uint64_t Symbol::getGotVA() const {
Rui Ueyama3837f422019-07-10 05:00:37 +0000159 if (gotInIgot)
160 return in.igotPlt->getVA() + getGotPltOffset();
161 return in.got->getVA() + getGotOffset();
Peter Collingbourne8331f612019-02-13 21:49:55 +0000162}
Rafael Espindola74031ba2016-04-07 15:20:56 +0000163
Rui Ueyama3837f422019-07-10 05:00:37 +0000164uint64_t Symbol::getGotOffset() const { return gotIndex * config->wordsize; }
Rui Ueyamab5a69702016-02-01 21:00:35 +0000165
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000166uint64_t Symbol::getGotPltVA() const {
Rui Ueyama3837f422019-07-10 05:00:37 +0000167 if (isInIplt)
168 return in.igotPlt->getVA() + getGotPltOffset();
169 return in.gotPlt->getVA() + getGotPltOffset();
Rafael Espindola74031ba2016-04-07 15:20:56 +0000170}
171
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000172uint64_t Symbol::getGotPltOffset() const {
Rui Ueyama3837f422019-07-10 05:00:37 +0000173 if (isInIplt)
174 return pltIndex * config->wordsize;
175 return (pltIndex + target->gotPltHeaderEntriesNum) * config->wordsize;
Rui Ueyamab5a69702016-02-01 21:00:35 +0000176}
177
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000178uint64_t Symbol::getPltVA() const {
Fangrui Song891a8652019-12-14 14:17:35 -0800179 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:58 +0000184 // 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:37 +0000187 if (config->emachine == EM_MIPS && isMicroMips())
188 outVA |= 1;
189 return outVA;
Rafael Espindolaab0cce52018-04-26 17:58:58 +0000190}
191
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000192uint64_t Symbol::getSize() const {
Rui Ueyama3837f422019-07-10 05:00:37 +0000193 if (const auto *dr = dyn_cast<Defined>(this))
194 return dr->size;
195 return cast<SharedSymbol>(this)->size;
Rui Ueyama512c61d2016-02-03 00:12:24 +0000196}
197
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000198OutputSection *Symbol::getOutputSection() const {
Rui Ueyama3837f422019-07-10 05:00:37 +0000199 if (auto *s = dyn_cast<Defined>(this)) {
200 if (auto *sec = s->section)
201 return sec->repl->getOutputSection();
Rui Ueyama968db482017-02-28 04:02:42 +0000202 return nullptr;
203 }
Rui Ueyama968db482017-02-28 04:02:42 +0000204 return nullptr;
205}
206
Rui Ueyama35fa6c52016-11-23 05:48:40 +0000207// 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:47 +0000209void Symbol::parseSymbolVersion() {
Rui Ueyama3837f422019-07-10 05:00:37 +0000210 StringRef s = getName();
211 size_t pos = s.find('@');
212 if (pos == 0 || pos == StringRef::npos)
Rui Ueyama35fa6c52016-11-23 05:48:40 +0000213 return;
Rui Ueyama3837f422019-07-10 05:00:37 +0000214 StringRef verstr = s.substr(pos + 1);
215 if (verstr.empty())
Rui Ueyama35fa6c52016-11-23 05:48:40 +0000216 return;
217
218 // Truncate the symbol name so that it doesn't include the version string.
Rui Ueyama3837f422019-07-10 05:00:37 +0000219 nameSize = pos;
Rui Ueyama35fa6c52016-11-23 05:48:40 +0000220
Rafael Espindola1d6d1b42017-01-17 16:08:06 +0000221 // If this is not in this DSO, it is not a definition.
Peter Collingbourneb472aa02017-11-06 04:39:07 +0000222 if (!isDefined())
Rafael Espindola2756e042017-01-06 22:30:35 +0000223 return;
224
Rui Ueyama35fa6c52016-11-23 05:48:40 +0000225 // '@@' in a symbol name means the default version.
226 // It is usually the most recent one.
Rui Ueyama3837f422019-07-10 05:00:37 +0000227 bool isDefault = (verstr[0] == '@');
228 if (isDefault)
229 verstr = verstr.substr(1);
Rui Ueyama35fa6c52016-11-23 05:48:40 +0000230
Fangrui Songe28a70d2019-08-05 14:31:39 +0000231 for (const VersionDefinition &ver : namedVersionDefs()) {
Rui Ueyama3837f422019-07-10 05:00:37 +0000232 if (ver.name != verstr)
Rui Ueyama35fa6c52016-11-23 05:48:40 +0000233 continue;
234
Rui Ueyama3837f422019-07-10 05:00:37 +0000235 if (isDefault)
236 versionId = ver.id;
Rui Ueyama35fa6c52016-11-23 05:48:40 +0000237 else
Rui Ueyama3837f422019-07-10 05:00:37 +0000238 versionId = ver.id | VERSYM_HIDDEN;
Rui Ueyama35fa6c52016-11-23 05:48:40 +0000239 return;
240 }
241
242 // It is an error if the specified version is not defined.
George Rimar4d2f97622017-07-04 13:19:13 +0000243 // 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:56 +0000245 // 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:37 +0000248 if (config->shared && versionId != VER_NDX_LOCAL)
249 error(toString(file) + ": symbol " + s + " has undefined version " +
250 verstr);
Rui Ueyama35fa6c52016-11-23 05:48:40 +0000251}
252
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000253void Symbol::fetch() const {
Rui Ueyama3837f422019-07-10 05:00:37 +0000254 if (auto *sym = dyn_cast<LazyArchive>(this)) {
255 cast<ArchiveFile>(sym->file)->fetch(sym->sym);
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000256 return;
257 }
258
Rui Ueyama3837f422019-07-10 05:00:37 +0000259 if (auto *sym = dyn_cast<LazyObject>(this)) {
260 dyn_cast<LazyObjFile>(sym->file)->fetch();
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000261 return;
262 }
263
264 llvm_unreachable("Symbol::fetch() is called on a non-lazy symbol");
Rui Ueyama7d476192019-05-16 02:14:00 +0000265}
Rui Ueyamaf8baa662016-04-07 19:24:51 +0000266
Peter Collingbourne98930112018-08-08 23:48:12 +0000267MemoryBufferRef LazyArchive::getMemberBuffer() {
Nico Weber9c0716f2019-07-23 19:00:01 +0000268 Archive::Child c =
269 CHECK(sym.getMember(),
270 "could not get the member for symbol " + toELFString(sym));
Peter Collingbourne98930112018-08-08 23:48:12 +0000271
Rui Ueyama3837f422019-07-10 05:00:37 +0000272 return CHECK(c.getMemoryBufferRef(),
Peter Collingbourne98930112018-08-08 23:48:12 +0000273 "could not get the buffer for the member defining symbol " +
Nico Weber9c0716f2019-07-23 19:00:01 +0000274 toELFString(sym));
Peter Collingbourne98930112018-08-08 23:48:12 +0000275}
276
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000277uint8_t Symbol::computeBinding() const {
Rui Ueyama3837f422019-07-10 05:00:37 +0000278 if (config->relocatable)
279 return binding;
Fangrui Songcfdd4582019-08-11 17:03:00 +0000280 if ((visibility != STV_DEFAULT && visibility != STV_PROTECTED) ||
Fangrui Songc1c679e2020-04-01 16:11:31 -0700281 (versionId == VER_NDX_LOCAL && isDefined()))
Rafael Espindolab7e2ee22017-01-10 17:08:13 +0000282 return STB_LOCAL;
Rui Ueyama3837f422019-07-10 05:00:37 +0000283 if (!config->gnuUnique && binding == STB_GNU_UNIQUE)
Rafael Espindolab7e2ee22017-01-10 17:08:13 +0000284 return STB_GLOBAL;
Rui Ueyama3837f422019-07-10 05:00:37 +0000285 return binding;
Rafael Espindolab7e2ee22017-01-10 17:08:13 +0000286}
287
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000288bool Symbol::includeInDynsym() const {
Rui Ueyama3837f422019-07-10 05:00:37 +0000289 if (!config->hasDynSymTab)
Rafael Espindolae05e2f82017-09-15 18:05:02 +0000290 return false;
Rafael Espindolab7e2ee22017-01-10 17:08:13 +0000291 if (computeBinding() == STB_LOCAL)
Rafael Espindolaae605c12016-04-21 20:35:25 +0000292 return false;
Fangrui Song375371c2020-01-09 15:53:52 -0800293 if (!isDefined() && !isCommon())
Fangrui Song0fbf28f2020-01-23 11:52:03 -0800294 // 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:07 +0000299
Fangrui Song375371c2020-01-09 15:53:52 -0800300 return exportDynamic || inDynamicList;
Rafael Espindolaae605c12016-04-21 20:35:25 +0000301}
Rui Ueyama69c778c2016-07-17 17:50:09 +0000302
303// Print out a log message for --trace-symbol.
Fangrui Songbd8cfe62019-10-07 08:31:18 +0000304void printTraceSymbol(const Symbol *sym) {
Rui Ueyama3837f422019-07-10 05:00:37 +0000305 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:09 +0000314 else
Rui Ueyama3837f422019-07-10 05:00:37 +0000315 s = ": definition of ";
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000316
Rui Ueyama3837f422019-07-10 05:00:37 +0000317 message(toString(sym->file) + s + sym->getName());
Rui Ueyama69c778c2016-07-17 17:50:09 +0000318}
319
Fangrui Songbd8cfe62019-10-07 08:31:18 +0000320void maybeWarnUnorderableSymbol(const Symbol *sym) {
Rui Ueyama3837f422019-07-10 05:00:37 +0000321 if (!config->warnSymbolOrdering)
Michael J. Spencerb8427252018-04-17 23:30:05 +0000322 return;
Rui Ueyamab774c3c2018-04-26 01:38:29 +0000323
Fangrui Song11ca54f2018-10-10 22:48:57 +0000324 // 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:37 +0000329 if (sym->isUndefined() &&
330 config->unresolvedSymbols == UnresolvedPolicy::Ignore)
Fangrui Song11ca54f2018-10-10 22:48:57 +0000331 return;
332
Rui Ueyama3837f422019-07-10 05:00:37 +0000333 const InputFile *file = sym->file;
334 auto *d = dyn_cast<Defined>(sym);
Rui Ueyamab774c3c2018-04-26 01:38:29 +0000335
Rui Ueyama3837f422019-07-10 05:00:37 +0000336 auto report = [&](StringRef s) { warn(toString(file) + s + sym->getName()); };
Rui Ueyamab774c3c2018-04-26 01:38:29 +0000337
Rui Ueyama3837f422019-07-10 05:00:37 +0000338 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:05 +0000348}
349
Fangrui Songcd0ab242019-11-29 21:58:36 -0800350// 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.
352bool computeIsPreemptible(const Symbol &sym) {
353 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
368 // If the dynamic list is present, it specifies preemptable symbols in a DSO.
369 if (config->hasDynamicList)
370 return sym.inDynamicList;
371
372 // -Bsymbolic means that definitions are not preempted.
373 if (config->bsymbolic || (config->bsymbolicFunctions && sym.isFunc()))
374 return false;
375 return true;
376}
377
Fangrui Song03c825c2020-04-05 22:27:46 -0700378void reportBackrefs() {
379 for (auto &it : backwardReferences) {
380 const Symbol &sym = *it.first;
381 warn("backward reference detected: " + sym.getName() + " in " +
382 toString(it.second) + " refers to " + toString(sym.file));
383 }
384}
385
Rui Ueyama3837f422019-07-10 05:00:37 +0000386static uint8_t getMinVisibility(uint8_t va, uint8_t vb) {
387 if (va == STV_DEFAULT)
388 return vb;
389 if (vb == STV_DEFAULT)
390 return va;
391 return std::min(va, vb);
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000392}
393
394// Merge symbol properties.
395//
396// When we have many symbols of the same name, we choose one of them,
397// and that's the result of symbol resolution. However, symbols that
398// were not chosen still affect some symbol properties.
Rui Ueyama3837f422019-07-10 05:00:37 +0000399void Symbol::mergeProperties(const Symbol &other) {
400 if (other.exportDynamic)
401 exportDynamic = true;
402 if (other.isUsedInRegularObj)
403 isUsedInRegularObj = true;
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000404
405 // DSO symbols do not affect visibility in the output.
Rui Ueyama3837f422019-07-10 05:00:37 +0000406 if (!other.isShared())
407 visibility = getMinVisibility(visibility, other.visibility);
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000408}
409
Rui Ueyama3837f422019-07-10 05:00:37 +0000410void Symbol::resolve(const Symbol &other) {
411 mergeProperties(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000412
413 if (isPlaceholder()) {
Rui Ueyama3837f422019-07-10 05:00:37 +0000414 replace(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000415 return;
416 }
417
Rui Ueyama3837f422019-07-10 05:00:37 +0000418 switch (other.kind()) {
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000419 case Symbol::UndefinedKind:
Rui Ueyama3837f422019-07-10 05:00:37 +0000420 resolveUndefined(cast<Undefined>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000421 break;
422 case Symbol::CommonKind:
Rui Ueyama3837f422019-07-10 05:00:37 +0000423 resolveCommon(cast<CommonSymbol>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000424 break;
425 case Symbol::DefinedKind:
Rui Ueyama3837f422019-07-10 05:00:37 +0000426 resolveDefined(cast<Defined>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000427 break;
428 case Symbol::LazyArchiveKind:
Rui Ueyama3837f422019-07-10 05:00:37 +0000429 resolveLazy(cast<LazyArchive>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000430 break;
431 case Symbol::LazyObjectKind:
Rui Ueyama3837f422019-07-10 05:00:37 +0000432 resolveLazy(cast<LazyObject>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000433 break;
434 case Symbol::SharedKind:
Rui Ueyama3837f422019-07-10 05:00:37 +0000435 resolveShared(cast<SharedSymbol>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000436 break;
437 case Symbol::PlaceholderKind:
438 llvm_unreachable("bad symbol kind");
439 }
440}
441
Rui Ueyama3837f422019-07-10 05:00:37 +0000442void Symbol::resolveUndefined(const Undefined &other) {
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000443 // An undefined symbol with non default visibility must be satisfied
444 // in the same DSO.
445 //
446 // If this is a non-weak defined symbol in a discarded section, override the
447 // existing undefined symbol for better error message later.
Rui Ueyama3837f422019-07-10 05:00:37 +0000448 if ((isShared() && other.visibility != STV_DEFAULT) ||
449 (isUndefined() && other.binding != STB_WEAK && other.discardedSecIdx)) {
450 replace(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000451 return;
452 }
453
Rui Ueyama3837f422019-07-10 05:00:37 +0000454 if (traced)
455 printTraceSymbol(&other);
Sam Clegg7991b682019-05-24 13:29:17 +0000456
Fangrui Songf3475412019-07-04 10:38:04 +0000457 if (isLazy()) {
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000458 // An undefined weak will not fetch archive members. See comment on Lazy in
459 // Symbols.h for the details.
Rui Ueyama3837f422019-07-10 05:00:37 +0000460 if (other.binding == STB_WEAK) {
461 binding = STB_WEAK;
462 type = other.type;
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000463 return;
464 }
465
466 // Do extra check for --warn-backrefs.
467 //
468 // --warn-backrefs is an option to prevent an undefined reference from
469 // fetching an archive member written earlier in the command line. It can be
470 // used to keep compatibility with GNU linkers to some degree.
471 // I'll explain the feature and why you may find it useful in this comment.
472 //
473 // lld's symbol resolution semantics is more relaxed than traditional Unix
474 // linkers. For example,
475 //
476 // ld.lld foo.a bar.o
477 //
478 // succeeds even if bar.o contains an undefined symbol that has to be
479 // resolved by some object file in foo.a. Traditional Unix linkers don't
480 // allow this kind of backward reference, as they visit each file only once
481 // from left to right in the command line while resolving all undefined
482 // symbols at the moment of visiting.
483 //
484 // In the above case, since there's no undefined symbol when a linker visits
485 // foo.a, no files are pulled out from foo.a, and because the linker forgets
486 // about foo.a after visiting, it can't resolve undefined symbols in bar.o
487 // that could have been resolved otherwise.
488 //
489 // That lld accepts more relaxed form means that (besides it'd make more
490 // sense) you can accidentally write a command line or a build file that
491 // works only with lld, even if you have a plan to distribute it to wider
492 // users who may be using GNU linkers. With --warn-backrefs, you can detect
493 // a library order that doesn't work with other Unix linkers.
494 //
495 // The option is also useful to detect cyclic dependencies between static
496 // archives. Again, lld accepts
497 //
498 // ld.lld foo.a bar.a
499 //
500 // even if foo.a and bar.a depend on each other. With --warn-backrefs, it is
501 // handled as an error.
502 //
503 // Here is how the option works. We assign a group ID to each file. A file
504 // with a smaller group ID can pull out object files from an archive file
505 // with an equal or greater group ID. Otherwise, it is a reverse dependency
506 // and an error.
507 //
508 // A file outside --{start,end}-group gets a fresh ID when instantiated. All
509 // files within the same --{start,end}-group get the same group ID. E.g.
510 //
511 // ld.lld A B --start-group C D --end-group E
512 //
513 // A forms group 0. B form group 1. C and D (including their member object
514 // files) form group 2. E forms group 3. I think that you can see how this
515 // group assignment rule simulates the traditional linker's semantics.
Rui Ueyama3837f422019-07-10 05:00:37 +0000516 bool backref = config->warnBackrefs && other.file &&
517 file->groupId < other.file->groupId;
Fangrui Song23257882020-04-04 21:31:36 -0700518 if (backref) {
519 // Some libraries have known problems and can cause noise. Filter them out
520 // with --warn-backrefs-exclude=.
521 StringRef name =
522 !file->archiveName.empty() ? file->archiveName : file->getName();
523 for (const llvm::GlobPattern &pat : config->warnBackrefsExclude)
524 if (pat.match(name)) {
525 backref = false;
526 break;
527 }
528 }
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000529 fetch();
530
531 // We don't report backward references to weak symbols as they can be
532 // overridden later.
Fangrui Song03c825c2020-04-05 22:27:46 -0700533 //
534 // A traditional linker does not error for -ldef1 -lref -ldef2 (linking
535 // sandwich), where def2 may or may not be the same as def1. We don't want
536 // to warn for this case, so dismiss the warning if we see a subsequent lazy
537 // definition.
Rui Ueyama3837f422019-07-10 05:00:37 +0000538 if (backref && !isWeak())
Fangrui Song03c825c2020-04-05 22:27:46 -0700539 backwardReferences.try_emplace(this, other.file);
Fangrui Songf3475412019-07-04 10:38:04 +0000540 return;
541 }
542
543 // Undefined symbols in a SharedFile do not change the binding.
Rui Ueyama3837f422019-07-10 05:00:37 +0000544 if (dyn_cast_or_null<SharedFile>(other.file))
Fangrui Songf3475412019-07-04 10:38:04 +0000545 return;
546
Fangrui Songe49c4172019-08-06 14:03:45 +0000547 if (isUndefined() || isShared()) {
548 // The binding will be weak if there is at least one reference and all are
549 // weak. The binding has one opportunity to change to weak: if the first
550 // reference is weak.
551 if (other.binding != STB_WEAK || !referenced)
Rui Ueyama3837f422019-07-10 05:00:37 +0000552 binding = other.binding;
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000553 }
554}
555
556// Using .symver foo,foo@@VER unfortunately creates two symbols: foo and
557// foo@@VER. We want to effectively ignore foo, so give precedence to
558// foo@@VER.
559// FIXME: If users can transition to using
560// .symver foo,foo@@@VER
561// we can delete this hack.
Rui Ueyama3837f422019-07-10 05:00:37 +0000562static int compareVersion(StringRef a, StringRef b) {
563 bool x = a.contains("@@");
564 bool y = b.contains("@@");
565 if (!x && y)
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000566 return 1;
Rui Ueyama3837f422019-07-10 05:00:37 +0000567 if (x && !y)
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000568 return -1;
569 return 0;
570}
571
572// Compare two symbols. Return 1 if the new symbol should win, -1 if
573// the new symbol should lose, or 0 if there is a conflict.
Rui Ueyama3837f422019-07-10 05:00:37 +0000574int Symbol::compare(const Symbol *other) const {
575 assert(other->isDefined() || other->isCommon());
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000576
577 if (!isDefined() && !isCommon())
578 return 1;
579
Rui Ueyama3837f422019-07-10 05:00:37 +0000580 if (int cmp = compareVersion(getName(), other->getName()))
581 return cmp;
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000582
Rui Ueyama3837f422019-07-10 05:00:37 +0000583 if (other->isWeak())
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000584 return -1;
585
586 if (isWeak())
587 return 1;
588
Rui Ueyama3837f422019-07-10 05:00:37 +0000589 if (isCommon() && other->isCommon()) {
590 if (config->warnCommon)
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000591 warn("multiple common of " + getName());
592 return 0;
593 }
594
595 if (isCommon()) {
Rui Ueyama3837f422019-07-10 05:00:37 +0000596 if (config->warnCommon)
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000597 warn("common " + getName() + " is overridden");
598 return 1;
599 }
600
Rui Ueyama3837f422019-07-10 05:00:37 +0000601 if (other->isCommon()) {
602 if (config->warnCommon)
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000603 warn("common " + getName() + " is overridden");
604 return -1;
605 }
606
Rui Ueyama3837f422019-07-10 05:00:37 +0000607 auto *oldSym = cast<Defined>(this);
608 auto *newSym = cast<Defined>(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000609
Fangrui Songd6c44822019-07-26 16:29:15 +0000610 if (dyn_cast_or_null<BitcodeFile>(other->file))
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000611 return 0;
612
Rui Ueyama3837f422019-07-10 05:00:37 +0000613 if (!oldSym->section && !newSym->section && oldSym->value == newSym->value &&
614 newSym->binding == STB_GLOBAL)
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000615 return -1;
616
617 return 0;
618}
619
Rui Ueyama3837f422019-07-10 05:00:37 +0000620static void reportDuplicate(Symbol *sym, InputFile *newFile,
621 InputSectionBase *errSec, uint64_t errOffset) {
622 if (config->allowMultipleDefinition)
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000623 return;
624
Rui Ueyama3837f422019-07-10 05:00:37 +0000625 Defined *d = cast<Defined>(sym);
626 if (!d->section || !errSec) {
627 error("duplicate symbol: " + toString(*sym) + "\n>>> defined in " +
628 toString(sym->file) + "\n>>> defined in " + toString(newFile));
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000629 return;
630 }
631
632 // Construct and print an error message in the form of:
633 //
634 // ld.lld: error: duplicate symbol: foo
635 // >>> defined at bar.c:30
636 // >>> bar.o (/home/alice/src/bar.o)
637 // >>> defined at baz.c:563
638 // >>> baz.o in archive libbaz.a
Rui Ueyama3837f422019-07-10 05:00:37 +0000639 auto *sec1 = cast<InputSectionBase>(d->section);
640 std::string src1 = sec1->getSrcMsg(*sym, d->value);
641 std::string obj1 = sec1->getObjMsg(d->value);
642 std::string src2 = errSec->getSrcMsg(*sym, errOffset);
643 std::string obj2 = errSec->getObjMsg(errOffset);
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000644
Rui Ueyama3837f422019-07-10 05:00:37 +0000645 std::string msg = "duplicate symbol: " + toString(*sym) + "\n>>> defined at ";
646 if (!src1.empty())
647 msg += src1 + "\n>>> ";
648 msg += obj1 + "\n>>> defined at ";
649 if (!src2.empty())
650 msg += src2 + "\n>>> ";
651 msg += obj2;
652 error(msg);
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000653}
654
Rui Ueyama3837f422019-07-10 05:00:37 +0000655void Symbol::resolveCommon(const CommonSymbol &other) {
656 int cmp = compare(&other);
657 if (cmp < 0)
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000658 return;
659
Rui Ueyama3837f422019-07-10 05:00:37 +0000660 if (cmp > 0) {
Fangrui Song69d10d22019-12-06 21:18:31 -0800661 if (auto *s = dyn_cast<SharedSymbol>(this)) {
662 // Increase st_size if the shared symbol has a larger st_size. The shared
663 // symbol may be created from common symbols. The fact that some object
664 // files were linked into a shared object first should not change the
665 // regular rule that picks the largest st_size.
666 uint64_t size = s->size;
667 replace(other);
668 if (size > cast<CommonSymbol>(this)->size)
669 cast<CommonSymbol>(this)->size = size;
670 } else {
671 replace(other);
672 }
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000673 return;
674 }
675
Rui Ueyama3837f422019-07-10 05:00:37 +0000676 CommonSymbol *oldSym = cast<CommonSymbol>(this);
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000677
Rui Ueyama3837f422019-07-10 05:00:37 +0000678 oldSym->alignment = std::max(oldSym->alignment, other.alignment);
679 if (oldSym->size < other.size) {
680 oldSym->file = other.file;
681 oldSym->size = other.size;
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000682 }
683}
684
Rui Ueyama3837f422019-07-10 05:00:37 +0000685void Symbol::resolveDefined(const Defined &other) {
686 int cmp = compare(&other);
687 if (cmp > 0)
688 replace(other);
689 else if (cmp == 0)
690 reportDuplicate(this, other.file,
691 dyn_cast_or_null<InputSectionBase>(other.section),
692 other.value);
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000693}
694
Rui Ueyama3837f422019-07-10 05:00:37 +0000695template <class LazyT> void Symbol::resolveLazy(const LazyT &other) {
Fangrui Song03c825c2020-04-05 22:27:46 -0700696 if (!isUndefined()) {
697 // See the comment in resolveUndefined().
698 if (isDefined())
699 backwardReferences.erase(this);
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000700 return;
Fangrui Song03c825c2020-04-05 22:27:46 -0700701 }
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000702
703 // An undefined weak will not fetch archive members. See comment on Lazy in
704 // Symbols.h for the details.
705 if (isWeak()) {
Rui Ueyama3837f422019-07-10 05:00:37 +0000706 uint8_t ty = type;
707 replace(other);
708 type = ty;
709 binding = STB_WEAK;
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000710 return;
711 }
712
Rui Ueyama3837f422019-07-10 05:00:37 +0000713 other.fetch();
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000714}
715
Rui Ueyama3837f422019-07-10 05:00:37 +0000716void Symbol::resolveShared(const SharedSymbol &other) {
Fangrui Song69d10d22019-12-06 21:18:31 -0800717 if (isCommon()) {
718 // See the comment in resolveCommon() above.
719 if (other.size > cast<CommonSymbol>(this)->size)
720 cast<CommonSymbol>(this)->size = other.size;
721 return;
722 }
Rui Ueyama3837f422019-07-10 05:00:37 +0000723 if (visibility == STV_DEFAULT && (isUndefined() || isLazy())) {
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000724 // An undefined symbol with non default visibility must be satisfied
725 // in the same DSO.
Rui Ueyama3837f422019-07-10 05:00:37 +0000726 uint8_t bind = binding;
727 replace(other);
728 binding = bind;
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000729 }
730}
Fangrui Songbd8cfe62019-10-07 08:31:18 +0000731
732} // namespace elf
733} // namespace lld