xref: /freebsd/contrib/llvm-project/lld/ELF/Relocations.cpp (revision 1ac55f4cb0001fed92329746c730aa9a947c09a5)
10b57cec5SDimitry Andric //===- Relocations.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 // This file contains platform-independent functions to process relocations.
100b57cec5SDimitry Andric // I'll describe the overview of this file here.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric // Simple relocations are easy to handle for the linker. For example,
130b57cec5SDimitry Andric // for R_X86_64_PC64 relocs, the linker just has to fix up locations
140b57cec5SDimitry Andric // with the relative offsets to the target symbols. It would just be
150b57cec5SDimitry Andric // reading records from relocation sections and applying them to output.
160b57cec5SDimitry Andric //
170b57cec5SDimitry Andric // But not all relocations are that easy to handle. For example, for
180b57cec5SDimitry Andric // R_386_GOTOFF relocs, the linker has to create new GOT entries for
190b57cec5SDimitry Andric // symbols if they don't exist, and fix up locations with GOT entry
200b57cec5SDimitry Andric // offsets from the beginning of GOT section. So there is more than
210b57cec5SDimitry Andric // fixing addresses in relocation processing.
220b57cec5SDimitry Andric //
230b57cec5SDimitry Andric // ELF defines a large number of complex relocations.
240b57cec5SDimitry Andric //
250b57cec5SDimitry Andric // The functions in this file analyze relocations and do whatever needs
260b57cec5SDimitry Andric // to be done. It includes, but not limited to, the following.
270b57cec5SDimitry Andric //
280b57cec5SDimitry Andric //  - create GOT/PLT entries
290b57cec5SDimitry Andric //  - create new relocations in .dynsym to let the dynamic linker resolve
300b57cec5SDimitry Andric //    them at runtime (since ELF supports dynamic linking, not all
310b57cec5SDimitry Andric //    relocations can be resolved at link-time)
320b57cec5SDimitry Andric //  - create COPY relocs and reserve space in .bss
330b57cec5SDimitry Andric //  - replace expensive relocs (in terms of runtime cost) with cheap ones
340b57cec5SDimitry Andric //  - error out infeasible combinations such as PIC and non-relative relocs
350b57cec5SDimitry Andric //
360b57cec5SDimitry Andric // Note that the functions in this file don't actually apply relocations
370b57cec5SDimitry Andric // because it doesn't know about the output file nor the output file buffer.
380b57cec5SDimitry Andric // It instead stores Relocation objects to InputSection's Relocations
390b57cec5SDimitry Andric // vector to let it apply later in InputSection::writeTo.
400b57cec5SDimitry Andric //
410b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
420b57cec5SDimitry Andric 
430b57cec5SDimitry Andric #include "Relocations.h"
440b57cec5SDimitry Andric #include "Config.h"
4581ad6265SDimitry Andric #include "InputFiles.h"
460b57cec5SDimitry Andric #include "LinkerScript.h"
470b57cec5SDimitry Andric #include "OutputSections.h"
480b57cec5SDimitry Andric #include "SymbolTable.h"
490b57cec5SDimitry Andric #include "Symbols.h"
500b57cec5SDimitry Andric #include "SyntheticSections.h"
510b57cec5SDimitry Andric #include "Target.h"
520b57cec5SDimitry Andric #include "Thunks.h"
530b57cec5SDimitry Andric #include "lld/Common/ErrorHandler.h"
540b57cec5SDimitry Andric #include "lld/Common/Memory.h"
550b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
56480093f4SDimitry Andric #include "llvm/Demangle/Demangle.h"
570b57cec5SDimitry Andric #include "llvm/Support/Endian.h"
580b57cec5SDimitry Andric #include <algorithm>
590b57cec5SDimitry Andric 
600b57cec5SDimitry Andric using namespace llvm;
610b57cec5SDimitry Andric using namespace llvm::ELF;
620b57cec5SDimitry Andric using namespace llvm::object;
630b57cec5SDimitry Andric using namespace llvm::support::endian;
645ffd83dbSDimitry Andric using namespace lld;
655ffd83dbSDimitry Andric using namespace lld::elf;
660b57cec5SDimitry Andric 
67bdd1243dSDimitry Andric static std::optional<std::string> getLinkerScriptLocation(const Symbol &sym) {
684824e7fdSDimitry Andric   for (SectionCommand *cmd : script->sectionCommands)
694824e7fdSDimitry Andric     if (auto *assign = dyn_cast<SymbolAssignment>(cmd))
704824e7fdSDimitry Andric       if (assign->sym == &sym)
714824e7fdSDimitry Andric         return assign->location;
72bdd1243dSDimitry Andric   return std::nullopt;
730b57cec5SDimitry Andric }
740b57cec5SDimitry Andric 
755ffd83dbSDimitry Andric static std::string getDefinedLocation(const Symbol &sym) {
76e8d8bef9SDimitry Andric   const char msg[] = "\n>>> defined in ";
775ffd83dbSDimitry Andric   if (sym.file)
78e8d8bef9SDimitry Andric     return msg + toString(sym.file);
79bdd1243dSDimitry Andric   if (std::optional<std::string> loc = getLinkerScriptLocation(sym))
80e8d8bef9SDimitry Andric     return msg + *loc;
81e8d8bef9SDimitry Andric   return "";
825ffd83dbSDimitry Andric }
835ffd83dbSDimitry Andric 
840b57cec5SDimitry Andric // Construct a message in the following format.
850b57cec5SDimitry Andric //
860b57cec5SDimitry Andric // >>> defined in /home/alice/src/foo.o
870b57cec5SDimitry Andric // >>> referenced by bar.c:12 (/home/alice/src/bar.c:12)
880b57cec5SDimitry Andric // >>>               /home/alice/src/bar.o:(.text+0x1)
890b57cec5SDimitry Andric static std::string getLocation(InputSectionBase &s, const Symbol &sym,
900b57cec5SDimitry Andric                                uint64_t off) {
915ffd83dbSDimitry Andric   std::string msg = getDefinedLocation(sym) + "\n>>> referenced by ";
920b57cec5SDimitry Andric   std::string src = s.getSrcMsg(sym, off);
930b57cec5SDimitry Andric   if (!src.empty())
940b57cec5SDimitry Andric     msg += src + "\n>>>               ";
950b57cec5SDimitry Andric   return msg + s.getObjMsg(off);
960b57cec5SDimitry Andric }
970b57cec5SDimitry Andric 
985ffd83dbSDimitry Andric void elf::reportRangeError(uint8_t *loc, const Relocation &rel, const Twine &v,
995ffd83dbSDimitry Andric                            int64_t min, uint64_t max) {
1005ffd83dbSDimitry Andric   ErrorPlace errPlace = getErrorPlace(loc);
1015ffd83dbSDimitry Andric   std::string hint;
10204eeddc0SDimitry Andric   if (rel.sym && !rel.sym->isSection())
103349cc55cSDimitry Andric     hint = "; references " + lld::toString(*rel.sym);
104349cc55cSDimitry Andric   if (!errPlace.srcLoc.empty())
105349cc55cSDimitry Andric     hint += "\n>>> referenced by " + errPlace.srcLoc;
10604eeddc0SDimitry Andric   if (rel.sym && !rel.sym->isSection())
107349cc55cSDimitry Andric     hint += getDefinedLocation(*rel.sym);
1085ffd83dbSDimitry Andric 
1095ffd83dbSDimitry Andric   if (errPlace.isec && errPlace.isec->name.startswith(".debug"))
1105ffd83dbSDimitry Andric     hint += "; consider recompiling with -fdebug-types-section to reduce size "
1115ffd83dbSDimitry Andric             "of debug sections";
1125ffd83dbSDimitry Andric 
1135ffd83dbSDimitry Andric   errorOrWarn(errPlace.loc + "relocation " + lld::toString(rel.type) +
1145ffd83dbSDimitry Andric               " out of range: " + v.str() + " is not in [" + Twine(min).str() +
1155ffd83dbSDimitry Andric               ", " + Twine(max).str() + "]" + hint);
1165ffd83dbSDimitry Andric }
1175ffd83dbSDimitry Andric 
118e8d8bef9SDimitry Andric void elf::reportRangeError(uint8_t *loc, int64_t v, int n, const Symbol &sym,
119e8d8bef9SDimitry Andric                            const Twine &msg) {
120e8d8bef9SDimitry Andric   ErrorPlace errPlace = getErrorPlace(loc);
121e8d8bef9SDimitry Andric   std::string hint;
122e8d8bef9SDimitry Andric   if (!sym.getName().empty())
123e8d8bef9SDimitry Andric     hint = "; references " + lld::toString(sym) + getDefinedLocation(sym);
124e8d8bef9SDimitry Andric   errorOrWarn(errPlace.loc + msg + " is out of range: " + Twine(v) +
125e8d8bef9SDimitry Andric               " is not in [" + Twine(llvm::minIntN(n)) + ", " +
126e8d8bef9SDimitry Andric               Twine(llvm::maxIntN(n)) + "]" + hint);
127e8d8bef9SDimitry Andric }
128e8d8bef9SDimitry Andric 
129349cc55cSDimitry Andric // Build a bitmask with one bit set for each 64 subset of RelExpr.
130349cc55cSDimitry Andric static constexpr uint64_t buildMask() { return 0; }
1310b57cec5SDimitry Andric 
132349cc55cSDimitry Andric template <typename... Tails>
133349cc55cSDimitry Andric static constexpr uint64_t buildMask(int head, Tails... tails) {
134349cc55cSDimitry Andric   return (0 <= head && head < 64 ? uint64_t(1) << head : 0) |
135349cc55cSDimitry Andric          buildMask(tails...);
1360b57cec5SDimitry Andric }
1370b57cec5SDimitry Andric 
1380b57cec5SDimitry Andric // Return true if `Expr` is one of `Exprs`.
139349cc55cSDimitry Andric // There are more than 64 but less than 128 RelExprs, so we divide the set of
140349cc55cSDimitry Andric // exprs into [0, 64) and [64, 128) and represent each range as a constant
141349cc55cSDimitry Andric // 64-bit mask. Then we decide which mask to test depending on the value of
142349cc55cSDimitry Andric // expr and use a simple shift and bitwise-and to test for membership.
143349cc55cSDimitry Andric template <RelExpr... Exprs> static bool oneof(RelExpr expr) {
144349cc55cSDimitry Andric   assert(0 <= expr && (int)expr < 128 &&
145349cc55cSDimitry Andric          "RelExpr is too large for 128-bit mask!");
1460b57cec5SDimitry Andric 
147349cc55cSDimitry Andric   if (expr >= 64)
148349cc55cSDimitry Andric     return (uint64_t(1) << (expr - 64)) & buildMask((Exprs - 64)...);
149349cc55cSDimitry Andric   return (uint64_t(1) << expr) & buildMask(Exprs...);
1500b57cec5SDimitry Andric }
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric static RelType getMipsPairType(RelType type, bool isLocal) {
1530b57cec5SDimitry Andric   switch (type) {
1540b57cec5SDimitry Andric   case R_MIPS_HI16:
1550b57cec5SDimitry Andric     return R_MIPS_LO16;
1560b57cec5SDimitry Andric   case R_MIPS_GOT16:
1570b57cec5SDimitry Andric     // In case of global symbol, the R_MIPS_GOT16 relocation does not
1580b57cec5SDimitry Andric     // have a pair. Each global symbol has a unique entry in the GOT
1590b57cec5SDimitry Andric     // and a corresponding instruction with help of the R_MIPS_GOT16
1600b57cec5SDimitry Andric     // relocation loads an address of the symbol. In case of local
1610b57cec5SDimitry Andric     // symbol, the R_MIPS_GOT16 relocation creates a GOT entry to hold
1620b57cec5SDimitry Andric     // the high 16 bits of the symbol's value. A paired R_MIPS_LO16
1630b57cec5SDimitry Andric     // relocations handle low 16 bits of the address. That allows
1640b57cec5SDimitry Andric     // to allocate only one GOT entry for every 64 KBytes of local data.
1650b57cec5SDimitry Andric     return isLocal ? R_MIPS_LO16 : R_MIPS_NONE;
1660b57cec5SDimitry Andric   case R_MICROMIPS_GOT16:
1670b57cec5SDimitry Andric     return isLocal ? R_MICROMIPS_LO16 : R_MIPS_NONE;
1680b57cec5SDimitry Andric   case R_MIPS_PCHI16:
1690b57cec5SDimitry Andric     return R_MIPS_PCLO16;
1700b57cec5SDimitry Andric   case R_MICROMIPS_HI16:
1710b57cec5SDimitry Andric     return R_MICROMIPS_LO16;
1720b57cec5SDimitry Andric   default:
1730b57cec5SDimitry Andric     return R_MIPS_NONE;
1740b57cec5SDimitry Andric   }
1750b57cec5SDimitry Andric }
1760b57cec5SDimitry Andric 
1770b57cec5SDimitry Andric // True if non-preemptable symbol always has the same value regardless of where
1780b57cec5SDimitry Andric // the DSO is loaded.
1790b57cec5SDimitry Andric static bool isAbsolute(const Symbol &sym) {
1800b57cec5SDimitry Andric   if (sym.isUndefWeak())
1810b57cec5SDimitry Andric     return true;
1820b57cec5SDimitry Andric   if (const auto *dr = dyn_cast<Defined>(&sym))
1830b57cec5SDimitry Andric     return dr->section == nullptr; // Absolute symbol.
1840b57cec5SDimitry Andric   return false;
1850b57cec5SDimitry Andric }
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric static bool isAbsoluteValue(const Symbol &sym) {
1880b57cec5SDimitry Andric   return isAbsolute(sym) || sym.isTls();
1890b57cec5SDimitry Andric }
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric // Returns true if Expr refers a PLT entry.
1920b57cec5SDimitry Andric static bool needsPlt(RelExpr expr) {
193349cc55cSDimitry Andric   return oneof<R_PLT, R_PLT_PC, R_PLT_GOTPLT, R_PPC32_PLTREL, R_PPC64_CALL_PLT>(
194349cc55cSDimitry Andric       expr);
1950b57cec5SDimitry Andric }
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric // Returns true if Expr refers a GOT entry. Note that this function
1980b57cec5SDimitry Andric // returns false for TLS variables even though they need GOT, because
1990b57cec5SDimitry Andric // TLS variables uses GOT differently than the regular variables.
2000b57cec5SDimitry Andric static bool needsGot(RelExpr expr) {
20185868e8aSDimitry Andric   return oneof<R_GOT, R_GOT_OFF, R_MIPS_GOT_LOCAL_PAGE, R_MIPS_GOT_OFF,
202e8d8bef9SDimitry Andric                R_MIPS_GOT_OFF32, R_AARCH64_GOT_PAGE_PC, R_GOT_PC, R_GOTPLT,
203e8d8bef9SDimitry Andric                R_AARCH64_GOT_PAGE>(expr);
2040b57cec5SDimitry Andric }
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric // True if this expression is of the form Sym - X, where X is a position in the
2070b57cec5SDimitry Andric // file (PC, or GOT for example).
2080b57cec5SDimitry Andric static bool isRelExpr(RelExpr expr) {
2090b57cec5SDimitry Andric   return oneof<R_PC, R_GOTREL, R_GOTPLTREL, R_MIPS_GOTREL, R_PPC64_CALL,
2100b57cec5SDimitry Andric                R_PPC64_RELAX_TOC, R_AARCH64_PAGE_PC, R_RELAX_GOT_PC,
211e8d8bef9SDimitry Andric                R_RISCV_PC_INDIRECT, R_PPC64_RELAX_GOT_PC>(expr);
2120b57cec5SDimitry Andric }
2130b57cec5SDimitry Andric 
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric static RelExpr toPlt(RelExpr expr) {
2160b57cec5SDimitry Andric   switch (expr) {
2170b57cec5SDimitry Andric   case R_PPC64_CALL:
2180b57cec5SDimitry Andric     return R_PPC64_CALL_PLT;
2190b57cec5SDimitry Andric   case R_PC:
2200b57cec5SDimitry Andric     return R_PLT_PC;
2210b57cec5SDimitry Andric   case R_ABS:
2220b57cec5SDimitry Andric     return R_PLT;
2230b57cec5SDimitry Andric   default:
2240b57cec5SDimitry Andric     return expr;
2250b57cec5SDimitry Andric   }
2260b57cec5SDimitry Andric }
2270b57cec5SDimitry Andric 
2280b57cec5SDimitry Andric static RelExpr fromPlt(RelExpr expr) {
2290b57cec5SDimitry Andric   // We decided not to use a plt. Optimize a reference to the plt to a
2300b57cec5SDimitry Andric   // reference to the symbol itself.
2310b57cec5SDimitry Andric   switch (expr) {
2320b57cec5SDimitry Andric   case R_PLT_PC:
2330b57cec5SDimitry Andric   case R_PPC32_PLTREL:
2340b57cec5SDimitry Andric     return R_PC;
2350b57cec5SDimitry Andric   case R_PPC64_CALL_PLT:
2360b57cec5SDimitry Andric     return R_PPC64_CALL;
2370b57cec5SDimitry Andric   case R_PLT:
2380b57cec5SDimitry Andric     return R_ABS;
239349cc55cSDimitry Andric   case R_PLT_GOTPLT:
240349cc55cSDimitry Andric     return R_GOTPLTREL;
2410b57cec5SDimitry Andric   default:
2420b57cec5SDimitry Andric     return expr;
2430b57cec5SDimitry Andric   }
2440b57cec5SDimitry Andric }
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric // Returns true if a given shared symbol is in a read-only segment in a DSO.
2470b57cec5SDimitry Andric template <class ELFT> static bool isReadOnly(SharedSymbol &ss) {
2480b57cec5SDimitry Andric   using Elf_Phdr = typename ELFT::Phdr;
2490b57cec5SDimitry Andric 
2500b57cec5SDimitry Andric   // Determine if the symbol is read-only by scanning the DSO's program headers.
25181ad6265SDimitry Andric   const auto &file = cast<SharedFile>(*ss.file);
2520b57cec5SDimitry Andric   for (const Elf_Phdr &phdr :
2530b57cec5SDimitry Andric        check(file.template getObj<ELFT>().program_headers()))
2540b57cec5SDimitry Andric     if ((phdr.p_type == ELF::PT_LOAD || phdr.p_type == ELF::PT_GNU_RELRO) &&
2550b57cec5SDimitry Andric         !(phdr.p_flags & ELF::PF_W) && ss.value >= phdr.p_vaddr &&
2560b57cec5SDimitry Andric         ss.value < phdr.p_vaddr + phdr.p_memsz)
2570b57cec5SDimitry Andric       return true;
2580b57cec5SDimitry Andric   return false;
2590b57cec5SDimitry Andric }
2600b57cec5SDimitry Andric 
2610b57cec5SDimitry Andric // Returns symbols at the same offset as a given symbol, including SS itself.
2620b57cec5SDimitry Andric //
2630b57cec5SDimitry Andric // If two or more symbols are at the same offset, and at least one of
2640b57cec5SDimitry Andric // them are copied by a copy relocation, all of them need to be copied.
2650b57cec5SDimitry Andric // Otherwise, they would refer to different places at runtime.
2660b57cec5SDimitry Andric template <class ELFT>
2670b57cec5SDimitry Andric static SmallSet<SharedSymbol *, 4> getSymbolsAt(SharedSymbol &ss) {
2680b57cec5SDimitry Andric   using Elf_Sym = typename ELFT::Sym;
2690b57cec5SDimitry Andric 
27081ad6265SDimitry Andric   const auto &file = cast<SharedFile>(*ss.file);
2710b57cec5SDimitry Andric 
2720b57cec5SDimitry Andric   SmallSet<SharedSymbol *, 4> ret;
2730b57cec5SDimitry Andric   for (const Elf_Sym &s : file.template getGlobalELFSyms<ELFT>()) {
2740b57cec5SDimitry Andric     if (s.st_shndx == SHN_UNDEF || s.st_shndx == SHN_ABS ||
2750b57cec5SDimitry Andric         s.getType() == STT_TLS || s.st_value != ss.value)
2760b57cec5SDimitry Andric       continue;
2770b57cec5SDimitry Andric     StringRef name = check(s.getName(file.getStringTable()));
278bdd1243dSDimitry Andric     Symbol *sym = symtab.find(name);
2790b57cec5SDimitry Andric     if (auto *alias = dyn_cast_or_null<SharedSymbol>(sym))
2800b57cec5SDimitry Andric       ret.insert(alias);
2810b57cec5SDimitry Andric   }
2826e75b2fbSDimitry Andric 
2836e75b2fbSDimitry Andric   // The loop does not check SHT_GNU_verneed, so ret does not contain
2846e75b2fbSDimitry Andric   // non-default version symbols. If ss has a non-default version, ret won't
2856e75b2fbSDimitry Andric   // contain ss. Just add ss unconditionally. If a non-default version alias is
2866e75b2fbSDimitry Andric   // separately copy relocated, it and ss will have different addresses.
2876e75b2fbSDimitry Andric   // Fortunately this case is impractical and fails with GNU ld as well.
2886e75b2fbSDimitry Andric   ret.insert(&ss);
2890b57cec5SDimitry Andric   return ret;
2900b57cec5SDimitry Andric }
2910b57cec5SDimitry Andric 
2920b57cec5SDimitry Andric // When a symbol is copy relocated or we create a canonical plt entry, it is
2930b57cec5SDimitry Andric // effectively a defined symbol. In the case of copy relocation the symbol is
2940b57cec5SDimitry Andric // in .bss and in the case of a canonical plt entry it is in .plt. This function
2950b57cec5SDimitry Andric // replaces the existing symbol with a Defined pointing to the appropriate
2960b57cec5SDimitry Andric // location.
2970eae32dcSDimitry Andric static void replaceWithDefined(Symbol &sym, SectionBase &sec, uint64_t value,
2980b57cec5SDimitry Andric                                uint64_t size) {
2990b57cec5SDimitry Andric   Symbol old = sym;
300bdd1243dSDimitry Andric   Defined(sym.file, StringRef(), sym.binding, sym.stOther, sym.type, value,
301bdd1243dSDimitry Andric           size, &sec)
302bdd1243dSDimitry Andric       .overwrite(sym);
3030b57cec5SDimitry Andric 
3040b57cec5SDimitry Andric   sym.verdefIndex = old.verdefIndex;
3050b57cec5SDimitry Andric   sym.exportDynamic = true;
3060b57cec5SDimitry Andric   sym.isUsedInRegularObj = true;
3070eae32dcSDimitry Andric   // A copy relocated alias may need a GOT entry.
308bdd1243dSDimitry Andric   sym.flags.store(old.flags.load(std::memory_order_relaxed) & NEEDS_GOT,
309bdd1243dSDimitry Andric                   std::memory_order_relaxed);
3100b57cec5SDimitry Andric }
3110b57cec5SDimitry Andric 
3120b57cec5SDimitry Andric // Reserve space in .bss or .bss.rel.ro for copy relocation.
3130b57cec5SDimitry Andric //
3140b57cec5SDimitry Andric // The copy relocation is pretty much a hack. If you use a copy relocation
3150b57cec5SDimitry Andric // in your program, not only the symbol name but the symbol's size, RW/RO
3160b57cec5SDimitry Andric // bit and alignment become part of the ABI. In addition to that, if the
3170b57cec5SDimitry Andric // symbol has aliases, the aliases become part of the ABI. That's subtle,
3180b57cec5SDimitry Andric // but if you violate that implicit ABI, that can cause very counter-
3190b57cec5SDimitry Andric // intuitive consequences.
3200b57cec5SDimitry Andric //
3210b57cec5SDimitry Andric // So, what is the copy relocation? It's for linking non-position
3220b57cec5SDimitry Andric // independent code to DSOs. In an ideal world, all references to data
3230b57cec5SDimitry Andric // exported by DSOs should go indirectly through GOT. But if object files
3240b57cec5SDimitry Andric // are compiled as non-PIC, all data references are direct. There is no
3250b57cec5SDimitry Andric // way for the linker to transform the code to use GOT, as machine
3260b57cec5SDimitry Andric // instructions are already set in stone in object files. This is where
3270b57cec5SDimitry Andric // the copy relocation takes a role.
3280b57cec5SDimitry Andric //
3290b57cec5SDimitry Andric // A copy relocation instructs the dynamic linker to copy data from a DSO
3300b57cec5SDimitry Andric // to a specified address (which is usually in .bss) at load-time. If the
3310b57cec5SDimitry Andric // static linker (that's us) finds a direct data reference to a DSO
3320b57cec5SDimitry Andric // symbol, it creates a copy relocation, so that the symbol can be
3330b57cec5SDimitry Andric // resolved as if it were in .bss rather than in a DSO.
3340b57cec5SDimitry Andric //
3350b57cec5SDimitry Andric // As you can see in this function, we create a copy relocation for the
3360b57cec5SDimitry Andric // dynamic linker, and the relocation contains not only symbol name but
337480093f4SDimitry Andric // various other information about the symbol. So, such attributes become a
3380b57cec5SDimitry Andric // part of the ABI.
3390b57cec5SDimitry Andric //
3400b57cec5SDimitry Andric // Note for application developers: I can give you a piece of advice if
3410b57cec5SDimitry Andric // you are writing a shared library. You probably should export only
3420b57cec5SDimitry Andric // functions from your library. You shouldn't export variables.
3430b57cec5SDimitry Andric //
3440b57cec5SDimitry Andric // As an example what can happen when you export variables without knowing
3450b57cec5SDimitry Andric // the semantics of copy relocations, assume that you have an exported
3460b57cec5SDimitry Andric // variable of type T. It is an ABI-breaking change to add new members at
3470b57cec5SDimitry Andric // end of T even though doing that doesn't change the layout of the
3480b57cec5SDimitry Andric // existing members. That's because the space for the new members are not
3490b57cec5SDimitry Andric // reserved in .bss unless you recompile the main program. That means they
3500b57cec5SDimitry Andric // are likely to overlap with other data that happens to be laid out next
3510b57cec5SDimitry Andric // to the variable in .bss. This kind of issue is sometimes very hard to
352480093f4SDimitry Andric // debug. What's a solution? Instead of exporting a variable V from a DSO,
3530b57cec5SDimitry Andric // define an accessor getV().
35481ad6265SDimitry Andric template <class ELFT> static void addCopyRelSymbol(SharedSymbol &ss) {
3550b57cec5SDimitry Andric   // Copy relocation against zero-sized symbol doesn't make sense.
3560b57cec5SDimitry Andric   uint64_t symSize = ss.getSize();
3570b57cec5SDimitry Andric   if (symSize == 0 || ss.alignment == 0)
3580b57cec5SDimitry Andric     fatal("cannot create a copy relocation for symbol " + toString(ss));
3590b57cec5SDimitry Andric 
3600b57cec5SDimitry Andric   // See if this symbol is in a read-only segment. If so, preserve the symbol's
3610b57cec5SDimitry Andric   // memory protection by reserving space in the .bss.rel.ro section.
3620b57cec5SDimitry Andric   bool isRO = isReadOnly<ELFT>(ss);
3630b57cec5SDimitry Andric   BssSection *sec =
3640b57cec5SDimitry Andric       make<BssSection>(isRO ? ".bss.rel.ro" : ".bss", symSize, ss.alignment);
36585868e8aSDimitry Andric   OutputSection *osec = (isRO ? in.bssRelRo : in.bss)->getParent();
36685868e8aSDimitry Andric 
36785868e8aSDimitry Andric   // At this point, sectionBases has been migrated to sections. Append sec to
36885868e8aSDimitry Andric   // sections.
3694824e7fdSDimitry Andric   if (osec->commands.empty() ||
3704824e7fdSDimitry Andric       !isa<InputSectionDescription>(osec->commands.back()))
3714824e7fdSDimitry Andric     osec->commands.push_back(make<InputSectionDescription>(""));
3724824e7fdSDimitry Andric   auto *isd = cast<InputSectionDescription>(osec->commands.back());
37385868e8aSDimitry Andric   isd->sections.push_back(sec);
37485868e8aSDimitry Andric   osec->commitSection(sec);
3750b57cec5SDimitry Andric 
3760b57cec5SDimitry Andric   // Look through the DSO's dynamic symbol table for aliases and create a
3770b57cec5SDimitry Andric   // dynamic symbol for each one. This causes the copy relocation to correctly
3780b57cec5SDimitry Andric   // interpose any aliases.
3790b57cec5SDimitry Andric   for (SharedSymbol *sym : getSymbolsAt<ELFT>(ss))
3800eae32dcSDimitry Andric     replaceWithDefined(*sym, *sec, 0, sym->size);
3810b57cec5SDimitry Andric 
3820eae32dcSDimitry Andric   mainPart->relaDyn->addSymbolReloc(target->copyRel, *sec, 0, ss);
3830eae32dcSDimitry Andric }
3840eae32dcSDimitry Andric 
38504eeddc0SDimitry Andric // .eh_frame sections are mergeable input sections, so their input
38604eeddc0SDimitry Andric // offsets are not linearly mapped to output section. For each input
38704eeddc0SDimitry Andric // offset, we need to find a section piece containing the offset and
38804eeddc0SDimitry Andric // add the piece's base address to the input offset to compute the
38904eeddc0SDimitry Andric // output offset. That isn't cheap.
39004eeddc0SDimitry Andric //
39104eeddc0SDimitry Andric // This class is to speed up the offset computation. When we process
39204eeddc0SDimitry Andric // relocations, we access offsets in the monotonically increasing
39304eeddc0SDimitry Andric // order. So we can optimize for that access pattern.
39404eeddc0SDimitry Andric //
39504eeddc0SDimitry Andric // For sections other than .eh_frame, this class doesn't do anything.
39604eeddc0SDimitry Andric namespace {
39704eeddc0SDimitry Andric class OffsetGetter {
39804eeddc0SDimitry Andric public:
399bdd1243dSDimitry Andric   OffsetGetter() = default;
40004eeddc0SDimitry Andric   explicit OffsetGetter(InputSectionBase &sec) {
401bdd1243dSDimitry Andric     if (auto *eh = dyn_cast<EhInputSection>(&sec)) {
402bdd1243dSDimitry Andric       cies = eh->cies;
403bdd1243dSDimitry Andric       fdes = eh->fdes;
404bdd1243dSDimitry Andric       i = cies.begin();
405bdd1243dSDimitry Andric       j = fdes.begin();
406bdd1243dSDimitry Andric     }
40704eeddc0SDimitry Andric   }
40804eeddc0SDimitry Andric 
40904eeddc0SDimitry Andric   // Translates offsets in input sections to offsets in output sections.
41004eeddc0SDimitry Andric   // Given offset must increase monotonically. We assume that Piece is
41104eeddc0SDimitry Andric   // sorted by inputOff.
41204eeddc0SDimitry Andric   uint64_t get(uint64_t off) {
413bdd1243dSDimitry Andric     if (cies.empty())
41404eeddc0SDimitry Andric       return off;
41504eeddc0SDimitry Andric 
416bdd1243dSDimitry Andric     while (j != fdes.end() && j->inputOff <= off)
417bdd1243dSDimitry Andric       ++j;
418bdd1243dSDimitry Andric     auto it = j;
419bdd1243dSDimitry Andric     if (j == fdes.begin() || j[-1].inputOff + j[-1].size <= off) {
420bdd1243dSDimitry Andric       while (i != cies.end() && i->inputOff <= off)
42104eeddc0SDimitry Andric         ++i;
422bdd1243dSDimitry Andric       if (i == cies.begin() || i[-1].inputOff + i[-1].size <= off)
42304eeddc0SDimitry Andric         fatal(".eh_frame: relocation is not in any piece");
424bdd1243dSDimitry Andric       it = i;
425bdd1243dSDimitry Andric     }
42604eeddc0SDimitry Andric 
42704eeddc0SDimitry Andric     // Offset -1 means that the piece is dead (i.e. garbage collected).
428bdd1243dSDimitry Andric     if (it[-1].outputOff == -1)
42904eeddc0SDimitry Andric       return -1;
430bdd1243dSDimitry Andric     return it[-1].outputOff + (off - it[-1].inputOff);
43104eeddc0SDimitry Andric   }
43204eeddc0SDimitry Andric 
43304eeddc0SDimitry Andric private:
434bdd1243dSDimitry Andric   ArrayRef<EhSectionPiece> cies, fdes;
435bdd1243dSDimitry Andric   ArrayRef<EhSectionPiece>::iterator i, j;
43604eeddc0SDimitry Andric };
43704eeddc0SDimitry Andric 
43804eeddc0SDimitry Andric // This class encapsulates states needed to scan relocations for one
43904eeddc0SDimitry Andric // InputSectionBase.
44004eeddc0SDimitry Andric class RelocationScanner {
44104eeddc0SDimitry Andric public:
442bdd1243dSDimitry Andric   template <class ELFT> void scanSection(InputSectionBase &s);
44304eeddc0SDimitry Andric 
44404eeddc0SDimitry Andric private:
445bdd1243dSDimitry Andric   InputSectionBase *sec;
44604eeddc0SDimitry Andric   OffsetGetter getter;
44704eeddc0SDimitry Andric 
44804eeddc0SDimitry Andric   // End of relocations, used by Mips/PPC64.
44904eeddc0SDimitry Andric   const void *end = nullptr;
45004eeddc0SDimitry Andric 
45104eeddc0SDimitry Andric   template <class RelTy> RelType getMipsN32RelType(RelTy *&rel) const;
45204eeddc0SDimitry Andric   template <class ELFT, class RelTy>
45304eeddc0SDimitry Andric   int64_t computeMipsAddend(const RelTy &rel, RelExpr expr, bool isLocal) const;
45404eeddc0SDimitry Andric   bool isStaticLinkTimeConstant(RelExpr e, RelType type, const Symbol &sym,
45504eeddc0SDimitry Andric                                 uint64_t relOff) const;
45604eeddc0SDimitry Andric   void processAux(RelExpr expr, RelType type, uint64_t offset, Symbol &sym,
45704eeddc0SDimitry Andric                   int64_t addend) const;
45804eeddc0SDimitry Andric   template <class ELFT, class RelTy> void scanOne(RelTy *&i);
459bdd1243dSDimitry Andric   template <class ELFT, class RelTy> void scan(ArrayRef<RelTy> rels);
46004eeddc0SDimitry Andric };
46104eeddc0SDimitry Andric } // namespace
46204eeddc0SDimitry Andric 
4630b57cec5SDimitry Andric // MIPS has an odd notion of "paired" relocations to calculate addends.
4640b57cec5SDimitry Andric // For example, if a relocation is of R_MIPS_HI16, there must be a
4650b57cec5SDimitry Andric // R_MIPS_LO16 relocation after that, and an addend is calculated using
4660b57cec5SDimitry Andric // the two relocations.
4670b57cec5SDimitry Andric template <class ELFT, class RelTy>
46804eeddc0SDimitry Andric int64_t RelocationScanner::computeMipsAddend(const RelTy &rel, RelExpr expr,
46904eeddc0SDimitry Andric                                              bool isLocal) const {
4700b57cec5SDimitry Andric   if (expr == R_MIPS_GOTREL && isLocal)
471bdd1243dSDimitry Andric     return sec->getFile<ELFT>()->mipsGp0;
4720b57cec5SDimitry Andric 
4730b57cec5SDimitry Andric   // The ABI says that the paired relocation is used only for REL.
4740b57cec5SDimitry Andric   // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
4750b57cec5SDimitry Andric   if (RelTy::IsRela)
4760b57cec5SDimitry Andric     return 0;
4770b57cec5SDimitry Andric 
4780b57cec5SDimitry Andric   RelType type = rel.getType(config->isMips64EL);
4790b57cec5SDimitry Andric   uint32_t pairTy = getMipsPairType(type, isLocal);
4800b57cec5SDimitry Andric   if (pairTy == R_MIPS_NONE)
4810b57cec5SDimitry Andric     return 0;
4820b57cec5SDimitry Andric 
483bdd1243dSDimitry Andric   const uint8_t *buf = sec->content().data();
4840b57cec5SDimitry Andric   uint32_t symIndex = rel.getSymbol(config->isMips64EL);
4850b57cec5SDimitry Andric 
4860b57cec5SDimitry Andric   // To make things worse, paired relocations might not be contiguous in
4870b57cec5SDimitry Andric   // the relocation table, so we need to do linear search. *sigh*
48804eeddc0SDimitry Andric   for (const RelTy *ri = &rel; ri != static_cast<const RelTy *>(end); ++ri)
4890b57cec5SDimitry Andric     if (ri->getType(config->isMips64EL) == pairTy &&
4900b57cec5SDimitry Andric         ri->getSymbol(config->isMips64EL) == symIndex)
491bdd1243dSDimitry Andric       return target->getImplicitAddend(buf + ri->r_offset, pairTy);
4920b57cec5SDimitry Andric 
4930b57cec5SDimitry Andric   warn("can't find matching " + toString(pairTy) + " relocation for " +
4940b57cec5SDimitry Andric        toString(type));
4950b57cec5SDimitry Andric   return 0;
4960b57cec5SDimitry Andric }
4970b57cec5SDimitry Andric 
4980b57cec5SDimitry Andric // Custom error message if Sym is defined in a discarded section.
4990b57cec5SDimitry Andric template <class ELFT>
5000b57cec5SDimitry Andric static std::string maybeReportDiscarded(Undefined &sym) {
5010b57cec5SDimitry Andric   auto *file = dyn_cast_or_null<ObjFile<ELFT>>(sym.file);
5020b57cec5SDimitry Andric   if (!file || !sym.discardedSecIdx ||
5030b57cec5SDimitry Andric       file->getSections()[sym.discardedSecIdx] != &InputSection::discarded)
5040b57cec5SDimitry Andric     return "";
5050eae32dcSDimitry Andric   ArrayRef<typename ELFT::Shdr> objSections =
5060eae32dcSDimitry Andric       file->template getELFShdrs<ELFT>();
5070b57cec5SDimitry Andric 
5080b57cec5SDimitry Andric   std::string msg;
5090b57cec5SDimitry Andric   if (sym.type == ELF::STT_SECTION) {
5100b57cec5SDimitry Andric     msg = "relocation refers to a discarded section: ";
5110b57cec5SDimitry Andric     msg += CHECK(
512e8d8bef9SDimitry Andric         file->getObj().getSectionName(objSections[sym.discardedSecIdx]), file);
5130b57cec5SDimitry Andric   } else {
5140b57cec5SDimitry Andric     msg = "relocation refers to a symbol in a discarded section: " +
5150b57cec5SDimitry Andric           toString(sym);
5160b57cec5SDimitry Andric   }
5170b57cec5SDimitry Andric   msg += "\n>>> defined in " + toString(file);
5180b57cec5SDimitry Andric 
5190b57cec5SDimitry Andric   Elf_Shdr_Impl<ELFT> elfSec = objSections[sym.discardedSecIdx - 1];
5200b57cec5SDimitry Andric   if (elfSec.sh_type != SHT_GROUP)
5210b57cec5SDimitry Andric     return msg;
5220b57cec5SDimitry Andric 
5230b57cec5SDimitry Andric   // If the discarded section is a COMDAT.
5240b57cec5SDimitry Andric   StringRef signature = file->getShtGroupSignature(objSections, elfSec);
5250b57cec5SDimitry Andric   if (const InputFile *prevailing =
526bdd1243dSDimitry Andric           symtab.comdatGroups.lookup(CachedHashStringRef(signature))) {
5270b57cec5SDimitry Andric     msg += "\n>>> section group signature: " + signature.str() +
5280b57cec5SDimitry Andric            "\n>>> prevailing definition is in " + toString(prevailing);
52981ad6265SDimitry Andric     if (sym.nonPrevailing) {
53081ad6265SDimitry Andric       msg += "\n>>> or the symbol in the prevailing group had STB_WEAK "
53181ad6265SDimitry Andric              "binding and the symbol in a non-prevailing group had STB_GLOBAL "
53281ad6265SDimitry Andric              "binding. Mixing groups with STB_WEAK and STB_GLOBAL binding "
53381ad6265SDimitry Andric              "signature is not supported";
53481ad6265SDimitry Andric     }
53581ad6265SDimitry Andric   }
5360b57cec5SDimitry Andric   return msg;
5370b57cec5SDimitry Andric }
5380b57cec5SDimitry Andric 
53981ad6265SDimitry Andric namespace {
5400b57cec5SDimitry Andric // Undefined diagnostics are collected in a vector and emitted once all of
5410b57cec5SDimitry Andric // them are known, so that some postprocessing on the list of undefined symbols
5420b57cec5SDimitry Andric // can happen before lld emits diagnostics.
5430b57cec5SDimitry Andric struct UndefinedDiag {
54404eeddc0SDimitry Andric   Undefined *sym;
5450b57cec5SDimitry Andric   struct Loc {
5460b57cec5SDimitry Andric     InputSectionBase *sec;
5470b57cec5SDimitry Andric     uint64_t offset;
5480b57cec5SDimitry Andric   };
5490b57cec5SDimitry Andric   std::vector<Loc> locs;
5500b57cec5SDimitry Andric   bool isWarning;
5510b57cec5SDimitry Andric };
5520b57cec5SDimitry Andric 
55381ad6265SDimitry Andric std::vector<UndefinedDiag> undefs;
554bdd1243dSDimitry Andric std::mutex relocMutex;
55581ad6265SDimitry Andric }
5560b57cec5SDimitry Andric 
557480093f4SDimitry Andric // Check whether the definition name def is a mangled function name that matches
558480093f4SDimitry Andric // the reference name ref.
559480093f4SDimitry Andric static bool canSuggestExternCForCXX(StringRef ref, StringRef def) {
560480093f4SDimitry Andric   llvm::ItaniumPartialDemangler d;
561480093f4SDimitry Andric   std::string name = def.str();
562480093f4SDimitry Andric   if (d.partialDemangle(name.c_str()))
563480093f4SDimitry Andric     return false;
564480093f4SDimitry Andric   char *buf = d.getFunctionName(nullptr, nullptr);
565480093f4SDimitry Andric   if (!buf)
566480093f4SDimitry Andric     return false;
567480093f4SDimitry Andric   bool ret = ref == buf;
568480093f4SDimitry Andric   free(buf);
569480093f4SDimitry Andric   return ret;
570480093f4SDimitry Andric }
571480093f4SDimitry Andric 
57285868e8aSDimitry Andric // Suggest an alternative spelling of an "undefined symbol" diagnostic. Returns
57385868e8aSDimitry Andric // the suggested symbol, which is either in the symbol table, or in the same
57485868e8aSDimitry Andric // file of sym.
575480093f4SDimitry Andric static const Symbol *getAlternativeSpelling(const Undefined &sym,
576480093f4SDimitry Andric                                             std::string &pre_hint,
577480093f4SDimitry Andric                                             std::string &post_hint) {
57885868e8aSDimitry Andric   DenseMap<StringRef, const Symbol *> map;
57904eeddc0SDimitry Andric   if (sym.file && sym.file->kind() == InputFile::ObjKind) {
58004eeddc0SDimitry Andric     auto *file = cast<ELFFileBase>(sym.file);
581480093f4SDimitry Andric     // If sym is a symbol defined in a discarded section, maybeReportDiscarded()
582480093f4SDimitry Andric     // will give an error. Don't suggest an alternative spelling.
583480093f4SDimitry Andric     if (file && sym.discardedSecIdx != 0 &&
584480093f4SDimitry Andric         file->getSections()[sym.discardedSecIdx] == &InputSection::discarded)
585480093f4SDimitry Andric       return nullptr;
586480093f4SDimitry Andric 
587480093f4SDimitry Andric     // Build a map of local defined symbols.
58885868e8aSDimitry Andric     for (const Symbol *s : sym.file->getSymbols())
589fe6060f1SDimitry Andric       if (s->isLocal() && s->isDefined() && !s->getName().empty())
59085868e8aSDimitry Andric         map.try_emplace(s->getName(), s);
59185868e8aSDimitry Andric   }
59285868e8aSDimitry Andric 
59385868e8aSDimitry Andric   auto suggest = [&](StringRef newName) -> const Symbol * {
59485868e8aSDimitry Andric     // If defined locally.
59585868e8aSDimitry Andric     if (const Symbol *s = map.lookup(newName))
59685868e8aSDimitry Andric       return s;
59785868e8aSDimitry Andric 
59885868e8aSDimitry Andric     // If in the symbol table and not undefined.
599bdd1243dSDimitry Andric     if (const Symbol *s = symtab.find(newName))
60085868e8aSDimitry Andric       if (!s->isUndefined())
60185868e8aSDimitry Andric         return s;
60285868e8aSDimitry Andric 
60385868e8aSDimitry Andric     return nullptr;
60485868e8aSDimitry Andric   };
60585868e8aSDimitry Andric 
60685868e8aSDimitry Andric   // This loop enumerates all strings of Levenshtein distance 1 as typo
60785868e8aSDimitry Andric   // correction candidates and suggests the one that exists as a non-undefined
60885868e8aSDimitry Andric   // symbol.
60985868e8aSDimitry Andric   StringRef name = sym.getName();
61085868e8aSDimitry Andric   for (size_t i = 0, e = name.size(); i != e + 1; ++i) {
61185868e8aSDimitry Andric     // Insert a character before name[i].
61285868e8aSDimitry Andric     std::string newName = (name.substr(0, i) + "0" + name.substr(i)).str();
61385868e8aSDimitry Andric     for (char c = '0'; c <= 'z'; ++c) {
61485868e8aSDimitry Andric       newName[i] = c;
61585868e8aSDimitry Andric       if (const Symbol *s = suggest(newName))
61685868e8aSDimitry Andric         return s;
61785868e8aSDimitry Andric     }
61885868e8aSDimitry Andric     if (i == e)
61985868e8aSDimitry Andric       break;
62085868e8aSDimitry Andric 
62185868e8aSDimitry Andric     // Substitute name[i].
6225ffd83dbSDimitry Andric     newName = std::string(name);
62385868e8aSDimitry Andric     for (char c = '0'; c <= 'z'; ++c) {
62485868e8aSDimitry Andric       newName[i] = c;
62585868e8aSDimitry Andric       if (const Symbol *s = suggest(newName))
62685868e8aSDimitry Andric         return s;
62785868e8aSDimitry Andric     }
62885868e8aSDimitry Andric 
62985868e8aSDimitry Andric     // Transpose name[i] and name[i+1]. This is of edit distance 2 but it is
63085868e8aSDimitry Andric     // common.
63185868e8aSDimitry Andric     if (i + 1 < e) {
63285868e8aSDimitry Andric       newName[i] = name[i + 1];
63385868e8aSDimitry Andric       newName[i + 1] = name[i];
63485868e8aSDimitry Andric       if (const Symbol *s = suggest(newName))
63585868e8aSDimitry Andric         return s;
63685868e8aSDimitry Andric     }
63785868e8aSDimitry Andric 
63885868e8aSDimitry Andric     // Delete name[i].
63985868e8aSDimitry Andric     newName = (name.substr(0, i) + name.substr(i + 1)).str();
64085868e8aSDimitry Andric     if (const Symbol *s = suggest(newName))
64185868e8aSDimitry Andric       return s;
64285868e8aSDimitry Andric   }
64385868e8aSDimitry Andric 
644480093f4SDimitry Andric   // Case mismatch, e.g. Foo vs FOO.
645480093f4SDimitry Andric   for (auto &it : map)
646fe6060f1SDimitry Andric     if (name.equals_insensitive(it.first))
647480093f4SDimitry Andric       return it.second;
648bdd1243dSDimitry Andric   for (Symbol *sym : symtab.getSymbols())
649fe6060f1SDimitry Andric     if (!sym->isUndefined() && name.equals_insensitive(sym->getName()))
650480093f4SDimitry Andric       return sym;
651480093f4SDimitry Andric 
652480093f4SDimitry Andric   // The reference may be a mangled name while the definition is not. Suggest a
653480093f4SDimitry Andric   // missing extern "C".
654480093f4SDimitry Andric   if (name.startswith("_Z")) {
655480093f4SDimitry Andric     std::string buf = name.str();
656480093f4SDimitry Andric     llvm::ItaniumPartialDemangler d;
657480093f4SDimitry Andric     if (!d.partialDemangle(buf.c_str()))
658480093f4SDimitry Andric       if (char *buf = d.getFunctionName(nullptr, nullptr)) {
659480093f4SDimitry Andric         const Symbol *s = suggest(buf);
660480093f4SDimitry Andric         free(buf);
661480093f4SDimitry Andric         if (s) {
662480093f4SDimitry Andric           pre_hint = ": extern \"C\" ";
663480093f4SDimitry Andric           return s;
664480093f4SDimitry Andric         }
665480093f4SDimitry Andric       }
666480093f4SDimitry Andric   } else {
667480093f4SDimitry Andric     const Symbol *s = nullptr;
668480093f4SDimitry Andric     for (auto &it : map)
669480093f4SDimitry Andric       if (canSuggestExternCForCXX(name, it.first)) {
670480093f4SDimitry Andric         s = it.second;
671480093f4SDimitry Andric         break;
672480093f4SDimitry Andric       }
673480093f4SDimitry Andric     if (!s)
674bdd1243dSDimitry Andric       for (Symbol *sym : symtab.getSymbols())
675480093f4SDimitry Andric         if (canSuggestExternCForCXX(name, sym->getName())) {
676480093f4SDimitry Andric           s = sym;
677480093f4SDimitry Andric           break;
678480093f4SDimitry Andric         }
679480093f4SDimitry Andric     if (s) {
680480093f4SDimitry Andric       pre_hint = " to declare ";
681480093f4SDimitry Andric       post_hint = " as extern \"C\"?";
682480093f4SDimitry Andric       return s;
683480093f4SDimitry Andric     }
684480093f4SDimitry Andric   }
685480093f4SDimitry Andric 
68685868e8aSDimitry Andric   return nullptr;
68785868e8aSDimitry Andric }
68885868e8aSDimitry Andric 
68985868e8aSDimitry Andric static void reportUndefinedSymbol(const UndefinedDiag &undef,
69085868e8aSDimitry Andric                                   bool correctSpelling) {
69104eeddc0SDimitry Andric   Undefined &sym = *undef.sym;
6920b57cec5SDimitry Andric 
6930b57cec5SDimitry Andric   auto visibility = [&]() -> std::string {
694bdd1243dSDimitry Andric     switch (sym.visibility()) {
6950b57cec5SDimitry Andric     case STV_INTERNAL:
6960b57cec5SDimitry Andric       return "internal ";
6970b57cec5SDimitry Andric     case STV_HIDDEN:
6980b57cec5SDimitry Andric       return "hidden ";
6990b57cec5SDimitry Andric     case STV_PROTECTED:
7000b57cec5SDimitry Andric       return "protected ";
7010b57cec5SDimitry Andric     default:
7020b57cec5SDimitry Andric       return "";
7030b57cec5SDimitry Andric     }
7040b57cec5SDimitry Andric   };
7050b57cec5SDimitry Andric 
70681ad6265SDimitry Andric   std::string msg;
70781ad6265SDimitry Andric   switch (config->ekind) {
70881ad6265SDimitry Andric   case ELF32LEKind:
70981ad6265SDimitry Andric     msg = maybeReportDiscarded<ELF32LE>(sym);
71081ad6265SDimitry Andric     break;
71181ad6265SDimitry Andric   case ELF32BEKind:
71281ad6265SDimitry Andric     msg = maybeReportDiscarded<ELF32BE>(sym);
71381ad6265SDimitry Andric     break;
71481ad6265SDimitry Andric   case ELF64LEKind:
71581ad6265SDimitry Andric     msg = maybeReportDiscarded<ELF64LE>(sym);
71681ad6265SDimitry Andric     break;
71781ad6265SDimitry Andric   case ELF64BEKind:
71881ad6265SDimitry Andric     msg = maybeReportDiscarded<ELF64BE>(sym);
71981ad6265SDimitry Andric     break;
72081ad6265SDimitry Andric   default:
72181ad6265SDimitry Andric     llvm_unreachable("");
72281ad6265SDimitry Andric   }
7230b57cec5SDimitry Andric   if (msg.empty())
7240b57cec5SDimitry Andric     msg = "undefined " + visibility() + "symbol: " + toString(sym);
7250b57cec5SDimitry Andric 
7265ffd83dbSDimitry Andric   const size_t maxUndefReferences = 3;
7270b57cec5SDimitry Andric   size_t i = 0;
7280b57cec5SDimitry Andric   for (UndefinedDiag::Loc l : undef.locs) {
7290b57cec5SDimitry Andric     if (i >= maxUndefReferences)
7300b57cec5SDimitry Andric       break;
7310b57cec5SDimitry Andric     InputSectionBase &sec = *l.sec;
7320b57cec5SDimitry Andric     uint64_t offset = l.offset;
7330b57cec5SDimitry Andric 
7340b57cec5SDimitry Andric     msg += "\n>>> referenced by ";
7350b57cec5SDimitry Andric     std::string src = sec.getSrcMsg(sym, offset);
7360b57cec5SDimitry Andric     if (!src.empty())
7370b57cec5SDimitry Andric       msg += src + "\n>>>               ";
7380b57cec5SDimitry Andric     msg += sec.getObjMsg(offset);
7390b57cec5SDimitry Andric     i++;
7400b57cec5SDimitry Andric   }
7410b57cec5SDimitry Andric 
7420b57cec5SDimitry Andric   if (i < undef.locs.size())
7430b57cec5SDimitry Andric     msg += ("\n>>> referenced " + Twine(undef.locs.size() - i) + " more times")
7440b57cec5SDimitry Andric                .str();
7450b57cec5SDimitry Andric 
746480093f4SDimitry Andric   if (correctSpelling) {
747480093f4SDimitry Andric     std::string pre_hint = ": ", post_hint;
74804eeddc0SDimitry Andric     if (const Symbol *corrected =
74904eeddc0SDimitry Andric             getAlternativeSpelling(sym, pre_hint, post_hint)) {
750480093f4SDimitry Andric       msg += "\n>>> did you mean" + pre_hint + toString(*corrected) + post_hint;
75185868e8aSDimitry Andric       if (corrected->file)
75285868e8aSDimitry Andric         msg += "\n>>> defined in: " + toString(corrected->file);
75385868e8aSDimitry Andric     }
754480093f4SDimitry Andric   }
75585868e8aSDimitry Andric 
7560b57cec5SDimitry Andric   if (sym.getName().startswith("_ZTV"))
7575ffd83dbSDimitry Andric     msg +=
7585ffd83dbSDimitry Andric         "\n>>> the vtable symbol may be undefined because the class is missing "
7590b57cec5SDimitry Andric         "its key function (see https://lld.llvm.org/missingkeyfunction)";
7600eae32dcSDimitry Andric   if (config->gcSections && config->zStartStopGC &&
7610eae32dcSDimitry Andric       sym.getName().startswith("__start_")) {
7620eae32dcSDimitry Andric     msg += "\n>>> the encapsulation symbol needs to be retained under "
7630eae32dcSDimitry Andric            "--gc-sections properly; consider -z nostart-stop-gc "
7640eae32dcSDimitry Andric            "(see https://lld.llvm.org/ELF/start-stop-gc)";
7650eae32dcSDimitry Andric   }
7660b57cec5SDimitry Andric 
7670b57cec5SDimitry Andric   if (undef.isWarning)
7680b57cec5SDimitry Andric     warn(msg);
7690b57cec5SDimitry Andric   else
770e8d8bef9SDimitry Andric     error(msg, ErrorTag::SymbolNotFound, {sym.getName()});
7710b57cec5SDimitry Andric }
7720b57cec5SDimitry Andric 
77381ad6265SDimitry Andric void elf::reportUndefinedSymbols() {
7740b57cec5SDimitry Andric   // Find the first "undefined symbol" diagnostic for each diagnostic, and
7750b57cec5SDimitry Andric   // collect all "referenced from" lines at the first diagnostic.
7760b57cec5SDimitry Andric   DenseMap<Symbol *, UndefinedDiag *> firstRef;
7770b57cec5SDimitry Andric   for (UndefinedDiag &undef : undefs) {
7780b57cec5SDimitry Andric     assert(undef.locs.size() == 1);
7790b57cec5SDimitry Andric     if (UndefinedDiag *canon = firstRef.lookup(undef.sym)) {
7800b57cec5SDimitry Andric       canon->locs.push_back(undef.locs[0]);
7810b57cec5SDimitry Andric       undef.locs.clear();
7820b57cec5SDimitry Andric     } else
7830b57cec5SDimitry Andric       firstRef[undef.sym] = &undef;
7840b57cec5SDimitry Andric   }
7850b57cec5SDimitry Andric 
78685868e8aSDimitry Andric   // Enable spell corrector for the first 2 diagnostics.
787bdd1243dSDimitry Andric   for (const auto &[i, undef] : llvm::enumerate(undefs))
788bdd1243dSDimitry Andric     if (!undef.locs.empty())
789bdd1243dSDimitry Andric       reportUndefinedSymbol(undef, i < 2);
7900b57cec5SDimitry Andric   undefs.clear();
7910b57cec5SDimitry Andric }
7920b57cec5SDimitry Andric 
7930b57cec5SDimitry Andric // Report an undefined symbol if necessary.
7940b57cec5SDimitry Andric // Returns true if the undefined symbol will produce an error message.
79504eeddc0SDimitry Andric static bool maybeReportUndefined(Undefined &sym, InputSectionBase &sec,
7960b57cec5SDimitry Andric                                  uint64_t offset) {
797bdd1243dSDimitry Andric   std::lock_guard<std::mutex> lock(relocMutex);
798e8d8bef9SDimitry Andric   // If versioned, issue an error (even if the symbol is weak) because we don't
799e8d8bef9SDimitry Andric   // know the defining filename which is required to construct a Verneed entry.
80004eeddc0SDimitry Andric   if (sym.hasVersionSuffix) {
801e8d8bef9SDimitry Andric     undefs.push_back({&sym, {{&sec, offset}}, false});
802e8d8bef9SDimitry Andric     return true;
803e8d8bef9SDimitry Andric   }
804e8d8bef9SDimitry Andric   if (sym.isWeak())
8050b57cec5SDimitry Andric     return false;
8060b57cec5SDimitry Andric 
807bdd1243dSDimitry Andric   bool canBeExternal = !sym.isLocal() && sym.visibility() == STV_DEFAULT;
8080b57cec5SDimitry Andric   if (config->unresolvedSymbols == UnresolvedPolicy::Ignore && canBeExternal)
8090b57cec5SDimitry Andric     return false;
8100b57cec5SDimitry Andric 
8110b57cec5SDimitry Andric   // clang (as of 2019-06-12) / gcc (as of 8.2.1) PPC64 may emit a .rela.toc
8120b57cec5SDimitry Andric   // which references a switch table in a discarded .rodata/.text section. The
8130b57cec5SDimitry Andric   // .toc and the .rela.toc are incorrectly not placed in the comdat. The ELF
8140b57cec5SDimitry Andric   // spec says references from outside the group to a STB_LOCAL symbol are not
8150b57cec5SDimitry Andric   // allowed. Work around the bug.
8165a0c326fSDimitry Andric   //
8175a0c326fSDimitry Andric   // PPC32 .got2 is similar but cannot be fixed. Multiple .got2 is infeasible
8185a0c326fSDimitry Andric   // because .LC0-.LTOC is not representable if the two labels are in different
8195a0c326fSDimitry Andric   // .got2
82004eeddc0SDimitry Andric   if (sym.discardedSecIdx != 0 && (sec.name == ".got2" || sec.name == ".toc"))
8210b57cec5SDimitry Andric     return false;
8220b57cec5SDimitry Andric 
8230b57cec5SDimitry Andric   bool isWarning =
8240b57cec5SDimitry Andric       (config->unresolvedSymbols == UnresolvedPolicy::Warn && canBeExternal) ||
8250b57cec5SDimitry Andric       config->noinhibitExec;
8260b57cec5SDimitry Andric   undefs.push_back({&sym, {{&sec, offset}}, isWarning});
8270b57cec5SDimitry Andric   return !isWarning;
8280b57cec5SDimitry Andric }
8290b57cec5SDimitry Andric 
8300b57cec5SDimitry Andric // MIPS N32 ABI treats series of successive relocations with the same offset
8310b57cec5SDimitry Andric // as a single relocation. The similar approach used by N64 ABI, but this ABI
8320b57cec5SDimitry Andric // packs all relocations into the single relocation record. Here we emulate
8330b57cec5SDimitry Andric // this for the N32 ABI. Iterate over relocation with the same offset and put
8340b57cec5SDimitry Andric // theirs types into the single bit-set.
83504eeddc0SDimitry Andric template <class RelTy>
83604eeddc0SDimitry Andric RelType RelocationScanner::getMipsN32RelType(RelTy *&rel) const {
8370b57cec5SDimitry Andric   RelType type = 0;
8380b57cec5SDimitry Andric   uint64_t offset = rel->r_offset;
8390b57cec5SDimitry Andric 
8400b57cec5SDimitry Andric   int n = 0;
84104eeddc0SDimitry Andric   while (rel != static_cast<const RelTy *>(end) && rel->r_offset == offset)
8420b57cec5SDimitry Andric     type |= (rel++)->getType(config->isMips64EL) << (8 * n++);
8430b57cec5SDimitry Andric   return type;
8440b57cec5SDimitry Andric }
8450b57cec5SDimitry Andric 
846bdd1243dSDimitry Andric template <bool shard = false>
8470eae32dcSDimitry Andric static void addRelativeReloc(InputSectionBase &isec, uint64_t offsetInSec,
848fe6060f1SDimitry Andric                              Symbol &sym, int64_t addend, RelExpr expr,
8490b57cec5SDimitry Andric                              RelType type) {
8500eae32dcSDimitry Andric   Partition &part = isec.getPartition();
8510b57cec5SDimitry Andric 
8520b57cec5SDimitry Andric   // Add a relative relocation. If relrDyn section is enabled, and the
8530b57cec5SDimitry Andric   // relocation offset is guaranteed to be even, add the relocation to
8540b57cec5SDimitry Andric   // the relrDyn section, otherwise add it to the relaDyn section.
8550b57cec5SDimitry Andric   // relrDyn sections don't support odd offsets. Also, relrDyn sections
8560b57cec5SDimitry Andric   // don't store the addend values, so we must write it to the relocated
8570b57cec5SDimitry Andric   // address.
858bdd1243dSDimitry Andric   if (part.relrDyn && isec.addralign >= 2 && offsetInSec % 2 == 0) {
859bdd1243dSDimitry Andric     isec.addReloc({expr, type, offsetInSec, addend, &sym});
860bdd1243dSDimitry Andric     if (shard)
861bdd1243dSDimitry Andric       part.relrDyn->relocsVec[parallel::getThreadIndex()].push_back(
862bdd1243dSDimitry Andric           {&isec, offsetInSec});
863bdd1243dSDimitry Andric     else
8640eae32dcSDimitry Andric       part.relrDyn->relocs.push_back({&isec, offsetInSec});
8650b57cec5SDimitry Andric     return;
8660b57cec5SDimitry Andric   }
867bdd1243dSDimitry Andric   part.relaDyn->addRelativeReloc<shard>(target->relativeRel, isec, offsetInSec,
868bdd1243dSDimitry Andric                                         sym, addend, type, expr);
8690b57cec5SDimitry Andric }
8700b57cec5SDimitry Andric 
871480093f4SDimitry Andric template <class PltSection, class GotPltSection>
8720eae32dcSDimitry Andric static void addPltEntry(PltSection &plt, GotPltSection &gotPlt,
8730eae32dcSDimitry Andric                         RelocationBaseSection &rel, RelType type, Symbol &sym) {
8740eae32dcSDimitry Andric   plt.addEntry(sym);
8750eae32dcSDimitry Andric   gotPlt.addEntry(sym);
8760eae32dcSDimitry Andric   rel.addReloc({type, &gotPlt, sym.getGotPltOffset(),
877fe6060f1SDimitry Andric                 sym.isPreemptible ? DynamicReloc::AgainstSymbol
878fe6060f1SDimitry Andric                                   : DynamicReloc::AddendOnlyWithTargetVA,
879fe6060f1SDimitry Andric                 sym, 0, R_ABS});
8800b57cec5SDimitry Andric }
8810b57cec5SDimitry Andric 
8820b57cec5SDimitry Andric static void addGotEntry(Symbol &sym) {
8830b57cec5SDimitry Andric   in.got->addEntry(sym);
8840b57cec5SDimitry Andric   uint64_t off = sym.getGotOffset();
8850b57cec5SDimitry Andric 
886349cc55cSDimitry Andric   // If preemptible, emit a GLOB_DAT relocation.
887349cc55cSDimitry Andric   if (sym.isPreemptible) {
88804eeddc0SDimitry Andric     mainPart->relaDyn->addReloc({target->gotRel, in.got.get(), off,
889349cc55cSDimitry Andric                                  DynamicReloc::AgainstSymbol, sym, 0, R_ABS});
8900b57cec5SDimitry Andric     return;
8910b57cec5SDimitry Andric   }
8920b57cec5SDimitry Andric 
893349cc55cSDimitry Andric   // Otherwise, the value is either a link-time constant or the load base
894349cc55cSDimitry Andric   // plus a constant.
895349cc55cSDimitry Andric   if (!config->isPic || isAbsolute(sym))
896bdd1243dSDimitry Andric     in.got->addConstant({R_ABS, target->symbolicRel, off, 0, &sym});
897349cc55cSDimitry Andric   else
8980eae32dcSDimitry Andric     addRelativeReloc(*in.got, off, sym, 0, R_ABS, target->symbolicRel);
899349cc55cSDimitry Andric }
900349cc55cSDimitry Andric 
901349cc55cSDimitry Andric static void addTpOffsetGotEntry(Symbol &sym) {
902349cc55cSDimitry Andric   in.got->addEntry(sym);
903349cc55cSDimitry Andric   uint64_t off = sym.getGotOffset();
904349cc55cSDimitry Andric   if (!sym.isPreemptible && !config->isPic) {
905bdd1243dSDimitry Andric     in.got->addConstant({R_TPREL, target->symbolicRel, off, 0, &sym});
9060b57cec5SDimitry Andric     return;
9070b57cec5SDimitry Andric   }
908fe6060f1SDimitry Andric   mainPart->relaDyn->addAddendOnlyRelocIfNonPreemptible(
9090eae32dcSDimitry Andric       target->tlsGotRel, *in.got, off, sym, target->symbolicRel);
9100b57cec5SDimitry Andric }
9110b57cec5SDimitry Andric 
9120b57cec5SDimitry Andric // Return true if we can define a symbol in the executable that
9130b57cec5SDimitry Andric // contains the value/function of a symbol defined in a shared
9140b57cec5SDimitry Andric // library.
9150b57cec5SDimitry Andric static bool canDefineSymbolInExecutable(Symbol &sym) {
9160b57cec5SDimitry Andric   // If the symbol has default visibility the symbol defined in the
9170b57cec5SDimitry Andric   // executable will preempt it.
9180b57cec5SDimitry Andric   // Note that we want the visibility of the shared symbol itself, not
919bdd1243dSDimitry Andric   // the visibility of the symbol in the output file we are producing.
920bdd1243dSDimitry Andric   if (!sym.dsoProtected)
9210b57cec5SDimitry Andric     return true;
9220b57cec5SDimitry Andric 
9230b57cec5SDimitry Andric   // If we are allowed to break address equality of functions, defining
9240b57cec5SDimitry Andric   // a plt entry will allow the program to call the function in the
9250b57cec5SDimitry Andric   // .so, but the .so and the executable will no agree on the address
9260b57cec5SDimitry Andric   // of the function. Similar logic for objects.
9270b57cec5SDimitry Andric   return ((sym.isFunc() && config->ignoreFunctionAddressEquality) ||
9280b57cec5SDimitry Andric           (sym.isObject() && config->ignoreDataAddressEquality));
9290b57cec5SDimitry Andric }
9300b57cec5SDimitry Andric 
931349cc55cSDimitry Andric // Returns true if a given relocation can be computed at link-time.
93281ad6265SDimitry Andric // This only handles relocation types expected in processAux.
933349cc55cSDimitry Andric //
934349cc55cSDimitry Andric // For instance, we know the offset from a relocation to its target at
935349cc55cSDimitry Andric // link-time if the relocation is PC-relative and refers a
936349cc55cSDimitry Andric // non-interposable function in the same executable. This function
937349cc55cSDimitry Andric // will return true for such relocation.
938349cc55cSDimitry Andric //
939349cc55cSDimitry Andric // If this function returns false, that means we need to emit a
940349cc55cSDimitry Andric // dynamic relocation so that the relocation will be fixed at load-time.
94104eeddc0SDimitry Andric bool RelocationScanner::isStaticLinkTimeConstant(RelExpr e, RelType type,
94204eeddc0SDimitry Andric                                                  const Symbol &sym,
94304eeddc0SDimitry Andric                                                  uint64_t relOff) const {
944349cc55cSDimitry Andric   // These expressions always compute a constant
945753f127fSDimitry Andric   if (oneof<R_GOTPLT, R_GOT_OFF, R_RELAX_HINT, R_MIPS_GOT_LOCAL_PAGE,
946753f127fSDimitry Andric             R_MIPS_GOTREL, R_MIPS_GOT_OFF, R_MIPS_GOT_OFF32, R_MIPS_GOT_GP_PC,
947349cc55cSDimitry Andric             R_AARCH64_GOT_PAGE_PC, R_GOT_PC, R_GOTONLY_PC, R_GOTPLTONLY_PC,
948349cc55cSDimitry Andric             R_PLT_PC, R_PLT_GOTPLT, R_PPC32_PLTREL, R_PPC64_CALL_PLT,
949349cc55cSDimitry Andric             R_PPC64_RELAX_TOC, R_RISCV_ADD, R_AARCH64_GOT_PAGE>(e))
950349cc55cSDimitry Andric     return true;
951349cc55cSDimitry Andric 
952349cc55cSDimitry Andric   // These never do, except if the entire file is position dependent or if
953349cc55cSDimitry Andric   // only the low bits are used.
954349cc55cSDimitry Andric   if (e == R_GOT || e == R_PLT)
955bdd1243dSDimitry Andric     return target->usesOnlyLowPageBits(type) || !config->isPic;
956349cc55cSDimitry Andric 
957349cc55cSDimitry Andric   if (sym.isPreemptible)
958349cc55cSDimitry Andric     return false;
959349cc55cSDimitry Andric   if (!config->isPic)
960349cc55cSDimitry Andric     return true;
961349cc55cSDimitry Andric 
962349cc55cSDimitry Andric   // The size of a non preemptible symbol is a constant.
963349cc55cSDimitry Andric   if (e == R_SIZE)
964349cc55cSDimitry Andric     return true;
965349cc55cSDimitry Andric 
966349cc55cSDimitry Andric   // For the target and the relocation, we want to know if they are
967349cc55cSDimitry Andric   // absolute or relative.
968349cc55cSDimitry Andric   bool absVal = isAbsoluteValue(sym);
969349cc55cSDimitry Andric   bool relE = isRelExpr(e);
970349cc55cSDimitry Andric   if (absVal && !relE)
971349cc55cSDimitry Andric     return true;
972349cc55cSDimitry Andric   if (!absVal && relE)
973349cc55cSDimitry Andric     return true;
974349cc55cSDimitry Andric   if (!absVal && !relE)
975bdd1243dSDimitry Andric     return target->usesOnlyLowPageBits(type);
976349cc55cSDimitry Andric 
977349cc55cSDimitry Andric   assert(absVal && relE);
978349cc55cSDimitry Andric 
979349cc55cSDimitry Andric   // Allow R_PLT_PC (optimized to R_PC here) to a hidden undefined weak symbol
980349cc55cSDimitry Andric   // in PIC mode. This is a little strange, but it allows us to link function
981349cc55cSDimitry Andric   // calls to such symbols (e.g. glibc/stdlib/exit.c:__run_exit_handlers).
982349cc55cSDimitry Andric   // Normally such a call will be guarded with a comparison, which will load a
983349cc55cSDimitry Andric   // zero from the GOT.
984349cc55cSDimitry Andric   if (sym.isUndefWeak())
985349cc55cSDimitry Andric     return true;
986349cc55cSDimitry Andric 
987349cc55cSDimitry Andric   // We set the final symbols values for linker script defined symbols later.
988349cc55cSDimitry Andric   // They always can be computed as a link time constant.
989349cc55cSDimitry Andric   if (sym.scriptDefined)
990349cc55cSDimitry Andric       return true;
991349cc55cSDimitry Andric 
992349cc55cSDimitry Andric   error("relocation " + toString(type) + " cannot refer to absolute symbol: " +
993bdd1243dSDimitry Andric         toString(sym) + getLocation(*sec, sym, relOff));
994349cc55cSDimitry Andric   return true;
995349cc55cSDimitry Andric }
996349cc55cSDimitry Andric 
9970b57cec5SDimitry Andric // The reason we have to do this early scan is as follows
9980b57cec5SDimitry Andric // * To mmap the output file, we need to know the size
9990b57cec5SDimitry Andric // * For that, we need to know how many dynamic relocs we will have.
10000b57cec5SDimitry Andric // It might be possible to avoid this by outputting the file with write:
10010b57cec5SDimitry Andric // * Write the allocated output sections, computing addresses.
10020b57cec5SDimitry Andric // * Apply relocations, recording which ones require a dynamic reloc.
10030b57cec5SDimitry Andric // * Write the dynamic relocations.
10040b57cec5SDimitry Andric // * Write the rest of the file.
10050b57cec5SDimitry Andric // This would have some drawbacks. For example, we would only know if .rela.dyn
10060b57cec5SDimitry Andric // is needed after applying relocations. If it is, it will go after rw and rx
10070b57cec5SDimitry Andric // sections. Given that it is ro, we will need an extra PT_LOAD. This
10080b57cec5SDimitry Andric // complicates things for the dynamic linker and means we would have to reserve
10090b57cec5SDimitry Andric // space for the extra PT_LOAD even if we end up not using it.
101004eeddc0SDimitry Andric void RelocationScanner::processAux(RelExpr expr, RelType type, uint64_t offset,
101104eeddc0SDimitry Andric                                    Symbol &sym, int64_t addend) const {
1012bdd1243dSDimitry Andric   // If non-ifunc non-preemptible, change PLT to direct call and optimize GOT
1013bdd1243dSDimitry Andric   // indirection.
1014bdd1243dSDimitry Andric   const bool isIfunc = sym.isGnuIFunc();
1015bdd1243dSDimitry Andric   if (!sym.isPreemptible && (!isIfunc || config->zIfuncNoplt)) {
1016bdd1243dSDimitry Andric     if (expr != R_GOT_PC) {
1017bdd1243dSDimitry Andric       // The 0x8000 bit of r_addend of R_PPC_PLTREL24 is used to choose call
1018bdd1243dSDimitry Andric       // stub type. It should be ignored if optimized to R_PC.
1019bdd1243dSDimitry Andric       if (config->emachine == EM_PPC && expr == R_PPC32_PLTREL)
1020bdd1243dSDimitry Andric         addend &= ~0x8000;
1021bdd1243dSDimitry Andric       // R_HEX_GD_PLT_B22_PCREL (call a@GDPLT) is transformed into
1022bdd1243dSDimitry Andric       // call __tls_get_addr even if the symbol is non-preemptible.
1023bdd1243dSDimitry Andric       if (!(config->emachine == EM_HEXAGON &&
1024bdd1243dSDimitry Andric             (type == R_HEX_GD_PLT_B22_PCREL ||
1025bdd1243dSDimitry Andric              type == R_HEX_GD_PLT_B22_PCREL_X ||
1026bdd1243dSDimitry Andric              type == R_HEX_GD_PLT_B32_PCREL_X)))
1027bdd1243dSDimitry Andric         expr = fromPlt(expr);
1028bdd1243dSDimitry Andric     } else if (!isAbsoluteValue(sym)) {
1029bdd1243dSDimitry Andric       expr =
1030bdd1243dSDimitry Andric           target->adjustGotPcExpr(type, addend, sec->content().data() + offset);
1031bdd1243dSDimitry Andric     }
1032bdd1243dSDimitry Andric   }
1033bdd1243dSDimitry Andric 
1034bdd1243dSDimitry Andric   // We were asked not to generate PLT entries for ifuncs. Instead, pass the
1035bdd1243dSDimitry Andric   // direct relocation on through.
1036bdd1243dSDimitry Andric   if (LLVM_UNLIKELY(isIfunc) && config->zIfuncNoplt) {
1037bdd1243dSDimitry Andric     std::lock_guard<std::mutex> lock(relocMutex);
1038bdd1243dSDimitry Andric     sym.exportDynamic = true;
1039bdd1243dSDimitry Andric     mainPart->relaDyn->addSymbolReloc(type, *sec, offset, sym, addend, type);
1040bdd1243dSDimitry Andric     return;
1041bdd1243dSDimitry Andric   }
1042bdd1243dSDimitry Andric 
1043bdd1243dSDimitry Andric   if (needsGot(expr)) {
1044bdd1243dSDimitry Andric     if (config->emachine == EM_MIPS) {
1045bdd1243dSDimitry Andric       // MIPS ABI has special rules to process GOT entries and doesn't
1046bdd1243dSDimitry Andric       // require relocation entries for them. A special case is TLS
1047bdd1243dSDimitry Andric       // relocations. In that case dynamic loader applies dynamic
1048bdd1243dSDimitry Andric       // relocations to initialize TLS GOT entries.
1049bdd1243dSDimitry Andric       // See "Global Offset Table" in Chapter 5 in the following document
1050bdd1243dSDimitry Andric       // for detailed description:
1051bdd1243dSDimitry Andric       // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1052bdd1243dSDimitry Andric       in.mipsGot->addEntry(*sec->file, sym, addend, expr);
1053bdd1243dSDimitry Andric     } else {
1054bdd1243dSDimitry Andric       sym.setFlags(NEEDS_GOT);
1055bdd1243dSDimitry Andric     }
1056bdd1243dSDimitry Andric   } else if (needsPlt(expr)) {
1057bdd1243dSDimitry Andric     sym.setFlags(NEEDS_PLT);
1058bdd1243dSDimitry Andric   } else if (LLVM_UNLIKELY(isIfunc)) {
1059bdd1243dSDimitry Andric     sym.setFlags(HAS_DIRECT_RELOC);
1060bdd1243dSDimitry Andric   }
1061bdd1243dSDimitry Andric 
10620b57cec5SDimitry Andric   // If the relocation is known to be a link-time constant, we know no dynamic
10630b57cec5SDimitry Andric   // relocation will be created, pass the control to relocateAlloc() or
10640b57cec5SDimitry Andric   // relocateNonAlloc() to resolve it.
10650b57cec5SDimitry Andric   //
1066fe6060f1SDimitry Andric   // The behavior of an undefined weak reference is implementation defined. For
1067fe6060f1SDimitry Andric   // non-link-time constants, we resolve relocations statically (let
1068fe6060f1SDimitry Andric   // relocate{,Non}Alloc() resolve them) for -no-pie and try producing dynamic
1069fe6060f1SDimitry Andric   // relocations for -pie and -shared.
1070fe6060f1SDimitry Andric   //
1071fe6060f1SDimitry Andric   // The general expectation of -no-pie static linking is that there is no
1072fe6060f1SDimitry Andric   // dynamic relocation (except IRELATIVE). Emitting dynamic relocations for
1073fe6060f1SDimitry Andric   // -shared matches the spirit of its -z undefs default. -pie has freedom on
1074fe6060f1SDimitry Andric   // choices, and we choose dynamic relocations to be consistent with the
1075fe6060f1SDimitry Andric   // handling of GOT-generating relocations.
107604eeddc0SDimitry Andric   if (isStaticLinkTimeConstant(expr, type, sym, offset) ||
1077fe6060f1SDimitry Andric       (!config->isPic && sym.isUndefWeak())) {
1078bdd1243dSDimitry Andric     sec->addReloc({expr, type, offset, addend, &sym});
10790b57cec5SDimitry Andric     return;
10800b57cec5SDimitry Andric   }
10810b57cec5SDimitry Andric 
1082*1ac55f4cSDimitry Andric   // Use a simple -z notext rule that treats all sections except .eh_frame as
1083*1ac55f4cSDimitry Andric   // writable. GNU ld does not produce dynamic relocations in .eh_frame (and our
1084*1ac55f4cSDimitry Andric   // SectionBase::getOffset would incorrectly adjust the offset).
1085*1ac55f4cSDimitry Andric   //
1086*1ac55f4cSDimitry Andric   // For MIPS, we don't implement GNU ld's DW_EH_PE_absptr to DW_EH_PE_pcrel
1087*1ac55f4cSDimitry Andric   // conversion. We still emit a dynamic relocation.
1088*1ac55f4cSDimitry Andric   bool canWrite = (sec->flags & SHF_WRITE) ||
1089*1ac55f4cSDimitry Andric                   !(config->zText ||
1090*1ac55f4cSDimitry Andric                     (isa<EhInputSection>(sec) && config->emachine != EM_MIPS));
10910b57cec5SDimitry Andric   if (canWrite) {
1092bdd1243dSDimitry Andric     RelType rel = target->getDynRel(type);
1093bdd1243dSDimitry Andric     if (expr == R_GOT || (rel == target->symbolicRel && !sym.isPreemptible)) {
1094bdd1243dSDimitry Andric       addRelativeReloc<true>(*sec, offset, sym, addend, expr, type);
10950b57cec5SDimitry Andric       return;
10960b57cec5SDimitry Andric     } else if (rel != 0) {
1097bdd1243dSDimitry Andric       if (config->emachine == EM_MIPS && rel == target->symbolicRel)
1098bdd1243dSDimitry Andric         rel = target->relativeRel;
1099bdd1243dSDimitry Andric       std::lock_guard<std::mutex> lock(relocMutex);
1100bdd1243dSDimitry Andric       sec->getPartition().relaDyn->addSymbolReloc(rel, *sec, offset, sym,
1101bdd1243dSDimitry Andric                                                   addend, type);
11020b57cec5SDimitry Andric 
11030b57cec5SDimitry Andric       // MIPS ABI turns using of GOT and dynamic relocations inside out.
11040b57cec5SDimitry Andric       // While regular ABI uses dynamic relocations to fill up GOT entries
11050b57cec5SDimitry Andric       // MIPS ABI requires dynamic linker to fills up GOT entries using
11060b57cec5SDimitry Andric       // specially sorted dynamic symbol table. This affects even dynamic
11070b57cec5SDimitry Andric       // relocations against symbols which do not require GOT entries
11080b57cec5SDimitry Andric       // creation explicitly, i.e. do not have any GOT-relocations. So if
11090b57cec5SDimitry Andric       // a preemptible symbol has a dynamic relocation we anyway have
11100b57cec5SDimitry Andric       // to create a GOT entry for it.
11110b57cec5SDimitry Andric       // If a non-preemptible symbol has a dynamic relocation against it,
11120b57cec5SDimitry Andric       // dynamic linker takes it st_value, adds offset and writes down
11130b57cec5SDimitry Andric       // result of the dynamic relocation. In case of preemptible symbol
11140b57cec5SDimitry Andric       // dynamic linker performs symbol resolution, writes the symbol value
11150b57cec5SDimitry Andric       // to the GOT entry and reads the GOT entry when it needs to perform
11160b57cec5SDimitry Andric       // a dynamic relocation.
11170b57cec5SDimitry Andric       // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19
11180b57cec5SDimitry Andric       if (config->emachine == EM_MIPS)
1119bdd1243dSDimitry Andric         in.mipsGot->addEntry(*sec->file, sym, addend, expr);
11200b57cec5SDimitry Andric       return;
11210b57cec5SDimitry Andric     }
11220b57cec5SDimitry Andric   }
11230b57cec5SDimitry Andric 
112485868e8aSDimitry Andric   // When producing an executable, we can perform copy relocations (for
112585868e8aSDimitry Andric   // STT_OBJECT) and canonical PLT (for STT_FUNC).
112685868e8aSDimitry Andric   if (!config->shared) {
11270b57cec5SDimitry Andric     if (!canDefineSymbolInExecutable(sym)) {
112885868e8aSDimitry Andric       errorOrWarn("cannot preempt symbol: " + toString(sym) +
1129bdd1243dSDimitry Andric                   getLocation(*sec, sym, offset));
11300b57cec5SDimitry Andric       return;
11310b57cec5SDimitry Andric     }
11320b57cec5SDimitry Andric 
11330b57cec5SDimitry Andric     if (sym.isObject()) {
11340b57cec5SDimitry Andric       // Produce a copy relocation.
11350b57cec5SDimitry Andric       if (auto *ss = dyn_cast<SharedSymbol>(&sym)) {
11360b57cec5SDimitry Andric         if (!config->zCopyreloc)
11370b57cec5SDimitry Andric           error("unresolvable relocation " + toString(type) +
11380b57cec5SDimitry Andric                 " against symbol '" + toString(*ss) +
11390b57cec5SDimitry Andric                 "'; recompile with -fPIC or remove '-z nocopyreloc'" +
1140bdd1243dSDimitry Andric                 getLocation(*sec, sym, offset));
1141bdd1243dSDimitry Andric         sym.setFlags(NEEDS_COPY);
11420b57cec5SDimitry Andric       }
1143bdd1243dSDimitry Andric       sec->addReloc({expr, type, offset, addend, &sym});
11440b57cec5SDimitry Andric       return;
11450b57cec5SDimitry Andric     }
11460b57cec5SDimitry Andric 
11470b57cec5SDimitry Andric     // This handles a non PIC program call to function in a shared library. In
11480b57cec5SDimitry Andric     // an ideal world, we could just report an error saying the relocation can
11490b57cec5SDimitry Andric     // overflow at runtime. In the real world with glibc, crt1.o has a
11500b57cec5SDimitry Andric     // R_X86_64_PC32 pointing to libc.so.
11510b57cec5SDimitry Andric     //
11520b57cec5SDimitry Andric     // The general idea on how to handle such cases is to create a PLT entry and
11530b57cec5SDimitry Andric     // use that as the function value.
11540b57cec5SDimitry Andric     //
11550b57cec5SDimitry Andric     // For the static linking part, we just return a plt expr and everything
11560b57cec5SDimitry Andric     // else will use the PLT entry as the address.
11570b57cec5SDimitry Andric     //
11580b57cec5SDimitry Andric     // The remaining problem is making sure pointer equality still works. We
11590b57cec5SDimitry Andric     // need the help of the dynamic linker for that. We let it know that we have
11600b57cec5SDimitry Andric     // a direct reference to a so symbol by creating an undefined symbol with a
11610b57cec5SDimitry Andric     // non zero st_value. Seeing that, the dynamic linker resolves the symbol to
11620b57cec5SDimitry Andric     // the value of the symbol we created. This is true even for got entries, so
11630b57cec5SDimitry Andric     // pointer equality is maintained. To avoid an infinite loop, the only entry
11640b57cec5SDimitry Andric     // that points to the real function is a dedicated got entry used by the
11650b57cec5SDimitry Andric     // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT,
11660b57cec5SDimitry Andric     // R_386_JMP_SLOT, etc).
11670b57cec5SDimitry Andric 
11680b57cec5SDimitry Andric     // For position independent executable on i386, the plt entry requires ebx
11690b57cec5SDimitry Andric     // to be set. This causes two problems:
11700b57cec5SDimitry Andric     // * If some code has a direct reference to a function, it was probably
11710b57cec5SDimitry Andric     //   compiled without -fPIE/-fPIC and doesn't maintain ebx.
11720b57cec5SDimitry Andric     // * If a library definition gets preempted to the executable, it will have
11730b57cec5SDimitry Andric     //   the wrong ebx value.
117485868e8aSDimitry Andric     if (sym.isFunc()) {
11750b57cec5SDimitry Andric       if (config->pie && config->emachine == EM_386)
11760b57cec5SDimitry Andric         errorOrWarn("symbol '" + toString(sym) +
11770b57cec5SDimitry Andric                     "' cannot be preempted; recompile with -fPIE" +
1178bdd1243dSDimitry Andric                     getLocation(*sec, sym, offset));
1179bdd1243dSDimitry Andric       sym.setFlags(NEEDS_COPY | NEEDS_PLT);
1180bdd1243dSDimitry Andric       sec->addReloc({expr, type, offset, addend, &sym});
11810b57cec5SDimitry Andric       return;
11820b57cec5SDimitry Andric     }
118385868e8aSDimitry Andric   }
118485868e8aSDimitry Andric 
1185349cc55cSDimitry Andric   errorOrWarn("relocation " + toString(type) + " cannot be used against " +
118685868e8aSDimitry Andric               (sym.getName().empty() ? "local symbol"
1187349cc55cSDimitry Andric                                      : "symbol '" + toString(sym) + "'") +
1188bdd1243dSDimitry Andric               "; recompile with -fPIC" + getLocation(*sec, sym, offset));
118985868e8aSDimitry Andric }
11900b57cec5SDimitry Andric 
1191349cc55cSDimitry Andric // This function is similar to the `handleTlsRelocation`. MIPS does not
1192349cc55cSDimitry Andric // support any relaxations for TLS relocations so by factoring out MIPS
1193349cc55cSDimitry Andric // handling in to the separate function we can simplify the code and do not
1194349cc55cSDimitry Andric // pollute other `handleTlsRelocation` by MIPS `ifs` statements.
1195349cc55cSDimitry Andric // Mips has a custom MipsGotSection that handles the writing of GOT entries
1196349cc55cSDimitry Andric // without dynamic relocations.
1197349cc55cSDimitry Andric static unsigned handleMipsTlsRelocation(RelType type, Symbol &sym,
1198349cc55cSDimitry Andric                                         InputSectionBase &c, uint64_t offset,
1199349cc55cSDimitry Andric                                         int64_t addend, RelExpr expr) {
1200349cc55cSDimitry Andric   if (expr == R_MIPS_TLSLD) {
1201349cc55cSDimitry Andric     in.mipsGot->addTlsIndex(*c.file);
1202bdd1243dSDimitry Andric     c.addReloc({expr, type, offset, addend, &sym});
1203349cc55cSDimitry Andric     return 1;
1204349cc55cSDimitry Andric   }
1205349cc55cSDimitry Andric   if (expr == R_MIPS_TLSGD) {
1206349cc55cSDimitry Andric     in.mipsGot->addDynTlsEntry(*c.file, sym);
1207bdd1243dSDimitry Andric     c.addReloc({expr, type, offset, addend, &sym});
1208349cc55cSDimitry Andric     return 1;
1209349cc55cSDimitry Andric   }
1210349cc55cSDimitry Andric   return 0;
1211349cc55cSDimitry Andric }
1212349cc55cSDimitry Andric 
1213349cc55cSDimitry Andric // Notes about General Dynamic and Local Dynamic TLS models below. They may
1214349cc55cSDimitry Andric // require the generation of a pair of GOT entries that have associated dynamic
1215349cc55cSDimitry Andric // relocations. The pair of GOT entries created are of the form GOT[e0] Module
1216349cc55cSDimitry Andric // Index (Used to find pointer to TLS block at run-time) GOT[e1] Offset of
1217349cc55cSDimitry Andric // symbol in TLS block.
1218349cc55cSDimitry Andric //
1219349cc55cSDimitry Andric // Returns the number of relocations processed.
122004eeddc0SDimitry Andric static unsigned handleTlsRelocation(RelType type, Symbol &sym,
122104eeddc0SDimitry Andric                                     InputSectionBase &c, uint64_t offset,
122204eeddc0SDimitry Andric                                     int64_t addend, RelExpr expr) {
1223bdd1243dSDimitry Andric   if (expr == R_TPREL || expr == R_TPREL_NEG) {
1224bdd1243dSDimitry Andric     if (config->shared) {
1225bdd1243dSDimitry Andric       errorOrWarn("relocation " + toString(type) + " against " + toString(sym) +
1226bdd1243dSDimitry Andric                   " cannot be used with -shared" + getLocation(c, sym, offset));
1227bdd1243dSDimitry Andric       return 1;
1228bdd1243dSDimitry Andric     }
1229349cc55cSDimitry Andric     return 0;
1230bdd1243dSDimitry Andric   }
1231349cc55cSDimitry Andric 
1232349cc55cSDimitry Andric   if (config->emachine == EM_MIPS)
1233349cc55cSDimitry Andric     return handleMipsTlsRelocation(type, sym, c, offset, addend, expr);
1234349cc55cSDimitry Andric 
1235349cc55cSDimitry Andric   if (oneof<R_AARCH64_TLSDESC_PAGE, R_TLSDESC, R_TLSDESC_CALL, R_TLSDESC_PC,
1236349cc55cSDimitry Andric             R_TLSDESC_GOTPLT>(expr) &&
1237349cc55cSDimitry Andric       config->shared) {
12380eae32dcSDimitry Andric     if (expr != R_TLSDESC_CALL) {
1239bdd1243dSDimitry Andric       sym.setFlags(NEEDS_TLSDESC);
1240bdd1243dSDimitry Andric       c.addReloc({expr, type, offset, addend, &sym});
12410eae32dcSDimitry Andric     }
1242349cc55cSDimitry Andric     return 1;
1243349cc55cSDimitry Andric   }
1244349cc55cSDimitry Andric 
1245349cc55cSDimitry Andric   // ARM, Hexagon and RISC-V do not support GD/LD to IE/LE relaxation.  For
1246349cc55cSDimitry Andric   // PPC64, if the file has missing R_PPC64_TLSGD/R_PPC64_TLSLD, disable
1247349cc55cSDimitry Andric   // relaxation as well.
1248349cc55cSDimitry Andric   bool toExecRelax = !config->shared && config->emachine != EM_ARM &&
1249349cc55cSDimitry Andric                      config->emachine != EM_HEXAGON &&
1250349cc55cSDimitry Andric                      config->emachine != EM_RISCV &&
1251349cc55cSDimitry Andric                      !c.file->ppc64DisableTLSRelax;
1252349cc55cSDimitry Andric 
1253349cc55cSDimitry Andric   // If we are producing an executable and the symbol is non-preemptable, it
1254349cc55cSDimitry Andric   // must be defined and the code sequence can be relaxed to use Local-Exec.
1255349cc55cSDimitry Andric   //
1256349cc55cSDimitry Andric   // ARM and RISC-V do not support any relaxations for TLS relocations, however,
1257349cc55cSDimitry Andric   // we can omit the DTPMOD dynamic relocations and resolve them at link time
1258349cc55cSDimitry Andric   // because them are always 1. This may be necessary for static linking as
1259349cc55cSDimitry Andric   // DTPMOD may not be expected at load time.
1260349cc55cSDimitry Andric   bool isLocalInExecutable = !sym.isPreemptible && !config->shared;
1261349cc55cSDimitry Andric 
1262349cc55cSDimitry Andric   // Local Dynamic is for access to module local TLS variables, while still
1263349cc55cSDimitry Andric   // being suitable for being dynamically loaded via dlopen. GOT[e0] is the
1264349cc55cSDimitry Andric   // module index, with a special value of 0 for the current module. GOT[e1] is
1265349cc55cSDimitry Andric   // unused. There only needs to be one module index entry.
1266349cc55cSDimitry Andric   if (oneof<R_TLSLD_GOT, R_TLSLD_GOTPLT, R_TLSLD_PC, R_TLSLD_HINT>(
1267349cc55cSDimitry Andric           expr)) {
1268349cc55cSDimitry Andric     // Local-Dynamic relocs can be relaxed to Local-Exec.
1269349cc55cSDimitry Andric     if (toExecRelax) {
1270bdd1243dSDimitry Andric       c.addReloc({target->adjustTlsExpr(type, R_RELAX_TLS_LD_TO_LE), type,
1271bdd1243dSDimitry Andric                   offset, addend, &sym});
1272349cc55cSDimitry Andric       return target->getTlsGdRelaxSkip(type);
1273349cc55cSDimitry Andric     }
1274349cc55cSDimitry Andric     if (expr == R_TLSLD_HINT)
1275349cc55cSDimitry Andric       return 1;
1276bdd1243dSDimitry Andric     ctx.needsTlsLd.store(true, std::memory_order_relaxed);
1277bdd1243dSDimitry Andric     c.addReloc({expr, type, offset, addend, &sym});
1278349cc55cSDimitry Andric     return 1;
1279349cc55cSDimitry Andric   }
1280349cc55cSDimitry Andric 
1281349cc55cSDimitry Andric   // Local-Dynamic relocs can be relaxed to Local-Exec.
1282349cc55cSDimitry Andric   if (expr == R_DTPREL) {
1283349cc55cSDimitry Andric     if (toExecRelax)
1284349cc55cSDimitry Andric       expr = target->adjustTlsExpr(type, R_RELAX_TLS_LD_TO_LE);
1285bdd1243dSDimitry Andric     c.addReloc({expr, type, offset, addend, &sym});
1286349cc55cSDimitry Andric     return 1;
1287349cc55cSDimitry Andric   }
1288349cc55cSDimitry Andric 
1289349cc55cSDimitry Andric   // Local-Dynamic sequence where offset of tls variable relative to dynamic
1290349cc55cSDimitry Andric   // thread pointer is stored in the got. This cannot be relaxed to Local-Exec.
1291349cc55cSDimitry Andric   if (expr == R_TLSLD_GOT_OFF) {
1292bdd1243dSDimitry Andric     sym.setFlags(NEEDS_GOT_DTPREL);
1293bdd1243dSDimitry Andric     c.addReloc({expr, type, offset, addend, &sym});
1294349cc55cSDimitry Andric     return 1;
1295349cc55cSDimitry Andric   }
1296349cc55cSDimitry Andric 
1297349cc55cSDimitry Andric   if (oneof<R_AARCH64_TLSDESC_PAGE, R_TLSDESC, R_TLSDESC_CALL, R_TLSDESC_PC,
1298349cc55cSDimitry Andric             R_TLSDESC_GOTPLT, R_TLSGD_GOT, R_TLSGD_GOTPLT, R_TLSGD_PC>(expr)) {
1299349cc55cSDimitry Andric     if (!toExecRelax) {
1300bdd1243dSDimitry Andric       sym.setFlags(NEEDS_TLSGD);
1301bdd1243dSDimitry Andric       c.addReloc({expr, type, offset, addend, &sym});
1302349cc55cSDimitry Andric       return 1;
1303349cc55cSDimitry Andric     }
1304349cc55cSDimitry Andric 
1305349cc55cSDimitry Andric     // Global-Dynamic relocs can be relaxed to Initial-Exec or Local-Exec
1306349cc55cSDimitry Andric     // depending on the symbol being locally defined or not.
1307349cc55cSDimitry Andric     if (sym.isPreemptible) {
1308bdd1243dSDimitry Andric       sym.setFlags(NEEDS_TLSGD_TO_IE);
1309bdd1243dSDimitry Andric       c.addReloc({target->adjustTlsExpr(type, R_RELAX_TLS_GD_TO_IE), type,
1310bdd1243dSDimitry Andric                   offset, addend, &sym});
1311349cc55cSDimitry Andric     } else {
1312bdd1243dSDimitry Andric       c.addReloc({target->adjustTlsExpr(type, R_RELAX_TLS_GD_TO_LE), type,
1313bdd1243dSDimitry Andric                   offset, addend, &sym});
1314349cc55cSDimitry Andric     }
1315349cc55cSDimitry Andric     return target->getTlsGdRelaxSkip(type);
1316349cc55cSDimitry Andric   }
1317349cc55cSDimitry Andric 
1318349cc55cSDimitry Andric   if (oneof<R_GOT, R_GOTPLT, R_GOT_PC, R_AARCH64_GOT_PAGE_PC, R_GOT_OFF,
1319349cc55cSDimitry Andric             R_TLSIE_HINT>(expr)) {
1320bdd1243dSDimitry Andric     ctx.hasTlsIe.store(true, std::memory_order_relaxed);
1321349cc55cSDimitry Andric     // Initial-Exec relocs can be relaxed to Local-Exec if the symbol is locally
1322349cc55cSDimitry Andric     // defined.
1323349cc55cSDimitry Andric     if (toExecRelax && isLocalInExecutable) {
1324bdd1243dSDimitry Andric       c.addReloc({R_RELAX_TLS_IE_TO_LE, type, offset, addend, &sym});
1325349cc55cSDimitry Andric     } else if (expr != R_TLSIE_HINT) {
1326bdd1243dSDimitry Andric       sym.setFlags(NEEDS_TLSIE);
1327349cc55cSDimitry Andric       // R_GOT needs a relative relocation for PIC on i386 and Hexagon.
1328349cc55cSDimitry Andric       if (expr == R_GOT && config->isPic && !target->usesOnlyLowPageBits(type))
1329bdd1243dSDimitry Andric         addRelativeReloc<true>(c, offset, sym, addend, expr, type);
1330349cc55cSDimitry Andric       else
1331bdd1243dSDimitry Andric         c.addReloc({expr, type, offset, addend, &sym});
1332349cc55cSDimitry Andric     }
1333349cc55cSDimitry Andric     return 1;
1334349cc55cSDimitry Andric   }
1335349cc55cSDimitry Andric 
1336349cc55cSDimitry Andric   return 0;
13370b57cec5SDimitry Andric }
13380b57cec5SDimitry Andric 
133904eeddc0SDimitry Andric template <class ELFT, class RelTy> void RelocationScanner::scanOne(RelTy *&i) {
13400b57cec5SDimitry Andric   const RelTy &rel = *i;
13410b57cec5SDimitry Andric   uint32_t symIndex = rel.getSymbol(config->isMips64EL);
1342bdd1243dSDimitry Andric   Symbol &sym = sec->getFile<ELFT>()->getSymbol(symIndex);
13430b57cec5SDimitry Andric   RelType type;
13440b57cec5SDimitry Andric   if (config->mipsN32Abi) {
134504eeddc0SDimitry Andric     type = getMipsN32RelType(i);
13460b57cec5SDimitry Andric   } else {
13470b57cec5SDimitry Andric     type = rel.getType(config->isMips64EL);
13480b57cec5SDimitry Andric     ++i;
13490b57cec5SDimitry Andric   }
13500b57cec5SDimitry Andric   // Get an offset in an output section this relocation is applied to.
135104eeddc0SDimitry Andric   uint64_t offset = getter.get(rel.r_offset);
13520b57cec5SDimitry Andric   if (offset == uint64_t(-1))
13530b57cec5SDimitry Andric     return;
13540b57cec5SDimitry Andric 
1355bdd1243dSDimitry Andric   RelExpr expr = target->getRelExpr(type, sym, sec->content().data() + offset);
1356bdd1243dSDimitry Andric   int64_t addend = RelTy::IsRela
1357bdd1243dSDimitry Andric                        ? getAddend<ELFT>(rel)
1358bdd1243dSDimitry Andric                        : target->getImplicitAddend(
1359bdd1243dSDimitry Andric                              sec->content().data() + rel.r_offset, type);
1360bdd1243dSDimitry Andric   if (LLVM_UNLIKELY(config->emachine == EM_MIPS))
1361bdd1243dSDimitry Andric     addend += computeMipsAddend<ELFT>(rel, expr, sym.isLocal());
1362bdd1243dSDimitry Andric   else if (config->emachine == EM_PPC64 && config->isPic && type == R_PPC64_TOC)
1363bdd1243dSDimitry Andric     addend += getPPC64TocBase();
13640b57cec5SDimitry Andric 
1365480093f4SDimitry Andric   // Ignore R_*_NONE and other marker relocations.
1366480093f4SDimitry Andric   if (expr == R_NONE)
13670b57cec5SDimitry Andric     return;
13680b57cec5SDimitry Andric 
1369bdd1243dSDimitry Andric   // Error if the target symbol is undefined. Symbol index 0 may be used by
1370bdd1243dSDimitry Andric   // marker relocations, e.g. R_*_NONE and R_ARM_V4BX. Don't error on them.
1371bdd1243dSDimitry Andric   if (sym.isUndefined() && symIndex != 0 &&
1372bdd1243dSDimitry Andric       maybeReportUndefined(cast<Undefined>(sym), *sec, offset))
1373bdd1243dSDimitry Andric     return;
13740b57cec5SDimitry Andric 
13755ffd83dbSDimitry Andric   if (config->emachine == EM_PPC64) {
13765ffd83dbSDimitry Andric     // We can separate the small code model relocations into 2 categories:
13775ffd83dbSDimitry Andric     // 1) Those that access the compiler generated .toc sections.
13785ffd83dbSDimitry Andric     // 2) Those that access the linker allocated got entries.
13795ffd83dbSDimitry Andric     // lld allocates got entries to symbols on demand. Since we don't try to
13805ffd83dbSDimitry Andric     // sort the got entries in any way, we don't have to track which objects
13815ffd83dbSDimitry Andric     // have got-based small code model relocs. The .toc sections get placed
13825ffd83dbSDimitry Andric     // after the end of the linker allocated .got section and we do sort those
13835ffd83dbSDimitry Andric     // so sections addressed with small code model relocations come first.
1384349cc55cSDimitry Andric     if (type == R_PPC64_TOC16 || type == R_PPC64_TOC16_DS)
1385bdd1243dSDimitry Andric       sec->file->ppc64SmallCodeModelTocRelocs = true;
13865ffd83dbSDimitry Andric 
13875ffd83dbSDimitry Andric     // Record the TOC entry (.toc + addend) as not relaxable. See the comment in
13885ffd83dbSDimitry Andric     // InputSectionBase::relocateAlloc().
13895ffd83dbSDimitry Andric     if (type == R_PPC64_TOC16_LO && sym.isSection() && isa<Defined>(sym) &&
13905ffd83dbSDimitry Andric         cast<Defined>(sym).section->name == ".toc")
13915ffd83dbSDimitry Andric       ppc64noTocRelax.insert({&sym, addend});
1392e8d8bef9SDimitry Andric 
1393e8d8bef9SDimitry Andric     if ((type == R_PPC64_TLSGD && expr == R_TLSDESC_CALL) ||
1394e8d8bef9SDimitry Andric         (type == R_PPC64_TLSLD && expr == R_TLSLD_HINT)) {
1395e8d8bef9SDimitry Andric       if (i == end) {
1396e8d8bef9SDimitry Andric         errorOrWarn("R_PPC64_TLSGD/R_PPC64_TLSLD may not be the last "
1397e8d8bef9SDimitry Andric                     "relocation" +
1398bdd1243dSDimitry Andric                     getLocation(*sec, sym, offset));
1399e8d8bef9SDimitry Andric         return;
1400e8d8bef9SDimitry Andric       }
1401e8d8bef9SDimitry Andric 
1402e8d8bef9SDimitry Andric       // Offset the 4-byte aligned R_PPC64_TLSGD by one byte in the NOTOC case,
1403e8d8bef9SDimitry Andric       // so we can discern it later from the toc-case.
1404e8d8bef9SDimitry Andric       if (i->getType(/*isMips64EL=*/false) == R_PPC64_REL24_NOTOC)
1405e8d8bef9SDimitry Andric         ++offset;
1406e8d8bef9SDimitry Andric     }
14075ffd83dbSDimitry Andric   }
14085ffd83dbSDimitry Andric 
14090b57cec5SDimitry Andric   // If the relocation does not emit a GOT or GOTPLT entry but its computation
14100b57cec5SDimitry Andric   // uses their addresses, we need GOT or GOTPLT to be created.
14110b57cec5SDimitry Andric   //
1412349cc55cSDimitry Andric   // The 5 types that relative GOTPLT are all x86 and x86-64 specific.
1413349cc55cSDimitry Andric   if (oneof<R_GOTPLTONLY_PC, R_GOTPLTREL, R_GOTPLT, R_PLT_GOTPLT,
1414349cc55cSDimitry Andric             R_TLSDESC_GOTPLT, R_TLSGD_GOTPLT>(expr)) {
1415bdd1243dSDimitry Andric     in.gotPlt->hasGotPltOffRel.store(true, std::memory_order_relaxed);
14160eae32dcSDimitry Andric   } else if (oneof<R_GOTONLY_PC, R_GOTREL, R_PPC32_PLTREL, R_PPC64_TOCBASE,
14170eae32dcSDimitry Andric                    R_PPC64_RELAX_TOC>(expr)) {
1418bdd1243dSDimitry Andric     in.got->hasGotOffRel.store(true, std::memory_order_relaxed);
14190b57cec5SDimitry Andric   }
14200b57cec5SDimitry Andric 
1421e8d8bef9SDimitry Andric   // Process TLS relocations, including relaxing TLS relocations. Note that
142204eeddc0SDimitry Andric   // R_TPREL and R_TPREL_NEG relocations are resolved in processAux.
1423bdd1243dSDimitry Andric   if (sym.isTls()) {
1424bdd1243dSDimitry Andric     if (unsigned processed =
1425bdd1243dSDimitry Andric             handleTlsRelocation(type, sym, *sec, offset, addend, expr)) {
1426bdd1243dSDimitry Andric       i += processed - 1;
1427e8d8bef9SDimitry Andric       return;
1428e8d8bef9SDimitry Andric     }
14290b57cec5SDimitry Andric   }
14300b57cec5SDimitry Andric 
143104eeddc0SDimitry Andric   processAux(expr, type, offset, sym, addend);
14320b57cec5SDimitry Andric }
14330b57cec5SDimitry Andric 
1434e8d8bef9SDimitry Andric // R_PPC64_TLSGD/R_PPC64_TLSLD is required to mark `bl __tls_get_addr` for
1435e8d8bef9SDimitry Andric // General Dynamic/Local Dynamic code sequences. If a GD/LD GOT relocation is
1436e8d8bef9SDimitry Andric // found but no R_PPC64_TLSGD/R_PPC64_TLSLD is seen, we assume that the
1437e8d8bef9SDimitry Andric // instructions are generated by very old IBM XL compilers. Work around the
1438e8d8bef9SDimitry Andric // issue by disabling GD/LD to IE/LE relaxation.
1439e8d8bef9SDimitry Andric template <class RelTy>
1440e8d8bef9SDimitry Andric static void checkPPC64TLSRelax(InputSectionBase &sec, ArrayRef<RelTy> rels) {
1441e8d8bef9SDimitry Andric   // Skip if sec is synthetic (sec.file is null) or if sec has been marked.
1442e8d8bef9SDimitry Andric   if (!sec.file || sec.file->ppc64DisableTLSRelax)
1443e8d8bef9SDimitry Andric     return;
1444e8d8bef9SDimitry Andric   bool hasGDLD = false;
1445e8d8bef9SDimitry Andric   for (const RelTy &rel : rels) {
1446e8d8bef9SDimitry Andric     RelType type = rel.getType(false);
1447e8d8bef9SDimitry Andric     switch (type) {
1448e8d8bef9SDimitry Andric     case R_PPC64_TLSGD:
1449e8d8bef9SDimitry Andric     case R_PPC64_TLSLD:
1450e8d8bef9SDimitry Andric       return; // Found a marker
1451e8d8bef9SDimitry Andric     case R_PPC64_GOT_TLSGD16:
1452e8d8bef9SDimitry Andric     case R_PPC64_GOT_TLSGD16_HA:
1453e8d8bef9SDimitry Andric     case R_PPC64_GOT_TLSGD16_HI:
1454e8d8bef9SDimitry Andric     case R_PPC64_GOT_TLSGD16_LO:
1455e8d8bef9SDimitry Andric     case R_PPC64_GOT_TLSLD16:
1456e8d8bef9SDimitry Andric     case R_PPC64_GOT_TLSLD16_HA:
1457e8d8bef9SDimitry Andric     case R_PPC64_GOT_TLSLD16_HI:
1458e8d8bef9SDimitry Andric     case R_PPC64_GOT_TLSLD16_LO:
1459e8d8bef9SDimitry Andric       hasGDLD = true;
1460e8d8bef9SDimitry Andric       break;
1461e8d8bef9SDimitry Andric     }
1462e8d8bef9SDimitry Andric   }
1463e8d8bef9SDimitry Andric   if (hasGDLD) {
1464e8d8bef9SDimitry Andric     sec.file->ppc64DisableTLSRelax = true;
1465e8d8bef9SDimitry Andric     warn(toString(sec.file) +
1466e8d8bef9SDimitry Andric          ": disable TLS relaxation due to R_PPC64_GOT_TLS* relocations without "
1467e8d8bef9SDimitry Andric          "R_PPC64_TLSGD/R_PPC64_TLSLD relocations");
1468e8d8bef9SDimitry Andric   }
1469e8d8bef9SDimitry Andric }
1470e8d8bef9SDimitry Andric 
14710b57cec5SDimitry Andric template <class ELFT, class RelTy>
147204eeddc0SDimitry Andric void RelocationScanner::scan(ArrayRef<RelTy> rels) {
1473bdd1243dSDimitry Andric   // Not all relocations end up in Sec->Relocations, but a lot do.
1474bdd1243dSDimitry Andric   sec->relocations.reserve(rels.size());
14750b57cec5SDimitry Andric 
1476e8d8bef9SDimitry Andric   if (config->emachine == EM_PPC64)
1477bdd1243dSDimitry Andric     checkPPC64TLSRelax<RelTy>(*sec, rels);
1478e8d8bef9SDimitry Andric 
1479fe6060f1SDimitry Andric   // For EhInputSection, OffsetGetter expects the relocations to be sorted by
1480fe6060f1SDimitry Andric   // r_offset. In rare cases (.eh_frame pieces are reordered by a linker
1481fe6060f1SDimitry Andric   // script), the relocations may be unordered.
1482fe6060f1SDimitry Andric   SmallVector<RelTy, 0> storage;
1483fe6060f1SDimitry Andric   if (isa<EhInputSection>(sec))
1484fe6060f1SDimitry Andric     rels = sortRels(rels, storage);
1485fe6060f1SDimitry Andric 
148604eeddc0SDimitry Andric   end = static_cast<const void *>(rels.end());
148704eeddc0SDimitry Andric   for (auto i = rels.begin(); i != end;)
148804eeddc0SDimitry Andric     scanOne<ELFT>(i);
14890b57cec5SDimitry Andric 
14900b57cec5SDimitry Andric   // Sort relocations by offset for more efficient searching for
14910b57cec5SDimitry Andric   // R_RISCV_PCREL_HI20 and R_PPC64_ADDR64.
14920b57cec5SDimitry Andric   if (config->emachine == EM_RISCV ||
1493bdd1243dSDimitry Andric       (config->emachine == EM_PPC64 && sec->name == ".toc"))
1494bdd1243dSDimitry Andric     llvm::stable_sort(sec->relocs(),
14950b57cec5SDimitry Andric                       [](const Relocation &lhs, const Relocation &rhs) {
14960b57cec5SDimitry Andric                         return lhs.offset < rhs.offset;
14970b57cec5SDimitry Andric                       });
14980b57cec5SDimitry Andric }
14990b57cec5SDimitry Andric 
1500bdd1243dSDimitry Andric template <class ELFT> void RelocationScanner::scanSection(InputSectionBase &s) {
1501bdd1243dSDimitry Andric   sec = &s;
1502bdd1243dSDimitry Andric   getter = OffsetGetter(s);
1503349cc55cSDimitry Andric   const RelsOrRelas<ELFT> rels = s.template relsOrRelas<ELFT>();
1504349cc55cSDimitry Andric   if (rels.areRelocsRel())
1505bdd1243dSDimitry Andric     scan<ELFT>(rels.rels);
15060b57cec5SDimitry Andric   else
1507bdd1243dSDimitry Andric     scan<ELFT>(rels.relas);
15080b57cec5SDimitry Andric }
15090b57cec5SDimitry Andric 
1510bdd1243dSDimitry Andric template <class ELFT> void elf::scanRelocations() {
1511bdd1243dSDimitry Andric   // Scan all relocations. Each relocation goes through a series of tests to
1512bdd1243dSDimitry Andric   // determine if it needs special treatment, such as creating GOT, PLT,
1513bdd1243dSDimitry Andric   // copy relocations, etc. Note that relocations for non-alloc sections are
1514bdd1243dSDimitry Andric   // directly processed by InputSection::relocateNonAlloc.
1515bdd1243dSDimitry Andric 
1516bdd1243dSDimitry Andric   // Deterministic parallellism needs sorting relocations which is unsuitable
1517bdd1243dSDimitry Andric   // for -z nocombreloc. MIPS and PPC64 use global states which are not suitable
1518bdd1243dSDimitry Andric   // for parallelism.
1519bdd1243dSDimitry Andric   bool serial = !config->zCombreloc || config->emachine == EM_MIPS ||
1520bdd1243dSDimitry Andric                 config->emachine == EM_PPC64;
1521bdd1243dSDimitry Andric   parallel::TaskGroup tg;
1522bdd1243dSDimitry Andric   for (ELFFileBase *f : ctx.objectFiles) {
1523bdd1243dSDimitry Andric     auto fn = [f]() {
1524bdd1243dSDimitry Andric       RelocationScanner scanner;
1525bdd1243dSDimitry Andric       for (InputSectionBase *s : f->getSections()) {
1526bdd1243dSDimitry Andric         if (s && s->kind() == SectionBase::Regular && s->isLive() &&
1527bdd1243dSDimitry Andric             (s->flags & SHF_ALLOC) &&
1528bdd1243dSDimitry Andric             !(s->type == SHT_ARM_EXIDX && config->emachine == EM_ARM))
1529bdd1243dSDimitry Andric           scanner.template scanSection<ELFT>(*s);
1530bdd1243dSDimitry Andric       }
1531bdd1243dSDimitry Andric     };
1532bdd1243dSDimitry Andric     if (serial)
1533bdd1243dSDimitry Andric       fn();
1534bdd1243dSDimitry Andric     else
1535bdd1243dSDimitry Andric       tg.execute(fn);
1536bdd1243dSDimitry Andric   }
1537bdd1243dSDimitry Andric 
1538bdd1243dSDimitry Andric   // Both the main thread and thread pool index 0 use getThreadIndex()==0. Be
1539bdd1243dSDimitry Andric   // careful that they don't concurrently run scanSections. When serial is
1540bdd1243dSDimitry Andric   // true, fn() has finished at this point, so running execute is safe.
1541bdd1243dSDimitry Andric   tg.execute([] {
1542bdd1243dSDimitry Andric     RelocationScanner scanner;
1543bdd1243dSDimitry Andric     for (Partition &part : partitions) {
1544bdd1243dSDimitry Andric       for (EhInputSection *sec : part.ehFrame->sections)
1545bdd1243dSDimitry Andric         scanner.template scanSection<ELFT>(*sec);
1546bdd1243dSDimitry Andric       if (part.armExidx && part.armExidx->isLive())
1547bdd1243dSDimitry Andric         for (InputSection *sec : part.armExidx->exidxSections)
1548bdd1243dSDimitry Andric           scanner.template scanSection<ELFT>(*sec);
1549bdd1243dSDimitry Andric     }
1550bdd1243dSDimitry Andric   });
1551bdd1243dSDimitry Andric }
1552bdd1243dSDimitry Andric 
1553bdd1243dSDimitry Andric static bool handleNonPreemptibleIfunc(Symbol &sym, uint16_t flags) {
15540eae32dcSDimitry Andric   // Handle a reference to a non-preemptible ifunc. These are special in a
15550eae32dcSDimitry Andric   // few ways:
15560eae32dcSDimitry Andric   //
15570eae32dcSDimitry Andric   // - Unlike most non-preemptible symbols, non-preemptible ifuncs do not have
15580eae32dcSDimitry Andric   //   a fixed value. But assuming that all references to the ifunc are
15590eae32dcSDimitry Andric   //   GOT-generating or PLT-generating, the handling of an ifunc is
15600eae32dcSDimitry Andric   //   relatively straightforward. We create a PLT entry in Iplt, which is
15610eae32dcSDimitry Andric   //   usually at the end of .plt, which makes an indirect call using a
15620eae32dcSDimitry Andric   //   matching GOT entry in igotPlt, which is usually at the end of .got.plt.
15630eae32dcSDimitry Andric   //   The GOT entry is relocated using an IRELATIVE relocation in relaIplt,
15640eae32dcSDimitry Andric   //   which is usually at the end of .rela.plt. Unlike most relocations in
15650eae32dcSDimitry Andric   //   .rela.plt, which may be evaluated lazily without -z now, dynamic
15660eae32dcSDimitry Andric   //   loaders evaluate IRELATIVE relocs eagerly, which means that for
15670eae32dcSDimitry Andric   //   IRELATIVE relocs only, GOT-generating relocations can point directly to
15680eae32dcSDimitry Andric   //   .got.plt without requiring a separate GOT entry.
15690eae32dcSDimitry Andric   //
15700eae32dcSDimitry Andric   // - Despite the fact that an ifunc does not have a fixed value, compilers
15710eae32dcSDimitry Andric   //   that are not passed -fPIC will assume that they do, and will emit
15720eae32dcSDimitry Andric   //   direct (non-GOT-generating, non-PLT-generating) relocations to the
15730eae32dcSDimitry Andric   //   symbol. This means that if a direct relocation to the symbol is
15740eae32dcSDimitry Andric   //   seen, the linker must set a value for the symbol, and this value must
15750eae32dcSDimitry Andric   //   be consistent no matter what type of reference is made to the symbol.
15760eae32dcSDimitry Andric   //   This can be done by creating a PLT entry for the symbol in the way
15770eae32dcSDimitry Andric   //   described above and making it canonical, that is, making all references
15780eae32dcSDimitry Andric   //   point to the PLT entry instead of the resolver. In lld we also store
15790eae32dcSDimitry Andric   //   the address of the PLT entry in the dynamic symbol table, which means
15800eae32dcSDimitry Andric   //   that the symbol will also have the same value in other modules.
15810eae32dcSDimitry Andric   //   Because the value loaded from the GOT needs to be consistent with
15820eae32dcSDimitry Andric   //   the value computed using a direct relocation, a non-preemptible ifunc
15830eae32dcSDimitry Andric   //   may end up with two GOT entries, one in .got.plt that points to the
15840eae32dcSDimitry Andric   //   address returned by the resolver and is used only by the PLT entry,
15850eae32dcSDimitry Andric   //   and another in .got that points to the PLT entry and is used by
15860eae32dcSDimitry Andric   //   GOT-generating relocations.
15870eae32dcSDimitry Andric   //
15880eae32dcSDimitry Andric   // - The fact that these symbols do not have a fixed value makes them an
15890eae32dcSDimitry Andric   //   exception to the general rule that a statically linked executable does
15900eae32dcSDimitry Andric   //   not require any form of dynamic relocation. To handle these relocations
15910eae32dcSDimitry Andric   //   correctly, the IRELATIVE relocations are stored in an array which a
15920eae32dcSDimitry Andric   //   statically linked executable's startup code must enumerate using the
15930eae32dcSDimitry Andric   //   linker-defined symbols __rela?_iplt_{start,end}.
15940eae32dcSDimitry Andric   if (!sym.isGnuIFunc() || sym.isPreemptible || config->zIfuncNoplt)
15950eae32dcSDimitry Andric     return false;
15960eae32dcSDimitry Andric   // Skip unreferenced non-preemptible ifunc.
1597bdd1243dSDimitry Andric   if (!(flags & (NEEDS_GOT | NEEDS_PLT | HAS_DIRECT_RELOC)))
15980eae32dcSDimitry Andric     return true;
15990eae32dcSDimitry Andric 
16000eae32dcSDimitry Andric   sym.isInIplt = true;
16010eae32dcSDimitry Andric 
16020eae32dcSDimitry Andric   // Create an Iplt and the associated IRELATIVE relocation pointing to the
16030eae32dcSDimitry Andric   // original section/value pairs. For non-GOT non-PLT relocation case below, we
16040eae32dcSDimitry Andric   // may alter section/value, so create a copy of the symbol to make
16050eae32dcSDimitry Andric   // section/value fixed.
16060eae32dcSDimitry Andric   auto *directSym = makeDefined(cast<Defined>(sym));
160704eeddc0SDimitry Andric   directSym->allocateAux();
16080eae32dcSDimitry Andric   addPltEntry(*in.iplt, *in.igotPlt, *in.relaIplt, target->iRelativeRel,
16090eae32dcSDimitry Andric               *directSym);
161004eeddc0SDimitry Andric   sym.allocateAux();
161104eeddc0SDimitry Andric   symAux.back().pltIdx = symAux[directSym->auxIdx].pltIdx;
16120eae32dcSDimitry Andric 
1613bdd1243dSDimitry Andric   if (flags & HAS_DIRECT_RELOC) {
16140eae32dcSDimitry Andric     // Change the value to the IPLT and redirect all references to it.
16150eae32dcSDimitry Andric     auto &d = cast<Defined>(sym);
161604eeddc0SDimitry Andric     d.section = in.iplt.get();
161704eeddc0SDimitry Andric     d.value = d.getPltIdx() * target->ipltEntrySize;
16180eae32dcSDimitry Andric     d.size = 0;
16190eae32dcSDimitry Andric     // It's important to set the symbol type here so that dynamic loaders
16200eae32dcSDimitry Andric     // don't try to call the PLT as if it were an ifunc resolver.
16210eae32dcSDimitry Andric     d.type = STT_FUNC;
16220eae32dcSDimitry Andric 
1623bdd1243dSDimitry Andric     if (flags & NEEDS_GOT)
16240eae32dcSDimitry Andric       addGotEntry(sym);
1625bdd1243dSDimitry Andric   } else if (flags & NEEDS_GOT) {
16260eae32dcSDimitry Andric     // Redirect GOT accesses to point to the Igot.
16270eae32dcSDimitry Andric     sym.gotInIgot = true;
16280eae32dcSDimitry Andric   }
16290eae32dcSDimitry Andric   return true;
16300eae32dcSDimitry Andric }
16310eae32dcSDimitry Andric 
16320eae32dcSDimitry Andric void elf::postScanRelocations() {
16330eae32dcSDimitry Andric   auto fn = [](Symbol &sym) {
1634bdd1243dSDimitry Andric     auto flags = sym.flags.load(std::memory_order_relaxed);
1635bdd1243dSDimitry Andric     if (handleNonPreemptibleIfunc(sym, flags))
16360eae32dcSDimitry Andric       return;
163704eeddc0SDimitry Andric     if (!sym.needsDynReloc())
163804eeddc0SDimitry Andric       return;
163904eeddc0SDimitry Andric     sym.allocateAux();
164004eeddc0SDimitry Andric 
1641bdd1243dSDimitry Andric     if (flags & NEEDS_GOT)
16420eae32dcSDimitry Andric       addGotEntry(sym);
1643bdd1243dSDimitry Andric     if (flags & NEEDS_PLT)
16440eae32dcSDimitry Andric       addPltEntry(*in.plt, *in.gotPlt, *in.relaPlt, target->pltRel, sym);
1645bdd1243dSDimitry Andric     if (flags & NEEDS_COPY) {
16460eae32dcSDimitry Andric       if (sym.isObject()) {
164781ad6265SDimitry Andric         invokeELFT(addCopyRelSymbol, cast<SharedSymbol>(sym));
1648bdd1243dSDimitry Andric         // NEEDS_COPY is cleared for sym and its aliases so that in
1649bdd1243dSDimitry Andric         // later iterations aliases won't cause redundant copies.
1650bdd1243dSDimitry Andric         assert(!sym.hasFlag(NEEDS_COPY));
16510eae32dcSDimitry Andric       } else {
1652bdd1243dSDimitry Andric         assert(sym.isFunc() && sym.hasFlag(NEEDS_PLT));
16530eae32dcSDimitry Andric         if (!sym.isDefined()) {
165404eeddc0SDimitry Andric           replaceWithDefined(sym, *in.plt,
165504eeddc0SDimitry Andric                              target->pltHeaderSize +
165604eeddc0SDimitry Andric                                  target->pltEntrySize * sym.getPltIdx(),
165704eeddc0SDimitry Andric                              0);
1658bdd1243dSDimitry Andric           sym.setFlags(NEEDS_COPY);
16590eae32dcSDimitry Andric           if (config->emachine == EM_PPC) {
16600eae32dcSDimitry Andric             // PPC32 canonical PLT entries are at the beginning of .glink
16610eae32dcSDimitry Andric             cast<Defined>(sym).value = in.plt->headerSize;
16620eae32dcSDimitry Andric             in.plt->headerSize += 16;
16630eae32dcSDimitry Andric             cast<PPC32GlinkSection>(*in.plt).canonical_plts.push_back(&sym);
16640eae32dcSDimitry Andric           }
16650eae32dcSDimitry Andric         }
16660eae32dcSDimitry Andric       }
16670eae32dcSDimitry Andric     }
16680eae32dcSDimitry Andric 
16690eae32dcSDimitry Andric     if (!sym.isTls())
16700eae32dcSDimitry Andric       return;
16710eae32dcSDimitry Andric     bool isLocalInExecutable = !sym.isPreemptible && !config->shared;
1672bdd1243dSDimitry Andric     GotSection *got = in.got.get();
16730eae32dcSDimitry Andric 
1674bdd1243dSDimitry Andric     if (flags & NEEDS_TLSDESC) {
1675bdd1243dSDimitry Andric       got->addTlsDescEntry(sym);
16760eae32dcSDimitry Andric       mainPart->relaDyn->addAddendOnlyRelocIfNonPreemptible(
1677bdd1243dSDimitry Andric           target->tlsDescRel, *got, got->getTlsDescOffset(sym), sym,
16780eae32dcSDimitry Andric           target->tlsDescRel);
16790eae32dcSDimitry Andric     }
1680bdd1243dSDimitry Andric     if (flags & NEEDS_TLSGD) {
1681bdd1243dSDimitry Andric       got->addDynTlsEntry(sym);
1682bdd1243dSDimitry Andric       uint64_t off = got->getGlobalDynOffset(sym);
16830eae32dcSDimitry Andric       if (isLocalInExecutable)
16840eae32dcSDimitry Andric         // Write one to the GOT slot.
1685bdd1243dSDimitry Andric         got->addConstant({R_ADDEND, target->symbolicRel, off, 1, &sym});
16860eae32dcSDimitry Andric       else
1687bdd1243dSDimitry Andric         mainPart->relaDyn->addSymbolReloc(target->tlsModuleIndexRel, *got, off,
1688bdd1243dSDimitry Andric                                           sym);
16890eae32dcSDimitry Andric 
16900eae32dcSDimitry Andric       // If the symbol is preemptible we need the dynamic linker to write
16910eae32dcSDimitry Andric       // the offset too.
16920eae32dcSDimitry Andric       uint64_t offsetOff = off + config->wordsize;
16930eae32dcSDimitry Andric       if (sym.isPreemptible)
1694bdd1243dSDimitry Andric         mainPart->relaDyn->addSymbolReloc(target->tlsOffsetRel, *got, offsetOff,
1695bdd1243dSDimitry Andric                                           sym);
16960eae32dcSDimitry Andric       else
1697bdd1243dSDimitry Andric         got->addConstant({R_ABS, target->tlsOffsetRel, offsetOff, 0, &sym});
16980eae32dcSDimitry Andric     }
1699bdd1243dSDimitry Andric     if (flags & NEEDS_TLSGD_TO_IE) {
1700bdd1243dSDimitry Andric       got->addEntry(sym);
1701bdd1243dSDimitry Andric       mainPart->relaDyn->addSymbolReloc(target->tlsGotRel, *got,
17020eae32dcSDimitry Andric                                         sym.getGotOffset(), sym);
17030eae32dcSDimitry Andric     }
1704bdd1243dSDimitry Andric     if (flags & NEEDS_GOT_DTPREL) {
1705bdd1243dSDimitry Andric       got->addEntry(sym);
1706bdd1243dSDimitry Andric       got->addConstant(
17070eae32dcSDimitry Andric           {R_ABS, target->tlsOffsetRel, sym.getGotOffset(), 0, &sym});
17080eae32dcSDimitry Andric     }
17090eae32dcSDimitry Andric 
1710bdd1243dSDimitry Andric     if ((flags & NEEDS_TLSIE) && !(flags & NEEDS_TLSGD_TO_IE))
17110eae32dcSDimitry Andric       addTpOffsetGotEntry(sym);
17120eae32dcSDimitry Andric   };
171304eeddc0SDimitry Andric 
1714bdd1243dSDimitry Andric   GotSection *got = in.got.get();
1715bdd1243dSDimitry Andric   if (ctx.needsTlsLd.load(std::memory_order_relaxed) && got->addTlsIndex()) {
171681ad6265SDimitry Andric     static Undefined dummy(nullptr, "", STB_LOCAL, 0, 0);
171781ad6265SDimitry Andric     if (config->shared)
171881ad6265SDimitry Andric       mainPart->relaDyn->addReloc(
1719bdd1243dSDimitry Andric           {target->tlsModuleIndexRel, got, got->getTlsIndexOff()});
172081ad6265SDimitry Andric     else
1721bdd1243dSDimitry Andric       got->addConstant(
1722bdd1243dSDimitry Andric           {R_ADDEND, target->symbolicRel, got->getTlsIndexOff(), 1, &dummy});
172381ad6265SDimitry Andric   }
172481ad6265SDimitry Andric 
1725bdd1243dSDimitry Andric   assert(symAux.size() == 1);
1726bdd1243dSDimitry Andric   for (Symbol *sym : symtab.getSymbols())
17270eae32dcSDimitry Andric     fn(*sym);
17280eae32dcSDimitry Andric 
17290eae32dcSDimitry Andric   // Local symbols may need the aforementioned non-preemptible ifunc and GOT
17300eae32dcSDimitry Andric   // handling. They don't need regular PLT.
1731bdd1243dSDimitry Andric   for (ELFFileBase *file : ctx.objectFiles)
173204eeddc0SDimitry Andric     for (Symbol *sym : file->getLocalSymbols())
17330eae32dcSDimitry Andric       fn(*sym);
17340eae32dcSDimitry Andric }
17350eae32dcSDimitry Andric 
17360b57cec5SDimitry Andric static bool mergeCmp(const InputSection *a, const InputSection *b) {
17370b57cec5SDimitry Andric   // std::merge requires a strict weak ordering.
17380b57cec5SDimitry Andric   if (a->outSecOff < b->outSecOff)
17390b57cec5SDimitry Andric     return true;
17400b57cec5SDimitry Andric 
174161cfbce3SDimitry Andric   // FIXME dyn_cast<ThunkSection> is non-null for any SyntheticSection.
174261cfbce3SDimitry Andric   if (a->outSecOff == b->outSecOff && a != b) {
17430b57cec5SDimitry Andric     auto *ta = dyn_cast<ThunkSection>(a);
17440b57cec5SDimitry Andric     auto *tb = dyn_cast<ThunkSection>(b);
17450b57cec5SDimitry Andric 
17460b57cec5SDimitry Andric     // Check if Thunk is immediately before any specific Target
17470b57cec5SDimitry Andric     // InputSection for example Mips LA25 Thunks.
17480b57cec5SDimitry Andric     if (ta && ta->getTargetInputSection() == b)
17490b57cec5SDimitry Andric       return true;
17500b57cec5SDimitry Andric 
17510b57cec5SDimitry Andric     // Place Thunk Sections without specific targets before
17520b57cec5SDimitry Andric     // non-Thunk Sections.
17530b57cec5SDimitry Andric     if (ta && !tb && !ta->getTargetInputSection())
17540b57cec5SDimitry Andric       return true;
17550b57cec5SDimitry Andric   }
17560b57cec5SDimitry Andric 
17570b57cec5SDimitry Andric   return false;
17580b57cec5SDimitry Andric }
17590b57cec5SDimitry Andric 
17600b57cec5SDimitry Andric // Call Fn on every executable InputSection accessed via the linker script
17610b57cec5SDimitry Andric // InputSectionDescription::Sections.
17620b57cec5SDimitry Andric static void forEachInputSectionDescription(
17630b57cec5SDimitry Andric     ArrayRef<OutputSection *> outputSections,
17640b57cec5SDimitry Andric     llvm::function_ref<void(OutputSection *, InputSectionDescription *)> fn) {
17650b57cec5SDimitry Andric   for (OutputSection *os : outputSections) {
17660b57cec5SDimitry Andric     if (!(os->flags & SHF_ALLOC) || !(os->flags & SHF_EXECINSTR))
17670b57cec5SDimitry Andric       continue;
17684824e7fdSDimitry Andric     for (SectionCommand *bc : os->commands)
17690b57cec5SDimitry Andric       if (auto *isd = dyn_cast<InputSectionDescription>(bc))
17700b57cec5SDimitry Andric         fn(os, isd);
17710b57cec5SDimitry Andric   }
17720b57cec5SDimitry Andric }
17730b57cec5SDimitry Andric 
17740b57cec5SDimitry Andric // Thunk Implementation
17750b57cec5SDimitry Andric //
17760b57cec5SDimitry Andric // Thunks (sometimes called stubs, veneers or branch islands) are small pieces
17770b57cec5SDimitry Andric // of code that the linker inserts inbetween a caller and a callee. The thunks
17780b57cec5SDimitry Andric // are added at link time rather than compile time as the decision on whether
17790b57cec5SDimitry Andric // a thunk is needed, such as the caller and callee being out of range, can only
17800b57cec5SDimitry Andric // be made at link time.
17810b57cec5SDimitry Andric //
17820b57cec5SDimitry Andric // It is straightforward to tell given the current state of the program when a
17830b57cec5SDimitry Andric // thunk is needed for a particular call. The more difficult part is that
17840b57cec5SDimitry Andric // the thunk needs to be placed in the program such that the caller can reach
17850b57cec5SDimitry Andric // the thunk and the thunk can reach the callee; furthermore, adding thunks to
17860b57cec5SDimitry Andric // the program alters addresses, which can mean more thunks etc.
17870b57cec5SDimitry Andric //
17880b57cec5SDimitry Andric // In lld we have a synthetic ThunkSection that can hold many Thunks.
17890b57cec5SDimitry Andric // The decision to have a ThunkSection act as a container means that we can
17900b57cec5SDimitry Andric // more easily handle the most common case of a single block of contiguous
17910b57cec5SDimitry Andric // Thunks by inserting just a single ThunkSection.
17920b57cec5SDimitry Andric //
17930b57cec5SDimitry Andric // The implementation of Thunks in lld is split across these areas
17940b57cec5SDimitry Andric // Relocations.cpp : Framework for creating and placing thunks
17950b57cec5SDimitry Andric // Thunks.cpp : The code generated for each supported thunk
17960b57cec5SDimitry Andric // Target.cpp : Target specific hooks that the framework uses to decide when
17970b57cec5SDimitry Andric //              a thunk is used
17980b57cec5SDimitry Andric // Synthetic.cpp : Implementation of ThunkSection
17990b57cec5SDimitry Andric // Writer.cpp : Iteratively call framework until no more Thunks added
18000b57cec5SDimitry Andric //
18010b57cec5SDimitry Andric // Thunk placement requirements:
18020b57cec5SDimitry Andric // Mips LA25 thunks. These must be placed immediately before the callee section
18030b57cec5SDimitry Andric // We can assume that the caller is in range of the Thunk. These are modelled
18040b57cec5SDimitry Andric // by Thunks that return the section they must precede with
18050b57cec5SDimitry Andric // getTargetInputSection().
18060b57cec5SDimitry Andric //
18070b57cec5SDimitry Andric // ARM interworking and range extension thunks. These thunks must be placed
18080b57cec5SDimitry Andric // within range of the caller. All implemented ARM thunks can always reach the
18090b57cec5SDimitry Andric // callee as they use an indirect jump via a register that has no range
18100b57cec5SDimitry Andric // restrictions.
18110b57cec5SDimitry Andric //
18120b57cec5SDimitry Andric // Thunk placement algorithm:
18130b57cec5SDimitry Andric // For Mips LA25 ThunkSections; the placement is explicit, it has to be before
18140b57cec5SDimitry Andric // getTargetInputSection().
18150b57cec5SDimitry Andric //
18160b57cec5SDimitry Andric // For thunks that must be placed within range of the caller there are many
18170b57cec5SDimitry Andric // possible choices given that the maximum range from the caller is usually
18180b57cec5SDimitry Andric // much larger than the average InputSection size. Desirable properties include:
18190b57cec5SDimitry Andric // - Maximize reuse of thunks by multiple callers
18200b57cec5SDimitry Andric // - Minimize number of ThunkSections to simplify insertion
18210b57cec5SDimitry Andric // - Handle impact of already added Thunks on addresses
18220b57cec5SDimitry Andric // - Simple to understand and implement
18230b57cec5SDimitry Andric //
18240b57cec5SDimitry Andric // In lld for the first pass, we pre-create one or more ThunkSections per
18250b57cec5SDimitry Andric // InputSectionDescription at Target specific intervals. A ThunkSection is
18260b57cec5SDimitry Andric // placed so that the estimated end of the ThunkSection is within range of the
18270b57cec5SDimitry Andric // start of the InputSectionDescription or the previous ThunkSection. For
18280b57cec5SDimitry Andric // example:
18290b57cec5SDimitry Andric // InputSectionDescription
18300b57cec5SDimitry Andric // Section 0
18310b57cec5SDimitry Andric // ...
18320b57cec5SDimitry Andric // Section N
18330b57cec5SDimitry Andric // ThunkSection 0
18340b57cec5SDimitry Andric // Section N + 1
18350b57cec5SDimitry Andric // ...
18360b57cec5SDimitry Andric // Section N + K
18370b57cec5SDimitry Andric // Thunk Section 1
18380b57cec5SDimitry Andric //
18390b57cec5SDimitry Andric // The intention is that we can add a Thunk to a ThunkSection that is well
18400b57cec5SDimitry Andric // spaced enough to service a number of callers without having to do a lot
18410b57cec5SDimitry Andric // of work. An important principle is that it is not an error if a Thunk cannot
18420b57cec5SDimitry Andric // be placed in a pre-created ThunkSection; when this happens we create a new
18430b57cec5SDimitry Andric // ThunkSection placed next to the caller. This allows us to handle the vast
18440b57cec5SDimitry Andric // majority of thunks simply, but also handle rare cases where the branch range
18450b57cec5SDimitry Andric // is smaller than the target specific spacing.
18460b57cec5SDimitry Andric //
18470b57cec5SDimitry Andric // The algorithm is expected to create all the thunks that are needed in a
18480b57cec5SDimitry Andric // single pass, with a small number of programs needing a second pass due to
18490b57cec5SDimitry Andric // the insertion of thunks in the first pass increasing the offset between
18500b57cec5SDimitry Andric // callers and callees that were only just in range.
18510b57cec5SDimitry Andric //
18520b57cec5SDimitry Andric // A consequence of allowing new ThunkSections to be created outside of the
18530b57cec5SDimitry Andric // pre-created ThunkSections is that in rare cases calls to Thunks that were in
18540b57cec5SDimitry Andric // range in pass K, are out of range in some pass > K due to the insertion of
18550b57cec5SDimitry Andric // more Thunks in between the caller and callee. When this happens we retarget
18560b57cec5SDimitry Andric // the relocation back to the original target and create another Thunk.
18570b57cec5SDimitry Andric 
18580b57cec5SDimitry Andric // Remove ThunkSections that are empty, this should only be the initial set
18590b57cec5SDimitry Andric // precreated on pass 0.
18600b57cec5SDimitry Andric 
18610b57cec5SDimitry Andric // Insert the Thunks for OutputSection OS into their designated place
18620b57cec5SDimitry Andric // in the Sections vector, and recalculate the InputSection output section
18630b57cec5SDimitry Andric // offsets.
18640b57cec5SDimitry Andric // This may invalidate any output section offsets stored outside of InputSection
18650b57cec5SDimitry Andric void ThunkCreator::mergeThunks(ArrayRef<OutputSection *> outputSections) {
18660b57cec5SDimitry Andric   forEachInputSectionDescription(
18670b57cec5SDimitry Andric       outputSections, [&](OutputSection *os, InputSectionDescription *isd) {
18680b57cec5SDimitry Andric         if (isd->thunkSections.empty())
18690b57cec5SDimitry Andric           return;
18700b57cec5SDimitry Andric 
18710b57cec5SDimitry Andric         // Remove any zero sized precreated Thunks.
18720b57cec5SDimitry Andric         llvm::erase_if(isd->thunkSections,
18730b57cec5SDimitry Andric                        [](const std::pair<ThunkSection *, uint32_t> &ts) {
18740b57cec5SDimitry Andric                          return ts.first->getSize() == 0;
18750b57cec5SDimitry Andric                        });
18760b57cec5SDimitry Andric 
18770b57cec5SDimitry Andric         // ISD->ThunkSections contains all created ThunkSections, including
18780b57cec5SDimitry Andric         // those inserted in previous passes. Extract the Thunks created this
18790b57cec5SDimitry Andric         // pass and order them in ascending outSecOff.
18800b57cec5SDimitry Andric         std::vector<ThunkSection *> newThunks;
1881480093f4SDimitry Andric         for (std::pair<ThunkSection *, uint32_t> ts : isd->thunkSections)
18820b57cec5SDimitry Andric           if (ts.second == pass)
18830b57cec5SDimitry Andric             newThunks.push_back(ts.first);
18840b57cec5SDimitry Andric         llvm::stable_sort(newThunks,
18850b57cec5SDimitry Andric                           [](const ThunkSection *a, const ThunkSection *b) {
18860b57cec5SDimitry Andric                             return a->outSecOff < b->outSecOff;
18870b57cec5SDimitry Andric                           });
18880b57cec5SDimitry Andric 
18890b57cec5SDimitry Andric         // Merge sorted vectors of Thunks and InputSections by outSecOff
189004eeddc0SDimitry Andric         SmallVector<InputSection *, 0> tmp;
18910b57cec5SDimitry Andric         tmp.reserve(isd->sections.size() + newThunks.size());
18920b57cec5SDimitry Andric 
18930b57cec5SDimitry Andric         std::merge(isd->sections.begin(), isd->sections.end(),
18940b57cec5SDimitry Andric                    newThunks.begin(), newThunks.end(), std::back_inserter(tmp),
18950b57cec5SDimitry Andric                    mergeCmp);
18960b57cec5SDimitry Andric 
18970b57cec5SDimitry Andric         isd->sections = std::move(tmp);
18980b57cec5SDimitry Andric       });
18990b57cec5SDimitry Andric }
19000b57cec5SDimitry Andric 
190181ad6265SDimitry Andric static int64_t getPCBias(RelType type) {
190281ad6265SDimitry Andric   if (config->emachine != EM_ARM)
190381ad6265SDimitry Andric     return 0;
190481ad6265SDimitry Andric   switch (type) {
190581ad6265SDimitry Andric   case R_ARM_THM_JUMP19:
190681ad6265SDimitry Andric   case R_ARM_THM_JUMP24:
190781ad6265SDimitry Andric   case R_ARM_THM_CALL:
190881ad6265SDimitry Andric     return 4;
190981ad6265SDimitry Andric   default:
191081ad6265SDimitry Andric     return 8;
191181ad6265SDimitry Andric   }
191281ad6265SDimitry Andric }
191381ad6265SDimitry Andric 
19140b57cec5SDimitry Andric // Find or create a ThunkSection within the InputSectionDescription (ISD) that
19150b57cec5SDimitry Andric // is in range of Src. An ISD maps to a range of InputSections described by a
19160b57cec5SDimitry Andric // linker script section pattern such as { .text .text.* }.
1917fe6060f1SDimitry Andric ThunkSection *ThunkCreator::getISDThunkSec(OutputSection *os,
1918fe6060f1SDimitry Andric                                            InputSection *isec,
19190b57cec5SDimitry Andric                                            InputSectionDescription *isd,
1920fe6060f1SDimitry Andric                                            const Relocation &rel,
1921fe6060f1SDimitry Andric                                            uint64_t src) {
192281ad6265SDimitry Andric   // See the comment in getThunk for -pcBias below.
192381ad6265SDimitry Andric   const int64_t pcBias = getPCBias(rel.type);
19240b57cec5SDimitry Andric   for (std::pair<ThunkSection *, uint32_t> tp : isd->thunkSections) {
19250b57cec5SDimitry Andric     ThunkSection *ts = tp.first;
192681ad6265SDimitry Andric     uint64_t tsBase = os->addr + ts->outSecOff - pcBias;
192781ad6265SDimitry Andric     uint64_t tsLimit = tsBase + ts->getSize();
1928fe6060f1SDimitry Andric     if (target->inBranchRange(rel.type, src,
1929fe6060f1SDimitry Andric                               (src > tsLimit) ? tsBase : tsLimit))
19300b57cec5SDimitry Andric       return ts;
19310b57cec5SDimitry Andric   }
19320b57cec5SDimitry Andric 
19330b57cec5SDimitry Andric   // No suitable ThunkSection exists. This can happen when there is a branch
19340b57cec5SDimitry Andric   // with lower range than the ThunkSection spacing or when there are too
19350b57cec5SDimitry Andric   // many Thunks. Create a new ThunkSection as close to the InputSection as
19360b57cec5SDimitry Andric   // possible. Error if InputSection is so large we cannot place ThunkSection
19370b57cec5SDimitry Andric   // anywhere in Range.
19380b57cec5SDimitry Andric   uint64_t thunkSecOff = isec->outSecOff;
1939fe6060f1SDimitry Andric   if (!target->inBranchRange(rel.type, src,
1940fe6060f1SDimitry Andric                              os->addr + thunkSecOff + rel.addend)) {
19410b57cec5SDimitry Andric     thunkSecOff = isec->outSecOff + isec->getSize();
1942fe6060f1SDimitry Andric     if (!target->inBranchRange(rel.type, src,
1943fe6060f1SDimitry Andric                                os->addr + thunkSecOff + rel.addend))
19440b57cec5SDimitry Andric       fatal("InputSection too large for range extension thunk " +
19450b57cec5SDimitry Andric             isec->getObjMsg(src - (os->addr + isec->outSecOff)));
19460b57cec5SDimitry Andric   }
19470b57cec5SDimitry Andric   return addThunkSection(os, isd, thunkSecOff);
19480b57cec5SDimitry Andric }
19490b57cec5SDimitry Andric 
19500b57cec5SDimitry Andric // Add a Thunk that needs to be placed in a ThunkSection that immediately
19510b57cec5SDimitry Andric // precedes its Target.
19520b57cec5SDimitry Andric ThunkSection *ThunkCreator::getISThunkSec(InputSection *isec) {
19530b57cec5SDimitry Andric   ThunkSection *ts = thunkedSections.lookup(isec);
19540b57cec5SDimitry Andric   if (ts)
19550b57cec5SDimitry Andric     return ts;
19560b57cec5SDimitry Andric 
19570b57cec5SDimitry Andric   // Find InputSectionRange within Target Output Section (TOS) that the
19580b57cec5SDimitry Andric   // InputSection (IS) that we need to precede is in.
19590b57cec5SDimitry Andric   OutputSection *tos = isec->getParent();
19604824e7fdSDimitry Andric   for (SectionCommand *bc : tos->commands) {
19610b57cec5SDimitry Andric     auto *isd = dyn_cast<InputSectionDescription>(bc);
19620b57cec5SDimitry Andric     if (!isd || isd->sections.empty())
19630b57cec5SDimitry Andric       continue;
19640b57cec5SDimitry Andric 
19650b57cec5SDimitry Andric     InputSection *first = isd->sections.front();
19660b57cec5SDimitry Andric     InputSection *last = isd->sections.back();
19670b57cec5SDimitry Andric 
19680b57cec5SDimitry Andric     if (isec->outSecOff < first->outSecOff || last->outSecOff < isec->outSecOff)
19690b57cec5SDimitry Andric       continue;
19700b57cec5SDimitry Andric 
19710b57cec5SDimitry Andric     ts = addThunkSection(tos, isd, isec->outSecOff);
19720b57cec5SDimitry Andric     thunkedSections[isec] = ts;
19730b57cec5SDimitry Andric     return ts;
19740b57cec5SDimitry Andric   }
19750b57cec5SDimitry Andric 
19760b57cec5SDimitry Andric   return nullptr;
19770b57cec5SDimitry Andric }
19780b57cec5SDimitry Andric 
19790b57cec5SDimitry Andric // Create one or more ThunkSections per OS that can be used to place Thunks.
19800b57cec5SDimitry Andric // We attempt to place the ThunkSections using the following desirable
19810b57cec5SDimitry Andric // properties:
19820b57cec5SDimitry Andric // - Within range of the maximum number of callers
19830b57cec5SDimitry Andric // - Minimise the number of ThunkSections
19840b57cec5SDimitry Andric //
19850b57cec5SDimitry Andric // We follow a simple but conservative heuristic to place ThunkSections at
19860b57cec5SDimitry Andric // offsets that are multiples of a Target specific branch range.
19870b57cec5SDimitry Andric // For an InputSectionDescription that is smaller than the range, a single
19880b57cec5SDimitry Andric // ThunkSection at the end of the range will do.
19890b57cec5SDimitry Andric //
19900b57cec5SDimitry Andric // For an InputSectionDescription that is more than twice the size of the range,
19910b57cec5SDimitry Andric // we place the last ThunkSection at range bytes from the end of the
19920b57cec5SDimitry Andric // InputSectionDescription in order to increase the likelihood that the
19930b57cec5SDimitry Andric // distance from a thunk to its target will be sufficiently small to
19940b57cec5SDimitry Andric // allow for the creation of a short thunk.
19950b57cec5SDimitry Andric void ThunkCreator::createInitialThunkSections(
19960b57cec5SDimitry Andric     ArrayRef<OutputSection *> outputSections) {
19970b57cec5SDimitry Andric   uint32_t thunkSectionSpacing = target->getThunkSectionSpacing();
19980b57cec5SDimitry Andric 
19990b57cec5SDimitry Andric   forEachInputSectionDescription(
20000b57cec5SDimitry Andric       outputSections, [&](OutputSection *os, InputSectionDescription *isd) {
20010b57cec5SDimitry Andric         if (isd->sections.empty())
20020b57cec5SDimitry Andric           return;
20030b57cec5SDimitry Andric 
20040b57cec5SDimitry Andric         uint32_t isdBegin = isd->sections.front()->outSecOff;
20050b57cec5SDimitry Andric         uint32_t isdEnd =
20060b57cec5SDimitry Andric             isd->sections.back()->outSecOff + isd->sections.back()->getSize();
20070b57cec5SDimitry Andric         uint32_t lastThunkLowerBound = -1;
20080b57cec5SDimitry Andric         if (isdEnd - isdBegin > thunkSectionSpacing * 2)
20090b57cec5SDimitry Andric           lastThunkLowerBound = isdEnd - thunkSectionSpacing;
20100b57cec5SDimitry Andric 
20110b57cec5SDimitry Andric         uint32_t isecLimit;
20120b57cec5SDimitry Andric         uint32_t prevIsecLimit = isdBegin;
20130b57cec5SDimitry Andric         uint32_t thunkUpperBound = isdBegin + thunkSectionSpacing;
20140b57cec5SDimitry Andric 
20150b57cec5SDimitry Andric         for (const InputSection *isec : isd->sections) {
20160b57cec5SDimitry Andric           isecLimit = isec->outSecOff + isec->getSize();
20170b57cec5SDimitry Andric           if (isecLimit > thunkUpperBound) {
20180b57cec5SDimitry Andric             addThunkSection(os, isd, prevIsecLimit);
20190b57cec5SDimitry Andric             thunkUpperBound = prevIsecLimit + thunkSectionSpacing;
20200b57cec5SDimitry Andric           }
20210b57cec5SDimitry Andric           if (isecLimit > lastThunkLowerBound)
20220b57cec5SDimitry Andric             break;
20230b57cec5SDimitry Andric           prevIsecLimit = isecLimit;
20240b57cec5SDimitry Andric         }
20250b57cec5SDimitry Andric         addThunkSection(os, isd, isecLimit);
20260b57cec5SDimitry Andric       });
20270b57cec5SDimitry Andric }
20280b57cec5SDimitry Andric 
20290b57cec5SDimitry Andric ThunkSection *ThunkCreator::addThunkSection(OutputSection *os,
20300b57cec5SDimitry Andric                                             InputSectionDescription *isd,
20310b57cec5SDimitry Andric                                             uint64_t off) {
20320b57cec5SDimitry Andric   auto *ts = make<ThunkSection>(os, off);
20330b57cec5SDimitry Andric   ts->partition = os->partition;
203413138422SDimitry Andric   if ((config->fixCortexA53Errata843419 || config->fixCortexA8) &&
203513138422SDimitry Andric       !isd->sections.empty()) {
203613138422SDimitry Andric     // The errata fixes are sensitive to addresses modulo 4 KiB. When we add
203713138422SDimitry Andric     // thunks we disturb the base addresses of sections placed after the thunks
203813138422SDimitry Andric     // this makes patches we have generated redundant, and may cause us to
203913138422SDimitry Andric     // generate more patches as different instructions are now in sensitive
204013138422SDimitry Andric     // locations. When we generate more patches we may force more branches to
204113138422SDimitry Andric     // go out of range, causing more thunks to be generated. In pathological
204213138422SDimitry Andric     // cases this can cause the address dependent content pass not to converge.
204313138422SDimitry Andric     // We fix this by rounding up the size of the ThunkSection to 4KiB, this
204413138422SDimitry Andric     // limits the insertion of a ThunkSection on the addresses modulo 4 KiB,
204513138422SDimitry Andric     // which means that adding Thunks to the section does not invalidate
204613138422SDimitry Andric     // errata patches for following code.
204713138422SDimitry Andric     // Rounding up the size to 4KiB has consequences for code-size and can
204813138422SDimitry Andric     // trip up linker script defined assertions. For example the linux kernel
204913138422SDimitry Andric     // has an assertion that what LLD represents as an InputSectionDescription
205013138422SDimitry Andric     // does not exceed 4 KiB even if the overall OutputSection is > 128 Mib.
205113138422SDimitry Andric     // We use the heuristic of rounding up the size when both of the following
205213138422SDimitry Andric     // conditions are true:
205313138422SDimitry Andric     // 1.) The OutputSection is larger than the ThunkSectionSpacing. This
205413138422SDimitry Andric     //     accounts for the case where no single InputSectionDescription is
205513138422SDimitry Andric     //     larger than the OutputSection size. This is conservative but simple.
205613138422SDimitry Andric     // 2.) The InputSectionDescription is larger than 4 KiB. This will prevent
205713138422SDimitry Andric     //     any assertion failures that an InputSectionDescription is < 4 KiB
205813138422SDimitry Andric     //     in size.
205913138422SDimitry Andric     uint64_t isdSize = isd->sections.back()->outSecOff +
206013138422SDimitry Andric                        isd->sections.back()->getSize() -
206113138422SDimitry Andric                        isd->sections.front()->outSecOff;
206213138422SDimitry Andric     if (os->size > target->getThunkSectionSpacing() && isdSize > 4096)
206313138422SDimitry Andric       ts->roundUpSizeForErrata = true;
206413138422SDimitry Andric   }
20650b57cec5SDimitry Andric   isd->thunkSections.push_back({ts, pass});
20660b57cec5SDimitry Andric   return ts;
20670b57cec5SDimitry Andric }
20680b57cec5SDimitry Andric 
20690b57cec5SDimitry Andric static bool isThunkSectionCompatible(InputSection *source,
20700b57cec5SDimitry Andric                                      SectionBase *target) {
20710b57cec5SDimitry Andric   // We can't reuse thunks in different loadable partitions because they might
20720b57cec5SDimitry Andric   // not be loaded. But partition 1 (the main partition) will always be loaded.
20730b57cec5SDimitry Andric   if (source->partition != target->partition)
20740b57cec5SDimitry Andric     return target->partition == 1;
20750b57cec5SDimitry Andric   return true;
20760b57cec5SDimitry Andric }
20770b57cec5SDimitry Andric 
20780b57cec5SDimitry Andric std::pair<Thunk *, bool> ThunkCreator::getThunk(InputSection *isec,
20790b57cec5SDimitry Andric                                                 Relocation &rel, uint64_t src) {
20800b57cec5SDimitry Andric   std::vector<Thunk *> *thunkVec = nullptr;
2081fe6060f1SDimitry Andric   // Arm and Thumb have a PC Bias of 8 and 4 respectively, this is cancelled
2082fe6060f1SDimitry Andric   // out in the relocation addend. We compensate for the PC bias so that
2083fe6060f1SDimitry Andric   // an Arm and Thumb relocation to the same destination get the same keyAddend,
2084fe6060f1SDimitry Andric   // which is usually 0.
20859b597132SPiotr Kubaj   const int64_t pcBias = getPCBias(rel.type);
20869b597132SPiotr Kubaj   const int64_t keyAddend = rel.addend + pcBias;
20870b57cec5SDimitry Andric 
2088480093f4SDimitry Andric   // We use a ((section, offset), addend) pair to find the thunk position if
2089480093f4SDimitry Andric   // possible so that we create only one thunk for aliased symbols or ICFed
2090480093f4SDimitry Andric   // sections. There may be multiple relocations sharing the same (section,
2091480093f4SDimitry Andric   // offset + addend) pair. We may revert the relocation back to its original
2092480093f4SDimitry Andric   // non-Thunk target, so we cannot fold offset + addend.
20930b57cec5SDimitry Andric   if (auto *d = dyn_cast<Defined>(rel.sym))
20940b57cec5SDimitry Andric     if (!d->isInPlt() && d->section)
20950eae32dcSDimitry Andric       thunkVec = &thunkedSymbolsBySectionAndAddend[{{d->section, d->value},
20960eae32dcSDimitry Andric                                                     keyAddend}];
20970b57cec5SDimitry Andric   if (!thunkVec)
2098fe6060f1SDimitry Andric     thunkVec = &thunkedSymbols[{rel.sym, keyAddend}];
20990b57cec5SDimitry Andric 
21000b57cec5SDimitry Andric   // Check existing Thunks for Sym to see if they can be reused
21010b57cec5SDimitry Andric   for (Thunk *t : *thunkVec)
21020b57cec5SDimitry Andric     if (isThunkSectionCompatible(isec, t->getThunkTargetSym()->section) &&
21030b57cec5SDimitry Andric         t->isCompatibleWith(*isec, rel) &&
2104480093f4SDimitry Andric         target->inBranchRange(rel.type, src,
21059b597132SPiotr Kubaj                               t->getThunkTargetSym()->getVA(-pcBias)))
21060b57cec5SDimitry Andric       return std::make_pair(t, false);
21070b57cec5SDimitry Andric 
21080b57cec5SDimitry Andric   // No existing compatible Thunk in range, create a new one
21090b57cec5SDimitry Andric   Thunk *t = addThunk(*isec, rel);
21100b57cec5SDimitry Andric   thunkVec->push_back(t);
21110b57cec5SDimitry Andric   return std::make_pair(t, true);
21120b57cec5SDimitry Andric }
21130b57cec5SDimitry Andric 
21140b57cec5SDimitry Andric // Return true if the relocation target is an in range Thunk.
21150b57cec5SDimitry Andric // Return false if the relocation is not to a Thunk. If the relocation target
21160b57cec5SDimitry Andric // was originally to a Thunk, but is no longer in range we revert the
21170b57cec5SDimitry Andric // relocation back to its original non-Thunk target.
21180b57cec5SDimitry Andric bool ThunkCreator::normalizeExistingThunk(Relocation &rel, uint64_t src) {
21190b57cec5SDimitry Andric   if (Thunk *t = thunks.lookup(rel.sym)) {
2120fe6060f1SDimitry Andric     if (target->inBranchRange(rel.type, src, rel.sym->getVA(rel.addend)))
21210b57cec5SDimitry Andric       return true;
21220b57cec5SDimitry Andric     rel.sym = &t->destination;
2123480093f4SDimitry Andric     rel.addend = t->addend;
21240b57cec5SDimitry Andric     if (rel.sym->isInPlt())
21250b57cec5SDimitry Andric       rel.expr = toPlt(rel.expr);
21260b57cec5SDimitry Andric   }
21270b57cec5SDimitry Andric   return false;
21280b57cec5SDimitry Andric }
21290b57cec5SDimitry Andric 
21300b57cec5SDimitry Andric // Process all relocations from the InputSections that have been assigned
21310b57cec5SDimitry Andric // to InputSectionDescriptions and redirect through Thunks if needed. The
21320b57cec5SDimitry Andric // function should be called iteratively until it returns false.
21330b57cec5SDimitry Andric //
21340b57cec5SDimitry Andric // PreConditions:
21350b57cec5SDimitry Andric // All InputSections that may need a Thunk are reachable from
21360b57cec5SDimitry Andric // OutputSectionCommands.
21370b57cec5SDimitry Andric //
21380b57cec5SDimitry Andric // All OutputSections have an address and all InputSections have an offset
21390b57cec5SDimitry Andric // within the OutputSection.
21400b57cec5SDimitry Andric //
21410b57cec5SDimitry Andric // The offsets between caller (relocation place) and callee
21420b57cec5SDimitry Andric // (relocation target) will not be modified outside of createThunks().
21430b57cec5SDimitry Andric //
21440b57cec5SDimitry Andric // PostConditions:
21450b57cec5SDimitry Andric // If return value is true then ThunkSections have been inserted into
21460b57cec5SDimitry Andric // OutputSections. All relocations that needed a Thunk based on the information
21470b57cec5SDimitry Andric // available to createThunks() on entry have been redirected to a Thunk. Note
21480b57cec5SDimitry Andric // that adding Thunks changes offsets between caller and callee so more Thunks
21490b57cec5SDimitry Andric // may be required.
21500b57cec5SDimitry Andric //
21510b57cec5SDimitry Andric // If return value is false then no more Thunks are needed, and createThunks has
21520b57cec5SDimitry Andric // made no changes. If the target requires range extension thunks, currently
21530b57cec5SDimitry Andric // ARM, then any future change in offset between caller and callee risks a
21540b57cec5SDimitry Andric // relocation out of range error.
2155753f127fSDimitry Andric bool ThunkCreator::createThunks(uint32_t pass,
2156753f127fSDimitry Andric                                 ArrayRef<OutputSection *> outputSections) {
2157753f127fSDimitry Andric   this->pass = pass;
21580b57cec5SDimitry Andric   bool addressesChanged = false;
21590b57cec5SDimitry Andric 
21600b57cec5SDimitry Andric   if (pass == 0 && target->getThunkSectionSpacing())
21610b57cec5SDimitry Andric     createInitialThunkSections(outputSections);
21620b57cec5SDimitry Andric 
21630b57cec5SDimitry Andric   // Create all the Thunks and insert them into synthetic ThunkSections. The
21640b57cec5SDimitry Andric   // ThunkSections are later inserted back into InputSectionDescriptions.
21650b57cec5SDimitry Andric   // We separate the creation of ThunkSections from the insertion of the
21660b57cec5SDimitry Andric   // ThunkSections as ThunkSections are not always inserted into the same
21670b57cec5SDimitry Andric   // InputSectionDescription as the caller.
21680b57cec5SDimitry Andric   forEachInputSectionDescription(
21690b57cec5SDimitry Andric       outputSections, [&](OutputSection *os, InputSectionDescription *isd) {
21700b57cec5SDimitry Andric         for (InputSection *isec : isd->sections)
2171bdd1243dSDimitry Andric           for (Relocation &rel : isec->relocs()) {
21720b57cec5SDimitry Andric             uint64_t src = isec->getVA(rel.offset);
21730b57cec5SDimitry Andric 
21740b57cec5SDimitry Andric             // If we are a relocation to an existing Thunk, check if it is
21750b57cec5SDimitry Andric             // still in range. If not then Rel will be altered to point to its
21760b57cec5SDimitry Andric             // original target so another Thunk can be generated.
21770b57cec5SDimitry Andric             if (pass > 0 && normalizeExistingThunk(rel, src))
21780b57cec5SDimitry Andric               continue;
21790b57cec5SDimitry Andric 
21800b57cec5SDimitry Andric             if (!target->needsThunk(rel.expr, rel.type, isec->file, src,
2181480093f4SDimitry Andric                                     *rel.sym, rel.addend))
21820b57cec5SDimitry Andric               continue;
21830b57cec5SDimitry Andric 
21840b57cec5SDimitry Andric             Thunk *t;
21850b57cec5SDimitry Andric             bool isNew;
21860b57cec5SDimitry Andric             std::tie(t, isNew) = getThunk(isec, rel, src);
21870b57cec5SDimitry Andric 
21880b57cec5SDimitry Andric             if (isNew) {
21890b57cec5SDimitry Andric               // Find or create a ThunkSection for the new Thunk
21900b57cec5SDimitry Andric               ThunkSection *ts;
21910b57cec5SDimitry Andric               if (auto *tis = t->getTargetInputSection())
21920b57cec5SDimitry Andric                 ts = getISThunkSec(tis);
21930b57cec5SDimitry Andric               else
2194fe6060f1SDimitry Andric                 ts = getISDThunkSec(os, isec, isd, rel, src);
21950b57cec5SDimitry Andric               ts->addThunk(t);
21960b57cec5SDimitry Andric               thunks[t->getThunkTargetSym()] = t;
21970b57cec5SDimitry Andric             }
21980b57cec5SDimitry Andric 
21990b57cec5SDimitry Andric             // Redirect relocation to Thunk, we never go via the PLT to a Thunk
22000b57cec5SDimitry Andric             rel.sym = t->getThunkTargetSym();
22010b57cec5SDimitry Andric             rel.expr = fromPlt(rel.expr);
22020b57cec5SDimitry Andric 
220313138422SDimitry Andric             // On AArch64 and PPC, a jump/call relocation may be encoded as
2204480093f4SDimitry Andric             // STT_SECTION + non-zero addend, clear the addend after
2205480093f4SDimitry Andric             // redirection.
220613138422SDimitry Andric             if (config->emachine != EM_MIPS)
220713138422SDimitry Andric               rel.addend = -getPCBias(rel.type);
22080b57cec5SDimitry Andric           }
22090b57cec5SDimitry Andric 
22100b57cec5SDimitry Andric         for (auto &p : isd->thunkSections)
22110b57cec5SDimitry Andric           addressesChanged |= p.first->assignOffsets();
22120b57cec5SDimitry Andric       });
22130b57cec5SDimitry Andric 
22140b57cec5SDimitry Andric   for (auto &p : thunkedSections)
22150b57cec5SDimitry Andric     addressesChanged |= p.second->assignOffsets();
22160b57cec5SDimitry Andric 
22170b57cec5SDimitry Andric   // Merge all created synthetic ThunkSections back into OutputSection
22180b57cec5SDimitry Andric   mergeThunks(outputSections);
22190b57cec5SDimitry Andric   return addressesChanged;
22200b57cec5SDimitry Andric }
22210b57cec5SDimitry Andric 
22225ffd83dbSDimitry Andric // The following aid in the conversion of call x@GDPLT to call __tls_get_addr
22235ffd83dbSDimitry Andric // hexagonNeedsTLSSymbol scans for relocations would require a call to
22245ffd83dbSDimitry Andric // __tls_get_addr.
22255ffd83dbSDimitry Andric // hexagonTLSSymbolUpdate rebinds the relocation to __tls_get_addr.
22265ffd83dbSDimitry Andric bool elf::hexagonNeedsTLSSymbol(ArrayRef<OutputSection *> outputSections) {
22275ffd83dbSDimitry Andric   bool needTlsSymbol = false;
22285ffd83dbSDimitry Andric   forEachInputSectionDescription(
22295ffd83dbSDimitry Andric       outputSections, [&](OutputSection *os, InputSectionDescription *isd) {
22305ffd83dbSDimitry Andric         for (InputSection *isec : isd->sections)
2231bdd1243dSDimitry Andric           for (Relocation &rel : isec->relocs())
22325ffd83dbSDimitry Andric             if (rel.sym->type == llvm::ELF::STT_TLS && rel.expr == R_PLT_PC) {
22335ffd83dbSDimitry Andric               needTlsSymbol = true;
22345ffd83dbSDimitry Andric               return;
22355ffd83dbSDimitry Andric             }
22365ffd83dbSDimitry Andric       });
22375ffd83dbSDimitry Andric   return needTlsSymbol;
22385ffd83dbSDimitry Andric }
223985868e8aSDimitry Andric 
22405ffd83dbSDimitry Andric void elf::hexagonTLSSymbolUpdate(ArrayRef<OutputSection *> outputSections) {
2241bdd1243dSDimitry Andric   Symbol *sym = symtab.find("__tls_get_addr");
22425ffd83dbSDimitry Andric   if (!sym)
22435ffd83dbSDimitry Andric     return;
22445ffd83dbSDimitry Andric   bool needEntry = true;
22455ffd83dbSDimitry Andric   forEachInputSectionDescription(
22465ffd83dbSDimitry Andric       outputSections, [&](OutputSection *os, InputSectionDescription *isd) {
22475ffd83dbSDimitry Andric         for (InputSection *isec : isd->sections)
2248bdd1243dSDimitry Andric           for (Relocation &rel : isec->relocs())
22495ffd83dbSDimitry Andric             if (rel.sym->type == llvm::ELF::STT_TLS && rel.expr == R_PLT_PC) {
22505ffd83dbSDimitry Andric               if (needEntry) {
225104eeddc0SDimitry Andric                 sym->allocateAux();
22520eae32dcSDimitry Andric                 addPltEntry(*in.plt, *in.gotPlt, *in.relaPlt, target->pltRel,
22535ffd83dbSDimitry Andric                             *sym);
22545ffd83dbSDimitry Andric                 needEntry = false;
22555ffd83dbSDimitry Andric               }
22565ffd83dbSDimitry Andric               rel.sym = sym;
22575ffd83dbSDimitry Andric             }
22585ffd83dbSDimitry Andric       });
22595ffd83dbSDimitry Andric }
22605ffd83dbSDimitry Andric 
2261bdd1243dSDimitry Andric template void elf::scanRelocations<ELF32LE>();
2262bdd1243dSDimitry Andric template void elf::scanRelocations<ELF32BE>();
2263bdd1243dSDimitry Andric template void elf::scanRelocations<ELF64LE>();
2264bdd1243dSDimitry Andric template void elf::scanRelocations<ELF64BE>();
2265