1 //===- Symbols.cpp --------------------------------------------------------===//
3 // 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
7 //===----------------------------------------------------------------------===//
10 #include "InputFiles.h"
11 #include "InputSection.h"
12 #include "OutputSections.h"
13 #include "SyntheticSections.h"
16 #include "lld/Common/ErrorHandler.h"
17 #include "lld/Common/Strings.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/Path.h"
24 using namespace llvm::object;
25 using namespace llvm::ELF;
27 using namespace lld::elf;
29 // Returns a symbol for an error message.
30 static std::string demangle(StringRef symName) {
31 if (elf::config->demangle)
32 return demangleItanium(symName);
33 return std::string(symName);
36 std::string lld::toString(const elf::Symbol &sym) {
37 StringRef name = sym.getName();
38 std::string ret = demangle(name);
40 // If sym has a non-default version, its name may have been truncated at '@'
41 // by Symbol::parseSymbolVersion(). Add the trailing part. This check is safe
42 // because every symbol name ends with '\0'.
43 if (name.data()[name.size()] == '@')
44 ret += name.data() + name.size();
48 std::string lld::toELFString(const Archive::Symbol &b) {
49 return demangle(b.getName());
53 Defined *ElfSym::etext1;
54 Defined *ElfSym::etext2;
55 Defined *ElfSym::edata1;
56 Defined *ElfSym::edata2;
57 Defined *ElfSym::end1;
58 Defined *ElfSym::end2;
59 Defined *ElfSym::globalOffsetTable;
60 Defined *ElfSym::mipsGp;
61 Defined *ElfSym::mipsGpDisp;
62 Defined *ElfSym::mipsLocalGp;
63 Defined *ElfSym::relaIpltStart;
64 Defined *ElfSym::relaIpltEnd;
65 Defined *ElfSym::riscvGlobalPointer;
66 Defined *ElfSym::tlsModuleBase;
67 DenseMap<const Symbol *, const InputFile *> elf::backwardReferences;
69 static uint64_t getSymVA(const Symbol &sym, int64_t &addend) {
71 case Symbol::DefinedKind: {
72 auto &d = cast<Defined>(sym);
73 SectionBase *isec = d.section;
75 // This is an absolute symbol.
79 assert(isec != &InputSection::discarded);
82 uint64_t offset = d.value;
84 // An object in an SHF_MERGE section might be referenced via a
85 // section symbol (as a hack for reducing the number of local
87 // Depending on the addend, the reference via a section symbol
88 // refers to a different object in the merge section.
89 // Since the objects in the merge section are not necessarily
90 // contiguous in the output, the addend can thus affect the final
91 // VA in a non-linear way.
92 // To make this work, we incorporate the addend into the section
93 // offset (and zero out the addend for later processing) so that
94 // we find the right object in the section.
100 // In the typical case, this is actually very simple and boils
101 // down to adding together 3 numbers:
102 // 1. The address of the output section.
103 // 2. The offset of the input section within the output section.
104 // 3. The offset within the input section (this addition happens
105 // inside InputSection::getOffset).
107 // If you understand the data structures involved with this next
108 // line (and how they get built), then you have a pretty good
109 // understanding of the linker.
110 uint64_t va = isec->getVA(offset);
112 // MIPS relocatable files can mix regular and microMIPS code.
113 // Linker needs to distinguish such code. To do so microMIPS
114 // symbols has the `STO_MIPS_MICROMIPS` flag in the `st_other`
115 // field. Unfortunately, the `MIPS::relocate()` method has
116 // a symbol value only. To pass type of the symbol (regular/microMIPS)
117 // to that routine as well as other places where we write
118 // a symbol value as-is (.dynamic section, `Elf_Ehdr::e_entry`
119 // field etc) do the same trick as compiler uses to mark microMIPS
120 // for CPU - set the less-significant bit.
121 if (config->emachine == EM_MIPS && isMicroMips() &&
122 ((sym.stOther & STO_MIPS_MICROMIPS) || sym.needsPltAddr))
125 if (d.isTls() && !config->relocatable) {
126 // Use the address of the TLS segment's first section rather than the
127 // segment's address, because segment addresses aren't initialized until
128 // after sections are finalized. (e.g. Measuring the size of .rela.dyn
129 // for Android relocation packing requires knowing TLS symbol addresses
130 // during section finalization.)
131 if (!Out::tlsPhdr || !Out::tlsPhdr->firstSec)
132 fatal(toString(d.file) +
133 " has an STT_TLS symbol but doesn't have an SHF_TLS section");
134 return va - Out::tlsPhdr->firstSec->addr;
138 case Symbol::SharedKind:
139 case Symbol::UndefinedKind:
141 case Symbol::LazyArchiveKind:
142 case Symbol::LazyObjectKind:
143 assert(sym.isUsedInRegularObj && "lazy symbol reached writer");
145 case Symbol::CommonKind:
146 llvm_unreachable("common symbol reached writer");
147 case Symbol::PlaceholderKind:
148 llvm_unreachable("placeholder symbol reached writer");
150 llvm_unreachable("invalid symbol kind");
153 uint64_t Symbol::getVA(int64_t addend) const {
154 uint64_t outVA = getSymVA(*this, addend);
155 return outVA + addend;
158 uint64_t Symbol::getGotVA() const {
160 return in.igotPlt->getVA() + getGotPltOffset();
161 return in.got->getVA() + getGotOffset();
164 uint64_t Symbol::getGotOffset() const { return gotIndex * config->wordsize; }
166 uint64_t Symbol::getGotPltVA() const {
168 return in.igotPlt->getVA() + getGotPltOffset();
169 return in.gotPlt->getVA() + getGotPltOffset();
172 uint64_t Symbol::getGotPltOffset() const {
174 return pltIndex * config->wordsize;
175 return (pltIndex + target->gotPltHeaderEntriesNum) * config->wordsize;
178 uint64_t Symbol::getPltVA() const {
179 uint64_t outVA = isInIplt
180 ? in.iplt->getVA() + pltIndex * target->ipltEntrySize
181 : in.plt->getVA() + in.plt->headerSize +
182 pltIndex * target->pltEntrySize;
184 // While linking microMIPS code PLT code are always microMIPS
185 // code. Set the less-significant bit to track that fact.
186 // See detailed comment in the `getSymVA` function.
187 if (config->emachine == EM_MIPS && isMicroMips())
192 uint64_t Symbol::getSize() const {
193 if (const auto *dr = dyn_cast<Defined>(this))
195 return cast<SharedSymbol>(this)->size;
198 OutputSection *Symbol::getOutputSection() const {
199 if (auto *s = dyn_cast<Defined>(this)) {
200 if (auto *sec = s->section)
201 return sec->repl->getOutputSection();
207 // If a symbol name contains '@', the characters after that is
208 // a symbol version name. This function parses that.
209 void Symbol::parseSymbolVersion() {
210 StringRef s = getName();
211 size_t pos = s.find('@');
212 if (pos == 0 || pos == StringRef::npos)
214 StringRef verstr = s.substr(pos + 1);
218 // Truncate the symbol name so that it doesn't include the version string.
221 // If this is not in this DSO, it is not a definition.
225 // '@@' in a symbol name means the default version.
226 // It is usually the most recent one.
227 bool isDefault = (verstr[0] == '@');
229 verstr = verstr.substr(1);
231 for (const VersionDefinition &ver : namedVersionDefs()) {
232 if (ver.name != verstr)
238 versionId = ver.id | VERSYM_HIDDEN;
242 // It is an error if the specified version is not defined.
243 // Usually version script is not provided when linking executable,
244 // but we may still want to override a versioned symbol from DSO,
245 // so we do not report error in this case. We also do not error
246 // if the symbol has a local version as it won't be in the dynamic
248 if (config->shared && versionId != VER_NDX_LOCAL)
249 error(toString(file) + ": symbol " + s + " has undefined version " +
253 void Symbol::fetch() const {
254 if (auto *sym = dyn_cast<LazyArchive>(this)) {
255 cast<ArchiveFile>(sym->file)->fetch(sym->sym);
259 if (auto *sym = dyn_cast<LazyObject>(this)) {
260 dyn_cast<LazyObjFile>(sym->file)->fetch();
264 llvm_unreachable("Symbol::fetch() is called on a non-lazy symbol");
267 MemoryBufferRef LazyArchive::getMemberBuffer() {
269 CHECK(sym.getMember(),
270 "could not get the member for symbol " + toELFString(sym));
272 return CHECK(c.getMemoryBufferRef(),
273 "could not get the buffer for the member defining symbol " +
277 uint8_t Symbol::computeBinding() const {
278 if (config->relocatable)
280 if ((visibility != STV_DEFAULT && visibility != STV_PROTECTED) ||
281 (versionId == VER_NDX_LOCAL && isDefined()))
283 if (!config->gnuUnique && binding == STB_GNU_UNIQUE)
288 bool Symbol::includeInDynsym() const {
289 if (!config->hasDynSymTab)
291 if (computeBinding() == STB_LOCAL)
293 if (!isDefined() && !isCommon())
294 // This should unconditionally return true, unfortunately glibc -static-pie
295 // expects undefined weak symbols not to exist in .dynsym, e.g.
296 // __pthread_mutex_lock reference in _dl_add_to_namespace_list,
297 // __pthread_initialize_minimal reference in csu/libc-start.c.
298 return !(config->noDynamicLinker && isUndefWeak());
300 return exportDynamic || inDynamicList;
303 // Print out a log message for --trace-symbol.
304 void elf::printTraceSymbol(const Symbol *sym) {
306 if (sym->isUndefined())
307 s = ": reference to ";
308 else if (sym->isLazy())
309 s = ": lazy definition of ";
310 else if (sym->isShared())
311 s = ": shared definition of ";
312 else if (sym->isCommon())
313 s = ": common definition of ";
315 s = ": definition of ";
317 message(toString(sym->file) + s + sym->getName());
320 void elf::maybeWarnUnorderableSymbol(const Symbol *sym) {
321 if (!config->warnSymbolOrdering)
324 // If UnresolvedPolicy::Ignore is used, no "undefined symbol" error/warning
325 // is emitted. It makes sense to not warn on undefined symbols.
327 // Note, ld.bfd --symbol-ordering-file= does not warn on undefined symbols,
328 // but we don't have to be compatible here.
329 if (sym->isUndefined() &&
330 config->unresolvedSymbols == UnresolvedPolicy::Ignore)
333 const InputFile *file = sym->file;
334 auto *d = dyn_cast<Defined>(sym);
336 auto report = [&](StringRef s) { warn(toString(file) + s + sym->getName()); };
338 if (sym->isUndefined())
339 report(": unable to order undefined symbol: ");
340 else if (sym->isShared())
341 report(": unable to order shared symbol: ");
342 else if (d && !d->section)
343 report(": unable to order absolute symbol: ");
344 else if (d && isa<OutputSection>(d->section))
345 report(": unable to order synthetic symbol: ");
346 else if (d && !d->section->repl->isLive())
347 report(": unable to order discarded symbol: ");
350 // Returns true if a symbol can be replaced at load-time by a symbol
351 // with the same name defined in other ELF executable or DSO.
352 bool elf::computeIsPreemptible(const Symbol &sym) {
353 assert(!sym.isLocal());
355 // Only symbols with default visibility that appear in dynsym can be
356 // preempted. Symbols with protected visibility cannot be preempted.
357 if (!sym.includeInDynsym() || sym.visibility != STV_DEFAULT)
360 // At this point copy relocations have not been created yet, so any
361 // symbol that is not defined locally is preemptible.
362 if (!sym.isDefined())
368 // If -Bsymbolic or --dynamic-list is specified, or -Bsymbolic-functions is
369 // specified and the symbol is STT_FUNC, the symbol is preemptible iff it is
370 // in the dynamic list.
371 if (config->symbolic || (config->bsymbolicFunctions && sym.isFunc()))
372 return sym.inDynamicList;
376 void elf::reportBackrefs() {
377 for (auto &it : backwardReferences) {
378 const Symbol &sym = *it.first;
379 warn("backward reference detected: " + sym.getName() + " in " +
380 toString(it.second) + " refers to " + toString(sym.file));
384 static uint8_t getMinVisibility(uint8_t va, uint8_t vb) {
385 if (va == STV_DEFAULT)
387 if (vb == STV_DEFAULT)
389 return std::min(va, vb);
392 // Merge symbol properties.
394 // When we have many symbols of the same name, we choose one of them,
395 // and that's the result of symbol resolution. However, symbols that
396 // were not chosen still affect some symbol properties.
397 void Symbol::mergeProperties(const Symbol &other) {
398 if (other.exportDynamic)
399 exportDynamic = true;
400 if (other.isUsedInRegularObj)
401 isUsedInRegularObj = true;
403 // DSO symbols do not affect visibility in the output.
404 if (!other.isShared())
405 visibility = getMinVisibility(visibility, other.visibility);
408 void Symbol::resolve(const Symbol &other) {
409 mergeProperties(other);
411 if (isPlaceholder()) {
416 switch (other.kind()) {
417 case Symbol::UndefinedKind:
418 resolveUndefined(cast<Undefined>(other));
420 case Symbol::CommonKind:
421 resolveCommon(cast<CommonSymbol>(other));
423 case Symbol::DefinedKind:
424 resolveDefined(cast<Defined>(other));
426 case Symbol::LazyArchiveKind:
427 resolveLazy(cast<LazyArchive>(other));
429 case Symbol::LazyObjectKind:
430 resolveLazy(cast<LazyObject>(other));
432 case Symbol::SharedKind:
433 resolveShared(cast<SharedSymbol>(other));
435 case Symbol::PlaceholderKind:
436 llvm_unreachable("bad symbol kind");
440 void Symbol::resolveUndefined(const Undefined &other) {
441 // An undefined symbol with non default visibility must be satisfied
444 // If this is a non-weak defined symbol in a discarded section, override the
445 // existing undefined symbol for better error message later.
446 if ((isShared() && other.visibility != STV_DEFAULT) ||
447 (isUndefined() && other.binding != STB_WEAK && other.discardedSecIdx)) {
453 printTraceSymbol(&other);
456 // An undefined weak will not fetch archive members. See comment on Lazy in
457 // Symbols.h for the details.
458 if (other.binding == STB_WEAK) {
464 // Do extra check for --warn-backrefs.
466 // --warn-backrefs is an option to prevent an undefined reference from
467 // fetching an archive member written earlier in the command line. It can be
468 // used to keep compatibility with GNU linkers to some degree.
469 // I'll explain the feature and why you may find it useful in this comment.
471 // lld's symbol resolution semantics is more relaxed than traditional Unix
472 // linkers. For example,
474 // ld.lld foo.a bar.o
476 // succeeds even if bar.o contains an undefined symbol that has to be
477 // resolved by some object file in foo.a. Traditional Unix linkers don't
478 // allow this kind of backward reference, as they visit each file only once
479 // from left to right in the command line while resolving all undefined
480 // symbols at the moment of visiting.
482 // In the above case, since there's no undefined symbol when a linker visits
483 // foo.a, no files are pulled out from foo.a, and because the linker forgets
484 // about foo.a after visiting, it can't resolve undefined symbols in bar.o
485 // that could have been resolved otherwise.
487 // That lld accepts more relaxed form means that (besides it'd make more
488 // sense) you can accidentally write a command line or a build file that
489 // works only with lld, even if you have a plan to distribute it to wider
490 // users who may be using GNU linkers. With --warn-backrefs, you can detect
491 // a library order that doesn't work with other Unix linkers.
493 // The option is also useful to detect cyclic dependencies between static
494 // archives. Again, lld accepts
496 // ld.lld foo.a bar.a
498 // even if foo.a and bar.a depend on each other. With --warn-backrefs, it is
499 // handled as an error.
501 // Here is how the option works. We assign a group ID to each file. A file
502 // with a smaller group ID can pull out object files from an archive file
503 // with an equal or greater group ID. Otherwise, it is a reverse dependency
506 // A file outside --{start,end}-group gets a fresh ID when instantiated. All
507 // files within the same --{start,end}-group get the same group ID. E.g.
509 // ld.lld A B --start-group C D --end-group E
511 // A forms group 0. B form group 1. C and D (including their member object
512 // files) form group 2. E forms group 3. I think that you can see how this
513 // group assignment rule simulates the traditional linker's semantics.
514 bool backref = config->warnBackrefs && other.file &&
515 file->groupId < other.file->groupId;
517 // Some libraries have known problems and can cause noise. Filter them out
518 // with --warn-backrefs-exclude=.
520 !file->archiveName.empty() ? file->archiveName : file->getName();
521 for (const llvm::GlobPattern &pat : config->warnBackrefsExclude)
522 if (pat.match(name)) {
529 // We don't report backward references to weak symbols as they can be
532 // A traditional linker does not error for -ldef1 -lref -ldef2 (linking
533 // sandwich), where def2 may or may not be the same as def1. We don't want
534 // to warn for this case, so dismiss the warning if we see a subsequent lazy
536 if (backref && !isWeak())
537 backwardReferences.try_emplace(this, other.file);
541 // Undefined symbols in a SharedFile do not change the binding.
542 if (dyn_cast_or_null<SharedFile>(other.file))
545 if (isUndefined() || isShared()) {
546 // The binding will be weak if there is at least one reference and all are
547 // weak. The binding has one opportunity to change to weak: if the first
548 // reference is weak.
549 if (other.binding != STB_WEAK || !referenced)
550 binding = other.binding;
554 // Using .symver foo,foo@@VER unfortunately creates two symbols: foo and
555 // foo@@VER. We want to effectively ignore foo, so give precedence to
557 // FIXME: If users can transition to using
558 // .symver foo,foo@@@VER
559 // we can delete this hack.
560 static int compareVersion(StringRef a, StringRef b) {
561 bool x = a.contains("@@");
562 bool y = b.contains("@@");
570 // Compare two symbols. Return 1 if the new symbol should win, -1 if
571 // the new symbol should lose, or 0 if there is a conflict.
572 int Symbol::compare(const Symbol *other) const {
573 assert(other->isDefined() || other->isCommon());
575 if (!isDefined() && !isCommon())
578 if (int cmp = compareVersion(getName(), other->getName()))
587 if (isCommon() && other->isCommon()) {
588 if (config->warnCommon)
589 warn("multiple common of " + getName());
594 if (config->warnCommon)
595 warn("common " + getName() + " is overridden");
599 if (other->isCommon()) {
600 if (config->warnCommon)
601 warn("common " + getName() + " is overridden");
605 auto *oldSym = cast<Defined>(this);
606 auto *newSym = cast<Defined>(other);
608 if (dyn_cast_or_null<BitcodeFile>(other->file))
611 if (!oldSym->section && !newSym->section && oldSym->value == newSym->value &&
612 newSym->binding == STB_GLOBAL)
618 static void reportDuplicate(Symbol *sym, InputFile *newFile,
619 InputSectionBase *errSec, uint64_t errOffset) {
620 if (config->allowMultipleDefinition)
623 Defined *d = cast<Defined>(sym);
624 if (!d->section || !errSec) {
625 error("duplicate symbol: " + toString(*sym) + "\n>>> defined in " +
626 toString(sym->file) + "\n>>> defined in " + toString(newFile));
630 // Construct and print an error message in the form of:
632 // ld.lld: error: duplicate symbol: foo
633 // >>> defined at bar.c:30
634 // >>> bar.o (/home/alice/src/bar.o)
635 // >>> defined at baz.c:563
636 // >>> baz.o in archive libbaz.a
637 auto *sec1 = cast<InputSectionBase>(d->section);
638 std::string src1 = sec1->getSrcMsg(*sym, d->value);
639 std::string obj1 = sec1->getObjMsg(d->value);
640 std::string src2 = errSec->getSrcMsg(*sym, errOffset);
641 std::string obj2 = errSec->getObjMsg(errOffset);
643 std::string msg = "duplicate symbol: " + toString(*sym) + "\n>>> defined at ";
645 msg += src1 + "\n>>> ";
646 msg += obj1 + "\n>>> defined at ";
648 msg += src2 + "\n>>> ";
653 void Symbol::resolveCommon(const CommonSymbol &other) {
654 int cmp = compare(&other);
659 if (auto *s = dyn_cast<SharedSymbol>(this)) {
660 // Increase st_size if the shared symbol has a larger st_size. The shared
661 // symbol may be created from common symbols. The fact that some object
662 // files were linked into a shared object first should not change the
663 // regular rule that picks the largest st_size.
664 uint64_t size = s->size;
666 if (size > cast<CommonSymbol>(this)->size)
667 cast<CommonSymbol>(this)->size = size;
674 CommonSymbol *oldSym = cast<CommonSymbol>(this);
676 oldSym->alignment = std::max(oldSym->alignment, other.alignment);
677 if (oldSym->size < other.size) {
678 oldSym->file = other.file;
679 oldSym->size = other.size;
683 void Symbol::resolveDefined(const Defined &other) {
684 int cmp = compare(&other);
688 reportDuplicate(this, other.file,
689 dyn_cast_or_null<InputSectionBase>(other.section),
693 template <class LazyT> void Symbol::resolveLazy(const LazyT &other) {
694 if (!isUndefined()) {
695 // See the comment in resolveUndefined().
697 backwardReferences.erase(this);
701 // An undefined weak will not fetch archive members. See comment on Lazy in
702 // Symbols.h for the details.
714 void Symbol::resolveShared(const SharedSymbol &other) {
716 // See the comment in resolveCommon() above.
717 if (other.size > cast<CommonSymbol>(this)->size)
718 cast<CommonSymbol>(this)->size = other.size;
721 if (visibility == STV_DEFAULT && (isUndefined() || isLazy())) {
722 // An undefined symbol with non default visibility must be satisfied
724 uint8_t bind = binding;
728 printTraceSymbol(&other);