blob: 5aa585d7bfe09fbeab9b178ac42761668c024ac6 [file] [log] [blame]
Michael J. Spencer84487f12015-07-24 21:03:071//===- Symbols.cpp --------------------------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:563// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Michael J. Spencer84487f12015-07-24 21:03:076//
7//===----------------------------------------------------------------------===//
8
9#include "Symbols.h"
Michael J. Spencercdae0a42015-07-28 22:58:2510#include "InputFiles.h"
Rui Ueyamab5a69702016-02-01 21:00:3511#include "InputSection.h"
12#include "OutputSections.h"
Rui Ueyamae8a61022016-11-05 23:05:4713#include "SyntheticSections.h"
Rui Ueyamab5a69702016-02-01 21:00:3514#include "Target.h"
Rafael Espindola17cb7c02016-12-19 17:01:0115#include "Writer.h"
Bob Haarmanb8a59c82017-10-25 22:28:3816#include "lld/Common/ErrorHandler.h"
Rui Ueyama53fe4692017-11-28 02:15:2617#include "lld/Common/Strings.h"
Michael J. Spencer1b348a62015-09-04 22:28:1018#include "llvm/ADT/STLExtras.h"
Fangrui Song23257882020-04-05 04:31:3619#include "llvm/Support/FileSystem.h"
Eugene Leviantc958d8d2016-10-12 08:19:3020#include "llvm/Support/Path.h"
Rui Ueyamac72ba3a2016-11-23 04:57:2521#include <cstring>
Michael J. Spencer1b348a62015-09-04 22:28:1022
23using namespace llvm;
Michael J. Spencer84487f12015-07-24 21:03:0724using namespace llvm::object;
Rafael Espindola78471f02015-09-01 23:12:5225using namespace llvm::ELF;
Fangrui Song07837b82020-05-15 05:18:5826using namespace lld;
27using namespace lld::elf;
Michael J. Spencer84487f12015-07-24 21:03:0728
Fangrui Song07837b82020-05-15 05:18:5829std::string lld::toString(const elf::Symbol &sym) {
Fangrui Songf2036a12020-03-28 22:48:3830 StringRef name = sym.getName();
Luís Ferreira10e40a42022-01-05 03:05:1031 std::string ret = demangle(name, config->demangle);
Fangrui Songf2036a12020-03-28 22:48:3832
Fangrui Song941e9332020-12-01 16:54:0133 const char *suffix = sym.getVersionSuffix();
34 if (*suffix == '@')
35 ret += suffix;
Fangrui Songf2036a12020-03-28 22:48:3836 return ret;
37}
38
Fangrui Song07837b82020-05-15 05:18:5839std::string lld::toELFString(const Archive::Symbol &b) {
Luís Ferreira10e40a42022-01-05 03:05:1040 return demangle(b.getName(), config->demangle);
Fangrui Songbd8cfe62019-10-07 08:31:1841}
42
Rui Ueyama3837f422019-07-10 05:00:3743Defined *ElfSym::bss;
44Defined *ElfSym::etext1;
45Defined *ElfSym::etext2;
46Defined *ElfSym::edata1;
47Defined *ElfSym::edata2;
48Defined *ElfSym::end1;
49Defined *ElfSym::end2;
50Defined *ElfSym::globalOffsetTable;
51Defined *ElfSym::mipsGp;
52Defined *ElfSym::mipsGpDisp;
53Defined *ElfSym::mipsLocalGp;
54Defined *ElfSym::relaIpltStart;
55Defined *ElfSym::relaIpltEnd;
56Defined *ElfSym::riscvGlobalPointer;
57Defined *ElfSym::tlsModuleBase;
Fangrui Songce3c5da2020-10-22 22:26:5258DenseMap<const Symbol *, std::pair<const InputFile *, const InputFile *>>
59 elf::backwardReferences;
Fangrui Songa954bb12021-09-20 16:52:3060SmallVector<std::tuple<std::string, const InputFile *, const Symbol &>, 0>
61 elf::whyExtract;
Fangrui Song5d3bd7f2022-01-09 21:43:2662SmallVector<SymbolAux, 0> elf::symAux;
Rui Ueyama80474a22017-02-28 19:29:5563
Fangrui Songa8024df2021-12-13 03:12:0164static uint64_t getSymVA(const Symbol &sym, int64_t addend) {
Rui Ueyama3837f422019-07-10 05:00:3765 switch (sym.kind()) {
Peter Collingbournee9a9e0a2017-11-06 04:35:3166 case Symbol::DefinedKind: {
Rui Ueyama3837f422019-07-10 05:00:3767 auto &d = cast<Defined>(sym);
68 SectionBase *isec = d.section;
Rui Ueyamab5a69702016-02-01 21:00:3569
70 // This is an absolute symbol.
Rui Ueyama3837f422019-07-10 05:00:3771 if (!isec)
72 return d.value;
Rui Ueyamab5a69702016-02-01 21:00:3573
Rui Ueyama3837f422019-07-10 05:00:3774 assert(isec != &InputSection::discarded);
Rafael Espindolaf4d6e8c2018-04-19 17:26:5075
Rui Ueyama3837f422019-07-10 05:00:3776 uint64_t offset = d.value;
Sean Silvaa9ba4502017-02-28 08:32:5677
78 // An object in an SHF_MERGE section might be referenced via a
79 // section symbol (as a hack for reducing the number of local
80 // symbols).
Sean Silvad4e60622017-03-01 04:44:0481 // Depending on the addend, the reference via a section symbol
82 // refers to a different object in the merge section.
83 // Since the objects in the merge section are not necessarily
84 // contiguous in the output, the addend can thus affect the final
85 // VA in a non-linear way.
86 // To make this work, we incorporate the addend into the section
87 // offset (and zero out the addend for later processing) so that
88 // we find the right object in the section.
Fangrui Songa8024df2021-12-13 03:12:0189 if (d.isSection())
Rui Ueyama3837f422019-07-10 05:00:3790 offset += addend;
Sean Silvaa9ba4502017-02-28 08:32:5691
Sean Silva6ab39262017-02-28 09:01:5892 // In the typical case, this is actually very simple and boils
93 // down to adding together 3 numbers:
94 // 1. The address of the output section.
95 // 2. The offset of the input section within the output section.
96 // 3. The offset within the input section (this addition happens
97 // inside InputSection::getOffset).
98 //
99 // If you understand the data structures involved with this next
100 // line (and how they get built), then you have a pretty good
101 // understanding of the linker.
Rui Ueyama3837f422019-07-10 05:00:37102 uint64_t va = isec->getVA(offset);
Fangrui Songa8024df2021-12-13 03:12:01103 if (d.isSection())
104 va -= addend;
Sean Silva6ab39262017-02-28 09:01:58105
Simon Atanasyanfae2a5092019-02-19 10:36:58106 // MIPS relocatable files can mix regular and microMIPS code.
107 // Linker needs to distinguish such code. To do so microMIPS
108 // symbols has the `STO_MIPS_MICROMIPS` flag in the `st_other`
Fangrui Songdeb58192020-01-23 05:39:16109 // field. Unfortunately, the `MIPS::relocate()` method has
Simon Atanasyanfae2a5092019-02-19 10:36:58110 // a symbol value only. To pass type of the symbol (regular/microMIPS)
111 // to that routine as well as other places where we write
112 // a symbol value as-is (.dynamic section, `Elf_Ehdr::e_entry`
113 // field etc) do the same trick as compiler uses to mark microMIPS
114 // for CPU - set the less-significant bit.
Rui Ueyama3837f422019-07-10 05:00:37115 if (config->emachine == EM_MIPS && isMicroMips() &&
Fangrui Songcf783be2021-12-15 00:28:41116 ((sym.stOther & STO_MIPS_MICROMIPS) || sym.needsCopy))
Rui Ueyama3837f422019-07-10 05:00:37117 va |= 1;
Simon Atanasyanfae2a5092019-02-19 10:36:58118
Rui Ueyama3837f422019-07-10 05:00:37119 if (d.isTls() && !config->relocatable) {
Ryan Prichard1c33d142018-09-18 00:24:48120 // Use the address of the TLS segment's first section rather than the
121 // segment's address, because segment addresses aren't initialized until
122 // after sections are finalized. (e.g. Measuring the size of .rela.dyn
123 // for Android relocation packing requires knowing TLS symbol addresses
124 // during section finalization.)
Rui Ueyama3837f422019-07-10 05:00:37125 if (!Out::tlsPhdr || !Out::tlsPhdr->firstSec)
126 fatal(toString(d.file) +
Peter Collingbourne3e2abde2017-07-14 00:22:46127 " has an STT_TLS symbol but doesn't have an SHF_TLS section");
Rui Ueyama3837f422019-07-10 05:00:37128 return va - Out::tlsPhdr->firstSec->addr;
George Rimar6a3b1542016-10-04 08:52:51129 }
Rui Ueyama3837f422019-07-10 05:00:37130 return va;
Rui Ueyamab5a69702016-02-01 21:00:35131 }
Rafael Espindolaab0cce52018-04-26 17:58:58132 case Symbol::SharedKind:
Rui Ueyamaf52496e2017-11-03 21:21:47133 case Symbol::UndefinedKind:
Rui Ueyamab5a69702016-02-01 21:00:35134 return 0;
Rui Ueyamaf52496e2017-11-03 21:21:47135 case Symbol::LazyArchiveKind:
136 case Symbol::LazyObjectKind:
Fangrui Song935229f2022-01-05 08:46:48137 llvm_unreachable("lazy symbol reached writer");
Rui Ueyama5c073a92019-05-16 03:29:03138 case Symbol::CommonKind:
139 llvm_unreachable("common symbol reached writer");
Rui Ueyamaf3fad552018-10-12 18:29:18140 case Symbol::PlaceholderKind:
141 llvm_unreachable("placeholder symbol reached writer");
Rui Ueyamab5a69702016-02-01 21:00:35142 }
George Rimar777f9632016-03-12 08:31:34143 llvm_unreachable("invalid symbol kind");
Rui Ueyamab5a69702016-02-01 21:00:35144}
145
Rui Ueyama3837f422019-07-10 05:00:37146uint64_t Symbol::getVA(int64_t addend) const {
Fangrui Songa8024df2021-12-13 03:12:01147 return getSymVA(*this, addend) + addend;
Rafael Espindola87d9f102016-03-11 12:19:05148}
149
Peter Collingbourne8331f612019-02-13 21:49:55150uint64_t Symbol::getGotVA() const {
Rui Ueyama3837f422019-07-10 05:00:37151 if (gotInIgot)
152 return in.igotPlt->getVA() + getGotPltOffset();
153 return in.got->getVA() + getGotOffset();
Peter Collingbourne8331f612019-02-13 21:49:55154}
Rafael Espindola74031ba2016-04-07 15:20:56155
Harald van Dijkd6241342021-05-16 23:13:00156uint64_t Symbol::getGotOffset() const {
Fangrui Song5d3bd7f2022-01-09 21:43:26157 return getGotIdx() * target->gotEntrySize;
Harald van Dijkd6241342021-05-16 23:13:00158}
Rui Ueyamab5a69702016-02-01 21:00:35159
Rui Ueyamaf52496e2017-11-03 21:21:47160uint64_t Symbol::getGotPltVA() const {
Rui Ueyama3837f422019-07-10 05:00:37161 if (isInIplt)
162 return in.igotPlt->getVA() + getGotPltOffset();
163 return in.gotPlt->getVA() + getGotPltOffset();
Rafael Espindola74031ba2016-04-07 15:20:56164}
165
Rui Ueyamaf52496e2017-11-03 21:21:47166uint64_t Symbol::getGotPltOffset() const {
Rui Ueyama3837f422019-07-10 05:00:37167 if (isInIplt)
Fangrui Song5d3bd7f2022-01-09 21:43:26168 return getPltIdx() * target->gotEntrySize;
169 return (getPltIdx() + target->gotPltHeaderEntriesNum) * target->gotEntrySize;
Rui Ueyamab5a69702016-02-01 21:00:35170}
171
Rui Ueyamaf52496e2017-11-03 21:21:47172uint64_t Symbol::getPltVA() const {
Fangrui Song891a8652019-12-14 22:17:35173 uint64_t outVA = isInIplt
Fangrui Song5d3bd7f2022-01-09 21:43:26174 ? in.iplt->getVA() + getPltIdx() * target->ipltEntrySize
Fangrui Song891a8652019-12-14 22:17:35175 : in.plt->getVA() + in.plt->headerSize +
Fangrui Song5d3bd7f2022-01-09 21:43:26176 getPltIdx() * target->pltEntrySize;
Fangrui Song891a8652019-12-14 22:17:35177
Simon Atanasyanfae2a5092019-02-19 10:36:58178 // While linking microMIPS code PLT code are always microMIPS
179 // code. Set the less-significant bit to track that fact.
180 // See detailed comment in the `getSymVA` function.
Rui Ueyama3837f422019-07-10 05:00:37181 if (config->emachine == EM_MIPS && isMicroMips())
182 outVA |= 1;
183 return outVA;
Rafael Espindolaab0cce52018-04-26 17:58:58184}
185
Rui Ueyamaf52496e2017-11-03 21:21:47186uint64_t Symbol::getSize() const {
Rui Ueyama3837f422019-07-10 05:00:37187 if (const auto *dr = dyn_cast<Defined>(this))
188 return dr->size;
189 return cast<SharedSymbol>(this)->size;
Rui Ueyama512c61d2016-02-03 00:12:24190}
191
Rui Ueyamaf52496e2017-11-03 21:21:47192OutputSection *Symbol::getOutputSection() const {
Rui Ueyama3837f422019-07-10 05:00:37193 if (auto *s = dyn_cast<Defined>(this)) {
194 if (auto *sec = s->section)
Fangrui Songc2f2bb02021-12-21 08:39:16195 return sec->getOutputSection();
Rui Ueyama968db482017-02-28 04:02:42196 return nullptr;
197 }
Rui Ueyama968db482017-02-28 04:02:42198 return nullptr;
199}
200
Rui Ueyama35fa6c52016-11-23 05:48:40201// If a symbol name contains '@', the characters after that is
202// a symbol version name. This function parses that.
Rui Ueyamaf52496e2017-11-03 21:21:47203void Symbol::parseSymbolVersion() {
Fangrui Song00809c82021-08-05 06:52:55204 // Return if localized by a local: pattern in a version script.
205 if (versionId == VER_NDX_LOCAL)
206 return;
Rui Ueyama3837f422019-07-10 05:00:37207 StringRef s = getName();
208 size_t pos = s.find('@');
Fangrui Song101407b2021-12-16 07:59:55209 if (pos == StringRef::npos)
Rui Ueyama35fa6c52016-11-23 05:48:40210 return;
Rui Ueyama3837f422019-07-10 05:00:37211 StringRef verstr = s.substr(pos + 1);
Rui Ueyama35fa6c52016-11-23 05:48:40212
213 // Truncate the symbol name so that it doesn't include the version string.
Rui Ueyama3837f422019-07-10 05:00:37214 nameSize = pos;
Rui Ueyama35fa6c52016-11-23 05:48:40215
Fangrui Song7924b382021-12-27 01:25:54216 if (verstr.empty())
217 return;
218
Rafael Espindola1d6d1b42017-01-17 16:08:06219 // If this is not in this DSO, it is not a definition.
Peter Collingbourneb472aa02017-11-06 04:39:07220 if (!isDefined())
Rafael Espindola2756e042017-01-06 22:30:35221 return;
222
Rui Ueyama35fa6c52016-11-23 05:48:40223 // '@@' in a symbol name means the default version.
224 // It is usually the most recent one.
Rui Ueyama3837f422019-07-10 05:00:37225 bool isDefault = (verstr[0] == '@');
226 if (isDefault)
227 verstr = verstr.substr(1);
Rui Ueyama35fa6c52016-11-23 05:48:40228
Fangrui Songe28a70d2019-08-05 14:31:39229 for (const VersionDefinition &ver : namedVersionDefs()) {
Rui Ueyama3837f422019-07-10 05:00:37230 if (ver.name != verstr)
Rui Ueyama35fa6c52016-11-23 05:48:40231 continue;
232
Rui Ueyama3837f422019-07-10 05:00:37233 if (isDefault)
234 versionId = ver.id;
Rui Ueyama35fa6c52016-11-23 05:48:40235 else
Rui Ueyama3837f422019-07-10 05:00:37236 versionId = ver.id | VERSYM_HIDDEN;
Rui Ueyama35fa6c52016-11-23 05:48:40237 return;
238 }
239
240 // It is an error if the specified version is not defined.
George Rimar4d2f97622017-07-04 13:19:13241 // Usually version script is not provided when linking executable,
242 // but we may still want to override a versioned symbol from DSO,
Peter Smith796fb992018-05-14 10:13:56243 // so we do not report error in this case. We also do not error
244 // if the symbol has a local version as it won't be in the dynamic
245 // symbol table.
Rui Ueyama3837f422019-07-10 05:00:37246 if (config->shared && versionId != VER_NDX_LOCAL)
247 error(toString(file) + ": symbol " + s + " has undefined version " +
248 verstr);
Rui Ueyama35fa6c52016-11-23 05:48:40249}
250
Fangrui Song09401df2021-11-26 18:58:50251void Symbol::extract() const {
Fangrui Song3a5fb572021-12-23 01:41:50252 if (auto *sym = dyn_cast<LazyArchive>(this)) {
Fangrui Song09401df2021-11-26 18:58:50253 cast<ArchiveFile>(sym->file)->extract(sym->sym);
Fangrui Song3a5fb572021-12-23 01:41:50254 } else if (file->lazy) {
255 file->lazy = false;
256 parseFile(file);
257 }
Rui Ueyama7d476192019-05-16 02:14:00258}
Rui Ueyamaf8baa662016-04-07 19:24:51259
Peter Collingbourne98930112018-08-08 23:48:12260MemoryBufferRef LazyArchive::getMemberBuffer() {
Nico Weber9c0716f2019-07-23 19:00:01261 Archive::Child c =
262 CHECK(sym.getMember(),
263 "could not get the member for symbol " + toELFString(sym));
Peter Collingbourne98930112018-08-08 23:48:12264
Rui Ueyama3837f422019-07-10 05:00:37265 return CHECK(c.getMemoryBufferRef(),
Peter Collingbourne98930112018-08-08 23:48:12266 "could not get the buffer for the member defining symbol " +
Nico Weber9c0716f2019-07-23 19:00:01267 toELFString(sym));
Peter Collingbourne98930112018-08-08 23:48:12268}
269
Rui Ueyamaf52496e2017-11-03 21:21:47270uint8_t Symbol::computeBinding() const {
Rui Ueyama3837f422019-07-10 05:00:37271 if (config->relocatable)
272 return binding;
Fangrui Songcfdd4582019-08-11 17:03:00273 if ((visibility != STV_DEFAULT && visibility != STV_PROTECTED) ||
Nathan Lanza2f651662021-03-16 08:33:50274 (versionId == VER_NDX_LOCAL && !isLazy()))
Rafael Espindolab7e2ee22017-01-10 17:08:13275 return STB_LOCAL;
Fangrui Songb3cc4702022-01-16 07:40:43276 if (binding == STB_GNU_UNIQUE && !config->gnuUnique)
Rafael Espindolab7e2ee22017-01-10 17:08:13277 return STB_GLOBAL;
Rui Ueyama3837f422019-07-10 05:00:37278 return binding;
Rafael Espindolab7e2ee22017-01-10 17:08:13279}
280
Rui Ueyamaf52496e2017-11-03 21:21:47281bool Symbol::includeInDynsym() const {
Rafael Espindolab7e2ee22017-01-10 17:08:13282 if (computeBinding() == STB_LOCAL)
Rafael Espindolaae605c12016-04-21 20:35:25283 return false;
Fangrui Song375371c2020-01-09 23:53:52284 if (!isDefined() && !isCommon())
Fangrui Song0fbf28f2020-01-23 19:52:03285 // This should unconditionally return true, unfortunately glibc -static-pie
286 // expects undefined weak symbols not to exist in .dynsym, e.g.
287 // __pthread_mutex_lock reference in _dl_add_to_namespace_list,
288 // __pthread_initialize_minimal reference in csu/libc-start.c.
Fangrui Song01a51622022-01-16 07:32:48289 return !(isUndefWeak() && config->noDynamicLinker);
Rui Ueyamae63ae7f2019-06-25 06:58:07290
Fangrui Song375371c2020-01-09 23:53:52291 return exportDynamic || inDynamicList;
Rafael Espindolaae605c12016-04-21 20:35:25292}
Rui Ueyama69c778c2016-07-17 17:50:09293
294// Print out a log message for --trace-symbol.
Fangrui Song07837b82020-05-15 05:18:58295void elf::printTraceSymbol(const Symbol *sym) {
Rui Ueyama3837f422019-07-10 05:00:37296 std::string s;
297 if (sym->isUndefined())
298 s = ": reference to ";
299 else if (sym->isLazy())
300 s = ": lazy definition of ";
301 else if (sym->isShared())
302 s = ": shared definition of ";
303 else if (sym->isCommon())
304 s = ": common definition of ";
Rui Ueyama69c778c2016-07-17 17:50:09305 else
Rui Ueyama3837f422019-07-10 05:00:37306 s = ": definition of ";
Rui Ueyamae6e206d2017-02-21 23:22:56307
Rui Ueyama3837f422019-07-10 05:00:37308 message(toString(sym->file) + s + sym->getName());
Rui Ueyama69c778c2016-07-17 17:50:09309}
310
Fangrui Songa954bb12021-09-20 16:52:30311static void recordWhyExtract(const InputFile *reference,
312 const InputFile &extracted, const Symbol &sym) {
313 whyExtract.emplace_back(toString(reference), &extracted, sym);
314}
315
Fangrui Song07837b82020-05-15 05:18:58316void elf::maybeWarnUnorderableSymbol(const Symbol *sym) {
Rui Ueyama3837f422019-07-10 05:00:37317 if (!config->warnSymbolOrdering)
Michael J. Spencerb8427252018-04-17 23:30:05318 return;
Rui Ueyamab774c3c2018-04-26 01:38:29319
Fangrui Song11ca54f2018-10-10 22:48:57320 // If UnresolvedPolicy::Ignore is used, no "undefined symbol" error/warning
321 // is emitted. It makes sense to not warn on undefined symbols.
322 //
323 // Note, ld.bfd --symbol-ordering-file= does not warn on undefined symbols,
324 // but we don't have to be compatible here.
Rui Ueyama3837f422019-07-10 05:00:37325 if (sym->isUndefined() &&
326 config->unresolvedSymbols == UnresolvedPolicy::Ignore)
Fangrui Song11ca54f2018-10-10 22:48:57327 return;
328
Rui Ueyama3837f422019-07-10 05:00:37329 const InputFile *file = sym->file;
330 auto *d = dyn_cast<Defined>(sym);
Rui Ueyamab774c3c2018-04-26 01:38:29331
Rui Ueyama3837f422019-07-10 05:00:37332 auto report = [&](StringRef s) { warn(toString(file) + s + sym->getName()); };
Rui Ueyamab774c3c2018-04-26 01:38:29333
Rui Ueyama3837f422019-07-10 05:00:37334 if (sym->isUndefined())
335 report(": unable to order undefined symbol: ");
336 else if (sym->isShared())
337 report(": unable to order shared symbol: ");
338 else if (d && !d->section)
339 report(": unable to order absolute symbol: ");
340 else if (d && isa<OutputSection>(d->section))
341 report(": unable to order synthetic symbol: ");
Fangrui Songe1b6b5b2021-12-24 20:09:48342 else if (d && !d->section->isLive())
Rui Ueyama3837f422019-07-10 05:00:37343 report(": unable to order discarded symbol: ");
Michael J. Spencerb8427252018-04-17 23:30:05344}
345
Fangrui Songcd0ab242019-11-30 05:58:36346// Returns true if a symbol can be replaced at load-time by a symbol
347// with the same name defined in other ELF executable or DSO.
Fangrui Song07837b82020-05-15 05:18:58348bool elf::computeIsPreemptible(const Symbol &sym) {
Fangrui Songe9262ed2021-12-27 02:11:45349 assert(!sym.isLocal() || sym.isPlaceholder());
Fangrui Songcd0ab242019-11-30 05:58:36350
351 // Only symbols with default visibility that appear in dynsym can be
352 // preempted. Symbols with protected visibility cannot be preempted.
353 if (!sym.includeInDynsym() || sym.visibility != STV_DEFAULT)
354 return false;
355
356 // At this point copy relocations have not been created yet, so any
357 // symbol that is not defined locally is preemptible.
358 if (!sym.isDefined())
359 return true;
360
361 if (!config->shared)
362 return false;
363
Fangrui Song751f18e2020-06-01 18:27:53364 // If -Bsymbolic or --dynamic-list is specified, or -Bsymbolic-functions is
365 // specified and the symbol is STT_FUNC, the symbol is preemptible iff it is
Fangrui Songb06426d2021-07-29 21:46:53366 // in the dynamic list. -Bsymbolic-non-weak-functions is a non-weak subset of
367 // -Bsymbolic-functions.
368 if (config->symbolic ||
369 (config->bsymbolic == BsymbolicKind::Functions && sym.isFunc()) ||
370 (config->bsymbolic == BsymbolicKind::NonWeakFunctions && sym.isFunc() &&
371 sym.binding != STB_WEAK))
Fangrui Songcd0ab242019-11-30 05:58:36372 return sym.inDynamicList;
Fangrui Songcd0ab242019-11-30 05:58:36373 return true;
374}
375
Fangrui Song07837b82020-05-15 05:18:58376void elf::reportBackrefs() {
Fangrui Song03c825c2020-04-06 05:27:46377 for (auto &it : backwardReferences) {
378 const Symbol &sym = *it.first;
Fangrui Song3ba334222020-11-08 04:17:41379 std::string to = toString(it.second.second);
380 // Some libraries have known problems and can cause noise. Filter them out
381 // with --warn-backrefs-exclude=. to may look like *.o or *.a(*.o).
382 bool exclude = false;
383 for (const llvm::GlobPattern &pat : config->warnBackrefsExclude)
384 if (pat.match(to)) {
385 exclude = true;
386 break;
387 }
388 if (!exclude)
389 warn("backward reference detected: " + sym.getName() + " in " +
390 toString(it.second.first) + " refers to " + to);
Fangrui Song03c825c2020-04-06 05:27:46391 }
392}
393
Rui Ueyama3837f422019-07-10 05:00:37394static uint8_t getMinVisibility(uint8_t va, uint8_t vb) {
395 if (va == STV_DEFAULT)
396 return vb;
397 if (vb == STV_DEFAULT)
398 return va;
399 return std::min(va, vb);
Rui Ueyama7f7d2b22019-05-23 09:58:08400}
401
402// Merge symbol properties.
403//
404// When we have many symbols of the same name, we choose one of them,
405// and that's the result of symbol resolution. However, symbols that
406// were not chosen still affect some symbol properties.
Rui Ueyama3837f422019-07-10 05:00:37407void Symbol::mergeProperties(const Symbol &other) {
408 if (other.exportDynamic)
409 exportDynamic = true;
410 if (other.isUsedInRegularObj)
411 isUsedInRegularObj = true;
Rui Ueyama7f7d2b22019-05-23 09:58:08412
413 // DSO symbols do not affect visibility in the output.
Rui Ueyama3837f422019-07-10 05:00:37414 if (!other.isShared())
415 visibility = getMinVisibility(visibility, other.visibility);
Rui Ueyama7f7d2b22019-05-23 09:58:08416}
417
Rui Ueyama3837f422019-07-10 05:00:37418void Symbol::resolve(const Symbol &other) {
419 mergeProperties(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08420
421 if (isPlaceholder()) {
Rui Ueyama3837f422019-07-10 05:00:37422 replace(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08423 return;
424 }
425
Rui Ueyama3837f422019-07-10 05:00:37426 switch (other.kind()) {
Rui Ueyama7f7d2b22019-05-23 09:58:08427 case Symbol::UndefinedKind:
Rui Ueyama3837f422019-07-10 05:00:37428 resolveUndefined(cast<Undefined>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08429 break;
430 case Symbol::CommonKind:
Rui Ueyama3837f422019-07-10 05:00:37431 resolveCommon(cast<CommonSymbol>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08432 break;
433 case Symbol::DefinedKind:
Rui Ueyama3837f422019-07-10 05:00:37434 resolveDefined(cast<Defined>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08435 break;
436 case Symbol::LazyArchiveKind:
Rui Ueyama3837f422019-07-10 05:00:37437 resolveLazy(cast<LazyArchive>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08438 break;
439 case Symbol::LazyObjectKind:
Rui Ueyama3837f422019-07-10 05:00:37440 resolveLazy(cast<LazyObject>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08441 break;
442 case Symbol::SharedKind:
Rui Ueyama3837f422019-07-10 05:00:37443 resolveShared(cast<SharedSymbol>(other));
Rui Ueyama7f7d2b22019-05-23 09:58:08444 break;
445 case Symbol::PlaceholderKind:
446 llvm_unreachable("bad symbol kind");
447 }
448}
449
Rui Ueyama3837f422019-07-10 05:00:37450void Symbol::resolveUndefined(const Undefined &other) {
Rui Ueyama7f7d2b22019-05-23 09:58:08451 // An undefined symbol with non default visibility must be satisfied
452 // in the same DSO.
453 //
454 // If this is a non-weak defined symbol in a discarded section, override the
455 // existing undefined symbol for better error message later.
Rui Ueyama3837f422019-07-10 05:00:37456 if ((isShared() && other.visibility != STV_DEFAULT) ||
457 (isUndefined() && other.binding != STB_WEAK && other.discardedSecIdx)) {
458 replace(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08459 return;
460 }
461
Rui Ueyama3837f422019-07-10 05:00:37462 if (traced)
463 printTraceSymbol(&other);
Sam Clegg7991b682019-05-24 13:29:17464
Fangrui Songf3475412019-07-04 10:38:04465 if (isLazy()) {
Fangrui Song09401df2021-11-26 18:58:50466 // An undefined weak will not extract archive members. See comment on Lazy
467 // in Symbols.h for the details.
Rui Ueyama3837f422019-07-10 05:00:37468 if (other.binding == STB_WEAK) {
469 binding = STB_WEAK;
470 type = other.type;
Rui Ueyama7f7d2b22019-05-23 09:58:08471 return;
472 }
473
474 // Do extra check for --warn-backrefs.
475 //
476 // --warn-backrefs is an option to prevent an undefined reference from
Fangrui Song09401df2021-11-26 18:58:50477 // extracting an archive member written earlier in the command line. It can
478 // be used to keep compatibility with GNU linkers to some degree. I'll
479 // explain the feature and why you may find it useful in this comment.
Rui Ueyama7f7d2b22019-05-23 09:58:08480 //
481 // lld's symbol resolution semantics is more relaxed than traditional Unix
482 // linkers. For example,
483 //
484 // ld.lld foo.a bar.o
485 //
486 // succeeds even if bar.o contains an undefined symbol that has to be
487 // resolved by some object file in foo.a. Traditional Unix linkers don't
488 // allow this kind of backward reference, as they visit each file only once
489 // from left to right in the command line while resolving all undefined
490 // symbols at the moment of visiting.
491 //
492 // In the above case, since there's no undefined symbol when a linker visits
493 // foo.a, no files are pulled out from foo.a, and because the linker forgets
494 // about foo.a after visiting, it can't resolve undefined symbols in bar.o
495 // that could have been resolved otherwise.
496 //
497 // That lld accepts more relaxed form means that (besides it'd make more
498 // sense) you can accidentally write a command line or a build file that
499 // works only with lld, even if you have a plan to distribute it to wider
500 // users who may be using GNU linkers. With --warn-backrefs, you can detect
501 // a library order that doesn't work with other Unix linkers.
502 //
503 // The option is also useful to detect cyclic dependencies between static
504 // archives. Again, lld accepts
505 //
506 // ld.lld foo.a bar.a
507 //
508 // even if foo.a and bar.a depend on each other. With --warn-backrefs, it is
509 // handled as an error.
510 //
511 // Here is how the option works. We assign a group ID to each file. A file
512 // with a smaller group ID can pull out object files from an archive file
513 // with an equal or greater group ID. Otherwise, it is a reverse dependency
514 // and an error.
515 //
516 // A file outside --{start,end}-group gets a fresh ID when instantiated. All
517 // files within the same --{start,end}-group get the same group ID. E.g.
518 //
519 // ld.lld A B --start-group C D --end-group E
520 //
521 // A forms group 0. B form group 1. C and D (including their member object
522 // files) form group 2. E forms group 3. I think that you can see how this
523 // group assignment rule simulates the traditional linker's semantics.
Rui Ueyama3837f422019-07-10 05:00:37524 bool backref = config->warnBackrefs && other.file &&
525 file->groupId < other.file->groupId;
Fangrui Song09401df2021-11-26 18:58:50526 extract();
Rui Ueyama7f7d2b22019-05-23 09:58:08527
Fangrui Songa954bb12021-09-20 16:52:30528 if (!config->whyExtract.empty())
529 recordWhyExtract(other.file, *file, *this);
530
Rui Ueyama7f7d2b22019-05-23 09:58:08531 // We don't report backward references to weak symbols as they can be
532 // overridden later.
Fangrui Song03c825c2020-04-06 05:27:46533 //
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
Fangrui Songce3c5da2020-10-22 22:26:52537 // definition. this->file needs to be saved because in the case of LTO it
538 // may be reset to nullptr or be replaced with a file named lto.tmp.
Rui Ueyama3837f422019-07-10 05:00:37539 if (backref && !isWeak())
Fangrui Songce3c5da2020-10-22 22:26:52540 backwardReferences.try_emplace(this, std::make_pair(other.file, file));
Fangrui Songf3475412019-07-04 10:38:04541 return;
542 }
543
544 // Undefined symbols in a SharedFile do not change the binding.
Kazu Hirata62e48ed2021-12-25 05:22:27545 if (isa_and_nonnull<SharedFile>(other.file))
Fangrui Songf3475412019-07-04 10:38:04546 return;
547
Fangrui Songe49c4172019-08-06 14:03:45548 if (isUndefined() || isShared()) {
549 // The binding will be weak if there is at least one reference and all are
550 // weak. The binding has one opportunity to change to weak: if the first
551 // reference is weak.
552 if (other.binding != STB_WEAK || !referenced)
Rui Ueyama3837f422019-07-10 05:00:37553 binding = other.binding;
Rui Ueyama7f7d2b22019-05-23 09:58:08554 }
555}
556
Rui Ueyama7f7d2b22019-05-23 09:58:08557// Compare two symbols. Return 1 if the new symbol should win, -1 if
558// the new symbol should lose, or 0 if there is a conflict.
Rui Ueyama3837f422019-07-10 05:00:37559int Symbol::compare(const Symbol *other) const {
560 assert(other->isDefined() || other->isCommon());
Rui Ueyama7f7d2b22019-05-23 09:58:08561
562 if (!isDefined() && !isCommon())
563 return 1;
564
Fangrui Song2bdad162021-12-15 23:19:35565 // .symver foo,foo@@VER unfortunately creates two defined symbols: foo and
566 // foo@@VER. In GNU ld, if foo and foo@@VER are in the same file, foo is
567 // ignored. In our implementation, when this is foo, this->getName() may still
568 // contain @@, return 1 in this case as well.
569 if (file == other->file) {
570 if (other->getName().contains("@@"))
571 return 1;
572 if (getName().contains("@@"))
573 return -1;
574 }
Rui Ueyama7f7d2b22019-05-23 09:58:08575
Rui Ueyama3837f422019-07-10 05:00:37576 if (other->isWeak())
Rui Ueyama7f7d2b22019-05-23 09:58:08577 return -1;
578
579 if (isWeak())
580 return 1;
581
Rui Ueyama3837f422019-07-10 05:00:37582 if (isCommon() && other->isCommon()) {
583 if (config->warnCommon)
Rui Ueyama7f7d2b22019-05-23 09:58:08584 warn("multiple common of " + getName());
585 return 0;
586 }
587
588 if (isCommon()) {
Rui Ueyama3837f422019-07-10 05:00:37589 if (config->warnCommon)
Rui Ueyama7f7d2b22019-05-23 09:58:08590 warn("common " + getName() + " is overridden");
591 return 1;
592 }
593
Rui Ueyama3837f422019-07-10 05:00:37594 if (other->isCommon()) {
595 if (config->warnCommon)
Rui Ueyama7f7d2b22019-05-23 09:58:08596 warn("common " + getName() + " is overridden");
597 return -1;
598 }
599
Rui Ueyama3837f422019-07-10 05:00:37600 auto *oldSym = cast<Defined>(this);
601 auto *newSym = cast<Defined>(other);
Rui Ueyama7f7d2b22019-05-23 09:58:08602
Kazu Hirata62e48ed2021-12-25 05:22:27603 if (isa_and_nonnull<BitcodeFile>(other->file))
Rui Ueyama7f7d2b22019-05-23 09:58:08604 return 0;
605
Rui Ueyama3837f422019-07-10 05:00:37606 if (!oldSym->section && !newSym->section && oldSym->value == newSym->value &&
607 newSym->binding == STB_GLOBAL)
Rui Ueyama7f7d2b22019-05-23 09:58:08608 return -1;
609
610 return 0;
611}
612
Rui Ueyama3837f422019-07-10 05:00:37613static void reportDuplicate(Symbol *sym, InputFile *newFile,
614 InputSectionBase *errSec, uint64_t errOffset) {
615 if (config->allowMultipleDefinition)
Rui Ueyama7f7d2b22019-05-23 09:58:08616 return;
617
Rui Ueyama3837f422019-07-10 05:00:37618 Defined *d = cast<Defined>(sym);
619 if (!d->section || !errSec) {
620 error("duplicate symbol: " + toString(*sym) + "\n>>> defined in " +
621 toString(sym->file) + "\n>>> defined in " + toString(newFile));
Rui Ueyama7f7d2b22019-05-23 09:58:08622 return;
623 }
624
625 // Construct and print an error message in the form of:
626 //
627 // ld.lld: error: duplicate symbol: foo
628 // >>> defined at bar.c:30
629 // >>> bar.o (/home/alice/src/bar.o)
630 // >>> defined at baz.c:563
631 // >>> baz.o in archive libbaz.a
Rui Ueyama3837f422019-07-10 05:00:37632 auto *sec1 = cast<InputSectionBase>(d->section);
633 std::string src1 = sec1->getSrcMsg(*sym, d->value);
634 std::string obj1 = sec1->getObjMsg(d->value);
635 std::string src2 = errSec->getSrcMsg(*sym, errOffset);
636 std::string obj2 = errSec->getObjMsg(errOffset);
Rui Ueyama7f7d2b22019-05-23 09:58:08637
Rui Ueyama3837f422019-07-10 05:00:37638 std::string msg = "duplicate symbol: " + toString(*sym) + "\n>>> defined at ";
639 if (!src1.empty())
640 msg += src1 + "\n>>> ";
641 msg += obj1 + "\n>>> defined at ";
642 if (!src2.empty())
643 msg += src2 + "\n>>> ";
644 msg += obj2;
645 error(msg);
Rui Ueyama7f7d2b22019-05-23 09:58:08646}
647
Rui Ueyama3837f422019-07-10 05:00:37648void Symbol::resolveCommon(const CommonSymbol &other) {
649 int cmp = compare(&other);
650 if (cmp < 0)
Rui Ueyama7f7d2b22019-05-23 09:58:08651 return;
652
Rui Ueyama3837f422019-07-10 05:00:37653 if (cmp > 0) {
Fangrui Song69d10d22019-12-07 05:18:31654 if (auto *s = dyn_cast<SharedSymbol>(this)) {
655 // Increase st_size if the shared symbol has a larger st_size. The shared
656 // symbol may be created from common symbols. The fact that some object
657 // files were linked into a shared object first should not change the
658 // regular rule that picks the largest st_size.
659 uint64_t size = s->size;
660 replace(other);
661 if (size > cast<CommonSymbol>(this)->size)
662 cast<CommonSymbol>(this)->size = size;
663 } else {
664 replace(other);
665 }
Rui Ueyama7f7d2b22019-05-23 09:58:08666 return;
667 }
668
Rui Ueyama3837f422019-07-10 05:00:37669 CommonSymbol *oldSym = cast<CommonSymbol>(this);
Rui Ueyama7f7d2b22019-05-23 09:58:08670
Rui Ueyama3837f422019-07-10 05:00:37671 oldSym->alignment = std::max(oldSym->alignment, other.alignment);
672 if (oldSym->size < other.size) {
673 oldSym->file = other.file;
674 oldSym->size = other.size;
Rui Ueyama7f7d2b22019-05-23 09:58:08675 }
676}
677
Rui Ueyama3837f422019-07-10 05:00:37678void Symbol::resolveDefined(const Defined &other) {
679 int cmp = compare(&other);
680 if (cmp > 0)
681 replace(other);
682 else if (cmp == 0)
683 reportDuplicate(this, other.file,
684 dyn_cast_or_null<InputSectionBase>(other.section),
685 other.value);
Rui Ueyama7f7d2b22019-05-23 09:58:08686}
687
Sean Fertile8f91f382020-12-07 14:28:17688template <class LazyT>
689static void replaceCommon(Symbol &oldSym, const LazyT &newSym) {
690 backwardReferences.erase(&oldSym);
691 oldSym.replace(newSym);
Fangrui Song09401df2021-11-26 18:58:50692 newSym.extract();
Sean Fertile8f91f382020-12-07 14:28:17693}
694
Rui Ueyama3837f422019-07-10 05:00:37695template <class LazyT> void Symbol::resolveLazy(const LazyT &other) {
Sean Fertile8f91f382020-12-07 14:28:17696 // For common objects, we want to look for global or weak definitions that
Fangrui Song09401df2021-11-26 18:58:50697 // should be extracted as the canonical definition instead.
Sean Fertile8f91f382020-12-07 14:28:17698 if (isCommon() && elf::config->fortranCommon) {
699 if (auto *laSym = dyn_cast<LazyArchive>(&other)) {
700 ArchiveFile *archive = cast<ArchiveFile>(laSym->file);
701 const Archive::Symbol &archiveSym = laSym->sym;
Fangrui Song09401df2021-11-26 18:58:50702 if (archive->shouldExtractForCommon(archiveSym)) {
Sean Fertile8f91f382020-12-07 14:28:17703 replaceCommon(*this, other);
704 return;
705 }
706 } else if (auto *loSym = dyn_cast<LazyObject>(&other)) {
Fangrui Song3a5fb572021-12-23 01:41:50707 if (loSym->file->shouldExtractForCommon(loSym->getName())) {
Sean Fertile8f91f382020-12-07 14:28:17708 replaceCommon(*this, other);
709 return;
710 }
711 }
712 }
713
Fangrui Song03c825c2020-04-06 05:27:46714 if (!isUndefined()) {
715 // See the comment in resolveUndefined().
716 if (isDefined())
717 backwardReferences.erase(this);
Rui Ueyama7f7d2b22019-05-23 09:58:08718 return;
Fangrui Song03c825c2020-04-06 05:27:46719 }
Rui Ueyama7f7d2b22019-05-23 09:58:08720
Fangrui Song09401df2021-11-26 18:58:50721 // An undefined weak will not extract archive members. See comment on Lazy in
Rui Ueyama7f7d2b22019-05-23 09:58:08722 // Symbols.h for the details.
723 if (isWeak()) {
Rui Ueyama3837f422019-07-10 05:00:37724 uint8_t ty = type;
725 replace(other);
726 type = ty;
727 binding = STB_WEAK;
Rui Ueyama7f7d2b22019-05-23 09:58:08728 return;
729 }
730
Fangrui Songa954bb12021-09-20 16:52:30731 const InputFile *oldFile = file;
Fangrui Song09401df2021-11-26 18:58:50732 other.extract();
Fangrui Songa954bb12021-09-20 16:52:30733 if (!config->whyExtract.empty())
734 recordWhyExtract(oldFile, *file, *this);
Rui Ueyama7f7d2b22019-05-23 09:58:08735}
736
Rui Ueyama3837f422019-07-10 05:00:37737void Symbol::resolveShared(const SharedSymbol &other) {
Fangrui Song69d10d22019-12-07 05:18:31738 if (isCommon()) {
739 // See the comment in resolveCommon() above.
740 if (other.size > cast<CommonSymbol>(this)->size)
741 cast<CommonSymbol>(this)->size = other.size;
742 return;
743 }
Rui Ueyama3837f422019-07-10 05:00:37744 if (visibility == STV_DEFAULT && (isUndefined() || isLazy())) {
Rui Ueyama7f7d2b22019-05-23 09:58:08745 // An undefined symbol with non default visibility must be satisfied
746 // in the same DSO.
Rui Ueyama3837f422019-07-10 05:00:37747 uint8_t bind = binding;
748 replace(other);
749 binding = bind;
Fangrui Song64676492020-05-18 17:15:59750 } else if (traced)
751 printTraceSymbol(&other);
Rui Ueyama7f7d2b22019-05-23 09:58:08752}