blob: 7a8e387239f5fbe90cf05fc532e0095cc38ee49e [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"
Rui Ueyamac72ba3a2016-11-23 04:57:2518#include <cstring>
Michael J. Spencer1b348a62015-09-04 22:28:1019
20using namespace llvm;
Michael J. Spencer84487f12015-07-24 21:03:0721using namespace llvm::object;
Rafael Espindola78471f02015-09-01 23:12:5222using namespace llvm::ELF;
Fangrui Song07837b82020-05-15 05:18:5823using namespace lld;
24using namespace lld::elf;
Michael J. Spencer84487f12015-07-24 21:03:0725
Fangrui Song07837b82020-05-15 05:18:5826std::string lld::toString(const elf::Symbol &sym) {
Fangrui Songf2036a12020-03-28 22:48:3827 StringRef name = sym.getName();
Luís Ferreira10e40a42022-01-05 03:05:1028 std::string ret = demangle(name, config->demangle);
Fangrui Songf2036a12020-03-28 22:48:3829
Fangrui Song941e9332020-12-01 16:54:0130 const char *suffix = sym.getVersionSuffix();
31 if (*suffix == '@')
32 ret += suffix;
Fangrui Songf2036a12020-03-28 22:48:3833 return ret;
34}
35
Rui Ueyama3837f422019-07-10 05:00:3736Defined *ElfSym::bss;
37Defined *ElfSym::etext1;
38Defined *ElfSym::etext2;
39Defined *ElfSym::edata1;
40Defined *ElfSym::edata2;
41Defined *ElfSym::end1;
42Defined *ElfSym::end2;
43Defined *ElfSym::globalOffsetTable;
44Defined *ElfSym::mipsGp;
45Defined *ElfSym::mipsGpDisp;
46Defined *ElfSym::mipsLocalGp;
47Defined *ElfSym::relaIpltStart;
48Defined *ElfSym::relaIpltEnd;
49Defined *ElfSym::riscvGlobalPointer;
50Defined *ElfSym::tlsModuleBase;
Fangrui Songce3c5da2020-10-22 22:26:5251DenseMap<const Symbol *, std::pair<const InputFile *, const InputFile *>>
52 elf::backwardReferences;
Fangrui Songa954bb12021-09-20 16:52:3053SmallVector<std::tuple<std::string, const InputFile *, const Symbol &>, 0>
54 elf::whyExtract;
Fangrui Song5d3bd7f2022-01-09 21:43:2655SmallVector<SymbolAux, 0> elf::symAux;
Rui Ueyama80474a22017-02-28 19:29:5556
Fangrui Songa8024df2021-12-13 03:12:0157static uint64_t getSymVA(const Symbol &sym, int64_t addend) {
Rui Ueyama3837f422019-07-10 05:00:3758 switch (sym.kind()) {
Peter Collingbournee9a9e0a2017-11-06 04:35:3159 case Symbol::DefinedKind: {
Rui Ueyama3837f422019-07-10 05:00:3760 auto &d = cast<Defined>(sym);
61 SectionBase *isec = d.section;
Rui Ueyamab5a69702016-02-01 21:00:3562
63 // This is an absolute symbol.
Rui Ueyama3837f422019-07-10 05:00:3764 if (!isec)
65 return d.value;
Rui Ueyamab5a69702016-02-01 21:00:3566
Rui Ueyama3837f422019-07-10 05:00:3767 assert(isec != &InputSection::discarded);
Rafael Espindolaf4d6e8c2018-04-19 17:26:5068
Rui Ueyama3837f422019-07-10 05:00:3769 uint64_t offset = d.value;
Sean Silvaa9ba4502017-02-28 08:32:5670
71 // An object in an SHF_MERGE section might be referenced via a
72 // section symbol (as a hack for reducing the number of local
73 // symbols).
Sean Silvad4e60622017-03-01 04:44:0474 // Depending on the addend, the reference via a section symbol
75 // refers to a different object in the merge section.
76 // Since the objects in the merge section are not necessarily
77 // contiguous in the output, the addend can thus affect the final
78 // VA in a non-linear way.
79 // To make this work, we incorporate the addend into the section
80 // offset (and zero out the addend for later processing) so that
81 // we find the right object in the section.
Fangrui Songa8024df2021-12-13 03:12:0182 if (d.isSection())
Rui Ueyama3837f422019-07-10 05:00:3783 offset += addend;
Sean Silvaa9ba4502017-02-28 08:32:5684
Sean Silva6ab39262017-02-28 09:01:5885 // In the typical case, this is actually very simple and boils
86 // down to adding together 3 numbers:
87 // 1. The address of the output section.
88 // 2. The offset of the input section within the output section.
89 // 3. The offset within the input section (this addition happens
90 // inside InputSection::getOffset).
91 //
92 // If you understand the data structures involved with this next
93 // line (and how they get built), then you have a pretty good
94 // understanding of the linker.
Rui Ueyama3837f422019-07-10 05:00:3795 uint64_t va = isec->getVA(offset);
Fangrui Songa8024df2021-12-13 03:12:0196 if (d.isSection())
97 va -= addend;
Sean Silva6ab39262017-02-28 09:01:5898
Simon Atanasyanfae2a5092019-02-19 10:36:5899 // MIPS relocatable files can mix regular and microMIPS code.
100 // Linker needs to distinguish such code. To do so microMIPS
101 // symbols has the `STO_MIPS_MICROMIPS` flag in the `st_other`
Fangrui Songdeb58192020-01-23 05:39:16102 // field. Unfortunately, the `MIPS::relocate()` method has
Simon Atanasyanfae2a5092019-02-19 10:36:58103 // a symbol value only. To pass type of the symbol (regular/microMIPS)
104 // to that routine as well as other places where we write
105 // a symbol value as-is (.dynamic section, `Elf_Ehdr::e_entry`
106 // field etc) do the same trick as compiler uses to mark microMIPS
107 // for CPU - set the less-significant bit.
Rui Ueyama3837f422019-07-10 05:00:37108 if (config->emachine == EM_MIPS && isMicroMips() &&
Fangrui Songcf783be2021-12-15 00:28:41109 ((sym.stOther & STO_MIPS_MICROMIPS) || sym.needsCopy))
Rui Ueyama3837f422019-07-10 05:00:37110 va |= 1;
Simon Atanasyanfae2a5092019-02-19 10:36:58111
Rui Ueyama3837f422019-07-10 05:00:37112 if (d.isTls() && !config->relocatable) {
Ryan Prichard1c33d142018-09-18 00:24:48113 // Use the address of the TLS segment's first section rather than the
114 // segment's address, because segment addresses aren't initialized until
115 // after sections are finalized. (e.g. Measuring the size of .rela.dyn
116 // for Android relocation packing requires knowing TLS symbol addresses
117 // during section finalization.)
Rui Ueyama3837f422019-07-10 05:00:37118 if (!Out::tlsPhdr || !Out::tlsPhdr->firstSec)
119 fatal(toString(d.file) +
Peter Collingbourne3e2abde2017-07-14 00:22:46120 " has an STT_TLS symbol but doesn't have an SHF_TLS section");
Rui Ueyama3837f422019-07-10 05:00:37121 return va - Out::tlsPhdr->firstSec->addr;
George Rimar6a3b1542016-10-04 08:52:51122 }
Rui Ueyama3837f422019-07-10 05:00:37123 return va;
Rui Ueyamab5a69702016-02-01 21:00:35124 }
Rafael Espindolaab0cce52018-04-26 17:58:58125 case Symbol::SharedKind:
Rui Ueyamaf52496e2017-11-03 21:21:47126 case Symbol::UndefinedKind:
Rui Ueyamab5a69702016-02-01 21:00:35127 return 0;
Rui Ueyamaf52496e2017-11-03 21:21:47128 case Symbol::LazyObjectKind:
Fangrui Song935229f2022-01-05 08:46:48129 llvm_unreachable("lazy symbol reached writer");
Rui Ueyama5c073a92019-05-16 03:29:03130 case Symbol::CommonKind:
131 llvm_unreachable("common symbol reached writer");
Rui Ueyamaf3fad552018-10-12 18:29:18132 case Symbol::PlaceholderKind:
133 llvm_unreachable("placeholder symbol reached writer");
Rui Ueyamab5a69702016-02-01 21:00:35134 }
George Rimar777f9632016-03-12 08:31:34135 llvm_unreachable("invalid symbol kind");
Rui Ueyamab5a69702016-02-01 21:00:35136}
137
Rui Ueyama3837f422019-07-10 05:00:37138uint64_t Symbol::getVA(int64_t addend) const {
Fangrui Songa8024df2021-12-13 03:12:01139 return getSymVA(*this, addend) + addend;
Rafael Espindola87d9f102016-03-11 12:19:05140}
141
Peter Collingbourne8331f612019-02-13 21:49:55142uint64_t Symbol::getGotVA() const {
Rui Ueyama3837f422019-07-10 05:00:37143 if (gotInIgot)
144 return in.igotPlt->getVA() + getGotPltOffset();
145 return in.got->getVA() + getGotOffset();
Peter Collingbourne8331f612019-02-13 21:49:55146}
Rafael Espindola74031ba2016-04-07 15:20:56147
Harald van Dijkd6241342021-05-16 23:13:00148uint64_t Symbol::getGotOffset() const {
Fangrui Song5d3bd7f2022-01-09 21:43:26149 return getGotIdx() * target->gotEntrySize;
Harald van Dijkd6241342021-05-16 23:13:00150}
Rui Ueyamab5a69702016-02-01 21:00:35151
Rui Ueyamaf52496e2017-11-03 21:21:47152uint64_t Symbol::getGotPltVA() const {
Rui Ueyama3837f422019-07-10 05:00:37153 if (isInIplt)
154 return in.igotPlt->getVA() + getGotPltOffset();
155 return in.gotPlt->getVA() + getGotPltOffset();
Rafael Espindola74031ba2016-04-07 15:20:56156}
157
Rui Ueyamaf52496e2017-11-03 21:21:47158uint64_t Symbol::getGotPltOffset() const {
Rui Ueyama3837f422019-07-10 05:00:37159 if (isInIplt)
Fangrui Song5d3bd7f2022-01-09 21:43:26160 return getPltIdx() * target->gotEntrySize;
161 return (getPltIdx() + target->gotPltHeaderEntriesNum) * target->gotEntrySize;
Rui Ueyamab5a69702016-02-01 21:00:35162}
163
Rui Ueyamaf52496e2017-11-03 21:21:47164uint64_t Symbol::getPltVA() const {
Fangrui Song891a8652019-12-14 22:17:35165 uint64_t outVA = isInIplt
Fangrui Song5d3bd7f2022-01-09 21:43:26166 ? in.iplt->getVA() + getPltIdx() * target->ipltEntrySize
Fangrui Song891a8652019-12-14 22:17:35167 : in.plt->getVA() + in.plt->headerSize +
Fangrui Song5d3bd7f2022-01-09 21:43:26168 getPltIdx() * target->pltEntrySize;
Fangrui Song891a8652019-12-14 22:17:35169
Simon Atanasyanfae2a5092019-02-19 10:36:58170 // While linking microMIPS code PLT code are always microMIPS
171 // code. Set the less-significant bit to track that fact.
172 // See detailed comment in the `getSymVA` function.
Rui Ueyama3837f422019-07-10 05:00:37173 if (config->emachine == EM_MIPS && isMicroMips())
174 outVA |= 1;
175 return outVA;
Rafael Espindolaab0cce52018-04-26 17:58:58176}
177
Rui Ueyamaf52496e2017-11-03 21:21:47178uint64_t Symbol::getSize() const {
Rui Ueyama3837f422019-07-10 05:00:37179 if (const auto *dr = dyn_cast<Defined>(this))
180 return dr->size;
181 return cast<SharedSymbol>(this)->size;
Rui Ueyama512c61d2016-02-03 00:12:24182}
183
Rui Ueyamaf52496e2017-11-03 21:21:47184OutputSection *Symbol::getOutputSection() const {
Rui Ueyama3837f422019-07-10 05:00:37185 if (auto *s = dyn_cast<Defined>(this)) {
186 if (auto *sec = s->section)
Fangrui Songc2f2bb02021-12-21 08:39:16187 return sec->getOutputSection();
Rui Ueyama968db482017-02-28 04:02:42188 return nullptr;
189 }
Rui Ueyama968db482017-02-28 04:02:42190 return nullptr;
191}
192
Rui Ueyama35fa6c52016-11-23 05:48:40193// If a symbol name contains '@', the characters after that is
194// a symbol version name. This function parses that.
Rui Ueyamaf52496e2017-11-03 21:21:47195void Symbol::parseSymbolVersion() {
Fangrui Song00809c82021-08-05 06:52:55196 // Return if localized by a local: pattern in a version script.
197 if (versionId == VER_NDX_LOCAL)
198 return;
Rui Ueyama3837f422019-07-10 05:00:37199 StringRef s = getName();
200 size_t pos = s.find('@');
Fangrui Song101407b2021-12-16 07:59:55201 if (pos == StringRef::npos)
Rui Ueyama35fa6c52016-11-23 05:48:40202 return;
Rui Ueyama3837f422019-07-10 05:00:37203 StringRef verstr = s.substr(pos + 1);
Rui Ueyama35fa6c52016-11-23 05:48:40204
205 // Truncate the symbol name so that it doesn't include the version string.
Rui Ueyama3837f422019-07-10 05:00:37206 nameSize = pos;
Rui Ueyama35fa6c52016-11-23 05:48:40207
Fangrui Song7924b382021-12-27 01:25:54208 if (verstr.empty())
209 return;
210
Rafael Espindola1d6d1b42017-01-17 16:08:06211 // If this is not in this DSO, it is not a definition.
Peter Collingbourneb472aa02017-11-06 04:39:07212 if (!isDefined())
Rafael Espindola2756e042017-01-06 22:30:35213 return;
214
Rui Ueyama35fa6c52016-11-23 05:48:40215 // '@@' in a symbol name means the default version.
216 // It is usually the most recent one.
Rui Ueyama3837f422019-07-10 05:00:37217 bool isDefault = (verstr[0] == '@');
218 if (isDefault)
219 verstr = verstr.substr(1);
Rui Ueyama35fa6c52016-11-23 05:48:40220
Fangrui Songe28a70d2019-08-05 14:31:39221 for (const VersionDefinition &ver : namedVersionDefs()) {
Rui Ueyama3837f422019-07-10 05:00:37222 if (ver.name != verstr)
Rui Ueyama35fa6c52016-11-23 05:48:40223 continue;
224
Rui Ueyama3837f422019-07-10 05:00:37225 if (isDefault)
226 versionId = ver.id;
Rui Ueyama35fa6c52016-11-23 05:48:40227 else
Rui Ueyama3837f422019-07-10 05:00:37228 versionId = ver.id | VERSYM_HIDDEN;
Rui Ueyama35fa6c52016-11-23 05:48:40229 return;
230 }
231
232 // It is an error if the specified version is not defined.
George Rimar4d2f97622017-07-04 13:19:13233 // Usually version script is not provided when linking executable,
234 // but we may still want to override a versioned symbol from DSO,
Peter Smith796fb992018-05-14 10:13:56235 // so we do not report error in this case. We also do not error
236 // if the symbol has a local version as it won't be in the dynamic
237 // symbol table.
Rui Ueyama3837f422019-07-10 05:00:37238 if (config->shared && versionId != VER_NDX_LOCAL)
239 error(toString(file) + ": symbol " + s + " has undefined version " +
240 verstr);
Rui Ueyama35fa6c52016-11-23 05:48:40241}
242
Fangrui Song09401df2021-11-26 18:58:50243void Symbol::extract() const {
Fangrui Song3d854242022-02-15 17:38:00244 if (file->lazy) {
Fangrui Song3a5fb572021-12-23 01:41:50245 file->lazy = false;
246 parseFile(file);
247 }
Rui Ueyama7d476192019-05-16 02:14:00248}
Rui Ueyamaf8baa662016-04-07 19:24:51249
Rui Ueyamaf52496e2017-11-03 21:21:47250uint8_t Symbol::computeBinding() const {
Fangrui Songcfdd4582019-08-11 17:03:00251 if ((visibility != STV_DEFAULT && visibility != STV_PROTECTED) ||
Fangrui Song9e885ea2022-01-16 07:58:15252 versionId == VER_NDX_LOCAL)
Rafael Espindolab7e2ee22017-01-10 17:08:13253 return STB_LOCAL;
Fangrui Songb3cc4702022-01-16 07:40:43254 if (binding == STB_GNU_UNIQUE && !config->gnuUnique)
Rafael Espindolab7e2ee22017-01-10 17:08:13255 return STB_GLOBAL;
Rui Ueyama3837f422019-07-10 05:00:37256 return binding;
Rafael Espindolab7e2ee22017-01-10 17:08:13257}
258
Rui Ueyamaf52496e2017-11-03 21:21:47259bool Symbol::includeInDynsym() const {
Rafael Espindolab7e2ee22017-01-10 17:08:13260 if (computeBinding() == STB_LOCAL)
Rafael Espindolaae605c12016-04-21 20:35:25261 return false;
Fangrui Song375371c2020-01-09 23:53:52262 if (!isDefined() && !isCommon())
Fangrui Song0fbf28f2020-01-23 19:52:03263 // This should unconditionally return true, unfortunately glibc -static-pie
264 // expects undefined weak symbols not to exist in .dynsym, e.g.
265 // __pthread_mutex_lock reference in _dl_add_to_namespace_list,
266 // __pthread_initialize_minimal reference in csu/libc-start.c.
Fangrui Song01a51622022-01-16 07:32:48267 return !(isUndefWeak() && config->noDynamicLinker);
Rui Ueyamae63ae7f2019-06-25 06:58:07268
Fangrui Song375371c2020-01-09 23:53:52269 return exportDynamic || inDynamicList;
Rafael Espindolaae605c12016-04-21 20:35:25270}
Rui Ueyama69c778c2016-07-17 17:50:09271
272// Print out a log message for --trace-symbol.
Fangrui Song977a1a52022-02-06 00:34:02273void elf::printTraceSymbol(const Symbol &sym, StringRef name) {
Rui Ueyama3837f422019-07-10 05:00:37274 std::string s;
Fangrui Song977a1a52022-02-06 00:34:02275 if (sym.isUndefined())
Rui Ueyama3837f422019-07-10 05:00:37276 s = ": reference to ";
Fangrui Song977a1a52022-02-06 00:34:02277 else if (sym.isLazy())
Rui Ueyama3837f422019-07-10 05:00:37278 s = ": lazy definition of ";
Fangrui Song977a1a52022-02-06 00:34:02279 else if (sym.isShared())
Rui Ueyama3837f422019-07-10 05:00:37280 s = ": shared definition of ";
Fangrui Song977a1a52022-02-06 00:34:02281 else if (sym.isCommon())
Rui Ueyama3837f422019-07-10 05:00:37282 s = ": common definition of ";
Rui Ueyama69c778c2016-07-17 17:50:09283 else
Rui Ueyama3837f422019-07-10 05:00:37284 s = ": definition of ";
Rui Ueyamae6e206d2017-02-21 23:22:56285
Fangrui Song977a1a52022-02-06 00:34:02286 message(toString(sym.file) + s + name);
Rui Ueyama69c778c2016-07-17 17:50:09287}
288
Fangrui Songa954bb12021-09-20 16:52:30289static void recordWhyExtract(const InputFile *reference,
290 const InputFile &extracted, const Symbol &sym) {
291 whyExtract.emplace_back(toString(reference), &extracted, sym);
292}
293
Fangrui Song07837b82020-05-15 05:18:58294void elf::maybeWarnUnorderableSymbol(const Symbol *sym) {
Rui Ueyama3837f422019-07-10 05:00:37295 if (!config->warnSymbolOrdering)
Michael J. Spencerb8427252018-04-17 23:30:05296 return;
Rui Ueyamab774c3c2018-04-26 01:38:29297
Fangrui Song11ca54f2018-10-10 22:48:57298 // If UnresolvedPolicy::Ignore is used, no "undefined symbol" error/warning
299 // is emitted. It makes sense to not warn on undefined symbols.
300 //
301 // Note, ld.bfd --symbol-ordering-file= does not warn on undefined symbols,
302 // but we don't have to be compatible here.
Rui Ueyama3837f422019-07-10 05:00:37303 if (sym->isUndefined() &&
304 config->unresolvedSymbols == UnresolvedPolicy::Ignore)
Fangrui Song11ca54f2018-10-10 22:48:57305 return;
306
Rui Ueyama3837f422019-07-10 05:00:37307 const InputFile *file = sym->file;
308 auto *d = dyn_cast<Defined>(sym);
Rui Ueyamab774c3c2018-04-26 01:38:29309
Rui Ueyama3837f422019-07-10 05:00:37310 auto report = [&](StringRef s) { warn(toString(file) + s + sym->getName()); };
Rui Ueyamab774c3c2018-04-26 01:38:29311
Rui Ueyama3837f422019-07-10 05:00:37312 if (sym->isUndefined())
313 report(": unable to order undefined symbol: ");
314 else if (sym->isShared())
315 report(": unable to order shared symbol: ");
316 else if (d && !d->section)
317 report(": unable to order absolute symbol: ");
318 else if (d && isa<OutputSection>(d->section))
319 report(": unable to order synthetic symbol: ");
Fangrui Songe1b6b5b2021-12-24 20:09:48320 else if (d && !d->section->isLive())
Rui Ueyama3837f422019-07-10 05:00:37321 report(": unable to order discarded symbol: ");
Michael J. Spencerb8427252018-04-17 23:30:05322}
323
Fangrui Songcd0ab242019-11-30 05:58:36324// Returns true if a symbol can be replaced at load-time by a symbol
325// with the same name defined in other ELF executable or DSO.
Fangrui Song07837b82020-05-15 05:18:58326bool elf::computeIsPreemptible(const Symbol &sym) {
Fangrui Songe9262ed2021-12-27 02:11:45327 assert(!sym.isLocal() || sym.isPlaceholder());
Fangrui Songcd0ab242019-11-30 05:58:36328
329 // Only symbols with default visibility that appear in dynsym can be
330 // preempted. Symbols with protected visibility cannot be preempted.
331 if (!sym.includeInDynsym() || sym.visibility != STV_DEFAULT)
332 return false;
333
334 // At this point copy relocations have not been created yet, so any
335 // symbol that is not defined locally is preemptible.
336 if (!sym.isDefined())
337 return true;
338
339 if (!config->shared)
340 return false;
341
Fangrui Song751f18e2020-06-01 18:27:53342 // If -Bsymbolic or --dynamic-list is specified, or -Bsymbolic-functions is
343 // specified and the symbol is STT_FUNC, the symbol is preemptible iff it is
Fangrui Songb06426d2021-07-29 21:46:53344 // in the dynamic list. -Bsymbolic-non-weak-functions is a non-weak subset of
345 // -Bsymbolic-functions.
346 if (config->symbolic ||
347 (config->bsymbolic == BsymbolicKind::Functions && sym.isFunc()) ||
348 (config->bsymbolic == BsymbolicKind::NonWeakFunctions && sym.isFunc() &&
349 sym.binding != STB_WEAK))
Fangrui Songcd0ab242019-11-30 05:58:36350 return sym.inDynamicList;
Fangrui Songcd0ab242019-11-30 05:58:36351 return true;
352}
353
Fangrui Song07837b82020-05-15 05:18:58354void elf::reportBackrefs() {
Fangrui Song03c825c2020-04-06 05:27:46355 for (auto &it : backwardReferences) {
356 const Symbol &sym = *it.first;
Fangrui Song3ba334222020-11-08 04:17:41357 std::string to = toString(it.second.second);
358 // Some libraries have known problems and can cause noise. Filter them out
359 // with --warn-backrefs-exclude=. to may look like *.o or *.a(*.o).
360 bool exclude = false;
361 for (const llvm::GlobPattern &pat : config->warnBackrefsExclude)
362 if (pat.match(to)) {
363 exclude = true;
364 break;
365 }
366 if (!exclude)
367 warn("backward reference detected: " + sym.getName() + " in " +
368 toString(it.second.first) + " refers to " + to);
Fangrui Song03c825c2020-04-06 05:27:46369 }
370}
371
Rui Ueyama3837f422019-07-10 05:00:37372static uint8_t getMinVisibility(uint8_t va, uint8_t vb) {
373 if (va == STV_DEFAULT)
374 return vb;
375 if (vb == STV_DEFAULT)
376 return va;
377 return std::min(va, vb);
Rui Ueyama7f7d2b22019-05-23 09:58:08378}
379
380// Merge symbol properties.
381//
382// When we have many symbols of the same name, we choose one of them,
383// and that's the result of symbol resolution. However, symbols that
384// were not chosen still affect some symbol properties.
Rui Ueyama3837f422019-07-10 05:00:37385void Symbol::mergeProperties(const Symbol &other) {
386 if (other.exportDynamic)
387 exportDynamic = true;
Rui Ueyama7f7d2b22019-05-23 09:58:08388
389 // DSO symbols do not affect visibility in the output.
Rui Ueyama3837f422019-07-10 05:00:37390 if (!other.isShared())
391 visibility = getMinVisibility(visibility, other.visibility);
Rui Ueyama7f7d2b22019-05-23 09:58:08392}
393
Rui Ueyama3837f422019-07-10 05:00:37394void Symbol::resolve(const Symbol &other) {
395 mergeProperties(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08396
397 if (isPlaceholder()) {
Rui Ueyama3837f422019-07-10 05:00:37398 replace(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08399 return;
400 }
401
Rui Ueyama3837f422019-07-10 05:00:37402 switch (other.kind()) {
Rui Ueyama7f7d2b22019-05-23 09:58:08403 case Symbol::UndefinedKind:
Rui Ueyama3837f422019-07-10 05:00:37404 resolveUndefined(cast<Undefined>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08405 break;
406 case Symbol::CommonKind:
Rui Ueyama3837f422019-07-10 05:00:37407 resolveCommon(cast<CommonSymbol>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08408 break;
409 case Symbol::DefinedKind:
Rui Ueyama3837f422019-07-10 05:00:37410 resolveDefined(cast<Defined>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08411 break;
Rui Ueyama7f7d2b22019-05-23 09:58:08412 case Symbol::LazyObjectKind:
Rui Ueyama3837f422019-07-10 05:00:37413 resolveLazy(cast<LazyObject>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08414 break;
415 case Symbol::SharedKind:
Rui Ueyama3837f422019-07-10 05:00:37416 resolveShared(cast<SharedSymbol>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08417 break;
418 case Symbol::PlaceholderKind:
419 llvm_unreachable("bad symbol kind");
420 }
421}
422
Rui Ueyama3837f422019-07-10 05:00:37423void Symbol::resolveUndefined(const Undefined &other) {
Rui Ueyama7f7d2b22019-05-23 09:58:08424 // An undefined symbol with non default visibility must be satisfied
425 // in the same DSO.
426 //
427 // If this is a non-weak defined symbol in a discarded section, override the
428 // existing undefined symbol for better error message later.
Rui Ueyama3837f422019-07-10 05:00:37429 if ((isShared() && other.visibility != STV_DEFAULT) ||
430 (isUndefined() && other.binding != STB_WEAK && other.discardedSecIdx)) {
431 replace(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08432 return;
433 }
434
Rui Ueyama3837f422019-07-10 05:00:37435 if (traced)
Fangrui Song977a1a52022-02-06 00:34:02436 printTraceSymbol(other, getName());
Sam Clegg7991b682019-05-24 13:29:17437
Fangrui Songf3475412019-07-04 10:38:04438 if (isLazy()) {
Fangrui Song09401df2021-11-26 18:58:50439 // An undefined weak will not extract archive members. See comment on Lazy
440 // in Symbols.h for the details.
Rui Ueyama3837f422019-07-10 05:00:37441 if (other.binding == STB_WEAK) {
442 binding = STB_WEAK;
443 type = other.type;
Rui Ueyama7f7d2b22019-05-23 09:58:08444 return;
445 }
446
447 // Do extra check for --warn-backrefs.
448 //
449 // --warn-backrefs is an option to prevent an undefined reference from
Fangrui Song09401df2021-11-26 18:58:50450 // extracting an archive member written earlier in the command line. It can
451 // be used to keep compatibility with GNU linkers to some degree. I'll
452 // explain the feature and why you may find it useful in this comment.
Rui Ueyama7f7d2b22019-05-23 09:58:08453 //
454 // lld's symbol resolution semantics is more relaxed than traditional Unix
455 // linkers. For example,
456 //
457 // ld.lld foo.a bar.o
458 //
459 // succeeds even if bar.o contains an undefined symbol that has to be
460 // resolved by some object file in foo.a. Traditional Unix linkers don't
461 // allow this kind of backward reference, as they visit each file only once
462 // from left to right in the command line while resolving all undefined
463 // symbols at the moment of visiting.
464 //
465 // In the above case, since there's no undefined symbol when a linker visits
466 // foo.a, no files are pulled out from foo.a, and because the linker forgets
467 // about foo.a after visiting, it can't resolve undefined symbols in bar.o
468 // that could have been resolved otherwise.
469 //
470 // That lld accepts more relaxed form means that (besides it'd make more
471 // sense) you can accidentally write a command line or a build file that
472 // works only with lld, even if you have a plan to distribute it to wider
473 // users who may be using GNU linkers. With --warn-backrefs, you can detect
474 // a library order that doesn't work with other Unix linkers.
475 //
476 // The option is also useful to detect cyclic dependencies between static
477 // archives. Again, lld accepts
478 //
479 // ld.lld foo.a bar.a
480 //
481 // even if foo.a and bar.a depend on each other. With --warn-backrefs, it is
482 // handled as an error.
483 //
484 // Here is how the option works. We assign a group ID to each file. A file
485 // with a smaller group ID can pull out object files from an archive file
486 // with an equal or greater group ID. Otherwise, it is a reverse dependency
487 // and an error.
488 //
489 // A file outside --{start,end}-group gets a fresh ID when instantiated. All
490 // files within the same --{start,end}-group get the same group ID. E.g.
491 //
492 // ld.lld A B --start-group C D --end-group E
493 //
494 // A forms group 0. B form group 1. C and D (including their member object
495 // files) form group 2. E forms group 3. I think that you can see how this
496 // group assignment rule simulates the traditional linker's semantics.
Rui Ueyama3837f422019-07-10 05:00:37497 bool backref = config->warnBackrefs && other.file &&
498 file->groupId < other.file->groupId;
Fangrui Song09401df2021-11-26 18:58:50499 extract();
Rui Ueyama7f7d2b22019-05-23 09:58:08500
Fangrui Songa954bb12021-09-20 16:52:30501 if (!config->whyExtract.empty())
502 recordWhyExtract(other.file, *file, *this);
503
Rui Ueyama7f7d2b22019-05-23 09:58:08504 // We don't report backward references to weak symbols as they can be
505 // overridden later.
Fangrui Song03c825c2020-04-06 05:27:46506 //
507 // A traditional linker does not error for -ldef1 -lref -ldef2 (linking
508 // sandwich), where def2 may or may not be the same as def1. We don't want
509 // to warn for this case, so dismiss the warning if we see a subsequent lazy
Fangrui Songce3c5da2020-10-22 22:26:52510 // definition. this->file needs to be saved because in the case of LTO it
511 // may be reset to nullptr or be replaced with a file named lto.tmp.
Rui Ueyama3837f422019-07-10 05:00:37512 if (backref && !isWeak())
Fangrui Songce3c5da2020-10-22 22:26:52513 backwardReferences.try_emplace(this, std::make_pair(other.file, file));
Fangrui Songf3475412019-07-04 10:38:04514 return;
515 }
516
517 // Undefined symbols in a SharedFile do not change the binding.
Kazu Hirata62e48ed2021-12-25 05:22:27518 if (isa_and_nonnull<SharedFile>(other.file))
Fangrui Songf3475412019-07-04 10:38:04519 return;
520
Fangrui Songe49c4172019-08-06 14:03:45521 if (isUndefined() || isShared()) {
522 // The binding will be weak if there is at least one reference and all are
523 // weak. The binding has one opportunity to change to weak: if the first
524 // reference is weak.
525 if (other.binding != STB_WEAK || !referenced)
Rui Ueyama3837f422019-07-10 05:00:37526 binding = other.binding;
Rui Ueyama7f7d2b22019-05-23 09:58:08527 }
528}
529
Rui Ueyama7f7d2b22019-05-23 09:58:08530// Compare two symbols. Return 1 if the new symbol should win, -1 if
531// the new symbol should lose, or 0 if there is a conflict.
Fangrui Song6d943402022-02-24 22:08:06532bool Symbol::compare(const Defined &other) const {
533 if (LLVM_UNLIKELY(isCommon())) {
534 if (config->warnCommon)
535 warn("common " + getName() + " is overridden");
536 return !other.isWeak();
537 }
538 if (!isDefined())
539 return true;
Rui Ueyama7f7d2b22019-05-23 09:58:08540
Fangrui Song2bdad162021-12-15 23:19:35541 // .symver foo,foo@@VER unfortunately creates two defined symbols: foo and
542 // foo@@VER. In GNU ld, if foo and foo@@VER are in the same file, foo is
543 // ignored. In our implementation, when this is foo, this->getName() may still
Fangrui Song6d943402022-02-24 22:08:06544 // contain @@, return true in this case as well.
545 if (LLVM_UNLIKELY(file == other.file)) {
546 if (other.getName().contains("@@"))
547 return true;
Fangrui Song2bdad162021-12-15 23:19:35548 if (getName().contains("@@"))
Fangrui Song6d943402022-02-24 22:08:06549 return false;
Fangrui Song2bdad162021-12-15 23:19:35550 }
Rui Ueyama7f7d2b22019-05-23 09:58:08551
Fangrui Song6d943402022-02-24 22:08:06552 return isWeak() && !other.isWeak();
Rui Ueyama7f7d2b22019-05-23 09:58:08553}
554
Fangrui Song88d66f62022-02-22 18:07:58555void elf::reportDuplicate(const Symbol &sym, InputFile *newFile,
556 InputSectionBase *errSec, uint64_t errOffset) {
Rui Ueyama3837f422019-07-10 05:00:37557 if (config->allowMultipleDefinition)
Rui Ueyama7f7d2b22019-05-23 09:58:08558 return;
Fangrui Song467e1b32022-02-15 19:18:31559 const Defined *d = cast<Defined>(&sym);
Rui Ueyama3837f422019-07-10 05:00:37560 if (!d->section || !errSec) {
Fangrui Song467e1b32022-02-15 19:18:31561 error("duplicate symbol: " + toString(sym) + "\n>>> defined in " +
562 toString(sym.file) + "\n>>> defined in " + toString(newFile));
Rui Ueyama7f7d2b22019-05-23 09:58:08563 return;
564 }
565
566 // Construct and print an error message in the form of:
567 //
568 // ld.lld: error: duplicate symbol: foo
569 // >>> defined at bar.c:30
570 // >>> bar.o (/home/alice/src/bar.o)
571 // >>> defined at baz.c:563
572 // >>> baz.o in archive libbaz.a
Rui Ueyama3837f422019-07-10 05:00:37573 auto *sec1 = cast<InputSectionBase>(d->section);
Fangrui Song467e1b32022-02-15 19:18:31574 std::string src1 = sec1->getSrcMsg(sym, d->value);
Rui Ueyama3837f422019-07-10 05:00:37575 std::string obj1 = sec1->getObjMsg(d->value);
Fangrui Song467e1b32022-02-15 19:18:31576 std::string src2 = errSec->getSrcMsg(sym, errOffset);
Rui Ueyama3837f422019-07-10 05:00:37577 std::string obj2 = errSec->getObjMsg(errOffset);
Rui Ueyama7f7d2b22019-05-23 09:58:08578
Fangrui Song467e1b32022-02-15 19:18:31579 std::string msg = "duplicate symbol: " + toString(sym) + "\n>>> defined at ";
Rui Ueyama3837f422019-07-10 05:00:37580 if (!src1.empty())
581 msg += src1 + "\n>>> ";
582 msg += obj1 + "\n>>> defined at ";
583 if (!src2.empty())
584 msg += src2 + "\n>>> ";
585 msg += obj2;
586 error(msg);
Rui Ueyama7f7d2b22019-05-23 09:58:08587}
588
Fangrui Song88d66f62022-02-22 18:07:58589void Symbol::checkDuplicate(const Defined &other) const {
Fangrui Song6d943402022-02-24 22:08:06590 if (isDefined() && !isWeak() && !other.isWeak())
Fangrui Song88d66f62022-02-22 18:07:58591 reportDuplicate(*this, other.file,
592 dyn_cast_or_null<InputSectionBase>(other.section),
593 other.value);
594}
595
Rui Ueyama3837f422019-07-10 05:00:37596void Symbol::resolveCommon(const CommonSymbol &other) {
Fangrui Song6d943402022-02-24 22:08:06597 if (isDefined() && !isWeak()) {
598 if (config->warnCommon)
599 warn("common " + getName() + " is overridden");
Rui Ueyama7f7d2b22019-05-23 09:58:08600 return;
Fangrui Song6d943402022-02-24 22:08:06601 }
Rui Ueyama7f7d2b22019-05-23 09:58:08602
Fangrui Song6d943402022-02-24 22:08:06603 if (CommonSymbol *oldSym = dyn_cast<CommonSymbol>(this)) {
604 if (config->warnCommon)
605 warn("multiple common of " + getName());
606 oldSym->alignment = std::max(oldSym->alignment, other.alignment);
607 if (oldSym->size < other.size) {
608 oldSym->file = other.file;
609 oldSym->size = other.size;
Fangrui Song69d10d22019-12-07 05:18:31610 }
Rui Ueyama7f7d2b22019-05-23 09:58:08611 return;
612 }
613
Fangrui Song6d943402022-02-24 22:08:06614 if (auto *s = dyn_cast<SharedSymbol>(this)) {
615 // Increase st_size if the shared symbol has a larger st_size. The shared
616 // symbol may be created from common symbols. The fact that some object
617 // files were linked into a shared object first should not change the
618 // regular rule that picks the largest st_size.
619 uint64_t size = s->size;
620 replace(other);
621 if (size > cast<CommonSymbol>(this)->size)
622 cast<CommonSymbol>(this)->size = size;
623 } else {
624 replace(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08625 }
626}
627
Rui Ueyama3837f422019-07-10 05:00:37628void Symbol::resolveDefined(const Defined &other) {
Fangrui Song6d943402022-02-24 22:08:06629 if (compare(other))
Rui Ueyama3837f422019-07-10 05:00:37630 replace(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08631}
632
Fangrui Song41298902022-02-24 20:20:05633void Symbol::resolveLazy(const LazyObject &other) {
Sean Fertile8f91f382020-12-07 14:28:17634 // For common objects, we want to look for global or weak definitions that
Fangrui Song09401df2021-11-26 18:58:50635 // should be extracted as the canonical definition instead.
Fangrui Song15617cd2022-02-24 20:21:40636 if (LLVM_UNLIKELY(isCommon()) && elf::config->fortranCommon &&
637 other.file->shouldExtractForCommon(getName())) {
638 backwardReferences.erase(this);
639 replace(other);
640 other.extract();
641 return;
Sean Fertile8f91f382020-12-07 14:28:17642 }
643
Fangrui Song03c825c2020-04-06 05:27:46644 if (!isUndefined()) {
645 // See the comment in resolveUndefined().
646 if (isDefined())
647 backwardReferences.erase(this);
Rui Ueyama7f7d2b22019-05-23 09:58:08648 return;
Fangrui Song03c825c2020-04-06 05:27:46649 }
Rui Ueyama7f7d2b22019-05-23 09:58:08650
Fangrui Song09401df2021-11-26 18:58:50651 // An undefined weak will not extract archive members. See comment on Lazy in
Rui Ueyama7f7d2b22019-05-23 09:58:08652 // Symbols.h for the details.
653 if (isWeak()) {
Rui Ueyama3837f422019-07-10 05:00:37654 uint8_t ty = type;
655 replace(other);
656 type = ty;
657 binding = STB_WEAK;
Rui Ueyama7f7d2b22019-05-23 09:58:08658 return;
659 }
660
Fangrui Songa954bb12021-09-20 16:52:30661 const InputFile *oldFile = file;
Fangrui Song09401df2021-11-26 18:58:50662 other.extract();
Fangrui Songa954bb12021-09-20 16:52:30663 if (!config->whyExtract.empty())
664 recordWhyExtract(oldFile, *file, *this);
Rui Ueyama7f7d2b22019-05-23 09:58:08665}
666
Rui Ueyama3837f422019-07-10 05:00:37667void Symbol::resolveShared(const SharedSymbol &other) {
Fangrui Song69d10d22019-12-07 05:18:31668 if (isCommon()) {
669 // See the comment in resolveCommon() above.
670 if (other.size > cast<CommonSymbol>(this)->size)
671 cast<CommonSymbol>(this)->size = other.size;
672 return;
673 }
Rui Ueyama3837f422019-07-10 05:00:37674 if (visibility == STV_DEFAULT && (isUndefined() || isLazy())) {
Rui Ueyama7f7d2b22019-05-23 09:58:08675 // An undefined symbol with non default visibility must be satisfied
676 // in the same DSO.
Rui Ueyama3837f422019-07-10 05:00:37677 uint8_t bind = binding;
678 replace(other);
679 binding = bind;
Fangrui Song64676492020-05-18 17:15:59680 } else if (traced)
Fangrui Song977a1a52022-02-06 00:34:02681 printTraceSymbol(other, getName());
Rui Ueyama7f7d2b22019-05-23 09:58:08682}