xref: /freebsd/contrib/llvm-project/lld/ELF/Symbols.cpp (revision 85868e8a1daeaae7a0e48effb2ea2310ae3b02c6)
10b57cec5SDimitry Andric //===- Symbols.cpp --------------------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #include "Symbols.h"
100b57cec5SDimitry Andric #include "InputFiles.h"
110b57cec5SDimitry Andric #include "InputSection.h"
120b57cec5SDimitry Andric #include "OutputSections.h"
130b57cec5SDimitry Andric #include "SyntheticSections.h"
140b57cec5SDimitry Andric #include "Target.h"
150b57cec5SDimitry Andric #include "Writer.h"
160b57cec5SDimitry Andric #include "lld/Common/ErrorHandler.h"
170b57cec5SDimitry Andric #include "lld/Common/Strings.h"
180b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
190b57cec5SDimitry Andric #include "llvm/Support/Path.h"
200b57cec5SDimitry Andric #include <cstring>
210b57cec5SDimitry Andric 
220b57cec5SDimitry Andric using namespace llvm;
230b57cec5SDimitry Andric using namespace llvm::object;
240b57cec5SDimitry Andric using namespace llvm::ELF;
250b57cec5SDimitry Andric 
26*85868e8aSDimitry Andric namespace lld {
27*85868e8aSDimitry Andric // Returns a symbol for an error message.
28*85868e8aSDimitry Andric static std::string demangle(StringRef symName) {
29*85868e8aSDimitry Andric   if (elf::config->demangle)
30*85868e8aSDimitry Andric     return demangleItanium(symName);
31*85868e8aSDimitry Andric   return symName;
32*85868e8aSDimitry Andric }
330b57cec5SDimitry Andric 
34*85868e8aSDimitry Andric std::string toString(const elf::Symbol &b) { return demangle(b.getName()); }
35*85868e8aSDimitry Andric std::string toELFString(const Archive::Symbol &b) {
36*85868e8aSDimitry Andric   return demangle(b.getName());
37*85868e8aSDimitry Andric }
38*85868e8aSDimitry Andric 
39*85868e8aSDimitry Andric namespace elf {
400b57cec5SDimitry Andric Defined *ElfSym::bss;
410b57cec5SDimitry Andric Defined *ElfSym::etext1;
420b57cec5SDimitry Andric Defined *ElfSym::etext2;
430b57cec5SDimitry Andric Defined *ElfSym::edata1;
440b57cec5SDimitry Andric Defined *ElfSym::edata2;
450b57cec5SDimitry Andric Defined *ElfSym::end1;
460b57cec5SDimitry Andric Defined *ElfSym::end2;
470b57cec5SDimitry Andric Defined *ElfSym::globalOffsetTable;
480b57cec5SDimitry Andric Defined *ElfSym::mipsGp;
490b57cec5SDimitry Andric Defined *ElfSym::mipsGpDisp;
500b57cec5SDimitry Andric Defined *ElfSym::mipsLocalGp;
510b57cec5SDimitry Andric Defined *ElfSym::relaIpltStart;
520b57cec5SDimitry Andric Defined *ElfSym::relaIpltEnd;
530b57cec5SDimitry Andric Defined *ElfSym::riscvGlobalPointer;
540b57cec5SDimitry Andric Defined *ElfSym::tlsModuleBase;
550b57cec5SDimitry Andric 
560b57cec5SDimitry Andric static uint64_t getSymVA(const Symbol &sym, int64_t &addend) {
570b57cec5SDimitry Andric   switch (sym.kind()) {
580b57cec5SDimitry Andric   case Symbol::DefinedKind: {
590b57cec5SDimitry Andric     auto &d = cast<Defined>(sym);
600b57cec5SDimitry Andric     SectionBase *isec = d.section;
610b57cec5SDimitry Andric 
620b57cec5SDimitry Andric     // This is an absolute symbol.
630b57cec5SDimitry Andric     if (!isec)
640b57cec5SDimitry Andric       return d.value;
650b57cec5SDimitry Andric 
660b57cec5SDimitry Andric     assert(isec != &InputSection::discarded);
670b57cec5SDimitry Andric     isec = isec->repl;
680b57cec5SDimitry Andric 
690b57cec5SDimitry Andric     uint64_t offset = d.value;
700b57cec5SDimitry Andric 
710b57cec5SDimitry Andric     // An object in an SHF_MERGE section might be referenced via a
720b57cec5SDimitry Andric     // section symbol (as a hack for reducing the number of local
730b57cec5SDimitry Andric     // symbols).
740b57cec5SDimitry Andric     // Depending on the addend, the reference via a section symbol
750b57cec5SDimitry Andric     // refers to a different object in the merge section.
760b57cec5SDimitry Andric     // Since the objects in the merge section are not necessarily
770b57cec5SDimitry Andric     // contiguous in the output, the addend can thus affect the final
780b57cec5SDimitry Andric     // VA in a non-linear way.
790b57cec5SDimitry Andric     // To make this work, we incorporate the addend into the section
800b57cec5SDimitry Andric     // offset (and zero out the addend for later processing) so that
810b57cec5SDimitry Andric     // we find the right object in the section.
820b57cec5SDimitry Andric     if (d.isSection()) {
830b57cec5SDimitry Andric       offset += addend;
840b57cec5SDimitry Andric       addend = 0;
850b57cec5SDimitry Andric     }
860b57cec5SDimitry Andric 
870b57cec5SDimitry Andric     // In the typical case, this is actually very simple and boils
880b57cec5SDimitry Andric     // down to adding together 3 numbers:
890b57cec5SDimitry Andric     // 1. The address of the output section.
900b57cec5SDimitry Andric     // 2. The offset of the input section within the output section.
910b57cec5SDimitry Andric     // 3. The offset within the input section (this addition happens
920b57cec5SDimitry Andric     //    inside InputSection::getOffset).
930b57cec5SDimitry Andric     //
940b57cec5SDimitry Andric     // If you understand the data structures involved with this next
950b57cec5SDimitry Andric     // line (and how they get built), then you have a pretty good
960b57cec5SDimitry Andric     // understanding of the linker.
970b57cec5SDimitry Andric     uint64_t va = isec->getVA(offset);
980b57cec5SDimitry Andric 
990b57cec5SDimitry Andric     // MIPS relocatable files can mix regular and microMIPS code.
1000b57cec5SDimitry Andric     // Linker needs to distinguish such code. To do so microMIPS
1010b57cec5SDimitry Andric     // symbols has the `STO_MIPS_MICROMIPS` flag in the `st_other`
1020b57cec5SDimitry Andric     // field. Unfortunately, the `MIPS::relocateOne()` method has
1030b57cec5SDimitry Andric     // a symbol value only. To pass type of the symbol (regular/microMIPS)
1040b57cec5SDimitry Andric     // to that routine as well as other places where we write
1050b57cec5SDimitry Andric     // a symbol value as-is (.dynamic section, `Elf_Ehdr::e_entry`
1060b57cec5SDimitry Andric     // field etc) do the same trick as compiler uses to mark microMIPS
1070b57cec5SDimitry Andric     // for CPU - set the less-significant bit.
1080b57cec5SDimitry Andric     if (config->emachine == EM_MIPS && isMicroMips() &&
1090b57cec5SDimitry Andric         ((sym.stOther & STO_MIPS_MICROMIPS) || sym.needsPltAddr))
1100b57cec5SDimitry Andric       va |= 1;
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric     if (d.isTls() && !config->relocatable) {
1130b57cec5SDimitry Andric       // Use the address of the TLS segment's first section rather than the
1140b57cec5SDimitry Andric       // segment's address, because segment addresses aren't initialized until
1150b57cec5SDimitry Andric       // after sections are finalized. (e.g. Measuring the size of .rela.dyn
1160b57cec5SDimitry Andric       // for Android relocation packing requires knowing TLS symbol addresses
1170b57cec5SDimitry Andric       // during section finalization.)
1180b57cec5SDimitry Andric       if (!Out::tlsPhdr || !Out::tlsPhdr->firstSec)
1190b57cec5SDimitry Andric         fatal(toString(d.file) +
1200b57cec5SDimitry Andric               " has an STT_TLS symbol but doesn't have an SHF_TLS section");
1210b57cec5SDimitry Andric       return va - Out::tlsPhdr->firstSec->addr;
1220b57cec5SDimitry Andric     }
1230b57cec5SDimitry Andric     return va;
1240b57cec5SDimitry Andric   }
1250b57cec5SDimitry Andric   case Symbol::SharedKind:
1260b57cec5SDimitry Andric   case Symbol::UndefinedKind:
1270b57cec5SDimitry Andric     return 0;
1280b57cec5SDimitry Andric   case Symbol::LazyArchiveKind:
1290b57cec5SDimitry Andric   case Symbol::LazyObjectKind:
1300b57cec5SDimitry Andric     assert(sym.isUsedInRegularObj && "lazy symbol reached writer");
1310b57cec5SDimitry Andric     return 0;
1320b57cec5SDimitry Andric   case Symbol::CommonKind:
1330b57cec5SDimitry Andric     llvm_unreachable("common symbol reached writer");
1340b57cec5SDimitry Andric   case Symbol::PlaceholderKind:
1350b57cec5SDimitry Andric     llvm_unreachable("placeholder symbol reached writer");
1360b57cec5SDimitry Andric   }
1370b57cec5SDimitry Andric   llvm_unreachable("invalid symbol kind");
1380b57cec5SDimitry Andric }
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric uint64_t Symbol::getVA(int64_t addend) const {
1410b57cec5SDimitry Andric   uint64_t outVA = getSymVA(*this, addend);
1420b57cec5SDimitry Andric   return outVA + addend;
1430b57cec5SDimitry Andric }
1440b57cec5SDimitry Andric 
1450b57cec5SDimitry Andric uint64_t Symbol::getGotVA() const {
1460b57cec5SDimitry Andric   if (gotInIgot)
1470b57cec5SDimitry Andric     return in.igotPlt->getVA() + getGotPltOffset();
1480b57cec5SDimitry Andric   return in.got->getVA() + getGotOffset();
1490b57cec5SDimitry Andric }
1500b57cec5SDimitry Andric 
1510b57cec5SDimitry Andric uint64_t Symbol::getGotOffset() const { return gotIndex * config->wordsize; }
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric uint64_t Symbol::getGotPltVA() const {
1540b57cec5SDimitry Andric   if (isInIplt)
1550b57cec5SDimitry Andric     return in.igotPlt->getVA() + getGotPltOffset();
1560b57cec5SDimitry Andric   return in.gotPlt->getVA() + getGotPltOffset();
1570b57cec5SDimitry Andric }
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric uint64_t Symbol::getGotPltOffset() const {
1600b57cec5SDimitry Andric   if (isInIplt)
1610b57cec5SDimitry Andric     return pltIndex * config->wordsize;
1620b57cec5SDimitry Andric   return (pltIndex + target->gotPltHeaderEntriesNum) * config->wordsize;
1630b57cec5SDimitry Andric }
1640b57cec5SDimitry Andric 
1650b57cec5SDimitry Andric uint64_t Symbol::getPPC64LongBranchOffset() const {
1660b57cec5SDimitry Andric   assert(ppc64BranchltIndex != 0xffff);
1670b57cec5SDimitry Andric   return ppc64BranchltIndex * config->wordsize;
1680b57cec5SDimitry Andric }
1690b57cec5SDimitry Andric 
1700b57cec5SDimitry Andric uint64_t Symbol::getPltVA() const {
1710b57cec5SDimitry Andric   PltSection *plt = isInIplt ? in.iplt : in.plt;
1720b57cec5SDimitry Andric   uint64_t outVA =
1730b57cec5SDimitry Andric       plt->getVA() + plt->headerSize + pltIndex * target->pltEntrySize;
1740b57cec5SDimitry Andric   // While linking microMIPS code PLT code are always microMIPS
1750b57cec5SDimitry Andric   // code. Set the less-significant bit to track that fact.
1760b57cec5SDimitry Andric   // See detailed comment in the `getSymVA` function.
1770b57cec5SDimitry Andric   if (config->emachine == EM_MIPS && isMicroMips())
1780b57cec5SDimitry Andric     outVA |= 1;
1790b57cec5SDimitry Andric   return outVA;
1800b57cec5SDimitry Andric }
1810b57cec5SDimitry Andric 
1820b57cec5SDimitry Andric uint64_t Symbol::getPPC64LongBranchTableVA() const {
1830b57cec5SDimitry Andric   assert(ppc64BranchltIndex != 0xffff);
1840b57cec5SDimitry Andric   return in.ppc64LongBranchTarget->getVA() +
1850b57cec5SDimitry Andric          ppc64BranchltIndex * config->wordsize;
1860b57cec5SDimitry Andric }
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric uint64_t Symbol::getSize() const {
1890b57cec5SDimitry Andric   if (const auto *dr = dyn_cast<Defined>(this))
1900b57cec5SDimitry Andric     return dr->size;
1910b57cec5SDimitry Andric   return cast<SharedSymbol>(this)->size;
1920b57cec5SDimitry Andric }
1930b57cec5SDimitry Andric 
1940b57cec5SDimitry Andric OutputSection *Symbol::getOutputSection() const {
1950b57cec5SDimitry Andric   if (auto *s = dyn_cast<Defined>(this)) {
1960b57cec5SDimitry Andric     if (auto *sec = s->section)
1970b57cec5SDimitry Andric       return sec->repl->getOutputSection();
1980b57cec5SDimitry Andric     return nullptr;
1990b57cec5SDimitry Andric   }
2000b57cec5SDimitry Andric   return nullptr;
2010b57cec5SDimitry Andric }
2020b57cec5SDimitry Andric 
2030b57cec5SDimitry Andric // If a symbol name contains '@', the characters after that is
2040b57cec5SDimitry Andric // a symbol version name. This function parses that.
2050b57cec5SDimitry Andric void Symbol::parseSymbolVersion() {
2060b57cec5SDimitry Andric   StringRef s = getName();
2070b57cec5SDimitry Andric   size_t pos = s.find('@');
2080b57cec5SDimitry Andric   if (pos == 0 || pos == StringRef::npos)
2090b57cec5SDimitry Andric     return;
2100b57cec5SDimitry Andric   StringRef verstr = s.substr(pos + 1);
2110b57cec5SDimitry Andric   if (verstr.empty())
2120b57cec5SDimitry Andric     return;
2130b57cec5SDimitry Andric 
2140b57cec5SDimitry Andric   // Truncate the symbol name so that it doesn't include the version string.
2150b57cec5SDimitry Andric   nameSize = pos;
2160b57cec5SDimitry Andric 
2170b57cec5SDimitry Andric   // If this is not in this DSO, it is not a definition.
2180b57cec5SDimitry Andric   if (!isDefined())
2190b57cec5SDimitry Andric     return;
2200b57cec5SDimitry Andric 
2210b57cec5SDimitry Andric   // '@@' in a symbol name means the default version.
2220b57cec5SDimitry Andric   // It is usually the most recent one.
2230b57cec5SDimitry Andric   bool isDefault = (verstr[0] == '@');
2240b57cec5SDimitry Andric   if (isDefault)
2250b57cec5SDimitry Andric     verstr = verstr.substr(1);
2260b57cec5SDimitry Andric 
227*85868e8aSDimitry Andric   for (const VersionDefinition &ver : namedVersionDefs()) {
2280b57cec5SDimitry Andric     if (ver.name != verstr)
2290b57cec5SDimitry Andric       continue;
2300b57cec5SDimitry Andric 
2310b57cec5SDimitry Andric     if (isDefault)
2320b57cec5SDimitry Andric       versionId = ver.id;
2330b57cec5SDimitry Andric     else
2340b57cec5SDimitry Andric       versionId = ver.id | VERSYM_HIDDEN;
2350b57cec5SDimitry Andric     return;
2360b57cec5SDimitry Andric   }
2370b57cec5SDimitry Andric 
2380b57cec5SDimitry Andric   // It is an error if the specified version is not defined.
2390b57cec5SDimitry Andric   // Usually version script is not provided when linking executable,
2400b57cec5SDimitry Andric   // but we may still want to override a versioned symbol from DSO,
2410b57cec5SDimitry Andric   // so we do not report error in this case. We also do not error
2420b57cec5SDimitry Andric   // if the symbol has a local version as it won't be in the dynamic
2430b57cec5SDimitry Andric   // symbol table.
2440b57cec5SDimitry Andric   if (config->shared && versionId != VER_NDX_LOCAL)
2450b57cec5SDimitry Andric     error(toString(file) + ": symbol " + s + " has undefined version " +
2460b57cec5SDimitry Andric           verstr);
2470b57cec5SDimitry Andric }
2480b57cec5SDimitry Andric 
2490b57cec5SDimitry Andric void Symbol::fetch() const {
2500b57cec5SDimitry Andric   if (auto *sym = dyn_cast<LazyArchive>(this)) {
2510b57cec5SDimitry Andric     cast<ArchiveFile>(sym->file)->fetch(sym->sym);
2520b57cec5SDimitry Andric     return;
2530b57cec5SDimitry Andric   }
2540b57cec5SDimitry Andric 
2550b57cec5SDimitry Andric   if (auto *sym = dyn_cast<LazyObject>(this)) {
2560b57cec5SDimitry Andric     dyn_cast<LazyObjFile>(sym->file)->fetch();
2570b57cec5SDimitry Andric     return;
2580b57cec5SDimitry Andric   }
2590b57cec5SDimitry Andric 
2600b57cec5SDimitry Andric   llvm_unreachable("Symbol::fetch() is called on a non-lazy symbol");
2610b57cec5SDimitry Andric }
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric MemoryBufferRef LazyArchive::getMemberBuffer() {
2640b57cec5SDimitry Andric   Archive::Child c =
2650b57cec5SDimitry Andric       CHECK(sym.getMember(),
2660b57cec5SDimitry Andric             "could not get the member for symbol " + toELFString(sym));
2670b57cec5SDimitry Andric 
2680b57cec5SDimitry Andric   return CHECK(c.getMemoryBufferRef(),
2690b57cec5SDimitry Andric                "could not get the buffer for the member defining symbol " +
2700b57cec5SDimitry Andric                    toELFString(sym));
2710b57cec5SDimitry Andric }
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric uint8_t Symbol::computeBinding() const {
2740b57cec5SDimitry Andric   if (config->relocatable)
2750b57cec5SDimitry Andric     return binding;
276*85868e8aSDimitry Andric   if ((visibility != STV_DEFAULT && visibility != STV_PROTECTED) ||
277*85868e8aSDimitry Andric       versionId == VER_NDX_LOCAL)
2780b57cec5SDimitry Andric     return STB_LOCAL;
2790b57cec5SDimitry Andric   if (!config->gnuUnique && binding == STB_GNU_UNIQUE)
2800b57cec5SDimitry Andric     return STB_GLOBAL;
2810b57cec5SDimitry Andric   return binding;
2820b57cec5SDimitry Andric }
2830b57cec5SDimitry Andric 
2840b57cec5SDimitry Andric bool Symbol::includeInDynsym() const {
2850b57cec5SDimitry Andric   if (!config->hasDynSymTab)
2860b57cec5SDimitry Andric     return false;
2870b57cec5SDimitry Andric   if (computeBinding() == STB_LOCAL)
2880b57cec5SDimitry Andric     return false;
2890b57cec5SDimitry Andric 
2900b57cec5SDimitry Andric   // If a PIE binary was not linked against any shared libraries, then we can
2910b57cec5SDimitry Andric   // safely drop weak undef symbols from .dynsym.
2920b57cec5SDimitry Andric   if (isUndefWeak() && config->pie && sharedFiles.empty())
2930b57cec5SDimitry Andric     return false;
2940b57cec5SDimitry Andric 
295*85868e8aSDimitry Andric   return isUndefined() || isShared() || exportDynamic || inDynamicList;
2960b57cec5SDimitry Andric }
2970b57cec5SDimitry Andric 
2980b57cec5SDimitry Andric // Print out a log message for --trace-symbol.
299*85868e8aSDimitry Andric void printTraceSymbol(const Symbol *sym) {
3000b57cec5SDimitry Andric   std::string s;
3010b57cec5SDimitry Andric   if (sym->isUndefined())
3020b57cec5SDimitry Andric     s = ": reference to ";
3030b57cec5SDimitry Andric   else if (sym->isLazy())
3040b57cec5SDimitry Andric     s = ": lazy definition of ";
3050b57cec5SDimitry Andric   else if (sym->isShared())
3060b57cec5SDimitry Andric     s = ": shared definition of ";
3070b57cec5SDimitry Andric   else if (sym->isCommon())
3080b57cec5SDimitry Andric     s = ": common definition of ";
3090b57cec5SDimitry Andric   else
3100b57cec5SDimitry Andric     s = ": definition of ";
3110b57cec5SDimitry Andric 
3120b57cec5SDimitry Andric   message(toString(sym->file) + s + sym->getName());
3130b57cec5SDimitry Andric }
3140b57cec5SDimitry Andric 
315*85868e8aSDimitry Andric void maybeWarnUnorderableSymbol(const Symbol *sym) {
3160b57cec5SDimitry Andric   if (!config->warnSymbolOrdering)
3170b57cec5SDimitry Andric     return;
3180b57cec5SDimitry Andric 
3190b57cec5SDimitry Andric   // If UnresolvedPolicy::Ignore is used, no "undefined symbol" error/warning
3200b57cec5SDimitry Andric   // is emitted. It makes sense to not warn on undefined symbols.
3210b57cec5SDimitry Andric   //
3220b57cec5SDimitry Andric   // Note, ld.bfd --symbol-ordering-file= does not warn on undefined symbols,
3230b57cec5SDimitry Andric   // but we don't have to be compatible here.
3240b57cec5SDimitry Andric   if (sym->isUndefined() &&
3250b57cec5SDimitry Andric       config->unresolvedSymbols == UnresolvedPolicy::Ignore)
3260b57cec5SDimitry Andric     return;
3270b57cec5SDimitry Andric 
3280b57cec5SDimitry Andric   const InputFile *file = sym->file;
3290b57cec5SDimitry Andric   auto *d = dyn_cast<Defined>(sym);
3300b57cec5SDimitry Andric 
3310b57cec5SDimitry Andric   auto report = [&](StringRef s) { warn(toString(file) + s + sym->getName()); };
3320b57cec5SDimitry Andric 
3330b57cec5SDimitry Andric   if (sym->isUndefined())
3340b57cec5SDimitry Andric     report(": unable to order undefined symbol: ");
3350b57cec5SDimitry Andric   else if (sym->isShared())
3360b57cec5SDimitry Andric     report(": unable to order shared symbol: ");
3370b57cec5SDimitry Andric   else if (d && !d->section)
3380b57cec5SDimitry Andric     report(": unable to order absolute symbol: ");
3390b57cec5SDimitry Andric   else if (d && isa<OutputSection>(d->section))
3400b57cec5SDimitry Andric     report(": unable to order synthetic symbol: ");
3410b57cec5SDimitry Andric   else if (d && !d->section->repl->isLive())
3420b57cec5SDimitry Andric     report(": unable to order discarded symbol: ");
3430b57cec5SDimitry Andric }
3440b57cec5SDimitry Andric 
3450b57cec5SDimitry Andric static uint8_t getMinVisibility(uint8_t va, uint8_t vb) {
3460b57cec5SDimitry Andric   if (va == STV_DEFAULT)
3470b57cec5SDimitry Andric     return vb;
3480b57cec5SDimitry Andric   if (vb == STV_DEFAULT)
3490b57cec5SDimitry Andric     return va;
3500b57cec5SDimitry Andric   return std::min(va, vb);
3510b57cec5SDimitry Andric }
3520b57cec5SDimitry Andric 
3530b57cec5SDimitry Andric // Merge symbol properties.
3540b57cec5SDimitry Andric //
3550b57cec5SDimitry Andric // When we have many symbols of the same name, we choose one of them,
3560b57cec5SDimitry Andric // and that's the result of symbol resolution. However, symbols that
3570b57cec5SDimitry Andric // were not chosen still affect some symbol properties.
3580b57cec5SDimitry Andric void Symbol::mergeProperties(const Symbol &other) {
3590b57cec5SDimitry Andric   if (other.exportDynamic)
3600b57cec5SDimitry Andric     exportDynamic = true;
3610b57cec5SDimitry Andric   if (other.isUsedInRegularObj)
3620b57cec5SDimitry Andric     isUsedInRegularObj = true;
3630b57cec5SDimitry Andric 
3640b57cec5SDimitry Andric   // DSO symbols do not affect visibility in the output.
3650b57cec5SDimitry Andric   if (!other.isShared())
3660b57cec5SDimitry Andric     visibility = getMinVisibility(visibility, other.visibility);
3670b57cec5SDimitry Andric }
3680b57cec5SDimitry Andric 
3690b57cec5SDimitry Andric void Symbol::resolve(const Symbol &other) {
3700b57cec5SDimitry Andric   mergeProperties(other);
3710b57cec5SDimitry Andric 
3720b57cec5SDimitry Andric   if (isPlaceholder()) {
3730b57cec5SDimitry Andric     replace(other);
3740b57cec5SDimitry Andric     return;
3750b57cec5SDimitry Andric   }
3760b57cec5SDimitry Andric 
3770b57cec5SDimitry Andric   switch (other.kind()) {
3780b57cec5SDimitry Andric   case Symbol::UndefinedKind:
3790b57cec5SDimitry Andric     resolveUndefined(cast<Undefined>(other));
3800b57cec5SDimitry Andric     break;
3810b57cec5SDimitry Andric   case Symbol::CommonKind:
3820b57cec5SDimitry Andric     resolveCommon(cast<CommonSymbol>(other));
3830b57cec5SDimitry Andric     break;
3840b57cec5SDimitry Andric   case Symbol::DefinedKind:
3850b57cec5SDimitry Andric     resolveDefined(cast<Defined>(other));
3860b57cec5SDimitry Andric     break;
3870b57cec5SDimitry Andric   case Symbol::LazyArchiveKind:
3880b57cec5SDimitry Andric     resolveLazy(cast<LazyArchive>(other));
3890b57cec5SDimitry Andric     break;
3900b57cec5SDimitry Andric   case Symbol::LazyObjectKind:
3910b57cec5SDimitry Andric     resolveLazy(cast<LazyObject>(other));
3920b57cec5SDimitry Andric     break;
3930b57cec5SDimitry Andric   case Symbol::SharedKind:
3940b57cec5SDimitry Andric     resolveShared(cast<SharedSymbol>(other));
3950b57cec5SDimitry Andric     break;
3960b57cec5SDimitry Andric   case Symbol::PlaceholderKind:
3970b57cec5SDimitry Andric     llvm_unreachable("bad symbol kind");
3980b57cec5SDimitry Andric   }
3990b57cec5SDimitry Andric }
4000b57cec5SDimitry Andric 
4010b57cec5SDimitry Andric void Symbol::resolveUndefined(const Undefined &other) {
4020b57cec5SDimitry Andric   // An undefined symbol with non default visibility must be satisfied
4030b57cec5SDimitry Andric   // in the same DSO.
4040b57cec5SDimitry Andric   //
4050b57cec5SDimitry Andric   // If this is a non-weak defined symbol in a discarded section, override the
4060b57cec5SDimitry Andric   // existing undefined symbol for better error message later.
4070b57cec5SDimitry Andric   if ((isShared() && other.visibility != STV_DEFAULT) ||
4080b57cec5SDimitry Andric       (isUndefined() && other.binding != STB_WEAK && other.discardedSecIdx)) {
4090b57cec5SDimitry Andric     replace(other);
4100b57cec5SDimitry Andric     return;
4110b57cec5SDimitry Andric   }
4120b57cec5SDimitry Andric 
4130b57cec5SDimitry Andric   if (traced)
4140b57cec5SDimitry Andric     printTraceSymbol(&other);
4150b57cec5SDimitry Andric 
4160b57cec5SDimitry Andric   if (isLazy()) {
4170b57cec5SDimitry Andric     // An undefined weak will not fetch archive members. See comment on Lazy in
4180b57cec5SDimitry Andric     // Symbols.h for the details.
4190b57cec5SDimitry Andric     if (other.binding == STB_WEAK) {
4200b57cec5SDimitry Andric       binding = STB_WEAK;
4210b57cec5SDimitry Andric       type = other.type;
4220b57cec5SDimitry Andric       return;
4230b57cec5SDimitry Andric     }
4240b57cec5SDimitry Andric 
4250b57cec5SDimitry Andric     // Do extra check for --warn-backrefs.
4260b57cec5SDimitry Andric     //
4270b57cec5SDimitry Andric     // --warn-backrefs is an option to prevent an undefined reference from
4280b57cec5SDimitry Andric     // fetching an archive member written earlier in the command line. It can be
4290b57cec5SDimitry Andric     // used to keep compatibility with GNU linkers to some degree.
4300b57cec5SDimitry Andric     // I'll explain the feature and why you may find it useful in this comment.
4310b57cec5SDimitry Andric     //
4320b57cec5SDimitry Andric     // lld's symbol resolution semantics is more relaxed than traditional Unix
4330b57cec5SDimitry Andric     // linkers. For example,
4340b57cec5SDimitry Andric     //
4350b57cec5SDimitry Andric     //   ld.lld foo.a bar.o
4360b57cec5SDimitry Andric     //
4370b57cec5SDimitry Andric     // succeeds even if bar.o contains an undefined symbol that has to be
4380b57cec5SDimitry Andric     // resolved by some object file in foo.a. Traditional Unix linkers don't
4390b57cec5SDimitry Andric     // allow this kind of backward reference, as they visit each file only once
4400b57cec5SDimitry Andric     // from left to right in the command line while resolving all undefined
4410b57cec5SDimitry Andric     // symbols at the moment of visiting.
4420b57cec5SDimitry Andric     //
4430b57cec5SDimitry Andric     // In the above case, since there's no undefined symbol when a linker visits
4440b57cec5SDimitry Andric     // foo.a, no files are pulled out from foo.a, and because the linker forgets
4450b57cec5SDimitry Andric     // about foo.a after visiting, it can't resolve undefined symbols in bar.o
4460b57cec5SDimitry Andric     // that could have been resolved otherwise.
4470b57cec5SDimitry Andric     //
4480b57cec5SDimitry Andric     // That lld accepts more relaxed form means that (besides it'd make more
4490b57cec5SDimitry Andric     // sense) you can accidentally write a command line or a build file that
4500b57cec5SDimitry Andric     // works only with lld, even if you have a plan to distribute it to wider
4510b57cec5SDimitry Andric     // users who may be using GNU linkers. With --warn-backrefs, you can detect
4520b57cec5SDimitry Andric     // a library order that doesn't work with other Unix linkers.
4530b57cec5SDimitry Andric     //
4540b57cec5SDimitry Andric     // The option is also useful to detect cyclic dependencies between static
4550b57cec5SDimitry Andric     // archives. Again, lld accepts
4560b57cec5SDimitry Andric     //
4570b57cec5SDimitry Andric     //   ld.lld foo.a bar.a
4580b57cec5SDimitry Andric     //
4590b57cec5SDimitry Andric     // even if foo.a and bar.a depend on each other. With --warn-backrefs, it is
4600b57cec5SDimitry Andric     // handled as an error.
4610b57cec5SDimitry Andric     //
4620b57cec5SDimitry Andric     // Here is how the option works. We assign a group ID to each file. A file
4630b57cec5SDimitry Andric     // with a smaller group ID can pull out object files from an archive file
4640b57cec5SDimitry Andric     // with an equal or greater group ID. Otherwise, it is a reverse dependency
4650b57cec5SDimitry Andric     // and an error.
4660b57cec5SDimitry Andric     //
4670b57cec5SDimitry Andric     // A file outside --{start,end}-group gets a fresh ID when instantiated. All
4680b57cec5SDimitry Andric     // files within the same --{start,end}-group get the same group ID. E.g.
4690b57cec5SDimitry Andric     //
4700b57cec5SDimitry Andric     //   ld.lld A B --start-group C D --end-group E
4710b57cec5SDimitry Andric     //
4720b57cec5SDimitry Andric     // A forms group 0. B form group 1. C and D (including their member object
4730b57cec5SDimitry Andric     // files) form group 2. E forms group 3. I think that you can see how this
4740b57cec5SDimitry Andric     // group assignment rule simulates the traditional linker's semantics.
4750b57cec5SDimitry Andric     bool backref = config->warnBackrefs && other.file &&
4760b57cec5SDimitry Andric                    file->groupId < other.file->groupId;
4770b57cec5SDimitry Andric     fetch();
4780b57cec5SDimitry Andric 
4790b57cec5SDimitry Andric     // We don't report backward references to weak symbols as they can be
4800b57cec5SDimitry Andric     // overridden later.
4810b57cec5SDimitry Andric     if (backref && !isWeak())
4820b57cec5SDimitry Andric       warn("backward reference detected: " + other.getName() + " in " +
4830b57cec5SDimitry Andric            toString(other.file) + " refers to " + toString(file));
4840b57cec5SDimitry Andric     return;
4850b57cec5SDimitry Andric   }
4860b57cec5SDimitry Andric 
4870b57cec5SDimitry Andric   // Undefined symbols in a SharedFile do not change the binding.
4880b57cec5SDimitry Andric   if (dyn_cast_or_null<SharedFile>(other.file))
4890b57cec5SDimitry Andric     return;
4900b57cec5SDimitry Andric 
491*85868e8aSDimitry Andric   if (isUndefined() || isShared()) {
492*85868e8aSDimitry Andric     // The binding will be weak if there is at least one reference and all are
493*85868e8aSDimitry Andric     // weak. The binding has one opportunity to change to weak: if the first
494*85868e8aSDimitry Andric     // reference is weak.
495*85868e8aSDimitry Andric     if (other.binding != STB_WEAK || !referenced)
4960b57cec5SDimitry Andric       binding = other.binding;
497*85868e8aSDimitry Andric     referenced = true;
4980b57cec5SDimitry Andric   }
4990b57cec5SDimitry Andric }
5000b57cec5SDimitry Andric 
5010b57cec5SDimitry Andric // Using .symver foo,foo@@VER unfortunately creates two symbols: foo and
5020b57cec5SDimitry Andric // foo@@VER. We want to effectively ignore foo, so give precedence to
5030b57cec5SDimitry Andric // foo@@VER.
5040b57cec5SDimitry Andric // FIXME: If users can transition to using
5050b57cec5SDimitry Andric // .symver foo,foo@@@VER
5060b57cec5SDimitry Andric // we can delete this hack.
5070b57cec5SDimitry Andric static int compareVersion(StringRef a, StringRef b) {
5080b57cec5SDimitry Andric   bool x = a.contains("@@");
5090b57cec5SDimitry Andric   bool y = b.contains("@@");
5100b57cec5SDimitry Andric   if (!x && y)
5110b57cec5SDimitry Andric     return 1;
5120b57cec5SDimitry Andric   if (x && !y)
5130b57cec5SDimitry Andric     return -1;
5140b57cec5SDimitry Andric   return 0;
5150b57cec5SDimitry Andric }
5160b57cec5SDimitry Andric 
5170b57cec5SDimitry Andric // Compare two symbols. Return 1 if the new symbol should win, -1 if
5180b57cec5SDimitry Andric // the new symbol should lose, or 0 if there is a conflict.
5190b57cec5SDimitry Andric int Symbol::compare(const Symbol *other) const {
5200b57cec5SDimitry Andric   assert(other->isDefined() || other->isCommon());
5210b57cec5SDimitry Andric 
5220b57cec5SDimitry Andric   if (!isDefined() && !isCommon())
5230b57cec5SDimitry Andric     return 1;
5240b57cec5SDimitry Andric 
5250b57cec5SDimitry Andric   if (int cmp = compareVersion(getName(), other->getName()))
5260b57cec5SDimitry Andric     return cmp;
5270b57cec5SDimitry Andric 
5280b57cec5SDimitry Andric   if (other->isWeak())
5290b57cec5SDimitry Andric     return -1;
5300b57cec5SDimitry Andric 
5310b57cec5SDimitry Andric   if (isWeak())
5320b57cec5SDimitry Andric     return 1;
5330b57cec5SDimitry Andric 
5340b57cec5SDimitry Andric   if (isCommon() && other->isCommon()) {
5350b57cec5SDimitry Andric     if (config->warnCommon)
5360b57cec5SDimitry Andric       warn("multiple common of " + getName());
5370b57cec5SDimitry Andric     return 0;
5380b57cec5SDimitry Andric   }
5390b57cec5SDimitry Andric 
5400b57cec5SDimitry Andric   if (isCommon()) {
5410b57cec5SDimitry Andric     if (config->warnCommon)
5420b57cec5SDimitry Andric       warn("common " + getName() + " is overridden");
5430b57cec5SDimitry Andric     return 1;
5440b57cec5SDimitry Andric   }
5450b57cec5SDimitry Andric 
5460b57cec5SDimitry Andric   if (other->isCommon()) {
5470b57cec5SDimitry Andric     if (config->warnCommon)
5480b57cec5SDimitry Andric       warn("common " + getName() + " is overridden");
5490b57cec5SDimitry Andric     return -1;
5500b57cec5SDimitry Andric   }
5510b57cec5SDimitry Andric 
5520b57cec5SDimitry Andric   auto *oldSym = cast<Defined>(this);
5530b57cec5SDimitry Andric   auto *newSym = cast<Defined>(other);
5540b57cec5SDimitry Andric 
555*85868e8aSDimitry Andric   if (dyn_cast_or_null<BitcodeFile>(other->file))
5560b57cec5SDimitry Andric     return 0;
5570b57cec5SDimitry Andric 
5580b57cec5SDimitry Andric   if (!oldSym->section && !newSym->section && oldSym->value == newSym->value &&
5590b57cec5SDimitry Andric       newSym->binding == STB_GLOBAL)
5600b57cec5SDimitry Andric     return -1;
5610b57cec5SDimitry Andric 
5620b57cec5SDimitry Andric   return 0;
5630b57cec5SDimitry Andric }
5640b57cec5SDimitry Andric 
5650b57cec5SDimitry Andric static void reportDuplicate(Symbol *sym, InputFile *newFile,
5660b57cec5SDimitry Andric                             InputSectionBase *errSec, uint64_t errOffset) {
5670b57cec5SDimitry Andric   if (config->allowMultipleDefinition)
5680b57cec5SDimitry Andric     return;
5690b57cec5SDimitry Andric 
5700b57cec5SDimitry Andric   Defined *d = cast<Defined>(sym);
5710b57cec5SDimitry Andric   if (!d->section || !errSec) {
5720b57cec5SDimitry Andric     error("duplicate symbol: " + toString(*sym) + "\n>>> defined in " +
5730b57cec5SDimitry Andric           toString(sym->file) + "\n>>> defined in " + toString(newFile));
5740b57cec5SDimitry Andric     return;
5750b57cec5SDimitry Andric   }
5760b57cec5SDimitry Andric 
5770b57cec5SDimitry Andric   // Construct and print an error message in the form of:
5780b57cec5SDimitry Andric   //
5790b57cec5SDimitry Andric   //   ld.lld: error: duplicate symbol: foo
5800b57cec5SDimitry Andric   //   >>> defined at bar.c:30
5810b57cec5SDimitry Andric   //   >>>            bar.o (/home/alice/src/bar.o)
5820b57cec5SDimitry Andric   //   >>> defined at baz.c:563
5830b57cec5SDimitry Andric   //   >>>            baz.o in archive libbaz.a
5840b57cec5SDimitry Andric   auto *sec1 = cast<InputSectionBase>(d->section);
5850b57cec5SDimitry Andric   std::string src1 = sec1->getSrcMsg(*sym, d->value);
5860b57cec5SDimitry Andric   std::string obj1 = sec1->getObjMsg(d->value);
5870b57cec5SDimitry Andric   std::string src2 = errSec->getSrcMsg(*sym, errOffset);
5880b57cec5SDimitry Andric   std::string obj2 = errSec->getObjMsg(errOffset);
5890b57cec5SDimitry Andric 
5900b57cec5SDimitry Andric   std::string msg = "duplicate symbol: " + toString(*sym) + "\n>>> defined at ";
5910b57cec5SDimitry Andric   if (!src1.empty())
5920b57cec5SDimitry Andric     msg += src1 + "\n>>>            ";
5930b57cec5SDimitry Andric   msg += obj1 + "\n>>> defined at ";
5940b57cec5SDimitry Andric   if (!src2.empty())
5950b57cec5SDimitry Andric     msg += src2 + "\n>>>            ";
5960b57cec5SDimitry Andric   msg += obj2;
5970b57cec5SDimitry Andric   error(msg);
5980b57cec5SDimitry Andric }
5990b57cec5SDimitry Andric 
6000b57cec5SDimitry Andric void Symbol::resolveCommon(const CommonSymbol &other) {
6010b57cec5SDimitry Andric   int cmp = compare(&other);
6020b57cec5SDimitry Andric   if (cmp < 0)
6030b57cec5SDimitry Andric     return;
6040b57cec5SDimitry Andric 
6050b57cec5SDimitry Andric   if (cmp > 0) {
6060b57cec5SDimitry Andric     replace(other);
6070b57cec5SDimitry Andric     return;
6080b57cec5SDimitry Andric   }
6090b57cec5SDimitry Andric 
6100b57cec5SDimitry Andric   CommonSymbol *oldSym = cast<CommonSymbol>(this);
6110b57cec5SDimitry Andric 
6120b57cec5SDimitry Andric   oldSym->alignment = std::max(oldSym->alignment, other.alignment);
6130b57cec5SDimitry Andric   if (oldSym->size < other.size) {
6140b57cec5SDimitry Andric     oldSym->file = other.file;
6150b57cec5SDimitry Andric     oldSym->size = other.size;
6160b57cec5SDimitry Andric   }
6170b57cec5SDimitry Andric }
6180b57cec5SDimitry Andric 
6190b57cec5SDimitry Andric void Symbol::resolveDefined(const Defined &other) {
6200b57cec5SDimitry Andric   int cmp = compare(&other);
6210b57cec5SDimitry Andric   if (cmp > 0)
6220b57cec5SDimitry Andric     replace(other);
6230b57cec5SDimitry Andric   else if (cmp == 0)
6240b57cec5SDimitry Andric     reportDuplicate(this, other.file,
6250b57cec5SDimitry Andric                     dyn_cast_or_null<InputSectionBase>(other.section),
6260b57cec5SDimitry Andric                     other.value);
6270b57cec5SDimitry Andric }
6280b57cec5SDimitry Andric 
6290b57cec5SDimitry Andric template <class LazyT> void Symbol::resolveLazy(const LazyT &other) {
6300b57cec5SDimitry Andric   if (!isUndefined())
6310b57cec5SDimitry Andric     return;
6320b57cec5SDimitry Andric 
6330b57cec5SDimitry Andric   // An undefined weak will not fetch archive members. See comment on Lazy in
6340b57cec5SDimitry Andric   // Symbols.h for the details.
6350b57cec5SDimitry Andric   if (isWeak()) {
6360b57cec5SDimitry Andric     uint8_t ty = type;
6370b57cec5SDimitry Andric     replace(other);
6380b57cec5SDimitry Andric     type = ty;
6390b57cec5SDimitry Andric     binding = STB_WEAK;
6400b57cec5SDimitry Andric     return;
6410b57cec5SDimitry Andric   }
6420b57cec5SDimitry Andric 
6430b57cec5SDimitry Andric   other.fetch();
6440b57cec5SDimitry Andric }
6450b57cec5SDimitry Andric 
6460b57cec5SDimitry Andric void Symbol::resolveShared(const SharedSymbol &other) {
6470b57cec5SDimitry Andric   if (visibility == STV_DEFAULT && (isUndefined() || isLazy())) {
6480b57cec5SDimitry Andric     // An undefined symbol with non default visibility must be satisfied
6490b57cec5SDimitry Andric     // in the same DSO.
6500b57cec5SDimitry Andric     uint8_t bind = binding;
6510b57cec5SDimitry Andric     replace(other);
6520b57cec5SDimitry Andric     binding = bind;
653*85868e8aSDimitry Andric     referenced = true;
6540b57cec5SDimitry Andric   }
6550b57cec5SDimitry Andric }
656*85868e8aSDimitry Andric 
657*85868e8aSDimitry Andric } // namespace elf
658*85868e8aSDimitry Andric } // namespace lld
659