blob: 8c410b4d5bfbb71688be49a832a11ec7fd9f922c [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;
Fangrui Song07837b82020-05-14 22:18:58 -070026using namespace lld;
27using namespace lld::elf;
Michael J. Spencer84487f12015-07-24 21:03:07 +000028
Fangrui Songbd8cfe62019-10-07 08:31:18 +000029// 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 20:23:46 +010033 return std::string(symName);
Fangrui Songbd8cfe62019-10-07 08:31:18 +000034}
Michael J. Spencer84487f12015-07-24 21:03:07 +000035
Fangrui Song07837b82020-05-14 22:18:58 -070036std::string lld::toString(const elf::Symbol &sym) {
Fangrui Songf2036a12020-03-28 15:48:38 -070037 StringRef name = sym.getName();
38 std::string ret = demangle(name);
39
Fangrui Song941e9332020-12-01 08:54:01 -080040 const char *suffix = sym.getVersionSuffix();
41 if (*suffix == '@')
42 ret += suffix;
Fangrui Songf2036a12020-03-28 15:48:38 -070043 return ret;
44}
45
Fangrui Song07837b82020-05-14 22:18:58 -070046std::string lld::toELFString(const Archive::Symbol &b) {
Fangrui Songbd8cfe62019-10-07 08:31:18 +000047 return demangle(b.getName());
48}
49
Rui Ueyama3837f422019-07-10 05:00:37 +000050Defined *ElfSym::bss;
51Defined *ElfSym::etext1;
52Defined *ElfSym::etext2;
53Defined *ElfSym::edata1;
54Defined *ElfSym::edata2;
55Defined *ElfSym::end1;
56Defined *ElfSym::end2;
57Defined *ElfSym::globalOffsetTable;
58Defined *ElfSym::mipsGp;
59Defined *ElfSym::mipsGpDisp;
60Defined *ElfSym::mipsLocalGp;
61Defined *ElfSym::relaIpltStart;
62Defined *ElfSym::relaIpltEnd;
63Defined *ElfSym::riscvGlobalPointer;
64Defined *ElfSym::tlsModuleBase;
Fangrui Songce3c5da2020-10-22 15:26:52 -070065DenseMap<const Symbol *, std::pair<const InputFile *, const InputFile *>>
66 elf::backwardReferences;
Fangrui Songa954bb12021-09-20 09:52:30 -070067SmallVector<std::tuple<std::string, const InputFile *, const Symbol &>, 0>
68 elf::whyExtract;
Rui Ueyama80474a22017-02-28 19:29:55 +000069
Rui Ueyama3837f422019-07-10 05:00:37 +000070static uint64_t getSymVA(const Symbol &sym, int64_t &addend) {
71 switch (sym.kind()) {
Peter Collingbournee9a9e0a2017-11-06 04:35:31 +000072 case Symbol::DefinedKind: {
Rui Ueyama3837f422019-07-10 05:00:37 +000073 auto &d = cast<Defined>(sym);
74 SectionBase *isec = d.section;
Rui Ueyamab5a69702016-02-01 21:00:35 +000075
76 // This is an absolute symbol.
Rui Ueyama3837f422019-07-10 05:00:37 +000077 if (!isec)
78 return d.value;
Rui Ueyamab5a69702016-02-01 21:00:35 +000079
Rui Ueyama3837f422019-07-10 05:00:37 +000080 assert(isec != &InputSection::discarded);
81 isec = isec->repl;
Rafael Espindolaf4d6e8c2018-04-19 17:26:50 +000082
Rui Ueyama3837f422019-07-10 05:00:37 +000083 uint64_t offset = d.value;
Sean Silvaa9ba4502017-02-28 08:32:56 +000084
85 // An object in an SHF_MERGE section might be referenced via a
86 // section symbol (as a hack for reducing the number of local
87 // symbols).
Sean Silvad4e60622017-03-01 04:44:04 +000088 // Depending on the addend, the reference via a section symbol
89 // refers to a different object in the merge section.
90 // Since the objects in the merge section are not necessarily
91 // contiguous in the output, the addend can thus affect the final
92 // VA in a non-linear way.
93 // To make this work, we incorporate the addend into the section
94 // offset (and zero out the addend for later processing) so that
95 // we find the right object in the section.
Rui Ueyama3837f422019-07-10 05:00:37 +000096 if (d.isSection()) {
97 offset += addend;
98 addend = 0;
Rafael Espindola1f5b70f2016-03-11 14:21:37 +000099 }
Sean Silvaa9ba4502017-02-28 08:32:56 +0000100
Sean Silva6ab39262017-02-28 09:01:58 +0000101 // In the typical case, this is actually very simple and boils
102 // down to adding together 3 numbers:
103 // 1. The address of the output section.
104 // 2. The offset of the input section within the output section.
105 // 3. The offset within the input section (this addition happens
106 // inside InputSection::getOffset).
107 //
108 // If you understand the data structures involved with this next
109 // line (and how they get built), then you have a pretty good
110 // understanding of the linker.
Rui Ueyama3837f422019-07-10 05:00:37 +0000111 uint64_t va = isec->getVA(offset);
Sean Silva6ab39262017-02-28 09:01:58 +0000112
Simon Atanasyanfae2a5092019-02-19 10:36:58 +0000113 // MIPS relocatable files can mix regular and microMIPS code.
114 // Linker needs to distinguish such code. To do so microMIPS
115 // symbols has the `STO_MIPS_MICROMIPS` flag in the `st_other`
Fangrui Songdeb58192020-01-22 21:39:16 -0800116 // field. Unfortunately, the `MIPS::relocate()` method has
Simon Atanasyanfae2a5092019-02-19 10:36:58 +0000117 // a symbol value only. To pass type of the symbol (regular/microMIPS)
118 // to that routine as well as other places where we write
119 // a symbol value as-is (.dynamic section, `Elf_Ehdr::e_entry`
120 // field etc) do the same trick as compiler uses to mark microMIPS
121 // for CPU - set the less-significant bit.
Rui Ueyama3837f422019-07-10 05:00:37 +0000122 if (config->emachine == EM_MIPS && isMicroMips() &&
123 ((sym.stOther & STO_MIPS_MICROMIPS) || sym.needsPltAddr))
124 va |= 1;
Simon Atanasyanfae2a5092019-02-19 10:36:58 +0000125
Rui Ueyama3837f422019-07-10 05:00:37 +0000126 if (d.isTls() && !config->relocatable) {
Ryan Prichard1c33d142018-09-18 00:24:48 +0000127 // Use the address of the TLS segment's first section rather than the
128 // segment's address, because segment addresses aren't initialized until
129 // after sections are finalized. (e.g. Measuring the size of .rela.dyn
130 // for Android relocation packing requires knowing TLS symbol addresses
131 // during section finalization.)
Rui Ueyama3837f422019-07-10 05:00:37 +0000132 if (!Out::tlsPhdr || !Out::tlsPhdr->firstSec)
133 fatal(toString(d.file) +
Peter Collingbourne3e2abde2017-07-14 00:22:46 +0000134 " has an STT_TLS symbol but doesn't have an SHF_TLS section");
Rui Ueyama3837f422019-07-10 05:00:37 +0000135 return va - Out::tlsPhdr->firstSec->addr;
George Rimar6a3b1542016-10-04 08:52:51 +0000136 }
Rui Ueyama3837f422019-07-10 05:00:37 +0000137 return va;
Rui Ueyamab5a69702016-02-01 21:00:35 +0000138 }
Rafael Espindolaab0cce52018-04-26 17:58:58 +0000139 case Symbol::SharedKind:
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000140 case Symbol::UndefinedKind:
Rui Ueyamab5a69702016-02-01 21:00:35 +0000141 return 0;
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000142 case Symbol::LazyArchiveKind:
143 case Symbol::LazyObjectKind:
Rui Ueyama3837f422019-07-10 05:00:37 +0000144 assert(sym.isUsedInRegularObj && "lazy symbol reached writer");
Chih-Hung Hsieh73e04842018-09-11 23:00:36 +0000145 return 0;
Rui Ueyama5c073a92019-05-16 03:29:03 +0000146 case Symbol::CommonKind:
147 llvm_unreachable("common symbol reached writer");
Rui Ueyamaf3fad552018-10-12 18:29:18 +0000148 case Symbol::PlaceholderKind:
149 llvm_unreachable("placeholder symbol reached writer");
Rui Ueyamab5a69702016-02-01 21:00:35 +0000150 }
George Rimar777f9632016-03-12 08:31:34 +0000151 llvm_unreachable("invalid symbol kind");
Rui Ueyamab5a69702016-02-01 21:00:35 +0000152}
153
Rui Ueyama3837f422019-07-10 05:00:37 +0000154uint64_t Symbol::getVA(int64_t addend) const {
155 uint64_t outVA = getSymVA(*this, addend);
156 return outVA + addend;
Rafael Espindola87d9f102016-03-11 12:19:05 +0000157}
158
Peter Collingbourne8331f612019-02-13 21:49:55 +0000159uint64_t Symbol::getGotVA() const {
Rui Ueyama3837f422019-07-10 05:00:37 +0000160 if (gotInIgot)
161 return in.igotPlt->getVA() + getGotPltOffset();
162 return in.got->getVA() + getGotOffset();
Peter Collingbourne8331f612019-02-13 21:49:55 +0000163}
Rafael Espindola74031ba2016-04-07 15:20:56 +0000164
Harald van Dijkd6241342021-05-17 00:13:00 +0100165uint64_t Symbol::getGotOffset() const {
166 return gotIndex * target->gotEntrySize;
167}
Rui Ueyamab5a69702016-02-01 21:00:35 +0000168
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000169uint64_t Symbol::getGotPltVA() const {
Rui Ueyama3837f422019-07-10 05:00:37 +0000170 if (isInIplt)
171 return in.igotPlt->getVA() + getGotPltOffset();
172 return in.gotPlt->getVA() + getGotPltOffset();
Rafael Espindola74031ba2016-04-07 15:20:56 +0000173}
174
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000175uint64_t Symbol::getGotPltOffset() const {
Rui Ueyama3837f422019-07-10 05:00:37 +0000176 if (isInIplt)
Harald van Dijkd6241342021-05-17 00:13:00 +0100177 return pltIndex * target->gotEntrySize;
178 return (pltIndex + target->gotPltHeaderEntriesNum) * target->gotEntrySize;
Rui Ueyamab5a69702016-02-01 21:00:35 +0000179}
180
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000181uint64_t Symbol::getPltVA() const {
Fangrui Song891a8652019-12-14 14:17:35 -0800182 uint64_t outVA = isInIplt
183 ? in.iplt->getVA() + pltIndex * target->ipltEntrySize
184 : in.plt->getVA() + in.plt->headerSize +
185 pltIndex * target->pltEntrySize;
186
Simon Atanasyanfae2a5092019-02-19 10:36:58 +0000187 // While linking microMIPS code PLT code are always microMIPS
188 // code. Set the less-significant bit to track that fact.
189 // See detailed comment in the `getSymVA` function.
Rui Ueyama3837f422019-07-10 05:00:37 +0000190 if (config->emachine == EM_MIPS && isMicroMips())
191 outVA |= 1;
192 return outVA;
Rafael Espindolaab0cce52018-04-26 17:58:58 +0000193}
194
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000195uint64_t Symbol::getSize() const {
Rui Ueyama3837f422019-07-10 05:00:37 +0000196 if (const auto *dr = dyn_cast<Defined>(this))
197 return dr->size;
198 return cast<SharedSymbol>(this)->size;
Rui Ueyama512c61d2016-02-03 00:12:24 +0000199}
200
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000201OutputSection *Symbol::getOutputSection() const {
Rui Ueyama3837f422019-07-10 05:00:37 +0000202 if (auto *s = dyn_cast<Defined>(this)) {
203 if (auto *sec = s->section)
204 return sec->repl->getOutputSection();
Rui Ueyama968db482017-02-28 04:02:42 +0000205 return nullptr;
206 }
Rui Ueyama968db482017-02-28 04:02:42 +0000207 return nullptr;
208}
209
Rui Ueyama35fa6c52016-11-23 05:48:40 +0000210// If a symbol name contains '@', the characters after that is
211// a symbol version name. This function parses that.
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000212void Symbol::parseSymbolVersion() {
Fangrui Song00809c82021-08-04 23:52:55 -0700213 // Return if localized by a local: pattern in a version script.
214 if (versionId == VER_NDX_LOCAL)
215 return;
Rui Ueyama3837f422019-07-10 05:00:37 +0000216 StringRef s = getName();
217 size_t pos = s.find('@');
218 if (pos == 0 || pos == StringRef::npos)
Rui Ueyama35fa6c52016-11-23 05:48:40 +0000219 return;
Rui Ueyama3837f422019-07-10 05:00:37 +0000220 StringRef verstr = s.substr(pos + 1);
221 if (verstr.empty())
Rui Ueyama35fa6c52016-11-23 05:48:40 +0000222 return;
223
224 // Truncate the symbol name so that it doesn't include the version string.
Rui Ueyama3837f422019-07-10 05:00:37 +0000225 nameSize = pos;
Rui Ueyama35fa6c52016-11-23 05:48:40 +0000226
Rafael Espindola1d6d1b42017-01-17 16:08:06 +0000227 // If this is not in this DSO, it is not a definition.
Peter Collingbourneb472aa02017-11-06 04:39:07 +0000228 if (!isDefined())
Rafael Espindola2756e042017-01-06 22:30:35 +0000229 return;
230
Rui Ueyama35fa6c52016-11-23 05:48:40 +0000231 // '@@' in a symbol name means the default version.
232 // It is usually the most recent one.
Rui Ueyama3837f422019-07-10 05:00:37 +0000233 bool isDefault = (verstr[0] == '@');
234 if (isDefault)
235 verstr = verstr.substr(1);
Rui Ueyama35fa6c52016-11-23 05:48:40 +0000236
Fangrui Songe28a70d2019-08-05 14:31:39 +0000237 for (const VersionDefinition &ver : namedVersionDefs()) {
Rui Ueyama3837f422019-07-10 05:00:37 +0000238 if (ver.name != verstr)
Rui Ueyama35fa6c52016-11-23 05:48:40 +0000239 continue;
240
Rui Ueyama3837f422019-07-10 05:00:37 +0000241 if (isDefault)
242 versionId = ver.id;
Rui Ueyama35fa6c52016-11-23 05:48:40 +0000243 else
Rui Ueyama3837f422019-07-10 05:00:37 +0000244 versionId = ver.id | VERSYM_HIDDEN;
Rui Ueyama35fa6c52016-11-23 05:48:40 +0000245 return;
246 }
247
248 // It is an error if the specified version is not defined.
George Rimar4d2f97622017-07-04 13:19:13 +0000249 // Usually version script is not provided when linking executable,
250 // but we may still want to override a versioned symbol from DSO,
Peter Smith796fb992018-05-14 10:13:56 +0000251 // so we do not report error in this case. We also do not error
252 // if the symbol has a local version as it won't be in the dynamic
253 // symbol table.
Rui Ueyama3837f422019-07-10 05:00:37 +0000254 if (config->shared && versionId != VER_NDX_LOCAL)
255 error(toString(file) + ": symbol " + s + " has undefined version " +
256 verstr);
Rui Ueyama35fa6c52016-11-23 05:48:40 +0000257}
258
Fangrui Song09401df2021-11-26 10:58:50 -0800259void Symbol::extract() const {
Fangrui Songf1ba48d2021-11-26 14:10:55 -0800260 if (auto *sym = dyn_cast<LazyArchive>(this))
Fangrui Song09401df2021-11-26 10:58:50 -0800261 cast<ArchiveFile>(sym->file)->extract(sym->sym);
Fangrui Songf1ba48d2021-11-26 14:10:55 -0800262 else
263 cast<LazyObjFile>(this->file)->extract();
Rui Ueyama7d476192019-05-16 02:14:00 +0000264}
Rui Ueyamaf8baa662016-04-07 19:24:51 +0000265
Peter Collingbourne98930112018-08-08 23:48:12 +0000266MemoryBufferRef LazyArchive::getMemberBuffer() {
Nico Weber9c0716f2019-07-23 19:00:01 +0000267 Archive::Child c =
268 CHECK(sym.getMember(),
269 "could not get the member for symbol " + toELFString(sym));
Peter Collingbourne98930112018-08-08 23:48:12 +0000270
Rui Ueyama3837f422019-07-10 05:00:37 +0000271 return CHECK(c.getMemoryBufferRef(),
Peter Collingbourne98930112018-08-08 23:48:12 +0000272 "could not get the buffer for the member defining symbol " +
Nico Weber9c0716f2019-07-23 19:00:01 +0000273 toELFString(sym));
Peter Collingbourne98930112018-08-08 23:48:12 +0000274}
275
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000276uint8_t Symbol::computeBinding() const {
Rui Ueyama3837f422019-07-10 05:00:37 +0000277 if (config->relocatable)
278 return binding;
Fangrui Songcfdd4582019-08-11 17:03:00 +0000279 if ((visibility != STV_DEFAULT && visibility != STV_PROTECTED) ||
Nathan Lanza2f651662021-03-16 04:33:50 -0400280 (versionId == VER_NDX_LOCAL && !isLazy()))
Rafael Espindolab7e2ee22017-01-10 17:08:13 +0000281 return STB_LOCAL;
Rui Ueyama3837f422019-07-10 05:00:37 +0000282 if (!config->gnuUnique && binding == STB_GNU_UNIQUE)
Rafael Espindolab7e2ee22017-01-10 17:08:13 +0000283 return STB_GLOBAL;
Rui Ueyama3837f422019-07-10 05:00:37 +0000284 return binding;
Rafael Espindolab7e2ee22017-01-10 17:08:13 +0000285}
286
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000287bool Symbol::includeInDynsym() const {
Rui Ueyama3837f422019-07-10 05:00:37 +0000288 if (!config->hasDynSymTab)
Rafael Espindolae05e2f82017-09-15 18:05:02 +0000289 return false;
Rafael Espindolab7e2ee22017-01-10 17:08:13 +0000290 if (computeBinding() == STB_LOCAL)
Rafael Espindolaae605c12016-04-21 20:35:25 +0000291 return false;
Fangrui Song375371c2020-01-09 15:53:52 -0800292 if (!isDefined() && !isCommon())
Fangrui Song0fbf28f2020-01-23 11:52:03 -0800293 // 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:07 +0000298
Fangrui Song375371c2020-01-09 15:53:52 -0800299 return exportDynamic || inDynamicList;
Rafael Espindolaae605c12016-04-21 20:35:25 +0000300}
Rui Ueyama69c778c2016-07-17 17:50:09 +0000301
302// Print out a log message for --trace-symbol.
Fangrui Song07837b82020-05-14 22:18:58 -0700303void elf::printTraceSymbol(const Symbol *sym) {
Rui Ueyama3837f422019-07-10 05:00:37 +0000304 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:09 +0000313 else
Rui Ueyama3837f422019-07-10 05:00:37 +0000314 s = ": definition of ";
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000315
Rui Ueyama3837f422019-07-10 05:00:37 +0000316 message(toString(sym->file) + s + sym->getName());
Rui Ueyama69c778c2016-07-17 17:50:09 +0000317}
318
Fangrui Songa954bb12021-09-20 09:52:30 -0700319static void recordWhyExtract(const InputFile *reference,
320 const InputFile &extracted, const Symbol &sym) {
321 whyExtract.emplace_back(toString(reference), &extracted, sym);
322}
323
Fangrui Song07837b82020-05-14 22:18:58 -0700324void elf::maybeWarnUnorderableSymbol(const Symbol *sym) {
Rui Ueyama3837f422019-07-10 05:00:37 +0000325 if (!config->warnSymbolOrdering)
Michael J. Spencerb8427252018-04-17 23:30:05 +0000326 return;
Rui Ueyamab774c3c2018-04-26 01:38:29 +0000327
Fangrui Song11ca54f2018-10-10 22:48:57 +0000328 // If UnresolvedPolicy::Ignore is used, no "undefined symbol" error/warning
329 // is emitted. It makes sense to not warn on undefined symbols.
330 //
331 // Note, ld.bfd --symbol-ordering-file= does not warn on undefined symbols,
332 // but we don't have to be compatible here.
Rui Ueyama3837f422019-07-10 05:00:37 +0000333 if (sym->isUndefined() &&
334 config->unresolvedSymbols == UnresolvedPolicy::Ignore)
Fangrui Song11ca54f2018-10-10 22:48:57 +0000335 return;
336
Rui Ueyama3837f422019-07-10 05:00:37 +0000337 const InputFile *file = sym->file;
338 auto *d = dyn_cast<Defined>(sym);
Rui Ueyamab774c3c2018-04-26 01:38:29 +0000339
Rui Ueyama3837f422019-07-10 05:00:37 +0000340 auto report = [&](StringRef s) { warn(toString(file) + s + sym->getName()); };
Rui Ueyamab774c3c2018-04-26 01:38:29 +0000341
Rui Ueyama3837f422019-07-10 05:00:37 +0000342 if (sym->isUndefined())
343 report(": unable to order undefined symbol: ");
344 else if (sym->isShared())
345 report(": unable to order shared symbol: ");
346 else if (d && !d->section)
347 report(": unable to order absolute symbol: ");
348 else if (d && isa<OutputSection>(d->section))
349 report(": unable to order synthetic symbol: ");
350 else if (d && !d->section->repl->isLive())
351 report(": unable to order discarded symbol: ");
Michael J. Spencerb8427252018-04-17 23:30:05 +0000352}
353
Fangrui Songcd0ab242019-11-29 21:58:36 -0800354// Returns true if a symbol can be replaced at load-time by a symbol
355// with the same name defined in other ELF executable or DSO.
Fangrui Song07837b82020-05-14 22:18:58 -0700356bool elf::computeIsPreemptible(const Symbol &sym) {
Fangrui Songcd0ab242019-11-29 21:58:36 -0800357 assert(!sym.isLocal());
358
359 // Only symbols with default visibility that appear in dynsym can be
360 // preempted. Symbols with protected visibility cannot be preempted.
361 if (!sym.includeInDynsym() || sym.visibility != STV_DEFAULT)
362 return false;
363
364 // At this point copy relocations have not been created yet, so any
365 // symbol that is not defined locally is preemptible.
366 if (!sym.isDefined())
367 return true;
368
369 if (!config->shared)
370 return false;
371
Fangrui Song751f18e2020-06-01 11:27:53 -0700372 // If -Bsymbolic or --dynamic-list is specified, or -Bsymbolic-functions is
373 // specified and the symbol is STT_FUNC, the symbol is preemptible iff it is
Fangrui Songb06426d2021-07-29 14:46:53 -0700374 // in the dynamic list. -Bsymbolic-non-weak-functions is a non-weak subset of
375 // -Bsymbolic-functions.
376 if (config->symbolic ||
377 (config->bsymbolic == BsymbolicKind::Functions && sym.isFunc()) ||
378 (config->bsymbolic == BsymbolicKind::NonWeakFunctions && sym.isFunc() &&
379 sym.binding != STB_WEAK))
Fangrui Songcd0ab242019-11-29 21:58:36 -0800380 return sym.inDynamicList;
Fangrui Songcd0ab242019-11-29 21:58:36 -0800381 return true;
382}
383
Fangrui Song07837b82020-05-14 22:18:58 -0700384void elf::reportBackrefs() {
Fangrui Song03c825c2020-04-05 22:27:46 -0700385 for (auto &it : backwardReferences) {
386 const Symbol &sym = *it.first;
Fangrui Song3ba334222020-11-07 20:17:41 -0800387 std::string to = toString(it.second.second);
388 // Some libraries have known problems and can cause noise. Filter them out
389 // with --warn-backrefs-exclude=. to may look like *.o or *.a(*.o).
390 bool exclude = false;
391 for (const llvm::GlobPattern &pat : config->warnBackrefsExclude)
392 if (pat.match(to)) {
393 exclude = true;
394 break;
395 }
396 if (!exclude)
397 warn("backward reference detected: " + sym.getName() + " in " +
398 toString(it.second.first) + " refers to " + to);
Fangrui Song03c825c2020-04-05 22:27:46 -0700399 }
400}
401
Rui Ueyama3837f422019-07-10 05:00:37 +0000402static uint8_t getMinVisibility(uint8_t va, uint8_t vb) {
403 if (va == STV_DEFAULT)
404 return vb;
405 if (vb == STV_DEFAULT)
406 return va;
407 return std::min(va, vb);
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000408}
409
410// Merge symbol properties.
411//
412// When we have many symbols of the same name, we choose one of them,
413// and that's the result of symbol resolution. However, symbols that
414// were not chosen still affect some symbol properties.
Rui Ueyama3837f422019-07-10 05:00:37 +0000415void Symbol::mergeProperties(const Symbol &other) {
416 if (other.exportDynamic)
417 exportDynamic = true;
418 if (other.isUsedInRegularObj)
419 isUsedInRegularObj = true;
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000420
421 // DSO symbols do not affect visibility in the output.
Rui Ueyama3837f422019-07-10 05:00:37 +0000422 if (!other.isShared())
423 visibility = getMinVisibility(visibility, other.visibility);
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000424}
425
Rui Ueyama3837f422019-07-10 05:00:37 +0000426void Symbol::resolve(const Symbol &other) {
427 mergeProperties(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000428
429 if (isPlaceholder()) {
Rui Ueyama3837f422019-07-10 05:00:37 +0000430 replace(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000431 return;
432 }
433
Rui Ueyama3837f422019-07-10 05:00:37 +0000434 switch (other.kind()) {
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000435 case Symbol::UndefinedKind:
Rui Ueyama3837f422019-07-10 05:00:37 +0000436 resolveUndefined(cast<Undefined>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000437 break;
438 case Symbol::CommonKind:
Rui Ueyama3837f422019-07-10 05:00:37 +0000439 resolveCommon(cast<CommonSymbol>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000440 break;
441 case Symbol::DefinedKind:
Rui Ueyama3837f422019-07-10 05:00:37 +0000442 resolveDefined(cast<Defined>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000443 break;
444 case Symbol::LazyArchiveKind:
Rui Ueyama3837f422019-07-10 05:00:37 +0000445 resolveLazy(cast<LazyArchive>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000446 break;
447 case Symbol::LazyObjectKind:
Rui Ueyama3837f422019-07-10 05:00:37 +0000448 resolveLazy(cast<LazyObject>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000449 break;
450 case Symbol::SharedKind:
Rui Ueyama3837f422019-07-10 05:00:37 +0000451 resolveShared(cast<SharedSymbol>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000452 break;
453 case Symbol::PlaceholderKind:
454 llvm_unreachable("bad symbol kind");
455 }
456}
457
Rui Ueyama3837f422019-07-10 05:00:37 +0000458void Symbol::resolveUndefined(const Undefined &other) {
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000459 // An undefined symbol with non default visibility must be satisfied
460 // in the same DSO.
461 //
462 // If this is a non-weak defined symbol in a discarded section, override the
463 // existing undefined symbol for better error message later.
Rui Ueyama3837f422019-07-10 05:00:37 +0000464 if ((isShared() && other.visibility != STV_DEFAULT) ||
465 (isUndefined() && other.binding != STB_WEAK && other.discardedSecIdx)) {
466 replace(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000467 return;
468 }
469
Rui Ueyama3837f422019-07-10 05:00:37 +0000470 if (traced)
471 printTraceSymbol(&other);
Sam Clegg7991b682019-05-24 13:29:17 +0000472
Fangrui Songf3475412019-07-04 10:38:04 +0000473 if (isLazy()) {
Fangrui Song09401df2021-11-26 10:58:50 -0800474 // An undefined weak will not extract archive members. See comment on Lazy
475 // in Symbols.h for the details.
Rui Ueyama3837f422019-07-10 05:00:37 +0000476 if (other.binding == STB_WEAK) {
477 binding = STB_WEAK;
478 type = other.type;
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000479 return;
480 }
481
482 // Do extra check for --warn-backrefs.
483 //
484 // --warn-backrefs is an option to prevent an undefined reference from
Fangrui Song09401df2021-11-26 10:58:50 -0800485 // extracting an archive member written earlier in the command line. It can
486 // be used to keep compatibility with GNU linkers to some degree. I'll
487 // explain the feature and why you may find it useful in this comment.
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000488 //
489 // lld's symbol resolution semantics is more relaxed than traditional Unix
490 // linkers. For example,
491 //
492 // ld.lld foo.a bar.o
493 //
494 // succeeds even if bar.o contains an undefined symbol that has to be
495 // resolved by some object file in foo.a. Traditional Unix linkers don't
496 // allow this kind of backward reference, as they visit each file only once
497 // from left to right in the command line while resolving all undefined
498 // symbols at the moment of visiting.
499 //
500 // In the above case, since there's no undefined symbol when a linker visits
501 // foo.a, no files are pulled out from foo.a, and because the linker forgets
502 // about foo.a after visiting, it can't resolve undefined symbols in bar.o
503 // that could have been resolved otherwise.
504 //
505 // That lld accepts more relaxed form means that (besides it'd make more
506 // sense) you can accidentally write a command line or a build file that
507 // works only with lld, even if you have a plan to distribute it to wider
508 // users who may be using GNU linkers. With --warn-backrefs, you can detect
509 // a library order that doesn't work with other Unix linkers.
510 //
511 // The option is also useful to detect cyclic dependencies between static
512 // archives. Again, lld accepts
513 //
514 // ld.lld foo.a bar.a
515 //
516 // even if foo.a and bar.a depend on each other. With --warn-backrefs, it is
517 // handled as an error.
518 //
519 // Here is how the option works. We assign a group ID to each file. A file
520 // with a smaller group ID can pull out object files from an archive file
521 // with an equal or greater group ID. Otherwise, it is a reverse dependency
522 // and an error.
523 //
524 // A file outside --{start,end}-group gets a fresh ID when instantiated. All
525 // files within the same --{start,end}-group get the same group ID. E.g.
526 //
527 // ld.lld A B --start-group C D --end-group E
528 //
529 // A forms group 0. B form group 1. C and D (including their member object
530 // files) form group 2. E forms group 3. I think that you can see how this
531 // group assignment rule simulates the traditional linker's semantics.
Rui Ueyama3837f422019-07-10 05:00:37 +0000532 bool backref = config->warnBackrefs && other.file &&
533 file->groupId < other.file->groupId;
Fangrui Song09401df2021-11-26 10:58:50 -0800534 extract();
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000535
Fangrui Songa954bb12021-09-20 09:52:30 -0700536 if (!config->whyExtract.empty())
537 recordWhyExtract(other.file, *file, *this);
538
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000539 // We don't report backward references to weak symbols as they can be
540 // overridden later.
Fangrui Song03c825c2020-04-05 22:27:46 -0700541 //
542 // A traditional linker does not error for -ldef1 -lref -ldef2 (linking
543 // sandwich), where def2 may or may not be the same as def1. We don't want
544 // to warn for this case, so dismiss the warning if we see a subsequent lazy
Fangrui Songce3c5da2020-10-22 15:26:52 -0700545 // definition. this->file needs to be saved because in the case of LTO it
546 // may be reset to nullptr or be replaced with a file named lto.tmp.
Rui Ueyama3837f422019-07-10 05:00:37 +0000547 if (backref && !isWeak())
Fangrui Songce3c5da2020-10-22 15:26:52 -0700548 backwardReferences.try_emplace(this, std::make_pair(other.file, file));
Fangrui Songf3475412019-07-04 10:38:04 +0000549 return;
550 }
551
552 // Undefined symbols in a SharedFile do not change the binding.
Rui Ueyama3837f422019-07-10 05:00:37 +0000553 if (dyn_cast_or_null<SharedFile>(other.file))
Fangrui Songf3475412019-07-04 10:38:04 +0000554 return;
555
Fangrui Songe49c4172019-08-06 14:03:45 +0000556 if (isUndefined() || isShared()) {
557 // The binding will be weak if there is at least one reference and all are
558 // weak. The binding has one opportunity to change to weak: if the first
559 // reference is weak.
560 if (other.binding != STB_WEAK || !referenced)
Rui Ueyama3837f422019-07-10 05:00:37 +0000561 binding = other.binding;
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000562 }
563}
564
565// Using .symver foo,foo@@VER unfortunately creates two symbols: foo and
566// foo@@VER. We want to effectively ignore foo, so give precedence to
567// foo@@VER.
568// FIXME: If users can transition to using
569// .symver foo,foo@@@VER
570// we can delete this hack.
Rui Ueyama3837f422019-07-10 05:00:37 +0000571static int compareVersion(StringRef a, StringRef b) {
572 bool x = a.contains("@@");
573 bool y = b.contains("@@");
574 if (!x && y)
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000575 return 1;
Rui Ueyama3837f422019-07-10 05:00:37 +0000576 if (x && !y)
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000577 return -1;
578 return 0;
579}
580
581// Compare two symbols. Return 1 if the new symbol should win, -1 if
582// the new symbol should lose, or 0 if there is a conflict.
Rui Ueyama3837f422019-07-10 05:00:37 +0000583int Symbol::compare(const Symbol *other) const {
584 assert(other->isDefined() || other->isCommon());
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000585
586 if (!isDefined() && !isCommon())
587 return 1;
588
Rui Ueyama3837f422019-07-10 05:00:37 +0000589 if (int cmp = compareVersion(getName(), other->getName()))
590 return cmp;
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000591
Rui Ueyama3837f422019-07-10 05:00:37 +0000592 if (other->isWeak())
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000593 return -1;
594
595 if (isWeak())
596 return 1;
597
Rui Ueyama3837f422019-07-10 05:00:37 +0000598 if (isCommon() && other->isCommon()) {
599 if (config->warnCommon)
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000600 warn("multiple common of " + getName());
601 return 0;
602 }
603
604 if (isCommon()) {
Rui Ueyama3837f422019-07-10 05:00:37 +0000605 if (config->warnCommon)
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000606 warn("common " + getName() + " is overridden");
607 return 1;
608 }
609
Rui Ueyama3837f422019-07-10 05:00:37 +0000610 if (other->isCommon()) {
611 if (config->warnCommon)
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000612 warn("common " + getName() + " is overridden");
613 return -1;
614 }
615
Rui Ueyama3837f422019-07-10 05:00:37 +0000616 auto *oldSym = cast<Defined>(this);
617 auto *newSym = cast<Defined>(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000618
Fangrui Songd6c44822019-07-26 16:29:15 +0000619 if (dyn_cast_or_null<BitcodeFile>(other->file))
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000620 return 0;
621
Rui Ueyama3837f422019-07-10 05:00:37 +0000622 if (!oldSym->section && !newSym->section && oldSym->value == newSym->value &&
623 newSym->binding == STB_GLOBAL)
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000624 return -1;
625
626 return 0;
627}
628
Rui Ueyama3837f422019-07-10 05:00:37 +0000629static void reportDuplicate(Symbol *sym, InputFile *newFile,
630 InputSectionBase *errSec, uint64_t errOffset) {
631 if (config->allowMultipleDefinition)
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000632 return;
633
Rui Ueyama3837f422019-07-10 05:00:37 +0000634 Defined *d = cast<Defined>(sym);
635 if (!d->section || !errSec) {
636 error("duplicate symbol: " + toString(*sym) + "\n>>> defined in " +
637 toString(sym->file) + "\n>>> defined in " + toString(newFile));
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000638 return;
639 }
640
641 // Construct and print an error message in the form of:
642 //
643 // ld.lld: error: duplicate symbol: foo
644 // >>> defined at bar.c:30
645 // >>> bar.o (/home/alice/src/bar.o)
646 // >>> defined at baz.c:563
647 // >>> baz.o in archive libbaz.a
Rui Ueyama3837f422019-07-10 05:00:37 +0000648 auto *sec1 = cast<InputSectionBase>(d->section);
649 std::string src1 = sec1->getSrcMsg(*sym, d->value);
650 std::string obj1 = sec1->getObjMsg(d->value);
651 std::string src2 = errSec->getSrcMsg(*sym, errOffset);
652 std::string obj2 = errSec->getObjMsg(errOffset);
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000653
Rui Ueyama3837f422019-07-10 05:00:37 +0000654 std::string msg = "duplicate symbol: " + toString(*sym) + "\n>>> defined at ";
655 if (!src1.empty())
656 msg += src1 + "\n>>> ";
657 msg += obj1 + "\n>>> defined at ";
658 if (!src2.empty())
659 msg += src2 + "\n>>> ";
660 msg += obj2;
661 error(msg);
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000662}
663
Rui Ueyama3837f422019-07-10 05:00:37 +0000664void Symbol::resolveCommon(const CommonSymbol &other) {
665 int cmp = compare(&other);
666 if (cmp < 0)
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000667 return;
668
Rui Ueyama3837f422019-07-10 05:00:37 +0000669 if (cmp > 0) {
Fangrui Song69d10d22019-12-06 21:18:31 -0800670 if (auto *s = dyn_cast<SharedSymbol>(this)) {
671 // Increase st_size if the shared symbol has a larger st_size. The shared
672 // symbol may be created from common symbols. The fact that some object
673 // files were linked into a shared object first should not change the
674 // regular rule that picks the largest st_size.
675 uint64_t size = s->size;
676 replace(other);
677 if (size > cast<CommonSymbol>(this)->size)
678 cast<CommonSymbol>(this)->size = size;
679 } else {
680 replace(other);
681 }
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000682 return;
683 }
684
Rui Ueyama3837f422019-07-10 05:00:37 +0000685 CommonSymbol *oldSym = cast<CommonSymbol>(this);
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000686
Rui Ueyama3837f422019-07-10 05:00:37 +0000687 oldSym->alignment = std::max(oldSym->alignment, other.alignment);
688 if (oldSym->size < other.size) {
689 oldSym->file = other.file;
690 oldSym->size = other.size;
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000691 }
692}
693
Rui Ueyama3837f422019-07-10 05:00:37 +0000694void Symbol::resolveDefined(const Defined &other) {
695 int cmp = compare(&other);
696 if (cmp > 0)
697 replace(other);
698 else if (cmp == 0)
699 reportDuplicate(this, other.file,
700 dyn_cast_or_null<InputSectionBase>(other.section),
701 other.value);
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000702}
703
Sean Fertile8f91f382020-12-07 09:28:17 -0500704template <class LazyT>
705static void replaceCommon(Symbol &oldSym, const LazyT &newSym) {
706 backwardReferences.erase(&oldSym);
707 oldSym.replace(newSym);
Fangrui Song09401df2021-11-26 10:58:50 -0800708 newSym.extract();
Sean Fertile8f91f382020-12-07 09:28:17 -0500709}
710
Rui Ueyama3837f422019-07-10 05:00:37 +0000711template <class LazyT> void Symbol::resolveLazy(const LazyT &other) {
Sean Fertile8f91f382020-12-07 09:28:17 -0500712 // For common objects, we want to look for global or weak definitions that
Fangrui Song09401df2021-11-26 10:58:50 -0800713 // should be extracted as the canonical definition instead.
Sean Fertile8f91f382020-12-07 09:28:17 -0500714 if (isCommon() && elf::config->fortranCommon) {
715 if (auto *laSym = dyn_cast<LazyArchive>(&other)) {
716 ArchiveFile *archive = cast<ArchiveFile>(laSym->file);
717 const Archive::Symbol &archiveSym = laSym->sym;
Fangrui Song09401df2021-11-26 10:58:50 -0800718 if (archive->shouldExtractForCommon(archiveSym)) {
Sean Fertile8f91f382020-12-07 09:28:17 -0500719 replaceCommon(*this, other);
720 return;
721 }
722 } else if (auto *loSym = dyn_cast<LazyObject>(&other)) {
723 LazyObjFile *obj = cast<LazyObjFile>(loSym->file);
Fangrui Song09401df2021-11-26 10:58:50 -0800724 if (obj->shouldExtractForCommon(loSym->getName())) {
Sean Fertile8f91f382020-12-07 09:28:17 -0500725 replaceCommon(*this, other);
726 return;
727 }
728 }
729 }
730
Fangrui Song03c825c2020-04-05 22:27:46 -0700731 if (!isUndefined()) {
732 // See the comment in resolveUndefined().
733 if (isDefined())
734 backwardReferences.erase(this);
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000735 return;
Fangrui Song03c825c2020-04-05 22:27:46 -0700736 }
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000737
Fangrui Song09401df2021-11-26 10:58:50 -0800738 // An undefined weak will not extract archive members. See comment on Lazy in
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000739 // Symbols.h for the details.
740 if (isWeak()) {
Rui Ueyama3837f422019-07-10 05:00:37 +0000741 uint8_t ty = type;
742 replace(other);
743 type = ty;
744 binding = STB_WEAK;
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000745 return;
746 }
747
Fangrui Songa954bb12021-09-20 09:52:30 -0700748 const InputFile *oldFile = file;
Fangrui Song09401df2021-11-26 10:58:50 -0800749 other.extract();
Fangrui Songa954bb12021-09-20 09:52:30 -0700750 if (!config->whyExtract.empty())
751 recordWhyExtract(oldFile, *file, *this);
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000752}
753
Rui Ueyama3837f422019-07-10 05:00:37 +0000754void Symbol::resolveShared(const SharedSymbol &other) {
Fangrui Song69d10d22019-12-06 21:18:31 -0800755 if (isCommon()) {
756 // See the comment in resolveCommon() above.
757 if (other.size > cast<CommonSymbol>(this)->size)
758 cast<CommonSymbol>(this)->size = other.size;
759 return;
760 }
Rui Ueyama3837f422019-07-10 05:00:37 +0000761 if (visibility == STV_DEFAULT && (isUndefined() || isLazy())) {
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000762 // An undefined symbol with non default visibility must be satisfied
763 // in the same DSO.
Rui Ueyama3837f422019-07-10 05:00:37 +0000764 uint8_t bind = binding;
765 replace(other);
766 binding = bind;
Fangrui Song64676492020-05-18 10:15:59 -0700767 } else if (traced)
768 printTraceSymbol(&other);
Rui Ueyama7f7d2b22019-05-23 09:58:08 +0000769}