xref: /freebsd/contrib/llvm-project/lld/ELF/Relocations.cpp (revision 0eae32dcef82f6f06de6419a0d623d7def0cc8f6)
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"
450b57cec5SDimitry Andric #include "LinkerScript.h"
460b57cec5SDimitry Andric #include "OutputSections.h"
470b57cec5SDimitry Andric #include "SymbolTable.h"
480b57cec5SDimitry Andric #include "Symbols.h"
490b57cec5SDimitry Andric #include "SyntheticSections.h"
500b57cec5SDimitry Andric #include "Target.h"
510b57cec5SDimitry Andric #include "Thunks.h"
520b57cec5SDimitry Andric #include "lld/Common/ErrorHandler.h"
530b57cec5SDimitry Andric #include "lld/Common/Memory.h"
540b57cec5SDimitry Andric #include "lld/Common/Strings.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 "llvm/Support/raw_ostream.h"
590b57cec5SDimitry Andric #include <algorithm>
600b57cec5SDimitry Andric 
610b57cec5SDimitry Andric using namespace llvm;
620b57cec5SDimitry Andric using namespace llvm::ELF;
630b57cec5SDimitry Andric using namespace llvm::object;
640b57cec5SDimitry Andric using namespace llvm::support::endian;
655ffd83dbSDimitry Andric using namespace lld;
665ffd83dbSDimitry Andric using namespace lld::elf;
670b57cec5SDimitry Andric 
680b57cec5SDimitry Andric static Optional<std::string> getLinkerScriptLocation(const Symbol &sym) {
694824e7fdSDimitry Andric   for (SectionCommand *cmd : script->sectionCommands)
704824e7fdSDimitry Andric     if (auto *assign = dyn_cast<SymbolAssignment>(cmd))
714824e7fdSDimitry Andric       if (assign->sym == &sym)
724824e7fdSDimitry Andric         return assign->location;
730b57cec5SDimitry Andric   return None;
740b57cec5SDimitry Andric }
750b57cec5SDimitry Andric 
765ffd83dbSDimitry Andric static std::string getDefinedLocation(const Symbol &sym) {
77e8d8bef9SDimitry Andric   const char msg[] = "\n>>> defined in ";
785ffd83dbSDimitry Andric   if (sym.file)
79e8d8bef9SDimitry Andric     return msg + toString(sym.file);
80e8d8bef9SDimitry Andric   if (Optional<std::string> loc = getLinkerScriptLocation(sym))
81e8d8bef9SDimitry Andric     return msg + *loc;
82e8d8bef9SDimitry Andric   return "";
835ffd83dbSDimitry Andric }
845ffd83dbSDimitry Andric 
850b57cec5SDimitry Andric // Construct a message in the following format.
860b57cec5SDimitry Andric //
870b57cec5SDimitry Andric // >>> defined in /home/alice/src/foo.o
880b57cec5SDimitry Andric // >>> referenced by bar.c:12 (/home/alice/src/bar.c:12)
890b57cec5SDimitry Andric // >>>               /home/alice/src/bar.o:(.text+0x1)
900b57cec5SDimitry Andric static std::string getLocation(InputSectionBase &s, const Symbol &sym,
910b57cec5SDimitry Andric                                uint64_t off) {
925ffd83dbSDimitry Andric   std::string msg = getDefinedLocation(sym) + "\n>>> referenced by ";
930b57cec5SDimitry Andric   std::string src = s.getSrcMsg(sym, off);
940b57cec5SDimitry Andric   if (!src.empty())
950b57cec5SDimitry Andric     msg += src + "\n>>>               ";
960b57cec5SDimitry Andric   return msg + s.getObjMsg(off);
970b57cec5SDimitry Andric }
980b57cec5SDimitry Andric 
995ffd83dbSDimitry Andric void elf::reportRangeError(uint8_t *loc, const Relocation &rel, const Twine &v,
1005ffd83dbSDimitry Andric                            int64_t min, uint64_t max) {
1015ffd83dbSDimitry Andric   ErrorPlace errPlace = getErrorPlace(loc);
1025ffd83dbSDimitry Andric   std::string hint;
1035ffd83dbSDimitry Andric   if (rel.sym && !rel.sym->isLocal())
104349cc55cSDimitry Andric     hint = "; references " + lld::toString(*rel.sym);
105349cc55cSDimitry Andric   if (!errPlace.srcLoc.empty())
106349cc55cSDimitry Andric     hint += "\n>>> referenced by " + errPlace.srcLoc;
107349cc55cSDimitry Andric   if (rel.sym && !rel.sym->isLocal())
108349cc55cSDimitry Andric     hint += getDefinedLocation(*rel.sym);
1095ffd83dbSDimitry Andric 
1105ffd83dbSDimitry Andric   if (errPlace.isec && errPlace.isec->name.startswith(".debug"))
1115ffd83dbSDimitry Andric     hint += "; consider recompiling with -fdebug-types-section to reduce size "
1125ffd83dbSDimitry Andric             "of debug sections";
1135ffd83dbSDimitry Andric 
1145ffd83dbSDimitry Andric   errorOrWarn(errPlace.loc + "relocation " + lld::toString(rel.type) +
1155ffd83dbSDimitry Andric               " out of range: " + v.str() + " is not in [" + Twine(min).str() +
1165ffd83dbSDimitry Andric               ", " + Twine(max).str() + "]" + hint);
1175ffd83dbSDimitry Andric }
1185ffd83dbSDimitry Andric 
119e8d8bef9SDimitry Andric void elf::reportRangeError(uint8_t *loc, int64_t v, int n, const Symbol &sym,
120e8d8bef9SDimitry Andric                            const Twine &msg) {
121e8d8bef9SDimitry Andric   ErrorPlace errPlace = getErrorPlace(loc);
122e8d8bef9SDimitry Andric   std::string hint;
123e8d8bef9SDimitry Andric   if (!sym.getName().empty())
124e8d8bef9SDimitry Andric     hint = "; references " + lld::toString(sym) + getDefinedLocation(sym);
125e8d8bef9SDimitry Andric   errorOrWarn(errPlace.loc + msg + " is out of range: " + Twine(v) +
126e8d8bef9SDimitry Andric               " is not in [" + Twine(llvm::minIntN(n)) + ", " +
127e8d8bef9SDimitry Andric               Twine(llvm::maxIntN(n)) + "]" + hint);
128e8d8bef9SDimitry Andric }
129e8d8bef9SDimitry Andric 
130349cc55cSDimitry Andric // Build a bitmask with one bit set for each 64 subset of RelExpr.
131349cc55cSDimitry Andric static constexpr uint64_t buildMask() { return 0; }
1320b57cec5SDimitry Andric 
133349cc55cSDimitry Andric template <typename... Tails>
134349cc55cSDimitry Andric static constexpr uint64_t buildMask(int head, Tails... tails) {
135349cc55cSDimitry Andric   return (0 <= head && head < 64 ? uint64_t(1) << head : 0) |
136349cc55cSDimitry Andric          buildMask(tails...);
1370b57cec5SDimitry Andric }
1380b57cec5SDimitry Andric 
1390b57cec5SDimitry Andric // Return true if `Expr` is one of `Exprs`.
140349cc55cSDimitry Andric // There are more than 64 but less than 128 RelExprs, so we divide the set of
141349cc55cSDimitry Andric // exprs into [0, 64) and [64, 128) and represent each range as a constant
142349cc55cSDimitry Andric // 64-bit mask. Then we decide which mask to test depending on the value of
143349cc55cSDimitry Andric // expr and use a simple shift and bitwise-and to test for membership.
144349cc55cSDimitry Andric template <RelExpr... Exprs> static bool oneof(RelExpr expr) {
145349cc55cSDimitry Andric   assert(0 <= expr && (int)expr < 128 &&
146349cc55cSDimitry Andric          "RelExpr is too large for 128-bit mask!");
1470b57cec5SDimitry Andric 
148349cc55cSDimitry Andric   if (expr >= 64)
149349cc55cSDimitry Andric     return (uint64_t(1) << (expr - 64)) & buildMask((Exprs - 64)...);
150349cc55cSDimitry Andric   return (uint64_t(1) << expr) & buildMask(Exprs...);
1510b57cec5SDimitry Andric }
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric static RelType getMipsPairType(RelType type, bool isLocal) {
1540b57cec5SDimitry Andric   switch (type) {
1550b57cec5SDimitry Andric   case R_MIPS_HI16:
1560b57cec5SDimitry Andric     return R_MIPS_LO16;
1570b57cec5SDimitry Andric   case R_MIPS_GOT16:
1580b57cec5SDimitry Andric     // In case of global symbol, the R_MIPS_GOT16 relocation does not
1590b57cec5SDimitry Andric     // have a pair. Each global symbol has a unique entry in the GOT
1600b57cec5SDimitry Andric     // and a corresponding instruction with help of the R_MIPS_GOT16
1610b57cec5SDimitry Andric     // relocation loads an address of the symbol. In case of local
1620b57cec5SDimitry Andric     // symbol, the R_MIPS_GOT16 relocation creates a GOT entry to hold
1630b57cec5SDimitry Andric     // the high 16 bits of the symbol's value. A paired R_MIPS_LO16
1640b57cec5SDimitry Andric     // relocations handle low 16 bits of the address. That allows
1650b57cec5SDimitry Andric     // to allocate only one GOT entry for every 64 KBytes of local data.
1660b57cec5SDimitry Andric     return isLocal ? R_MIPS_LO16 : R_MIPS_NONE;
1670b57cec5SDimitry Andric   case R_MICROMIPS_GOT16:
1680b57cec5SDimitry Andric     return isLocal ? R_MICROMIPS_LO16 : R_MIPS_NONE;
1690b57cec5SDimitry Andric   case R_MIPS_PCHI16:
1700b57cec5SDimitry Andric     return R_MIPS_PCLO16;
1710b57cec5SDimitry Andric   case R_MICROMIPS_HI16:
1720b57cec5SDimitry Andric     return R_MICROMIPS_LO16;
1730b57cec5SDimitry Andric   default:
1740b57cec5SDimitry Andric     return R_MIPS_NONE;
1750b57cec5SDimitry Andric   }
1760b57cec5SDimitry Andric }
1770b57cec5SDimitry Andric 
1780b57cec5SDimitry Andric // True if non-preemptable symbol always has the same value regardless of where
1790b57cec5SDimitry Andric // the DSO is loaded.
1800b57cec5SDimitry Andric static bool isAbsolute(const Symbol &sym) {
1810b57cec5SDimitry Andric   if (sym.isUndefWeak())
1820b57cec5SDimitry Andric     return true;
1830b57cec5SDimitry Andric   if (const auto *dr = dyn_cast<Defined>(&sym))
1840b57cec5SDimitry Andric     return dr->section == nullptr; // Absolute symbol.
1850b57cec5SDimitry Andric   return false;
1860b57cec5SDimitry Andric }
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric static bool isAbsoluteValue(const Symbol &sym) {
1890b57cec5SDimitry Andric   return isAbsolute(sym) || sym.isTls();
1900b57cec5SDimitry Andric }
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric // Returns true if Expr refers a PLT entry.
1930b57cec5SDimitry Andric static bool needsPlt(RelExpr expr) {
194349cc55cSDimitry Andric   return oneof<R_PLT, R_PLT_PC, R_PLT_GOTPLT, R_PPC32_PLTREL, R_PPC64_CALL_PLT>(
195349cc55cSDimitry Andric       expr);
1960b57cec5SDimitry Andric }
1970b57cec5SDimitry Andric 
1980b57cec5SDimitry Andric // Returns true if Expr refers a GOT entry. Note that this function
1990b57cec5SDimitry Andric // returns false for TLS variables even though they need GOT, because
2000b57cec5SDimitry Andric // TLS variables uses GOT differently than the regular variables.
2010b57cec5SDimitry Andric static bool needsGot(RelExpr expr) {
20285868e8aSDimitry Andric   return oneof<R_GOT, R_GOT_OFF, R_MIPS_GOT_LOCAL_PAGE, R_MIPS_GOT_OFF,
203e8d8bef9SDimitry Andric                R_MIPS_GOT_OFF32, R_AARCH64_GOT_PAGE_PC, R_GOT_PC, R_GOTPLT,
204e8d8bef9SDimitry Andric                R_AARCH64_GOT_PAGE>(expr);
2050b57cec5SDimitry Andric }
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric // True if this expression is of the form Sym - X, where X is a position in the
2080b57cec5SDimitry Andric // file (PC, or GOT for example).
2090b57cec5SDimitry Andric static bool isRelExpr(RelExpr expr) {
2100b57cec5SDimitry Andric   return oneof<R_PC, R_GOTREL, R_GOTPLTREL, R_MIPS_GOTREL, R_PPC64_CALL,
2110b57cec5SDimitry Andric                R_PPC64_RELAX_TOC, R_AARCH64_PAGE_PC, R_RELAX_GOT_PC,
212e8d8bef9SDimitry Andric                R_RISCV_PC_INDIRECT, R_PPC64_RELAX_GOT_PC>(expr);
2130b57cec5SDimitry Andric }
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric 
2160b57cec5SDimitry Andric static RelExpr toPlt(RelExpr expr) {
2170b57cec5SDimitry Andric   switch (expr) {
2180b57cec5SDimitry Andric   case R_PPC64_CALL:
2190b57cec5SDimitry Andric     return R_PPC64_CALL_PLT;
2200b57cec5SDimitry Andric   case R_PC:
2210b57cec5SDimitry Andric     return R_PLT_PC;
2220b57cec5SDimitry Andric   case R_ABS:
2230b57cec5SDimitry Andric     return R_PLT;
2240b57cec5SDimitry Andric   default:
2250b57cec5SDimitry Andric     return expr;
2260b57cec5SDimitry Andric   }
2270b57cec5SDimitry Andric }
2280b57cec5SDimitry Andric 
2290b57cec5SDimitry Andric static RelExpr fromPlt(RelExpr expr) {
2300b57cec5SDimitry Andric   // We decided not to use a plt. Optimize a reference to the plt to a
2310b57cec5SDimitry Andric   // reference to the symbol itself.
2320b57cec5SDimitry Andric   switch (expr) {
2330b57cec5SDimitry Andric   case R_PLT_PC:
2340b57cec5SDimitry Andric   case R_PPC32_PLTREL:
2350b57cec5SDimitry Andric     return R_PC;
2360b57cec5SDimitry Andric   case R_PPC64_CALL_PLT:
2370b57cec5SDimitry Andric     return R_PPC64_CALL;
2380b57cec5SDimitry Andric   case R_PLT:
2390b57cec5SDimitry Andric     return R_ABS;
240349cc55cSDimitry Andric   case R_PLT_GOTPLT:
241349cc55cSDimitry Andric     return R_GOTPLTREL;
2420b57cec5SDimitry Andric   default:
2430b57cec5SDimitry Andric     return expr;
2440b57cec5SDimitry Andric   }
2450b57cec5SDimitry Andric }
2460b57cec5SDimitry Andric 
2470b57cec5SDimitry Andric // Returns true if a given shared symbol is in a read-only segment in a DSO.
2480b57cec5SDimitry Andric template <class ELFT> static bool isReadOnly(SharedSymbol &ss) {
2490b57cec5SDimitry Andric   using Elf_Phdr = typename ELFT::Phdr;
2500b57cec5SDimitry Andric 
2510b57cec5SDimitry Andric   // Determine if the symbol is read-only by scanning the DSO's program headers.
2520b57cec5SDimitry Andric   const SharedFile &file = ss.getFile();
2530b57cec5SDimitry Andric   for (const Elf_Phdr &phdr :
2540b57cec5SDimitry Andric        check(file.template getObj<ELFT>().program_headers()))
2550b57cec5SDimitry Andric     if ((phdr.p_type == ELF::PT_LOAD || phdr.p_type == ELF::PT_GNU_RELRO) &&
2560b57cec5SDimitry Andric         !(phdr.p_flags & ELF::PF_W) && ss.value >= phdr.p_vaddr &&
2570b57cec5SDimitry Andric         ss.value < phdr.p_vaddr + phdr.p_memsz)
2580b57cec5SDimitry Andric       return true;
2590b57cec5SDimitry Andric   return false;
2600b57cec5SDimitry Andric }
2610b57cec5SDimitry Andric 
2620b57cec5SDimitry Andric // Returns symbols at the same offset as a given symbol, including SS itself.
2630b57cec5SDimitry Andric //
2640b57cec5SDimitry Andric // If two or more symbols are at the same offset, and at least one of
2650b57cec5SDimitry Andric // them are copied by a copy relocation, all of them need to be copied.
2660b57cec5SDimitry Andric // Otherwise, they would refer to different places at runtime.
2670b57cec5SDimitry Andric template <class ELFT>
2680b57cec5SDimitry Andric static SmallSet<SharedSymbol *, 4> getSymbolsAt(SharedSymbol &ss) {
2690b57cec5SDimitry Andric   using Elf_Sym = typename ELFT::Sym;
2700b57cec5SDimitry Andric 
2710b57cec5SDimitry Andric   SharedFile &file = ss.getFile();
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric   SmallSet<SharedSymbol *, 4> ret;
2740b57cec5SDimitry Andric   for (const Elf_Sym &s : file.template getGlobalELFSyms<ELFT>()) {
2750b57cec5SDimitry Andric     if (s.st_shndx == SHN_UNDEF || s.st_shndx == SHN_ABS ||
2760b57cec5SDimitry Andric         s.getType() == STT_TLS || s.st_value != ss.value)
2770b57cec5SDimitry Andric       continue;
2780b57cec5SDimitry Andric     StringRef name = check(s.getName(file.getStringTable()));
2790b57cec5SDimitry Andric     Symbol *sym = symtab->find(name);
2800b57cec5SDimitry Andric     if (auto *alias = dyn_cast_or_null<SharedSymbol>(sym))
2810b57cec5SDimitry Andric       ret.insert(alias);
2820b57cec5SDimitry Andric   }
2836e75b2fbSDimitry Andric 
2846e75b2fbSDimitry Andric   // The loop does not check SHT_GNU_verneed, so ret does not contain
2856e75b2fbSDimitry Andric   // non-default version symbols. If ss has a non-default version, ret won't
2866e75b2fbSDimitry Andric   // contain ss. Just add ss unconditionally. If a non-default version alias is
2876e75b2fbSDimitry Andric   // separately copy relocated, it and ss will have different addresses.
2886e75b2fbSDimitry Andric   // Fortunately this case is impractical and fails with GNU ld as well.
2896e75b2fbSDimitry Andric   ret.insert(&ss);
2900b57cec5SDimitry Andric   return ret;
2910b57cec5SDimitry Andric }
2920b57cec5SDimitry Andric 
2930b57cec5SDimitry Andric // When a symbol is copy relocated or we create a canonical plt entry, it is
2940b57cec5SDimitry Andric // effectively a defined symbol. In the case of copy relocation the symbol is
2950b57cec5SDimitry Andric // in .bss and in the case of a canonical plt entry it is in .plt. This function
2960b57cec5SDimitry Andric // replaces the existing symbol with a Defined pointing to the appropriate
2970b57cec5SDimitry Andric // location.
298*0eae32dcSDimitry Andric static void replaceWithDefined(Symbol &sym, SectionBase &sec, uint64_t value,
2990b57cec5SDimitry Andric                                uint64_t size) {
3000b57cec5SDimitry Andric   Symbol old = sym;
3010b57cec5SDimitry Andric 
3020b57cec5SDimitry Andric   sym.replace(Defined{sym.file, sym.getName(), sym.binding, sym.stOther,
303*0eae32dcSDimitry Andric                       sym.type, value, size, &sec});
3040b57cec5SDimitry Andric 
3050b57cec5SDimitry Andric   sym.pltIndex = old.pltIndex;
3060b57cec5SDimitry Andric   sym.gotIndex = old.gotIndex;
3070b57cec5SDimitry Andric   sym.verdefIndex = old.verdefIndex;
3080b57cec5SDimitry Andric   sym.exportDynamic = true;
3090b57cec5SDimitry Andric   sym.isUsedInRegularObj = true;
310*0eae32dcSDimitry Andric   // A copy relocated alias may need a GOT entry.
311*0eae32dcSDimitry Andric   sym.needsGot = old.needsGot;
3120b57cec5SDimitry Andric }
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric // Reserve space in .bss or .bss.rel.ro for copy relocation.
3150b57cec5SDimitry Andric //
3160b57cec5SDimitry Andric // The copy relocation is pretty much a hack. If you use a copy relocation
3170b57cec5SDimitry Andric // in your program, not only the symbol name but the symbol's size, RW/RO
3180b57cec5SDimitry Andric // bit and alignment become part of the ABI. In addition to that, if the
3190b57cec5SDimitry Andric // symbol has aliases, the aliases become part of the ABI. That's subtle,
3200b57cec5SDimitry Andric // but if you violate that implicit ABI, that can cause very counter-
3210b57cec5SDimitry Andric // intuitive consequences.
3220b57cec5SDimitry Andric //
3230b57cec5SDimitry Andric // So, what is the copy relocation? It's for linking non-position
3240b57cec5SDimitry Andric // independent code to DSOs. In an ideal world, all references to data
3250b57cec5SDimitry Andric // exported by DSOs should go indirectly through GOT. But if object files
3260b57cec5SDimitry Andric // are compiled as non-PIC, all data references are direct. There is no
3270b57cec5SDimitry Andric // way for the linker to transform the code to use GOT, as machine
3280b57cec5SDimitry Andric // instructions are already set in stone in object files. This is where
3290b57cec5SDimitry Andric // the copy relocation takes a role.
3300b57cec5SDimitry Andric //
3310b57cec5SDimitry Andric // A copy relocation instructs the dynamic linker to copy data from a DSO
3320b57cec5SDimitry Andric // to a specified address (which is usually in .bss) at load-time. If the
3330b57cec5SDimitry Andric // static linker (that's us) finds a direct data reference to a DSO
3340b57cec5SDimitry Andric // symbol, it creates a copy relocation, so that the symbol can be
3350b57cec5SDimitry Andric // resolved as if it were in .bss rather than in a DSO.
3360b57cec5SDimitry Andric //
3370b57cec5SDimitry Andric // As you can see in this function, we create a copy relocation for the
3380b57cec5SDimitry Andric // dynamic linker, and the relocation contains not only symbol name but
339480093f4SDimitry Andric // various other information about the symbol. So, such attributes become a
3400b57cec5SDimitry Andric // part of the ABI.
3410b57cec5SDimitry Andric //
3420b57cec5SDimitry Andric // Note for application developers: I can give you a piece of advice if
3430b57cec5SDimitry Andric // you are writing a shared library. You probably should export only
3440b57cec5SDimitry Andric // functions from your library. You shouldn't export variables.
3450b57cec5SDimitry Andric //
3460b57cec5SDimitry Andric // As an example what can happen when you export variables without knowing
3470b57cec5SDimitry Andric // the semantics of copy relocations, assume that you have an exported
3480b57cec5SDimitry Andric // variable of type T. It is an ABI-breaking change to add new members at
3490b57cec5SDimitry Andric // end of T even though doing that doesn't change the layout of the
3500b57cec5SDimitry Andric // existing members. That's because the space for the new members are not
3510b57cec5SDimitry Andric // reserved in .bss unless you recompile the main program. That means they
3520b57cec5SDimitry Andric // are likely to overlap with other data that happens to be laid out next
3530b57cec5SDimitry Andric // to the variable in .bss. This kind of issue is sometimes very hard to
354480093f4SDimitry Andric // debug. What's a solution? Instead of exporting a variable V from a DSO,
3550b57cec5SDimitry Andric // define an accessor getV().
356*0eae32dcSDimitry Andric template <class ELFT> static void addCopyRelSymbolImpl(SharedSymbol &ss) {
3570b57cec5SDimitry Andric   // Copy relocation against zero-sized symbol doesn't make sense.
3580b57cec5SDimitry Andric   uint64_t symSize = ss.getSize();
3590b57cec5SDimitry Andric   if (symSize == 0 || ss.alignment == 0)
3600b57cec5SDimitry Andric     fatal("cannot create a copy relocation for symbol " + toString(ss));
3610b57cec5SDimitry Andric 
3620b57cec5SDimitry Andric   // See if this symbol is in a read-only segment. If so, preserve the symbol's
3630b57cec5SDimitry Andric   // memory protection by reserving space in the .bss.rel.ro section.
3640b57cec5SDimitry Andric   bool isRO = isReadOnly<ELFT>(ss);
3650b57cec5SDimitry Andric   BssSection *sec =
3660b57cec5SDimitry Andric       make<BssSection>(isRO ? ".bss.rel.ro" : ".bss", symSize, ss.alignment);
36785868e8aSDimitry Andric   OutputSection *osec = (isRO ? in.bssRelRo : in.bss)->getParent();
36885868e8aSDimitry Andric 
36985868e8aSDimitry Andric   // At this point, sectionBases has been migrated to sections. Append sec to
37085868e8aSDimitry Andric   // sections.
3714824e7fdSDimitry Andric   if (osec->commands.empty() ||
3724824e7fdSDimitry Andric       !isa<InputSectionDescription>(osec->commands.back()))
3734824e7fdSDimitry Andric     osec->commands.push_back(make<InputSectionDescription>(""));
3744824e7fdSDimitry Andric   auto *isd = cast<InputSectionDescription>(osec->commands.back());
37585868e8aSDimitry Andric   isd->sections.push_back(sec);
37685868e8aSDimitry Andric   osec->commitSection(sec);
3770b57cec5SDimitry Andric 
3780b57cec5SDimitry Andric   // Look through the DSO's dynamic symbol table for aliases and create a
3790b57cec5SDimitry Andric   // dynamic symbol for each one. This causes the copy relocation to correctly
3800b57cec5SDimitry Andric   // interpose any aliases.
3810b57cec5SDimitry Andric   for (SharedSymbol *sym : getSymbolsAt<ELFT>(ss))
382*0eae32dcSDimitry Andric     replaceWithDefined(*sym, *sec, 0, sym->size);
3830b57cec5SDimitry Andric 
384*0eae32dcSDimitry Andric   mainPart->relaDyn->addSymbolReloc(target->copyRel, *sec, 0, ss);
385*0eae32dcSDimitry Andric }
386*0eae32dcSDimitry Andric 
387*0eae32dcSDimitry Andric static void addCopyRelSymbol(SharedSymbol &ss) {
388*0eae32dcSDimitry Andric   const SharedFile &file = ss.getFile();
389*0eae32dcSDimitry Andric   switch (file.ekind) {
390*0eae32dcSDimitry Andric   case ELF32LEKind:
391*0eae32dcSDimitry Andric     addCopyRelSymbolImpl<ELF32LE>(ss);
392*0eae32dcSDimitry Andric     break;
393*0eae32dcSDimitry Andric   case ELF32BEKind:
394*0eae32dcSDimitry Andric     addCopyRelSymbolImpl<ELF32BE>(ss);
395*0eae32dcSDimitry Andric     break;
396*0eae32dcSDimitry Andric   case ELF64LEKind:
397*0eae32dcSDimitry Andric     addCopyRelSymbolImpl<ELF64LE>(ss);
398*0eae32dcSDimitry Andric     break;
399*0eae32dcSDimitry Andric   case ELF64BEKind:
400*0eae32dcSDimitry Andric     addCopyRelSymbolImpl<ELF64BE>(ss);
401*0eae32dcSDimitry Andric     break;
402*0eae32dcSDimitry Andric   default:
403*0eae32dcSDimitry Andric     llvm_unreachable("");
404*0eae32dcSDimitry Andric   }
4050b57cec5SDimitry Andric }
4060b57cec5SDimitry Andric 
4070b57cec5SDimitry Andric // MIPS has an odd notion of "paired" relocations to calculate addends.
4080b57cec5SDimitry Andric // For example, if a relocation is of R_MIPS_HI16, there must be a
4090b57cec5SDimitry Andric // R_MIPS_LO16 relocation after that, and an addend is calculated using
4100b57cec5SDimitry Andric // the two relocations.
4110b57cec5SDimitry Andric template <class ELFT, class RelTy>
4120b57cec5SDimitry Andric static int64_t computeMipsAddend(const RelTy &rel, const RelTy *end,
4130b57cec5SDimitry Andric                                  InputSectionBase &sec, RelExpr expr,
4140b57cec5SDimitry Andric                                  bool isLocal) {
4150b57cec5SDimitry Andric   if (expr == R_MIPS_GOTREL && isLocal)
4160b57cec5SDimitry Andric     return sec.getFile<ELFT>()->mipsGp0;
4170b57cec5SDimitry Andric 
4180b57cec5SDimitry Andric   // The ABI says that the paired relocation is used only for REL.
4190b57cec5SDimitry Andric   // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
4200b57cec5SDimitry Andric   if (RelTy::IsRela)
4210b57cec5SDimitry Andric     return 0;
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric   RelType type = rel.getType(config->isMips64EL);
4240b57cec5SDimitry Andric   uint32_t pairTy = getMipsPairType(type, isLocal);
4250b57cec5SDimitry Andric   if (pairTy == R_MIPS_NONE)
4260b57cec5SDimitry Andric     return 0;
4270b57cec5SDimitry Andric 
4280b57cec5SDimitry Andric   const uint8_t *buf = sec.data().data();
4290b57cec5SDimitry Andric   uint32_t symIndex = rel.getSymbol(config->isMips64EL);
4300b57cec5SDimitry Andric 
4310b57cec5SDimitry Andric   // To make things worse, paired relocations might not be contiguous in
4320b57cec5SDimitry Andric   // the relocation table, so we need to do linear search. *sigh*
4330b57cec5SDimitry Andric   for (const RelTy *ri = &rel; ri != end; ++ri)
4340b57cec5SDimitry Andric     if (ri->getType(config->isMips64EL) == pairTy &&
4350b57cec5SDimitry Andric         ri->getSymbol(config->isMips64EL) == symIndex)
4360b57cec5SDimitry Andric       return target->getImplicitAddend(buf + ri->r_offset, pairTy);
4370b57cec5SDimitry Andric 
4380b57cec5SDimitry Andric   warn("can't find matching " + toString(pairTy) + " relocation for " +
4390b57cec5SDimitry Andric        toString(type));
4400b57cec5SDimitry Andric   return 0;
4410b57cec5SDimitry Andric }
4420b57cec5SDimitry Andric 
4430b57cec5SDimitry Andric // Returns an addend of a given relocation. If it is RELA, an addend
4440b57cec5SDimitry Andric // is in a relocation itself. If it is REL, we need to read it from an
4450b57cec5SDimitry Andric // input section.
4460b57cec5SDimitry Andric template <class ELFT, class RelTy>
4470b57cec5SDimitry Andric static int64_t computeAddend(const RelTy &rel, const RelTy *end,
4480b57cec5SDimitry Andric                              InputSectionBase &sec, RelExpr expr,
4490b57cec5SDimitry Andric                              bool isLocal) {
4500b57cec5SDimitry Andric   int64_t addend;
4510b57cec5SDimitry Andric   RelType type = rel.getType(config->isMips64EL);
4520b57cec5SDimitry Andric 
4530b57cec5SDimitry Andric   if (RelTy::IsRela) {
4540b57cec5SDimitry Andric     addend = getAddend<ELFT>(rel);
4550b57cec5SDimitry Andric   } else {
4560b57cec5SDimitry Andric     const uint8_t *buf = sec.data().data();
4570b57cec5SDimitry Andric     addend = target->getImplicitAddend(buf + rel.r_offset, type);
4580b57cec5SDimitry Andric   }
4590b57cec5SDimitry Andric 
4600b57cec5SDimitry Andric   if (config->emachine == EM_PPC64 && config->isPic && type == R_PPC64_TOC)
4610b57cec5SDimitry Andric     addend += getPPC64TocBase();
4620b57cec5SDimitry Andric   if (config->emachine == EM_MIPS)
4630b57cec5SDimitry Andric     addend += computeMipsAddend<ELFT>(rel, end, sec, expr, isLocal);
4640b57cec5SDimitry Andric 
4650b57cec5SDimitry Andric   return addend;
4660b57cec5SDimitry Andric }
4670b57cec5SDimitry Andric 
4680b57cec5SDimitry Andric // Custom error message if Sym is defined in a discarded section.
4690b57cec5SDimitry Andric template <class ELFT>
4700b57cec5SDimitry Andric static std::string maybeReportDiscarded(Undefined &sym) {
4710b57cec5SDimitry Andric   auto *file = dyn_cast_or_null<ObjFile<ELFT>>(sym.file);
4720b57cec5SDimitry Andric   if (!file || !sym.discardedSecIdx ||
4730b57cec5SDimitry Andric       file->getSections()[sym.discardedSecIdx] != &InputSection::discarded)
4740b57cec5SDimitry Andric     return "";
475*0eae32dcSDimitry Andric   ArrayRef<typename ELFT::Shdr> objSections =
476*0eae32dcSDimitry Andric       file->template getELFShdrs<ELFT>();
4770b57cec5SDimitry Andric 
4780b57cec5SDimitry Andric   std::string msg;
4790b57cec5SDimitry Andric   if (sym.type == ELF::STT_SECTION) {
4800b57cec5SDimitry Andric     msg = "relocation refers to a discarded section: ";
4810b57cec5SDimitry Andric     msg += CHECK(
482e8d8bef9SDimitry Andric         file->getObj().getSectionName(objSections[sym.discardedSecIdx]), file);
4830b57cec5SDimitry Andric   } else {
4840b57cec5SDimitry Andric     msg = "relocation refers to a symbol in a discarded section: " +
4850b57cec5SDimitry Andric           toString(sym);
4860b57cec5SDimitry Andric   }
4870b57cec5SDimitry Andric   msg += "\n>>> defined in " + toString(file);
4880b57cec5SDimitry Andric 
4890b57cec5SDimitry Andric   Elf_Shdr_Impl<ELFT> elfSec = objSections[sym.discardedSecIdx - 1];
4900b57cec5SDimitry Andric   if (elfSec.sh_type != SHT_GROUP)
4910b57cec5SDimitry Andric     return msg;
4920b57cec5SDimitry Andric 
4930b57cec5SDimitry Andric   // If the discarded section is a COMDAT.
4940b57cec5SDimitry Andric   StringRef signature = file->getShtGroupSignature(objSections, elfSec);
4950b57cec5SDimitry Andric   if (const InputFile *prevailing =
4960b57cec5SDimitry Andric           symtab->comdatGroups.lookup(CachedHashStringRef(signature)))
4970b57cec5SDimitry Andric     msg += "\n>>> section group signature: " + signature.str() +
4980b57cec5SDimitry Andric            "\n>>> prevailing definition is in " + toString(prevailing);
4990b57cec5SDimitry Andric   return msg;
5000b57cec5SDimitry Andric }
5010b57cec5SDimitry Andric 
5020b57cec5SDimitry Andric // Undefined diagnostics are collected in a vector and emitted once all of
5030b57cec5SDimitry Andric // them are known, so that some postprocessing on the list of undefined symbols
5040b57cec5SDimitry Andric // can happen before lld emits diagnostics.
5050b57cec5SDimitry Andric struct UndefinedDiag {
5060b57cec5SDimitry Andric   Symbol *sym;
5070b57cec5SDimitry Andric   struct Loc {
5080b57cec5SDimitry Andric     InputSectionBase *sec;
5090b57cec5SDimitry Andric     uint64_t offset;
5100b57cec5SDimitry Andric   };
5110b57cec5SDimitry Andric   std::vector<Loc> locs;
5120b57cec5SDimitry Andric   bool isWarning;
5130b57cec5SDimitry Andric };
5140b57cec5SDimitry Andric 
5150b57cec5SDimitry Andric static std::vector<UndefinedDiag> undefs;
5160b57cec5SDimitry Andric 
517480093f4SDimitry Andric // Check whether the definition name def is a mangled function name that matches
518480093f4SDimitry Andric // the reference name ref.
519480093f4SDimitry Andric static bool canSuggestExternCForCXX(StringRef ref, StringRef def) {
520480093f4SDimitry Andric   llvm::ItaniumPartialDemangler d;
521480093f4SDimitry Andric   std::string name = def.str();
522480093f4SDimitry Andric   if (d.partialDemangle(name.c_str()))
523480093f4SDimitry Andric     return false;
524480093f4SDimitry Andric   char *buf = d.getFunctionName(nullptr, nullptr);
525480093f4SDimitry Andric   if (!buf)
526480093f4SDimitry Andric     return false;
527480093f4SDimitry Andric   bool ret = ref == buf;
528480093f4SDimitry Andric   free(buf);
529480093f4SDimitry Andric   return ret;
530480093f4SDimitry Andric }
531480093f4SDimitry Andric 
53285868e8aSDimitry Andric // Suggest an alternative spelling of an "undefined symbol" diagnostic. Returns
53385868e8aSDimitry Andric // the suggested symbol, which is either in the symbol table, or in the same
53485868e8aSDimitry Andric // file of sym.
535480093f4SDimitry Andric template <class ELFT>
536480093f4SDimitry Andric static const Symbol *getAlternativeSpelling(const Undefined &sym,
537480093f4SDimitry Andric                                             std::string &pre_hint,
538480093f4SDimitry Andric                                             std::string &post_hint) {
53985868e8aSDimitry Andric   DenseMap<StringRef, const Symbol *> map;
540480093f4SDimitry Andric   if (auto *file = dyn_cast_or_null<ObjFile<ELFT>>(sym.file)) {
541480093f4SDimitry Andric     // If sym is a symbol defined in a discarded section, maybeReportDiscarded()
542480093f4SDimitry Andric     // will give an error. Don't suggest an alternative spelling.
543480093f4SDimitry Andric     if (file && sym.discardedSecIdx != 0 &&
544480093f4SDimitry Andric         file->getSections()[sym.discardedSecIdx] == &InputSection::discarded)
545480093f4SDimitry Andric       return nullptr;
546480093f4SDimitry Andric 
547480093f4SDimitry Andric     // Build a map of local defined symbols.
54885868e8aSDimitry Andric     for (const Symbol *s : sym.file->getSymbols())
549fe6060f1SDimitry Andric       if (s->isLocal() && s->isDefined() && !s->getName().empty())
55085868e8aSDimitry Andric         map.try_emplace(s->getName(), s);
55185868e8aSDimitry Andric   }
55285868e8aSDimitry Andric 
55385868e8aSDimitry Andric   auto suggest = [&](StringRef newName) -> const Symbol * {
55485868e8aSDimitry Andric     // If defined locally.
55585868e8aSDimitry Andric     if (const Symbol *s = map.lookup(newName))
55685868e8aSDimitry Andric       return s;
55785868e8aSDimitry Andric 
55885868e8aSDimitry Andric     // If in the symbol table and not undefined.
55985868e8aSDimitry Andric     if (const Symbol *s = symtab->find(newName))
56085868e8aSDimitry Andric       if (!s->isUndefined())
56185868e8aSDimitry Andric         return s;
56285868e8aSDimitry Andric 
56385868e8aSDimitry Andric     return nullptr;
56485868e8aSDimitry Andric   };
56585868e8aSDimitry Andric 
56685868e8aSDimitry Andric   // This loop enumerates all strings of Levenshtein distance 1 as typo
56785868e8aSDimitry Andric   // correction candidates and suggests the one that exists as a non-undefined
56885868e8aSDimitry Andric   // symbol.
56985868e8aSDimitry Andric   StringRef name = sym.getName();
57085868e8aSDimitry Andric   for (size_t i = 0, e = name.size(); i != e + 1; ++i) {
57185868e8aSDimitry Andric     // Insert a character before name[i].
57285868e8aSDimitry Andric     std::string newName = (name.substr(0, i) + "0" + name.substr(i)).str();
57385868e8aSDimitry Andric     for (char c = '0'; c <= 'z'; ++c) {
57485868e8aSDimitry Andric       newName[i] = c;
57585868e8aSDimitry Andric       if (const Symbol *s = suggest(newName))
57685868e8aSDimitry Andric         return s;
57785868e8aSDimitry Andric     }
57885868e8aSDimitry Andric     if (i == e)
57985868e8aSDimitry Andric       break;
58085868e8aSDimitry Andric 
58185868e8aSDimitry Andric     // Substitute name[i].
5825ffd83dbSDimitry Andric     newName = std::string(name);
58385868e8aSDimitry Andric     for (char c = '0'; c <= 'z'; ++c) {
58485868e8aSDimitry Andric       newName[i] = c;
58585868e8aSDimitry Andric       if (const Symbol *s = suggest(newName))
58685868e8aSDimitry Andric         return s;
58785868e8aSDimitry Andric     }
58885868e8aSDimitry Andric 
58985868e8aSDimitry Andric     // Transpose name[i] and name[i+1]. This is of edit distance 2 but it is
59085868e8aSDimitry Andric     // common.
59185868e8aSDimitry Andric     if (i + 1 < e) {
59285868e8aSDimitry Andric       newName[i] = name[i + 1];
59385868e8aSDimitry Andric       newName[i + 1] = name[i];
59485868e8aSDimitry Andric       if (const Symbol *s = suggest(newName))
59585868e8aSDimitry Andric         return s;
59685868e8aSDimitry Andric     }
59785868e8aSDimitry Andric 
59885868e8aSDimitry Andric     // Delete name[i].
59985868e8aSDimitry Andric     newName = (name.substr(0, i) + name.substr(i + 1)).str();
60085868e8aSDimitry Andric     if (const Symbol *s = suggest(newName))
60185868e8aSDimitry Andric       return s;
60285868e8aSDimitry Andric   }
60385868e8aSDimitry Andric 
604480093f4SDimitry Andric   // Case mismatch, e.g. Foo vs FOO.
605480093f4SDimitry Andric   for (auto &it : map)
606fe6060f1SDimitry Andric     if (name.equals_insensitive(it.first))
607480093f4SDimitry Andric       return it.second;
608480093f4SDimitry Andric   for (Symbol *sym : symtab->symbols())
609fe6060f1SDimitry Andric     if (!sym->isUndefined() && name.equals_insensitive(sym->getName()))
610480093f4SDimitry Andric       return sym;
611480093f4SDimitry Andric 
612480093f4SDimitry Andric   // The reference may be a mangled name while the definition is not. Suggest a
613480093f4SDimitry Andric   // missing extern "C".
614480093f4SDimitry Andric   if (name.startswith("_Z")) {
615480093f4SDimitry Andric     std::string buf = name.str();
616480093f4SDimitry Andric     llvm::ItaniumPartialDemangler d;
617480093f4SDimitry Andric     if (!d.partialDemangle(buf.c_str()))
618480093f4SDimitry Andric       if (char *buf = d.getFunctionName(nullptr, nullptr)) {
619480093f4SDimitry Andric         const Symbol *s = suggest(buf);
620480093f4SDimitry Andric         free(buf);
621480093f4SDimitry Andric         if (s) {
622480093f4SDimitry Andric           pre_hint = ": extern \"C\" ";
623480093f4SDimitry Andric           return s;
624480093f4SDimitry Andric         }
625480093f4SDimitry Andric       }
626480093f4SDimitry Andric   } else {
627480093f4SDimitry Andric     const Symbol *s = nullptr;
628480093f4SDimitry Andric     for (auto &it : map)
629480093f4SDimitry Andric       if (canSuggestExternCForCXX(name, it.first)) {
630480093f4SDimitry Andric         s = it.second;
631480093f4SDimitry Andric         break;
632480093f4SDimitry Andric       }
633480093f4SDimitry Andric     if (!s)
634480093f4SDimitry Andric       for (Symbol *sym : symtab->symbols())
635480093f4SDimitry Andric         if (canSuggestExternCForCXX(name, sym->getName())) {
636480093f4SDimitry Andric           s = sym;
637480093f4SDimitry Andric           break;
638480093f4SDimitry Andric         }
639480093f4SDimitry Andric     if (s) {
640480093f4SDimitry Andric       pre_hint = " to declare ";
641480093f4SDimitry Andric       post_hint = " as extern \"C\"?";
642480093f4SDimitry Andric       return s;
643480093f4SDimitry Andric     }
644480093f4SDimitry Andric   }
645480093f4SDimitry Andric 
64685868e8aSDimitry Andric   return nullptr;
64785868e8aSDimitry Andric }
64885868e8aSDimitry Andric 
6490b57cec5SDimitry Andric template <class ELFT>
65085868e8aSDimitry Andric static void reportUndefinedSymbol(const UndefinedDiag &undef,
65185868e8aSDimitry Andric                                   bool correctSpelling) {
6520b57cec5SDimitry Andric   Symbol &sym = *undef.sym;
6530b57cec5SDimitry Andric 
6540b57cec5SDimitry Andric   auto visibility = [&]() -> std::string {
6550b57cec5SDimitry Andric     switch (sym.visibility) {
6560b57cec5SDimitry Andric     case STV_INTERNAL:
6570b57cec5SDimitry Andric       return "internal ";
6580b57cec5SDimitry Andric     case STV_HIDDEN:
6590b57cec5SDimitry Andric       return "hidden ";
6600b57cec5SDimitry Andric     case STV_PROTECTED:
6610b57cec5SDimitry Andric       return "protected ";
6620b57cec5SDimitry Andric     default:
6630b57cec5SDimitry Andric       return "";
6640b57cec5SDimitry Andric     }
6650b57cec5SDimitry Andric   };
6660b57cec5SDimitry Andric 
6670b57cec5SDimitry Andric   std::string msg = maybeReportDiscarded<ELFT>(cast<Undefined>(sym));
6680b57cec5SDimitry Andric   if (msg.empty())
6690b57cec5SDimitry Andric     msg = "undefined " + visibility() + "symbol: " + toString(sym);
6700b57cec5SDimitry Andric 
6715ffd83dbSDimitry Andric   const size_t maxUndefReferences = 3;
6720b57cec5SDimitry Andric   size_t i = 0;
6730b57cec5SDimitry Andric   for (UndefinedDiag::Loc l : undef.locs) {
6740b57cec5SDimitry Andric     if (i >= maxUndefReferences)
6750b57cec5SDimitry Andric       break;
6760b57cec5SDimitry Andric     InputSectionBase &sec = *l.sec;
6770b57cec5SDimitry Andric     uint64_t offset = l.offset;
6780b57cec5SDimitry Andric 
6790b57cec5SDimitry Andric     msg += "\n>>> referenced by ";
6800b57cec5SDimitry Andric     std::string src = sec.getSrcMsg(sym, offset);
6810b57cec5SDimitry Andric     if (!src.empty())
6820b57cec5SDimitry Andric       msg += src + "\n>>>               ";
6830b57cec5SDimitry Andric     msg += sec.getObjMsg(offset);
6840b57cec5SDimitry Andric     i++;
6850b57cec5SDimitry Andric   }
6860b57cec5SDimitry Andric 
6870b57cec5SDimitry Andric   if (i < undef.locs.size())
6880b57cec5SDimitry Andric     msg += ("\n>>> referenced " + Twine(undef.locs.size() - i) + " more times")
6890b57cec5SDimitry Andric                .str();
6900b57cec5SDimitry Andric 
691480093f4SDimitry Andric   if (correctSpelling) {
692480093f4SDimitry Andric     std::string pre_hint = ": ", post_hint;
693480093f4SDimitry Andric     if (const Symbol *corrected = getAlternativeSpelling<ELFT>(
694480093f4SDimitry Andric             cast<Undefined>(sym), pre_hint, post_hint)) {
695480093f4SDimitry Andric       msg += "\n>>> did you mean" + pre_hint + toString(*corrected) + post_hint;
69685868e8aSDimitry Andric       if (corrected->file)
69785868e8aSDimitry Andric         msg += "\n>>> defined in: " + toString(corrected->file);
69885868e8aSDimitry Andric     }
699480093f4SDimitry Andric   }
70085868e8aSDimitry Andric 
7010b57cec5SDimitry Andric   if (sym.getName().startswith("_ZTV"))
7025ffd83dbSDimitry Andric     msg +=
7035ffd83dbSDimitry Andric         "\n>>> the vtable symbol may be undefined because the class is missing "
7040b57cec5SDimitry Andric         "its key function (see https://lld.llvm.org/missingkeyfunction)";
705*0eae32dcSDimitry Andric   if (config->gcSections && config->zStartStopGC &&
706*0eae32dcSDimitry Andric       sym.getName().startswith("__start_")) {
707*0eae32dcSDimitry Andric     msg += "\n>>> the encapsulation symbol needs to be retained under "
708*0eae32dcSDimitry Andric            "--gc-sections properly; consider -z nostart-stop-gc "
709*0eae32dcSDimitry Andric            "(see https://lld.llvm.org/ELF/start-stop-gc)";
710*0eae32dcSDimitry Andric   }
7110b57cec5SDimitry Andric 
7120b57cec5SDimitry Andric   if (undef.isWarning)
7130b57cec5SDimitry Andric     warn(msg);
7140b57cec5SDimitry Andric   else
715e8d8bef9SDimitry Andric     error(msg, ErrorTag::SymbolNotFound, {sym.getName()});
7160b57cec5SDimitry Andric }
7170b57cec5SDimitry Andric 
7185ffd83dbSDimitry Andric template <class ELFT> void elf::reportUndefinedSymbols() {
7190b57cec5SDimitry Andric   // Find the first "undefined symbol" diagnostic for each diagnostic, and
7200b57cec5SDimitry Andric   // collect all "referenced from" lines at the first diagnostic.
7210b57cec5SDimitry Andric   DenseMap<Symbol *, UndefinedDiag *> firstRef;
7220b57cec5SDimitry Andric   for (UndefinedDiag &undef : undefs) {
7230b57cec5SDimitry Andric     assert(undef.locs.size() == 1);
7240b57cec5SDimitry Andric     if (UndefinedDiag *canon = firstRef.lookup(undef.sym)) {
7250b57cec5SDimitry Andric       canon->locs.push_back(undef.locs[0]);
7260b57cec5SDimitry Andric       undef.locs.clear();
7270b57cec5SDimitry Andric     } else
7280b57cec5SDimitry Andric       firstRef[undef.sym] = &undef;
7290b57cec5SDimitry Andric   }
7300b57cec5SDimitry Andric 
73185868e8aSDimitry Andric   // Enable spell corrector for the first 2 diagnostics.
73285868e8aSDimitry Andric   for (auto it : enumerate(undefs))
73385868e8aSDimitry Andric     if (!it.value().locs.empty())
73485868e8aSDimitry Andric       reportUndefinedSymbol<ELFT>(it.value(), it.index() < 2);
7350b57cec5SDimitry Andric   undefs.clear();
7360b57cec5SDimitry Andric }
7370b57cec5SDimitry Andric 
7380b57cec5SDimitry Andric // Report an undefined symbol if necessary.
7390b57cec5SDimitry Andric // Returns true if the undefined symbol will produce an error message.
7400b57cec5SDimitry Andric static bool maybeReportUndefined(Symbol &sym, InputSectionBase &sec,
7410b57cec5SDimitry Andric                                  uint64_t offset) {
742e8d8bef9SDimitry Andric   // If versioned, issue an error (even if the symbol is weak) because we don't
743e8d8bef9SDimitry Andric   // know the defining filename which is required to construct a Verneed entry.
744e8d8bef9SDimitry Andric   if (*sym.getVersionSuffix() == '@') {
745e8d8bef9SDimitry Andric     undefs.push_back({&sym, {{&sec, offset}}, false});
746e8d8bef9SDimitry Andric     return true;
747e8d8bef9SDimitry Andric   }
748e8d8bef9SDimitry Andric   if (sym.isWeak())
7490b57cec5SDimitry Andric     return false;
7500b57cec5SDimitry Andric 
75185868e8aSDimitry Andric   bool canBeExternal = !sym.isLocal() && sym.visibility == STV_DEFAULT;
7520b57cec5SDimitry Andric   if (config->unresolvedSymbols == UnresolvedPolicy::Ignore && canBeExternal)
7530b57cec5SDimitry Andric     return false;
7540b57cec5SDimitry Andric 
7550b57cec5SDimitry Andric   // clang (as of 2019-06-12) / gcc (as of 8.2.1) PPC64 may emit a .rela.toc
7560b57cec5SDimitry Andric   // which references a switch table in a discarded .rodata/.text section. The
7570b57cec5SDimitry Andric   // .toc and the .rela.toc are incorrectly not placed in the comdat. The ELF
7580b57cec5SDimitry Andric   // spec says references from outside the group to a STB_LOCAL symbol are not
7590b57cec5SDimitry Andric   // allowed. Work around the bug.
7605a0c326fSDimitry Andric   //
7615a0c326fSDimitry Andric   // PPC32 .got2 is similar but cannot be fixed. Multiple .got2 is infeasible
7625a0c326fSDimitry Andric   // because .LC0-.LTOC is not representable if the two labels are in different
7635a0c326fSDimitry Andric   // .got2
7645a0c326fSDimitry Andric   if (cast<Undefined>(sym).discardedSecIdx != 0 &&
7655a0c326fSDimitry Andric       (sec.name == ".got2" || sec.name == ".toc"))
7660b57cec5SDimitry Andric     return false;
7670b57cec5SDimitry Andric 
7680b57cec5SDimitry Andric   bool isWarning =
7690b57cec5SDimitry Andric       (config->unresolvedSymbols == UnresolvedPolicy::Warn && canBeExternal) ||
7700b57cec5SDimitry Andric       config->noinhibitExec;
7710b57cec5SDimitry Andric   undefs.push_back({&sym, {{&sec, offset}}, isWarning});
7720b57cec5SDimitry Andric   return !isWarning;
7730b57cec5SDimitry Andric }
7740b57cec5SDimitry Andric 
7750b57cec5SDimitry Andric // MIPS N32 ABI treats series of successive relocations with the same offset
7760b57cec5SDimitry Andric // as a single relocation. The similar approach used by N64 ABI, but this ABI
7770b57cec5SDimitry Andric // packs all relocations into the single relocation record. Here we emulate
7780b57cec5SDimitry Andric // this for the N32 ABI. Iterate over relocation with the same offset and put
7790b57cec5SDimitry Andric // theirs types into the single bit-set.
7800b57cec5SDimitry Andric template <class RelTy> static RelType getMipsN32RelType(RelTy *&rel, RelTy *end) {
7810b57cec5SDimitry Andric   RelType type = 0;
7820b57cec5SDimitry Andric   uint64_t offset = rel->r_offset;
7830b57cec5SDimitry Andric 
7840b57cec5SDimitry Andric   int n = 0;
7850b57cec5SDimitry Andric   while (rel != end && rel->r_offset == offset)
7860b57cec5SDimitry Andric     type |= (rel++)->getType(config->isMips64EL) << (8 * n++);
7870b57cec5SDimitry Andric   return type;
7880b57cec5SDimitry Andric }
7890b57cec5SDimitry Andric 
7900b57cec5SDimitry Andric // .eh_frame sections are mergeable input sections, so their input
7910b57cec5SDimitry Andric // offsets are not linearly mapped to output section. For each input
7920b57cec5SDimitry Andric // offset, we need to find a section piece containing the offset and
7930b57cec5SDimitry Andric // add the piece's base address to the input offset to compute the
7940b57cec5SDimitry Andric // output offset. That isn't cheap.
7950b57cec5SDimitry Andric //
7960b57cec5SDimitry Andric // This class is to speed up the offset computation. When we process
7970b57cec5SDimitry Andric // relocations, we access offsets in the monotonically increasing
7980b57cec5SDimitry Andric // order. So we can optimize for that access pattern.
7990b57cec5SDimitry Andric //
8000b57cec5SDimitry Andric // For sections other than .eh_frame, this class doesn't do anything.
8010b57cec5SDimitry Andric namespace {
8020b57cec5SDimitry Andric class OffsetGetter {
8030b57cec5SDimitry Andric public:
8040b57cec5SDimitry Andric   explicit OffsetGetter(InputSectionBase &sec) {
8050b57cec5SDimitry Andric     if (auto *eh = dyn_cast<EhInputSection>(&sec))
8060b57cec5SDimitry Andric       pieces = eh->pieces;
8070b57cec5SDimitry Andric   }
8080b57cec5SDimitry Andric 
8090b57cec5SDimitry Andric   // Translates offsets in input sections to offsets in output sections.
8100b57cec5SDimitry Andric   // Given offset must increase monotonically. We assume that Piece is
8110b57cec5SDimitry Andric   // sorted by inputOff.
8120b57cec5SDimitry Andric   uint64_t get(uint64_t off) {
8130b57cec5SDimitry Andric     if (pieces.empty())
8140b57cec5SDimitry Andric       return off;
8150b57cec5SDimitry Andric 
8160b57cec5SDimitry Andric     while (i != pieces.size() && pieces[i].inputOff + pieces[i].size <= off)
8170b57cec5SDimitry Andric       ++i;
8180b57cec5SDimitry Andric     if (i == pieces.size())
8190b57cec5SDimitry Andric       fatal(".eh_frame: relocation is not in any piece");
8200b57cec5SDimitry Andric 
8210b57cec5SDimitry Andric     // Pieces must be contiguous, so there must be no holes in between.
8220b57cec5SDimitry Andric     assert(pieces[i].inputOff <= off && "Relocation not in any piece");
8230b57cec5SDimitry Andric 
8240b57cec5SDimitry Andric     // Offset -1 means that the piece is dead (i.e. garbage collected).
8250b57cec5SDimitry Andric     if (pieces[i].outputOff == -1)
8260b57cec5SDimitry Andric       return -1;
8270b57cec5SDimitry Andric     return pieces[i].outputOff + off - pieces[i].inputOff;
8280b57cec5SDimitry Andric   }
8290b57cec5SDimitry Andric 
8300b57cec5SDimitry Andric private:
8310b57cec5SDimitry Andric   ArrayRef<EhSectionPiece> pieces;
8320b57cec5SDimitry Andric   size_t i = 0;
8330b57cec5SDimitry Andric };
8340b57cec5SDimitry Andric } // namespace
8350b57cec5SDimitry Andric 
836*0eae32dcSDimitry Andric static void addRelativeReloc(InputSectionBase &isec, uint64_t offsetInSec,
837fe6060f1SDimitry Andric                              Symbol &sym, int64_t addend, RelExpr expr,
8380b57cec5SDimitry Andric                              RelType type) {
839*0eae32dcSDimitry Andric   Partition &part = isec.getPartition();
8400b57cec5SDimitry Andric 
8410b57cec5SDimitry Andric   // Add a relative relocation. If relrDyn section is enabled, and the
8420b57cec5SDimitry Andric   // relocation offset is guaranteed to be even, add the relocation to
8430b57cec5SDimitry Andric   // the relrDyn section, otherwise add it to the relaDyn section.
8440b57cec5SDimitry Andric   // relrDyn sections don't support odd offsets. Also, relrDyn sections
8450b57cec5SDimitry Andric   // don't store the addend values, so we must write it to the relocated
8460b57cec5SDimitry Andric   // address.
847*0eae32dcSDimitry Andric   if (part.relrDyn && isec.alignment >= 2 && offsetInSec % 2 == 0) {
848*0eae32dcSDimitry Andric     isec.relocations.push_back({expr, type, offsetInSec, addend, &sym});
849*0eae32dcSDimitry Andric     part.relrDyn->relocs.push_back({&isec, offsetInSec});
8500b57cec5SDimitry Andric     return;
8510b57cec5SDimitry Andric   }
852fe6060f1SDimitry Andric   part.relaDyn->addRelativeReloc(target->relativeRel, isec, offsetInSec, sym,
853fe6060f1SDimitry Andric                                  addend, type, expr);
8540b57cec5SDimitry Andric }
8550b57cec5SDimitry Andric 
856480093f4SDimitry Andric template <class PltSection, class GotPltSection>
857*0eae32dcSDimitry Andric static void addPltEntry(PltSection &plt, GotPltSection &gotPlt,
858*0eae32dcSDimitry Andric                         RelocationBaseSection &rel, RelType type, Symbol &sym) {
859*0eae32dcSDimitry Andric   plt.addEntry(sym);
860*0eae32dcSDimitry Andric   gotPlt.addEntry(sym);
861*0eae32dcSDimitry Andric   rel.addReloc({type, &gotPlt, sym.getGotPltOffset(),
862fe6060f1SDimitry Andric                 sym.isPreemptible ? DynamicReloc::AgainstSymbol
863fe6060f1SDimitry Andric                                   : DynamicReloc::AddendOnlyWithTargetVA,
864fe6060f1SDimitry Andric                 sym, 0, R_ABS});
8650b57cec5SDimitry Andric }
8660b57cec5SDimitry Andric 
8670b57cec5SDimitry Andric static void addGotEntry(Symbol &sym) {
8680b57cec5SDimitry Andric   in.got->addEntry(sym);
8690b57cec5SDimitry Andric   uint64_t off = sym.getGotOffset();
8700b57cec5SDimitry Andric 
871349cc55cSDimitry Andric   // If preemptible, emit a GLOB_DAT relocation.
872349cc55cSDimitry Andric   if (sym.isPreemptible) {
873349cc55cSDimitry Andric     mainPart->relaDyn->addReloc({target->gotRel, in.got, off,
874349cc55cSDimitry Andric                                  DynamicReloc::AgainstSymbol, sym, 0, R_ABS});
8750b57cec5SDimitry Andric     return;
8760b57cec5SDimitry Andric   }
8770b57cec5SDimitry Andric 
878349cc55cSDimitry Andric   // Otherwise, the value is either a link-time constant or the load base
879349cc55cSDimitry Andric   // plus a constant.
880349cc55cSDimitry Andric   if (!config->isPic || isAbsolute(sym))
881349cc55cSDimitry Andric     in.got->relocations.push_back({R_ABS, target->symbolicRel, off, 0, &sym});
882349cc55cSDimitry Andric   else
883*0eae32dcSDimitry Andric     addRelativeReloc(*in.got, off, sym, 0, R_ABS, target->symbolicRel);
884349cc55cSDimitry Andric }
885349cc55cSDimitry Andric 
886349cc55cSDimitry Andric static void addTpOffsetGotEntry(Symbol &sym) {
887349cc55cSDimitry Andric   in.got->addEntry(sym);
888349cc55cSDimitry Andric   uint64_t off = sym.getGotOffset();
889349cc55cSDimitry Andric   if (!sym.isPreemptible && !config->isPic) {
890349cc55cSDimitry Andric     in.got->relocations.push_back({R_TPREL, target->symbolicRel, off, 0, &sym});
8910b57cec5SDimitry Andric     return;
8920b57cec5SDimitry Andric   }
893fe6060f1SDimitry Andric   mainPart->relaDyn->addAddendOnlyRelocIfNonPreemptible(
894*0eae32dcSDimitry Andric       target->tlsGotRel, *in.got, off, sym, target->symbolicRel);
8950b57cec5SDimitry Andric }
8960b57cec5SDimitry Andric 
8970b57cec5SDimitry Andric // Return true if we can define a symbol in the executable that
8980b57cec5SDimitry Andric // contains the value/function of a symbol defined in a shared
8990b57cec5SDimitry Andric // library.
9000b57cec5SDimitry Andric static bool canDefineSymbolInExecutable(Symbol &sym) {
9010b57cec5SDimitry Andric   // If the symbol has default visibility the symbol defined in the
9020b57cec5SDimitry Andric   // executable will preempt it.
9030b57cec5SDimitry Andric   // Note that we want the visibility of the shared symbol itself, not
9040b57cec5SDimitry Andric   // the visibility of the symbol in the output file we are producing. That is
9050b57cec5SDimitry Andric   // why we use Sym.stOther.
9060b57cec5SDimitry Andric   if ((sym.stOther & 0x3) == STV_DEFAULT)
9070b57cec5SDimitry Andric     return true;
9080b57cec5SDimitry Andric 
9090b57cec5SDimitry Andric   // If we are allowed to break address equality of functions, defining
9100b57cec5SDimitry Andric   // a plt entry will allow the program to call the function in the
9110b57cec5SDimitry Andric   // .so, but the .so and the executable will no agree on the address
9120b57cec5SDimitry Andric   // of the function. Similar logic for objects.
9130b57cec5SDimitry Andric   return ((sym.isFunc() && config->ignoreFunctionAddressEquality) ||
9140b57cec5SDimitry Andric           (sym.isObject() && config->ignoreDataAddressEquality));
9150b57cec5SDimitry Andric }
9160b57cec5SDimitry Andric 
917349cc55cSDimitry Andric // Returns true if a given relocation can be computed at link-time.
918349cc55cSDimitry Andric // This only handles relocation types expected in processRelocAux.
919349cc55cSDimitry Andric //
920349cc55cSDimitry Andric // For instance, we know the offset from a relocation to its target at
921349cc55cSDimitry Andric // link-time if the relocation is PC-relative and refers a
922349cc55cSDimitry Andric // non-interposable function in the same executable. This function
923349cc55cSDimitry Andric // will return true for such relocation.
924349cc55cSDimitry Andric //
925349cc55cSDimitry Andric // If this function returns false, that means we need to emit a
926349cc55cSDimitry Andric // dynamic relocation so that the relocation will be fixed at load-time.
927349cc55cSDimitry Andric static bool isStaticLinkTimeConstant(RelExpr e, RelType type, const Symbol &sym,
928349cc55cSDimitry Andric                                      InputSectionBase &s, uint64_t relOff) {
929349cc55cSDimitry Andric   // These expressions always compute a constant
930349cc55cSDimitry Andric   if (oneof<R_GOTPLT, R_GOT_OFF, R_MIPS_GOT_LOCAL_PAGE, R_MIPS_GOTREL,
931349cc55cSDimitry Andric             R_MIPS_GOT_OFF, R_MIPS_GOT_OFF32, R_MIPS_GOT_GP_PC,
932349cc55cSDimitry Andric             R_AARCH64_GOT_PAGE_PC, R_GOT_PC, R_GOTONLY_PC, R_GOTPLTONLY_PC,
933349cc55cSDimitry Andric             R_PLT_PC, R_PLT_GOTPLT, R_PPC32_PLTREL, R_PPC64_CALL_PLT,
934349cc55cSDimitry Andric             R_PPC64_RELAX_TOC, R_RISCV_ADD, R_AARCH64_GOT_PAGE>(e))
935349cc55cSDimitry Andric     return true;
936349cc55cSDimitry Andric 
937349cc55cSDimitry Andric   // These never do, except if the entire file is position dependent or if
938349cc55cSDimitry Andric   // only the low bits are used.
939349cc55cSDimitry Andric   if (e == R_GOT || e == R_PLT)
940349cc55cSDimitry Andric     return target->usesOnlyLowPageBits(type) || !config->isPic;
941349cc55cSDimitry Andric 
942349cc55cSDimitry Andric   if (sym.isPreemptible)
943349cc55cSDimitry Andric     return false;
944349cc55cSDimitry Andric   if (!config->isPic)
945349cc55cSDimitry Andric     return true;
946349cc55cSDimitry Andric 
947349cc55cSDimitry Andric   // The size of a non preemptible symbol is a constant.
948349cc55cSDimitry Andric   if (e == R_SIZE)
949349cc55cSDimitry Andric     return true;
950349cc55cSDimitry Andric 
951349cc55cSDimitry Andric   // For the target and the relocation, we want to know if they are
952349cc55cSDimitry Andric   // absolute or relative.
953349cc55cSDimitry Andric   bool absVal = isAbsoluteValue(sym);
954349cc55cSDimitry Andric   bool relE = isRelExpr(e);
955349cc55cSDimitry Andric   if (absVal && !relE)
956349cc55cSDimitry Andric     return true;
957349cc55cSDimitry Andric   if (!absVal && relE)
958349cc55cSDimitry Andric     return true;
959349cc55cSDimitry Andric   if (!absVal && !relE)
960349cc55cSDimitry Andric     return target->usesOnlyLowPageBits(type);
961349cc55cSDimitry Andric 
962349cc55cSDimitry Andric   assert(absVal && relE);
963349cc55cSDimitry Andric 
964349cc55cSDimitry Andric   // Allow R_PLT_PC (optimized to R_PC here) to a hidden undefined weak symbol
965349cc55cSDimitry Andric   // in PIC mode. This is a little strange, but it allows us to link function
966349cc55cSDimitry Andric   // calls to such symbols (e.g. glibc/stdlib/exit.c:__run_exit_handlers).
967349cc55cSDimitry Andric   // Normally such a call will be guarded with a comparison, which will load a
968349cc55cSDimitry Andric   // zero from the GOT.
969349cc55cSDimitry Andric   if (sym.isUndefWeak())
970349cc55cSDimitry Andric     return true;
971349cc55cSDimitry Andric 
972349cc55cSDimitry Andric   // We set the final symbols values for linker script defined symbols later.
973349cc55cSDimitry Andric   // They always can be computed as a link time constant.
974349cc55cSDimitry Andric   if (sym.scriptDefined)
975349cc55cSDimitry Andric       return true;
976349cc55cSDimitry Andric 
977349cc55cSDimitry Andric   error("relocation " + toString(type) + " cannot refer to absolute symbol: " +
978349cc55cSDimitry Andric         toString(sym) + getLocation(s, sym, relOff));
979349cc55cSDimitry Andric   return true;
980349cc55cSDimitry Andric }
981349cc55cSDimitry Andric 
9820b57cec5SDimitry Andric // The reason we have to do this early scan is as follows
9830b57cec5SDimitry Andric // * To mmap the output file, we need to know the size
9840b57cec5SDimitry Andric // * For that, we need to know how many dynamic relocs we will have.
9850b57cec5SDimitry Andric // It might be possible to avoid this by outputting the file with write:
9860b57cec5SDimitry Andric // * Write the allocated output sections, computing addresses.
9870b57cec5SDimitry Andric // * Apply relocations, recording which ones require a dynamic reloc.
9880b57cec5SDimitry Andric // * Write the dynamic relocations.
9890b57cec5SDimitry Andric // * Write the rest of the file.
9900b57cec5SDimitry Andric // This would have some drawbacks. For example, we would only know if .rela.dyn
9910b57cec5SDimitry Andric // is needed after applying relocations. If it is, it will go after rw and rx
9920b57cec5SDimitry Andric // sections. Given that it is ro, we will need an extra PT_LOAD. This
9930b57cec5SDimitry Andric // complicates things for the dynamic linker and means we would have to reserve
9940b57cec5SDimitry Andric // space for the extra PT_LOAD even if we end up not using it.
995349cc55cSDimitry Andric template <class ELFT>
9960b57cec5SDimitry Andric static void processRelocAux(InputSectionBase &sec, RelExpr expr, RelType type,
997349cc55cSDimitry Andric                             uint64_t offset, Symbol &sym, int64_t addend) {
9980b57cec5SDimitry Andric   // If the relocation is known to be a link-time constant, we know no dynamic
9990b57cec5SDimitry Andric   // relocation will be created, pass the control to relocateAlloc() or
10000b57cec5SDimitry Andric   // relocateNonAlloc() to resolve it.
10010b57cec5SDimitry Andric   //
1002fe6060f1SDimitry Andric   // The behavior of an undefined weak reference is implementation defined. For
1003fe6060f1SDimitry Andric   // non-link-time constants, we resolve relocations statically (let
1004fe6060f1SDimitry Andric   // relocate{,Non}Alloc() resolve them) for -no-pie and try producing dynamic
1005fe6060f1SDimitry Andric   // relocations for -pie and -shared.
1006fe6060f1SDimitry Andric   //
1007fe6060f1SDimitry Andric   // The general expectation of -no-pie static linking is that there is no
1008fe6060f1SDimitry Andric   // dynamic relocation (except IRELATIVE). Emitting dynamic relocations for
1009fe6060f1SDimitry Andric   // -shared matches the spirit of its -z undefs default. -pie has freedom on
1010fe6060f1SDimitry Andric   // choices, and we choose dynamic relocations to be consistent with the
1011fe6060f1SDimitry Andric   // handling of GOT-generating relocations.
10120b57cec5SDimitry Andric   if (isStaticLinkTimeConstant(expr, type, sym, sec, offset) ||
1013fe6060f1SDimitry Andric       (!config->isPic && sym.isUndefWeak())) {
10140b57cec5SDimitry Andric     sec.relocations.push_back({expr, type, offset, addend, &sym});
10150b57cec5SDimitry Andric     return;
10160b57cec5SDimitry Andric   }
10170b57cec5SDimitry Andric 
10180b57cec5SDimitry Andric   bool canWrite = (sec.flags & SHF_WRITE) || !config->zText;
10190b57cec5SDimitry Andric   if (canWrite) {
10200b57cec5SDimitry Andric     RelType rel = target->getDynRel(type);
10210b57cec5SDimitry Andric     if (expr == R_GOT || (rel == target->symbolicRel && !sym.isPreemptible)) {
1022*0eae32dcSDimitry Andric       addRelativeReloc(sec, offset, sym, addend, expr, type);
10230b57cec5SDimitry Andric       return;
10240b57cec5SDimitry Andric     } else if (rel != 0) {
10250b57cec5SDimitry Andric       if (config->emachine == EM_MIPS && rel == target->symbolicRel)
10260b57cec5SDimitry Andric         rel = target->relativeRel;
1027*0eae32dcSDimitry Andric       sec.getPartition().relaDyn->addSymbolReloc(rel, sec, offset, sym, addend,
1028fe6060f1SDimitry Andric                                                  type);
10290b57cec5SDimitry Andric 
10300b57cec5SDimitry Andric       // MIPS ABI turns using of GOT and dynamic relocations inside out.
10310b57cec5SDimitry Andric       // While regular ABI uses dynamic relocations to fill up GOT entries
10320b57cec5SDimitry Andric       // MIPS ABI requires dynamic linker to fills up GOT entries using
10330b57cec5SDimitry Andric       // specially sorted dynamic symbol table. This affects even dynamic
10340b57cec5SDimitry Andric       // relocations against symbols which do not require GOT entries
10350b57cec5SDimitry Andric       // creation explicitly, i.e. do not have any GOT-relocations. So if
10360b57cec5SDimitry Andric       // a preemptible symbol has a dynamic relocation we anyway have
10370b57cec5SDimitry Andric       // to create a GOT entry for it.
10380b57cec5SDimitry Andric       // If a non-preemptible symbol has a dynamic relocation against it,
10390b57cec5SDimitry Andric       // dynamic linker takes it st_value, adds offset and writes down
10400b57cec5SDimitry Andric       // result of the dynamic relocation. In case of preemptible symbol
10410b57cec5SDimitry Andric       // dynamic linker performs symbol resolution, writes the symbol value
10420b57cec5SDimitry Andric       // to the GOT entry and reads the GOT entry when it needs to perform
10430b57cec5SDimitry Andric       // a dynamic relocation.
10440b57cec5SDimitry Andric       // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19
10450b57cec5SDimitry Andric       if (config->emachine == EM_MIPS)
10460b57cec5SDimitry Andric         in.mipsGot->addEntry(*sec.file, sym, addend, expr);
10470b57cec5SDimitry Andric       return;
10480b57cec5SDimitry Andric     }
10490b57cec5SDimitry Andric   }
10500b57cec5SDimitry Andric 
105185868e8aSDimitry Andric   // When producing an executable, we can perform copy relocations (for
105285868e8aSDimitry Andric   // STT_OBJECT) and canonical PLT (for STT_FUNC).
105385868e8aSDimitry Andric   if (!config->shared) {
10540b57cec5SDimitry Andric     if (!canDefineSymbolInExecutable(sym)) {
105585868e8aSDimitry Andric       errorOrWarn("cannot preempt symbol: " + toString(sym) +
10560b57cec5SDimitry Andric                   getLocation(sec, sym, offset));
10570b57cec5SDimitry Andric       return;
10580b57cec5SDimitry Andric     }
10590b57cec5SDimitry Andric 
10600b57cec5SDimitry Andric     if (sym.isObject()) {
10610b57cec5SDimitry Andric       // Produce a copy relocation.
10620b57cec5SDimitry Andric       if (auto *ss = dyn_cast<SharedSymbol>(&sym)) {
10630b57cec5SDimitry Andric         if (!config->zCopyreloc)
10640b57cec5SDimitry Andric           error("unresolvable relocation " + toString(type) +
10650b57cec5SDimitry Andric                 " against symbol '" + toString(*ss) +
10660b57cec5SDimitry Andric                 "'; recompile with -fPIC or remove '-z nocopyreloc'" +
10670b57cec5SDimitry Andric                 getLocation(sec, sym, offset));
1068*0eae32dcSDimitry Andric         sym.needsCopy = true;
10690b57cec5SDimitry Andric       }
10700b57cec5SDimitry Andric       sec.relocations.push_back({expr, type, offset, addend, &sym});
10710b57cec5SDimitry Andric       return;
10720b57cec5SDimitry Andric     }
10730b57cec5SDimitry Andric 
10740b57cec5SDimitry Andric     // This handles a non PIC program call to function in a shared library. In
10750b57cec5SDimitry Andric     // an ideal world, we could just report an error saying the relocation can
10760b57cec5SDimitry Andric     // overflow at runtime. In the real world with glibc, crt1.o has a
10770b57cec5SDimitry Andric     // R_X86_64_PC32 pointing to libc.so.
10780b57cec5SDimitry Andric     //
10790b57cec5SDimitry Andric     // The general idea on how to handle such cases is to create a PLT entry and
10800b57cec5SDimitry Andric     // use that as the function value.
10810b57cec5SDimitry Andric     //
10820b57cec5SDimitry Andric     // For the static linking part, we just return a plt expr and everything
10830b57cec5SDimitry Andric     // else will use the PLT entry as the address.
10840b57cec5SDimitry Andric     //
10850b57cec5SDimitry Andric     // The remaining problem is making sure pointer equality still works. We
10860b57cec5SDimitry Andric     // need the help of the dynamic linker for that. We let it know that we have
10870b57cec5SDimitry Andric     // a direct reference to a so symbol by creating an undefined symbol with a
10880b57cec5SDimitry Andric     // non zero st_value. Seeing that, the dynamic linker resolves the symbol to
10890b57cec5SDimitry Andric     // the value of the symbol we created. This is true even for got entries, so
10900b57cec5SDimitry Andric     // pointer equality is maintained. To avoid an infinite loop, the only entry
10910b57cec5SDimitry Andric     // that points to the real function is a dedicated got entry used by the
10920b57cec5SDimitry Andric     // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT,
10930b57cec5SDimitry Andric     // R_386_JMP_SLOT, etc).
10940b57cec5SDimitry Andric 
10950b57cec5SDimitry Andric     // For position independent executable on i386, the plt entry requires ebx
10960b57cec5SDimitry Andric     // to be set. This causes two problems:
10970b57cec5SDimitry Andric     // * If some code has a direct reference to a function, it was probably
10980b57cec5SDimitry Andric     //   compiled without -fPIE/-fPIC and doesn't maintain ebx.
10990b57cec5SDimitry Andric     // * If a library definition gets preempted to the executable, it will have
11000b57cec5SDimitry Andric     //   the wrong ebx value.
110185868e8aSDimitry Andric     if (sym.isFunc()) {
11020b57cec5SDimitry Andric       if (config->pie && config->emachine == EM_386)
11030b57cec5SDimitry Andric         errorOrWarn("symbol '" + toString(sym) +
11040b57cec5SDimitry Andric                     "' cannot be preempted; recompile with -fPIE" +
11050b57cec5SDimitry Andric                     getLocation(sec, sym, offset));
1106*0eae32dcSDimitry Andric       sym.needsCopy = true;
1107*0eae32dcSDimitry Andric       sym.needsPlt = true;
11080b57cec5SDimitry Andric       sec.relocations.push_back({expr, type, offset, addend, &sym});
11090b57cec5SDimitry Andric       return;
11100b57cec5SDimitry Andric     }
111185868e8aSDimitry Andric   }
111285868e8aSDimitry Andric 
1113349cc55cSDimitry Andric   errorOrWarn("relocation " + toString(type) + " cannot be used against " +
111485868e8aSDimitry Andric               (sym.getName().empty() ? "local symbol"
1115349cc55cSDimitry Andric                                      : "symbol '" + toString(sym) + "'") +
111685868e8aSDimitry Andric               "; recompile with -fPIC" + getLocation(sec, sym, offset));
111785868e8aSDimitry Andric }
11180b57cec5SDimitry Andric 
1119349cc55cSDimitry Andric // This function is similar to the `handleTlsRelocation`. MIPS does not
1120349cc55cSDimitry Andric // support any relaxations for TLS relocations so by factoring out MIPS
1121349cc55cSDimitry Andric // handling in to the separate function we can simplify the code and do not
1122349cc55cSDimitry Andric // pollute other `handleTlsRelocation` by MIPS `ifs` statements.
1123349cc55cSDimitry Andric // Mips has a custom MipsGotSection that handles the writing of GOT entries
1124349cc55cSDimitry Andric // without dynamic relocations.
1125349cc55cSDimitry Andric static unsigned handleMipsTlsRelocation(RelType type, Symbol &sym,
1126349cc55cSDimitry Andric                                         InputSectionBase &c, uint64_t offset,
1127349cc55cSDimitry Andric                                         int64_t addend, RelExpr expr) {
1128349cc55cSDimitry Andric   if (expr == R_MIPS_TLSLD) {
1129349cc55cSDimitry Andric     in.mipsGot->addTlsIndex(*c.file);
1130349cc55cSDimitry Andric     c.relocations.push_back({expr, type, offset, addend, &sym});
1131349cc55cSDimitry Andric     return 1;
1132349cc55cSDimitry Andric   }
1133349cc55cSDimitry Andric   if (expr == R_MIPS_TLSGD) {
1134349cc55cSDimitry Andric     in.mipsGot->addDynTlsEntry(*c.file, sym);
1135349cc55cSDimitry Andric     c.relocations.push_back({expr, type, offset, addend, &sym});
1136349cc55cSDimitry Andric     return 1;
1137349cc55cSDimitry Andric   }
1138349cc55cSDimitry Andric   return 0;
1139349cc55cSDimitry Andric }
1140349cc55cSDimitry Andric 
1141349cc55cSDimitry Andric // Notes about General Dynamic and Local Dynamic TLS models below. They may
1142349cc55cSDimitry Andric // require the generation of a pair of GOT entries that have associated dynamic
1143349cc55cSDimitry Andric // relocations. The pair of GOT entries created are of the form GOT[e0] Module
1144349cc55cSDimitry Andric // Index (Used to find pointer to TLS block at run-time) GOT[e1] Offset of
1145349cc55cSDimitry Andric // symbol in TLS block.
1146349cc55cSDimitry Andric //
1147349cc55cSDimitry Andric // Returns the number of relocations processed.
1148349cc55cSDimitry Andric template <class ELFT>
1149349cc55cSDimitry Andric static unsigned
1150349cc55cSDimitry Andric handleTlsRelocation(RelType type, Symbol &sym, InputSectionBase &c,
1151349cc55cSDimitry Andric                     typename ELFT::uint offset, int64_t addend, RelExpr expr) {
1152349cc55cSDimitry Andric   if (!sym.isTls())
1153349cc55cSDimitry Andric     return 0;
1154349cc55cSDimitry Andric 
1155349cc55cSDimitry Andric   if (config->emachine == EM_MIPS)
1156349cc55cSDimitry Andric     return handleMipsTlsRelocation(type, sym, c, offset, addend, expr);
1157349cc55cSDimitry Andric 
1158349cc55cSDimitry Andric   if (oneof<R_AARCH64_TLSDESC_PAGE, R_TLSDESC, R_TLSDESC_CALL, R_TLSDESC_PC,
1159349cc55cSDimitry Andric             R_TLSDESC_GOTPLT>(expr) &&
1160349cc55cSDimitry Andric       config->shared) {
1161*0eae32dcSDimitry Andric     if (expr != R_TLSDESC_CALL) {
1162*0eae32dcSDimitry Andric       sym.needsTlsDesc = true;
1163349cc55cSDimitry Andric       c.relocations.push_back({expr, type, offset, addend, &sym});
1164*0eae32dcSDimitry Andric     }
1165349cc55cSDimitry Andric     return 1;
1166349cc55cSDimitry Andric   }
1167349cc55cSDimitry Andric 
1168349cc55cSDimitry Andric   // ARM, Hexagon and RISC-V do not support GD/LD to IE/LE relaxation.  For
1169349cc55cSDimitry Andric   // PPC64, if the file has missing R_PPC64_TLSGD/R_PPC64_TLSLD, disable
1170349cc55cSDimitry Andric   // relaxation as well.
1171349cc55cSDimitry Andric   bool toExecRelax = !config->shared && config->emachine != EM_ARM &&
1172349cc55cSDimitry Andric                      config->emachine != EM_HEXAGON &&
1173349cc55cSDimitry Andric                      config->emachine != EM_RISCV &&
1174349cc55cSDimitry Andric                      !c.file->ppc64DisableTLSRelax;
1175349cc55cSDimitry Andric 
1176349cc55cSDimitry Andric   // If we are producing an executable and the symbol is non-preemptable, it
1177349cc55cSDimitry Andric   // must be defined and the code sequence can be relaxed to use Local-Exec.
1178349cc55cSDimitry Andric   //
1179349cc55cSDimitry Andric   // ARM and RISC-V do not support any relaxations for TLS relocations, however,
1180349cc55cSDimitry Andric   // we can omit the DTPMOD dynamic relocations and resolve them at link time
1181349cc55cSDimitry Andric   // because them are always 1. This may be necessary for static linking as
1182349cc55cSDimitry Andric   // DTPMOD may not be expected at load time.
1183349cc55cSDimitry Andric   bool isLocalInExecutable = !sym.isPreemptible && !config->shared;
1184349cc55cSDimitry Andric 
1185349cc55cSDimitry Andric   // Local Dynamic is for access to module local TLS variables, while still
1186349cc55cSDimitry Andric   // being suitable for being dynamically loaded via dlopen. GOT[e0] is the
1187349cc55cSDimitry Andric   // module index, with a special value of 0 for the current module. GOT[e1] is
1188349cc55cSDimitry Andric   // unused. There only needs to be one module index entry.
1189349cc55cSDimitry Andric   if (oneof<R_TLSLD_GOT, R_TLSLD_GOTPLT, R_TLSLD_PC, R_TLSLD_HINT>(
1190349cc55cSDimitry Andric           expr)) {
1191349cc55cSDimitry Andric     // Local-Dynamic relocs can be relaxed to Local-Exec.
1192349cc55cSDimitry Andric     if (toExecRelax) {
1193349cc55cSDimitry Andric       c.relocations.push_back(
1194349cc55cSDimitry Andric           {target->adjustTlsExpr(type, R_RELAX_TLS_LD_TO_LE), type, offset,
1195349cc55cSDimitry Andric            addend, &sym});
1196349cc55cSDimitry Andric       return target->getTlsGdRelaxSkip(type);
1197349cc55cSDimitry Andric     }
1198349cc55cSDimitry Andric     if (expr == R_TLSLD_HINT)
1199349cc55cSDimitry Andric       return 1;
1200*0eae32dcSDimitry Andric     sym.needsTlsLd = true;
1201349cc55cSDimitry Andric     c.relocations.push_back({expr, type, offset, addend, &sym});
1202349cc55cSDimitry Andric     return 1;
1203349cc55cSDimitry Andric   }
1204349cc55cSDimitry Andric 
1205349cc55cSDimitry Andric   // Local-Dynamic relocs can be relaxed to Local-Exec.
1206349cc55cSDimitry Andric   if (expr == R_DTPREL) {
1207349cc55cSDimitry Andric     if (toExecRelax)
1208349cc55cSDimitry Andric       expr = target->adjustTlsExpr(type, R_RELAX_TLS_LD_TO_LE);
1209349cc55cSDimitry Andric     c.relocations.push_back({expr, type, offset, addend, &sym});
1210349cc55cSDimitry Andric     return 1;
1211349cc55cSDimitry Andric   }
1212349cc55cSDimitry Andric 
1213349cc55cSDimitry Andric   // Local-Dynamic sequence where offset of tls variable relative to dynamic
1214349cc55cSDimitry Andric   // thread pointer is stored in the got. This cannot be relaxed to Local-Exec.
1215349cc55cSDimitry Andric   if (expr == R_TLSLD_GOT_OFF) {
1216*0eae32dcSDimitry Andric     sym.needsGotDtprel = true;
1217349cc55cSDimitry Andric     c.relocations.push_back({expr, type, offset, addend, &sym});
1218349cc55cSDimitry Andric     return 1;
1219349cc55cSDimitry Andric   }
1220349cc55cSDimitry Andric 
1221349cc55cSDimitry Andric   if (oneof<R_AARCH64_TLSDESC_PAGE, R_TLSDESC, R_TLSDESC_CALL, R_TLSDESC_PC,
1222349cc55cSDimitry Andric             R_TLSDESC_GOTPLT, R_TLSGD_GOT, R_TLSGD_GOTPLT, R_TLSGD_PC>(expr)) {
1223349cc55cSDimitry Andric     if (!toExecRelax) {
1224*0eae32dcSDimitry Andric       sym.needsTlsGd = true;
1225349cc55cSDimitry Andric       c.relocations.push_back({expr, type, offset, addend, &sym});
1226349cc55cSDimitry Andric       return 1;
1227349cc55cSDimitry Andric     }
1228349cc55cSDimitry Andric 
1229349cc55cSDimitry Andric     // Global-Dynamic relocs can be relaxed to Initial-Exec or Local-Exec
1230349cc55cSDimitry Andric     // depending on the symbol being locally defined or not.
1231349cc55cSDimitry Andric     if (sym.isPreemptible) {
1232*0eae32dcSDimitry Andric       sym.needsTlsGdToIe = true;
1233349cc55cSDimitry Andric       c.relocations.push_back(
1234349cc55cSDimitry Andric           {target->adjustTlsExpr(type, R_RELAX_TLS_GD_TO_IE), type, offset,
1235349cc55cSDimitry Andric            addend, &sym});
1236349cc55cSDimitry Andric     } else {
1237349cc55cSDimitry Andric       c.relocations.push_back(
1238349cc55cSDimitry Andric           {target->adjustTlsExpr(type, R_RELAX_TLS_GD_TO_LE), type, offset,
1239349cc55cSDimitry Andric            addend, &sym});
1240349cc55cSDimitry Andric     }
1241349cc55cSDimitry Andric     return target->getTlsGdRelaxSkip(type);
1242349cc55cSDimitry Andric   }
1243349cc55cSDimitry Andric 
1244349cc55cSDimitry Andric   if (oneof<R_GOT, R_GOTPLT, R_GOT_PC, R_AARCH64_GOT_PAGE_PC, R_GOT_OFF,
1245349cc55cSDimitry Andric             R_TLSIE_HINT>(expr)) {
1246349cc55cSDimitry Andric     // Initial-Exec relocs can be relaxed to Local-Exec if the symbol is locally
1247349cc55cSDimitry Andric     // defined.
1248349cc55cSDimitry Andric     if (toExecRelax && isLocalInExecutable) {
1249349cc55cSDimitry Andric       c.relocations.push_back(
1250349cc55cSDimitry Andric           {R_RELAX_TLS_IE_TO_LE, type, offset, addend, &sym});
1251349cc55cSDimitry Andric     } else if (expr != R_TLSIE_HINT) {
1252*0eae32dcSDimitry Andric       sym.needsTlsIe = true;
1253349cc55cSDimitry Andric       // R_GOT needs a relative relocation for PIC on i386 and Hexagon.
1254349cc55cSDimitry Andric       if (expr == R_GOT && config->isPic && !target->usesOnlyLowPageBits(type))
1255*0eae32dcSDimitry Andric         addRelativeReloc(c, offset, sym, addend, expr, type);
1256349cc55cSDimitry Andric       else
1257349cc55cSDimitry Andric         c.relocations.push_back({expr, type, offset, addend, &sym});
1258349cc55cSDimitry Andric     }
1259349cc55cSDimitry Andric     return 1;
1260349cc55cSDimitry Andric   }
1261349cc55cSDimitry Andric 
1262349cc55cSDimitry Andric   return 0;
12630b57cec5SDimitry Andric }
12640b57cec5SDimitry Andric 
12650b57cec5SDimitry Andric template <class ELFT, class RelTy>
12660b57cec5SDimitry Andric static void scanReloc(InputSectionBase &sec, OffsetGetter &getOffset, RelTy *&i,
1267e8d8bef9SDimitry Andric                       RelTy *start, RelTy *end) {
12680b57cec5SDimitry Andric   const RelTy &rel = *i;
12690b57cec5SDimitry Andric   uint32_t symIndex = rel.getSymbol(config->isMips64EL);
12700b57cec5SDimitry Andric   Symbol &sym = sec.getFile<ELFT>()->getSymbol(symIndex);
12710b57cec5SDimitry Andric   RelType type;
12720b57cec5SDimitry Andric 
12730b57cec5SDimitry Andric   // Deal with MIPS oddity.
12740b57cec5SDimitry Andric   if (config->mipsN32Abi) {
12750b57cec5SDimitry Andric     type = getMipsN32RelType(i, end);
12760b57cec5SDimitry Andric   } else {
12770b57cec5SDimitry Andric     type = rel.getType(config->isMips64EL);
12780b57cec5SDimitry Andric     ++i;
12790b57cec5SDimitry Andric   }
12800b57cec5SDimitry Andric 
12810b57cec5SDimitry Andric   // Get an offset in an output section this relocation is applied to.
12820b57cec5SDimitry Andric   uint64_t offset = getOffset.get(rel.r_offset);
12830b57cec5SDimitry Andric   if (offset == uint64_t(-1))
12840b57cec5SDimitry Andric     return;
12850b57cec5SDimitry Andric 
12860b57cec5SDimitry Andric   // Error if the target symbol is undefined. Symbol index 0 may be used by
12870b57cec5SDimitry Andric   // marker relocations, e.g. R_*_NONE and R_ARM_V4BX. Don't error on them.
1288*0eae32dcSDimitry Andric   if (sym.isUndefined() && symIndex != 0 &&
1289*0eae32dcSDimitry Andric       maybeReportUndefined(sym, sec, rel.r_offset))
12900b57cec5SDimitry Andric     return;
12910b57cec5SDimitry Andric 
12920b57cec5SDimitry Andric   const uint8_t *relocatedAddr = sec.data().begin() + rel.r_offset;
12930b57cec5SDimitry Andric   RelExpr expr = target->getRelExpr(type, sym, relocatedAddr);
12940b57cec5SDimitry Andric 
1295480093f4SDimitry Andric   // Ignore R_*_NONE and other marker relocations.
1296480093f4SDimitry Andric   if (expr == R_NONE)
12970b57cec5SDimitry Andric     return;
12980b57cec5SDimitry Andric 
12990b57cec5SDimitry Andric   // Read an addend.
13000b57cec5SDimitry Andric   int64_t addend = computeAddend<ELFT>(rel, end, sec, expr, sym.isLocal());
13010b57cec5SDimitry Andric 
13025ffd83dbSDimitry Andric   if (config->emachine == EM_PPC64) {
13035ffd83dbSDimitry Andric     // We can separate the small code model relocations into 2 categories:
13045ffd83dbSDimitry Andric     // 1) Those that access the compiler generated .toc sections.
13055ffd83dbSDimitry Andric     // 2) Those that access the linker allocated got entries.
13065ffd83dbSDimitry Andric     // lld allocates got entries to symbols on demand. Since we don't try to
13075ffd83dbSDimitry Andric     // sort the got entries in any way, we don't have to track which objects
13085ffd83dbSDimitry Andric     // have got-based small code model relocs. The .toc sections get placed
13095ffd83dbSDimitry Andric     // after the end of the linker allocated .got section and we do sort those
13105ffd83dbSDimitry Andric     // so sections addressed with small code model relocations come first.
1311349cc55cSDimitry Andric     if (type == R_PPC64_TOC16 || type == R_PPC64_TOC16_DS)
13125ffd83dbSDimitry Andric       sec.file->ppc64SmallCodeModelTocRelocs = true;
13135ffd83dbSDimitry Andric 
13145ffd83dbSDimitry Andric     // Record the TOC entry (.toc + addend) as not relaxable. See the comment in
13155ffd83dbSDimitry Andric     // InputSectionBase::relocateAlloc().
13165ffd83dbSDimitry Andric     if (type == R_PPC64_TOC16_LO && sym.isSection() && isa<Defined>(sym) &&
13175ffd83dbSDimitry Andric         cast<Defined>(sym).section->name == ".toc")
13185ffd83dbSDimitry Andric       ppc64noTocRelax.insert({&sym, addend});
1319e8d8bef9SDimitry Andric 
1320e8d8bef9SDimitry Andric     if ((type == R_PPC64_TLSGD && expr == R_TLSDESC_CALL) ||
1321e8d8bef9SDimitry Andric         (type == R_PPC64_TLSLD && expr == R_TLSLD_HINT)) {
1322e8d8bef9SDimitry Andric       if (i == end) {
1323e8d8bef9SDimitry Andric         errorOrWarn("R_PPC64_TLSGD/R_PPC64_TLSLD may not be the last "
1324e8d8bef9SDimitry Andric                     "relocation" +
1325e8d8bef9SDimitry Andric                     getLocation(sec, sym, offset));
1326e8d8bef9SDimitry Andric         return;
1327e8d8bef9SDimitry Andric       }
1328e8d8bef9SDimitry Andric 
1329e8d8bef9SDimitry Andric       // Offset the 4-byte aligned R_PPC64_TLSGD by one byte in the NOTOC case,
1330e8d8bef9SDimitry Andric       // so we can discern it later from the toc-case.
1331e8d8bef9SDimitry Andric       if (i->getType(/*isMips64EL=*/false) == R_PPC64_REL24_NOTOC)
1332e8d8bef9SDimitry Andric         ++offset;
1333e8d8bef9SDimitry Andric     }
13345ffd83dbSDimitry Andric   }
13355ffd83dbSDimitry Andric 
13360b57cec5SDimitry Andric   // If the relocation does not emit a GOT or GOTPLT entry but its computation
13370b57cec5SDimitry Andric   // uses their addresses, we need GOT or GOTPLT to be created.
13380b57cec5SDimitry Andric   //
1339349cc55cSDimitry Andric   // The 5 types that relative GOTPLT are all x86 and x86-64 specific.
1340349cc55cSDimitry Andric   if (oneof<R_GOTPLTONLY_PC, R_GOTPLTREL, R_GOTPLT, R_PLT_GOTPLT,
1341349cc55cSDimitry Andric             R_TLSDESC_GOTPLT, R_TLSGD_GOTPLT>(expr)) {
13420b57cec5SDimitry Andric     in.gotPlt->hasGotPltOffRel = true;
1343*0eae32dcSDimitry Andric   } else if (oneof<R_GOTONLY_PC, R_GOTREL, R_PPC32_PLTREL, R_PPC64_TOCBASE,
1344*0eae32dcSDimitry Andric                    R_PPC64_RELAX_TOC>(expr)) {
13450b57cec5SDimitry Andric     in.got->hasGotOffRel = true;
13460b57cec5SDimitry Andric   }
13470b57cec5SDimitry Andric 
1348e8d8bef9SDimitry Andric   // Process TLS relocations, including relaxing TLS relocations. Note that
1349e8d8bef9SDimitry Andric   // R_TPREL and R_TPREL_NEG relocations are resolved in processRelocAux.
1350e8d8bef9SDimitry Andric   if (expr == R_TPREL || expr == R_TPREL_NEG) {
1351e8d8bef9SDimitry Andric     if (config->shared) {
1352e8d8bef9SDimitry Andric       errorOrWarn("relocation " + toString(type) + " against " + toString(sym) +
1353e8d8bef9SDimitry Andric                   " cannot be used with -shared" +
1354e8d8bef9SDimitry Andric                   getLocation(sec, sym, offset));
1355e8d8bef9SDimitry Andric       return;
1356e8d8bef9SDimitry Andric     }
1357e8d8bef9SDimitry Andric   } else if (unsigned processed = handleTlsRelocation<ELFT>(
1358e8d8bef9SDimitry Andric                  type, sym, sec, offset, addend, expr)) {
13590b57cec5SDimitry Andric     i += (processed - 1);
13600b57cec5SDimitry Andric     return;
13610b57cec5SDimitry Andric   }
13620b57cec5SDimitry Andric 
13634824e7fdSDimitry Andric   // Relax relocations.
13644824e7fdSDimitry Andric   //
13654824e7fdSDimitry Andric   // If we know that a PLT entry will be resolved within the same ELF module, we
13664824e7fdSDimitry Andric   // can skip PLT access and directly jump to the destination function. For
13674824e7fdSDimitry Andric   // example, if we are linking a main executable, all dynamic symbols that can
13684824e7fdSDimitry Andric   // be resolved within the executable will actually be resolved that way at
13694824e7fdSDimitry Andric   // runtime, because the main executable is always at the beginning of a search
13704824e7fdSDimitry Andric   // list. We can leverage that fact.
13714824e7fdSDimitry Andric   if (!sym.isPreemptible && (!sym.isGnuIFunc() || config->zIfuncNoplt)) {
13724824e7fdSDimitry Andric     if (expr != R_GOT_PC) {
13734824e7fdSDimitry Andric       // The 0x8000 bit of r_addend of R_PPC_PLTREL24 is used to choose call
13744824e7fdSDimitry Andric       // stub type. It should be ignored if optimized to R_PC.
13754824e7fdSDimitry Andric       if (config->emachine == EM_PPC && expr == R_PPC32_PLTREL)
13764824e7fdSDimitry Andric         addend &= ~0x8000;
13774824e7fdSDimitry Andric       // R_HEX_GD_PLT_B22_PCREL (call a@GDPLT) is transformed into
13784824e7fdSDimitry Andric       // call __tls_get_addr even if the symbol is non-preemptible.
13794824e7fdSDimitry Andric       if (!(config->emachine == EM_HEXAGON &&
13804824e7fdSDimitry Andric            (type == R_HEX_GD_PLT_B22_PCREL ||
13814824e7fdSDimitry Andric             type == R_HEX_GD_PLT_B22_PCREL_X ||
13824824e7fdSDimitry Andric             type == R_HEX_GD_PLT_B32_PCREL_X)))
13834824e7fdSDimitry Andric       expr = fromPlt(expr);
13844824e7fdSDimitry Andric     } else if (!isAbsoluteValue(sym)) {
13854824e7fdSDimitry Andric       expr = target->adjustGotPcExpr(type, addend, relocatedAddr);
13864824e7fdSDimitry Andric     }
13874824e7fdSDimitry Andric   }
13884824e7fdSDimitry Andric 
13890b57cec5SDimitry Andric   // We were asked not to generate PLT entries for ifuncs. Instead, pass the
13900b57cec5SDimitry Andric   // direct relocation on through.
13910b57cec5SDimitry Andric   if (sym.isGnuIFunc() && config->zIfuncNoplt) {
13920b57cec5SDimitry Andric     sym.exportDynamic = true;
1393*0eae32dcSDimitry Andric     mainPart->relaDyn->addSymbolReloc(type, sec, offset, sym, addend, type);
13940b57cec5SDimitry Andric     return;
13950b57cec5SDimitry Andric   }
13960b57cec5SDimitry Andric 
13970b57cec5SDimitry Andric   if (needsGot(expr)) {
13980b57cec5SDimitry Andric     if (config->emachine == EM_MIPS) {
13990b57cec5SDimitry Andric       // MIPS ABI has special rules to process GOT entries and doesn't
14000b57cec5SDimitry Andric       // require relocation entries for them. A special case is TLS
14010b57cec5SDimitry Andric       // relocations. In that case dynamic loader applies dynamic
14020b57cec5SDimitry Andric       // relocations to initialize TLS GOT entries.
14030b57cec5SDimitry Andric       // See "Global Offset Table" in Chapter 5 in the following document
14040b57cec5SDimitry Andric       // for detailed description:
14050b57cec5SDimitry Andric       // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
14060b57cec5SDimitry Andric       in.mipsGot->addEntry(*sec.file, sym, addend, expr);
14070b57cec5SDimitry Andric     } else {
1408*0eae32dcSDimitry Andric       sym.needsGot = true;
14090b57cec5SDimitry Andric     }
1410*0eae32dcSDimitry Andric   } else if (needsPlt(expr)) {
1411*0eae32dcSDimitry Andric     sym.needsPlt = true;
1412*0eae32dcSDimitry Andric   } else {
1413*0eae32dcSDimitry Andric     sym.hasDirectReloc = true;
14140b57cec5SDimitry Andric   }
14150b57cec5SDimitry Andric 
1416349cc55cSDimitry Andric   processRelocAux<ELFT>(sec, expr, type, offset, sym, addend);
14170b57cec5SDimitry Andric }
14180b57cec5SDimitry Andric 
1419e8d8bef9SDimitry Andric // R_PPC64_TLSGD/R_PPC64_TLSLD is required to mark `bl __tls_get_addr` for
1420e8d8bef9SDimitry Andric // General Dynamic/Local Dynamic code sequences. If a GD/LD GOT relocation is
1421e8d8bef9SDimitry Andric // found but no R_PPC64_TLSGD/R_PPC64_TLSLD is seen, we assume that the
1422e8d8bef9SDimitry Andric // instructions are generated by very old IBM XL compilers. Work around the
1423e8d8bef9SDimitry Andric // issue by disabling GD/LD to IE/LE relaxation.
1424e8d8bef9SDimitry Andric template <class RelTy>
1425e8d8bef9SDimitry Andric static void checkPPC64TLSRelax(InputSectionBase &sec, ArrayRef<RelTy> rels) {
1426e8d8bef9SDimitry Andric   // Skip if sec is synthetic (sec.file is null) or if sec has been marked.
1427e8d8bef9SDimitry Andric   if (!sec.file || sec.file->ppc64DisableTLSRelax)
1428e8d8bef9SDimitry Andric     return;
1429e8d8bef9SDimitry Andric   bool hasGDLD = false;
1430e8d8bef9SDimitry Andric   for (const RelTy &rel : rels) {
1431e8d8bef9SDimitry Andric     RelType type = rel.getType(false);
1432e8d8bef9SDimitry Andric     switch (type) {
1433e8d8bef9SDimitry Andric     case R_PPC64_TLSGD:
1434e8d8bef9SDimitry Andric     case R_PPC64_TLSLD:
1435e8d8bef9SDimitry Andric       return; // Found a marker
1436e8d8bef9SDimitry Andric     case R_PPC64_GOT_TLSGD16:
1437e8d8bef9SDimitry Andric     case R_PPC64_GOT_TLSGD16_HA:
1438e8d8bef9SDimitry Andric     case R_PPC64_GOT_TLSGD16_HI:
1439e8d8bef9SDimitry Andric     case R_PPC64_GOT_TLSGD16_LO:
1440e8d8bef9SDimitry Andric     case R_PPC64_GOT_TLSLD16:
1441e8d8bef9SDimitry Andric     case R_PPC64_GOT_TLSLD16_HA:
1442e8d8bef9SDimitry Andric     case R_PPC64_GOT_TLSLD16_HI:
1443e8d8bef9SDimitry Andric     case R_PPC64_GOT_TLSLD16_LO:
1444e8d8bef9SDimitry Andric       hasGDLD = true;
1445e8d8bef9SDimitry Andric       break;
1446e8d8bef9SDimitry Andric     }
1447e8d8bef9SDimitry Andric   }
1448e8d8bef9SDimitry Andric   if (hasGDLD) {
1449e8d8bef9SDimitry Andric     sec.file->ppc64DisableTLSRelax = true;
1450e8d8bef9SDimitry Andric     warn(toString(sec.file) +
1451e8d8bef9SDimitry Andric          ": disable TLS relaxation due to R_PPC64_GOT_TLS* relocations without "
1452e8d8bef9SDimitry Andric          "R_PPC64_TLSGD/R_PPC64_TLSLD relocations");
1453e8d8bef9SDimitry Andric   }
1454e8d8bef9SDimitry Andric }
1455e8d8bef9SDimitry Andric 
14560b57cec5SDimitry Andric template <class ELFT, class RelTy>
14570b57cec5SDimitry Andric static void scanRelocs(InputSectionBase &sec, ArrayRef<RelTy> rels) {
14580b57cec5SDimitry Andric   OffsetGetter getOffset(sec);
14590b57cec5SDimitry Andric 
14600b57cec5SDimitry Andric   // Not all relocations end up in Sec.Relocations, but a lot do.
14610b57cec5SDimitry Andric   sec.relocations.reserve(rels.size());
14620b57cec5SDimitry Andric 
1463e8d8bef9SDimitry Andric   if (config->emachine == EM_PPC64)
1464e8d8bef9SDimitry Andric     checkPPC64TLSRelax<RelTy>(sec, rels);
1465e8d8bef9SDimitry Andric 
1466fe6060f1SDimitry Andric   // For EhInputSection, OffsetGetter expects the relocations to be sorted by
1467fe6060f1SDimitry Andric   // r_offset. In rare cases (.eh_frame pieces are reordered by a linker
1468fe6060f1SDimitry Andric   // script), the relocations may be unordered.
1469fe6060f1SDimitry Andric   SmallVector<RelTy, 0> storage;
1470fe6060f1SDimitry Andric   if (isa<EhInputSection>(sec))
1471fe6060f1SDimitry Andric     rels = sortRels(rels, storage);
1472fe6060f1SDimitry Andric 
14730b57cec5SDimitry Andric   for (auto i = rels.begin(), end = rels.end(); i != end;)
1474e8d8bef9SDimitry Andric     scanReloc<ELFT>(sec, getOffset, i, rels.begin(), end);
14750b57cec5SDimitry Andric 
14760b57cec5SDimitry Andric   // Sort relocations by offset for more efficient searching for
14770b57cec5SDimitry Andric   // R_RISCV_PCREL_HI20 and R_PPC64_ADDR64.
14780b57cec5SDimitry Andric   if (config->emachine == EM_RISCV ||
14790b57cec5SDimitry Andric       (config->emachine == EM_PPC64 && sec.name == ".toc"))
14800b57cec5SDimitry Andric     llvm::stable_sort(sec.relocations,
14810b57cec5SDimitry Andric                       [](const Relocation &lhs, const Relocation &rhs) {
14820b57cec5SDimitry Andric                         return lhs.offset < rhs.offset;
14830b57cec5SDimitry Andric                       });
14840b57cec5SDimitry Andric }
14850b57cec5SDimitry Andric 
14865ffd83dbSDimitry Andric template <class ELFT> void elf::scanRelocations(InputSectionBase &s) {
1487349cc55cSDimitry Andric   const RelsOrRelas<ELFT> rels = s.template relsOrRelas<ELFT>();
1488349cc55cSDimitry Andric   if (rels.areRelocsRel())
1489349cc55cSDimitry Andric     scanRelocs<ELFT>(s, rels.rels);
14900b57cec5SDimitry Andric   else
1491349cc55cSDimitry Andric     scanRelocs<ELFT>(s, rels.relas);
14920b57cec5SDimitry Andric }
14930b57cec5SDimitry Andric 
1494*0eae32dcSDimitry Andric static bool handleNonPreemptibleIfunc(Symbol &sym) {
1495*0eae32dcSDimitry Andric   // Handle a reference to a non-preemptible ifunc. These are special in a
1496*0eae32dcSDimitry Andric   // few ways:
1497*0eae32dcSDimitry Andric   //
1498*0eae32dcSDimitry Andric   // - Unlike most non-preemptible symbols, non-preemptible ifuncs do not have
1499*0eae32dcSDimitry Andric   //   a fixed value. But assuming that all references to the ifunc are
1500*0eae32dcSDimitry Andric   //   GOT-generating or PLT-generating, the handling of an ifunc is
1501*0eae32dcSDimitry Andric   //   relatively straightforward. We create a PLT entry in Iplt, which is
1502*0eae32dcSDimitry Andric   //   usually at the end of .plt, which makes an indirect call using a
1503*0eae32dcSDimitry Andric   //   matching GOT entry in igotPlt, which is usually at the end of .got.plt.
1504*0eae32dcSDimitry Andric   //   The GOT entry is relocated using an IRELATIVE relocation in relaIplt,
1505*0eae32dcSDimitry Andric   //   which is usually at the end of .rela.plt. Unlike most relocations in
1506*0eae32dcSDimitry Andric   //   .rela.plt, which may be evaluated lazily without -z now, dynamic
1507*0eae32dcSDimitry Andric   //   loaders evaluate IRELATIVE relocs eagerly, which means that for
1508*0eae32dcSDimitry Andric   //   IRELATIVE relocs only, GOT-generating relocations can point directly to
1509*0eae32dcSDimitry Andric   //   .got.plt without requiring a separate GOT entry.
1510*0eae32dcSDimitry Andric   //
1511*0eae32dcSDimitry Andric   // - Despite the fact that an ifunc does not have a fixed value, compilers
1512*0eae32dcSDimitry Andric   //   that are not passed -fPIC will assume that they do, and will emit
1513*0eae32dcSDimitry Andric   //   direct (non-GOT-generating, non-PLT-generating) relocations to the
1514*0eae32dcSDimitry Andric   //   symbol. This means that if a direct relocation to the symbol is
1515*0eae32dcSDimitry Andric   //   seen, the linker must set a value for the symbol, and this value must
1516*0eae32dcSDimitry Andric   //   be consistent no matter what type of reference is made to the symbol.
1517*0eae32dcSDimitry Andric   //   This can be done by creating a PLT entry for the symbol in the way
1518*0eae32dcSDimitry Andric   //   described above and making it canonical, that is, making all references
1519*0eae32dcSDimitry Andric   //   point to the PLT entry instead of the resolver. In lld we also store
1520*0eae32dcSDimitry Andric   //   the address of the PLT entry in the dynamic symbol table, which means
1521*0eae32dcSDimitry Andric   //   that the symbol will also have the same value in other modules.
1522*0eae32dcSDimitry Andric   //   Because the value loaded from the GOT needs to be consistent with
1523*0eae32dcSDimitry Andric   //   the value computed using a direct relocation, a non-preemptible ifunc
1524*0eae32dcSDimitry Andric   //   may end up with two GOT entries, one in .got.plt that points to the
1525*0eae32dcSDimitry Andric   //   address returned by the resolver and is used only by the PLT entry,
1526*0eae32dcSDimitry Andric   //   and another in .got that points to the PLT entry and is used by
1527*0eae32dcSDimitry Andric   //   GOT-generating relocations.
1528*0eae32dcSDimitry Andric   //
1529*0eae32dcSDimitry Andric   // - The fact that these symbols do not have a fixed value makes them an
1530*0eae32dcSDimitry Andric   //   exception to the general rule that a statically linked executable does
1531*0eae32dcSDimitry Andric   //   not require any form of dynamic relocation. To handle these relocations
1532*0eae32dcSDimitry Andric   //   correctly, the IRELATIVE relocations are stored in an array which a
1533*0eae32dcSDimitry Andric   //   statically linked executable's startup code must enumerate using the
1534*0eae32dcSDimitry Andric   //   linker-defined symbols __rela?_iplt_{start,end}.
1535*0eae32dcSDimitry Andric   if (!sym.isGnuIFunc() || sym.isPreemptible || config->zIfuncNoplt)
1536*0eae32dcSDimitry Andric     return false;
1537*0eae32dcSDimitry Andric   // Skip unreferenced non-preemptible ifunc.
1538*0eae32dcSDimitry Andric   if (!(sym.needsGot || sym.needsPlt || sym.hasDirectReloc))
1539*0eae32dcSDimitry Andric     return true;
1540*0eae32dcSDimitry Andric 
1541*0eae32dcSDimitry Andric   sym.isInIplt = true;
1542*0eae32dcSDimitry Andric 
1543*0eae32dcSDimitry Andric   // Create an Iplt and the associated IRELATIVE relocation pointing to the
1544*0eae32dcSDimitry Andric   // original section/value pairs. For non-GOT non-PLT relocation case below, we
1545*0eae32dcSDimitry Andric   // may alter section/value, so create a copy of the symbol to make
1546*0eae32dcSDimitry Andric   // section/value fixed.
1547*0eae32dcSDimitry Andric   auto *directSym = makeDefined(cast<Defined>(sym));
1548*0eae32dcSDimitry Andric   addPltEntry(*in.iplt, *in.igotPlt, *in.relaIplt, target->iRelativeRel,
1549*0eae32dcSDimitry Andric               *directSym);
1550*0eae32dcSDimitry Andric   sym.pltIndex = directSym->pltIndex;
1551*0eae32dcSDimitry Andric 
1552*0eae32dcSDimitry Andric   if (sym.hasDirectReloc) {
1553*0eae32dcSDimitry Andric     // Change the value to the IPLT and redirect all references to it.
1554*0eae32dcSDimitry Andric     auto &d = cast<Defined>(sym);
1555*0eae32dcSDimitry Andric     d.section = in.iplt;
1556*0eae32dcSDimitry Andric     d.value = sym.pltIndex * target->ipltEntrySize;
1557*0eae32dcSDimitry Andric     d.size = 0;
1558*0eae32dcSDimitry Andric     // It's important to set the symbol type here so that dynamic loaders
1559*0eae32dcSDimitry Andric     // don't try to call the PLT as if it were an ifunc resolver.
1560*0eae32dcSDimitry Andric     d.type = STT_FUNC;
1561*0eae32dcSDimitry Andric 
1562*0eae32dcSDimitry Andric     if (sym.needsGot)
1563*0eae32dcSDimitry Andric       addGotEntry(sym);
1564*0eae32dcSDimitry Andric   } else if (sym.needsGot) {
1565*0eae32dcSDimitry Andric     // Redirect GOT accesses to point to the Igot.
1566*0eae32dcSDimitry Andric     sym.gotInIgot = true;
1567*0eae32dcSDimitry Andric   }
1568*0eae32dcSDimitry Andric   return true;
1569*0eae32dcSDimitry Andric }
1570*0eae32dcSDimitry Andric 
1571*0eae32dcSDimitry Andric void elf::postScanRelocations() {
1572*0eae32dcSDimitry Andric   auto fn = [](Symbol &sym) {
1573*0eae32dcSDimitry Andric     if (handleNonPreemptibleIfunc(sym))
1574*0eae32dcSDimitry Andric       return;
1575*0eae32dcSDimitry Andric     if (sym.needsGot)
1576*0eae32dcSDimitry Andric       addGotEntry(sym);
1577*0eae32dcSDimitry Andric     if (sym.needsPlt)
1578*0eae32dcSDimitry Andric       addPltEntry(*in.plt, *in.gotPlt, *in.relaPlt, target->pltRel, sym);
1579*0eae32dcSDimitry Andric     if (sym.needsCopy) {
1580*0eae32dcSDimitry Andric       if (sym.isObject()) {
1581*0eae32dcSDimitry Andric         addCopyRelSymbol(cast<SharedSymbol>(sym));
1582*0eae32dcSDimitry Andric         // needsCopy is cleared for sym and its aliases so that in later
1583*0eae32dcSDimitry Andric         // iterations aliases won't cause redundant copies.
1584*0eae32dcSDimitry Andric         assert(!sym.needsCopy);
1585*0eae32dcSDimitry Andric       } else {
1586*0eae32dcSDimitry Andric         assert(sym.isFunc() && sym.needsPlt);
1587*0eae32dcSDimitry Andric         if (!sym.isDefined()) {
1588*0eae32dcSDimitry Andric           replaceWithDefined(
1589*0eae32dcSDimitry Andric               sym, *in.plt,
1590*0eae32dcSDimitry Andric               target->pltHeaderSize + target->pltEntrySize * sym.pltIndex, 0);
1591*0eae32dcSDimitry Andric           sym.needsCopy = true;
1592*0eae32dcSDimitry Andric           if (config->emachine == EM_PPC) {
1593*0eae32dcSDimitry Andric             // PPC32 canonical PLT entries are at the beginning of .glink
1594*0eae32dcSDimitry Andric             cast<Defined>(sym).value = in.plt->headerSize;
1595*0eae32dcSDimitry Andric             in.plt->headerSize += 16;
1596*0eae32dcSDimitry Andric             cast<PPC32GlinkSection>(*in.plt).canonical_plts.push_back(&sym);
1597*0eae32dcSDimitry Andric           }
1598*0eae32dcSDimitry Andric         }
1599*0eae32dcSDimitry Andric       }
1600*0eae32dcSDimitry Andric     }
1601*0eae32dcSDimitry Andric 
1602*0eae32dcSDimitry Andric     if (!sym.isTls())
1603*0eae32dcSDimitry Andric       return;
1604*0eae32dcSDimitry Andric     bool isLocalInExecutable = !sym.isPreemptible && !config->shared;
1605*0eae32dcSDimitry Andric 
1606*0eae32dcSDimitry Andric     if (sym.needsTlsDesc) {
1607*0eae32dcSDimitry Andric       in.got->addDynTlsEntry(sym);
1608*0eae32dcSDimitry Andric       mainPart->relaDyn->addAddendOnlyRelocIfNonPreemptible(
1609*0eae32dcSDimitry Andric           target->tlsDescRel, *in.got, in.got->getGlobalDynOffset(sym), sym,
1610*0eae32dcSDimitry Andric           target->tlsDescRel);
1611*0eae32dcSDimitry Andric     }
1612*0eae32dcSDimitry Andric     if (sym.needsTlsGd && !sym.needsTlsDesc) {
1613*0eae32dcSDimitry Andric       // TODO Support mixed TLSDESC and TLS GD.
1614*0eae32dcSDimitry Andric       in.got->addDynTlsEntry(sym);
1615*0eae32dcSDimitry Andric       uint64_t off = in.got->getGlobalDynOffset(sym);
1616*0eae32dcSDimitry Andric       if (isLocalInExecutable)
1617*0eae32dcSDimitry Andric         // Write one to the GOT slot.
1618*0eae32dcSDimitry Andric         in.got->relocations.push_back(
1619*0eae32dcSDimitry Andric             {R_ADDEND, target->symbolicRel, off, 1, &sym});
1620*0eae32dcSDimitry Andric       else
1621*0eae32dcSDimitry Andric         mainPart->relaDyn->addSymbolReloc(target->tlsModuleIndexRel, *in.got,
1622*0eae32dcSDimitry Andric                                           off, sym);
1623*0eae32dcSDimitry Andric 
1624*0eae32dcSDimitry Andric       // If the symbol is preemptible we need the dynamic linker to write
1625*0eae32dcSDimitry Andric       // the offset too.
1626*0eae32dcSDimitry Andric       uint64_t offsetOff = off + config->wordsize;
1627*0eae32dcSDimitry Andric       if (sym.isPreemptible)
1628*0eae32dcSDimitry Andric         mainPart->relaDyn->addSymbolReloc(target->tlsOffsetRel, *in.got,
1629*0eae32dcSDimitry Andric                                           offsetOff, sym);
1630*0eae32dcSDimitry Andric       else
1631*0eae32dcSDimitry Andric         in.got->relocations.push_back(
1632*0eae32dcSDimitry Andric             {R_ABS, target->tlsOffsetRel, offsetOff, 0, &sym});
1633*0eae32dcSDimitry Andric     }
1634*0eae32dcSDimitry Andric     if (sym.needsTlsGdToIe) {
1635*0eae32dcSDimitry Andric       in.got->addEntry(sym);
1636*0eae32dcSDimitry Andric       mainPart->relaDyn->addSymbolReloc(target->tlsGotRel, *in.got,
1637*0eae32dcSDimitry Andric                                         sym.getGotOffset(), sym);
1638*0eae32dcSDimitry Andric     }
1639*0eae32dcSDimitry Andric 
1640*0eae32dcSDimitry Andric     if (sym.needsTlsLd && in.got->addTlsIndex()) {
1641*0eae32dcSDimitry Andric       if (isLocalInExecutable)
1642*0eae32dcSDimitry Andric         in.got->relocations.push_back(
1643*0eae32dcSDimitry Andric             {R_ADDEND, target->symbolicRel, in.got->getTlsIndexOff(), 1, &sym});
1644*0eae32dcSDimitry Andric       else
1645*0eae32dcSDimitry Andric         mainPart->relaDyn->addReloc(
1646*0eae32dcSDimitry Andric             {target->tlsModuleIndexRel, in.got, in.got->getTlsIndexOff()});
1647*0eae32dcSDimitry Andric     }
1648*0eae32dcSDimitry Andric     if (sym.needsGotDtprel) {
1649*0eae32dcSDimitry Andric       in.got->addEntry(sym);
1650*0eae32dcSDimitry Andric       in.got->relocations.push_back(
1651*0eae32dcSDimitry Andric           {R_ABS, target->tlsOffsetRel, sym.getGotOffset(), 0, &sym});
1652*0eae32dcSDimitry Andric     }
1653*0eae32dcSDimitry Andric 
1654*0eae32dcSDimitry Andric     if (sym.needsTlsIe && !sym.needsTlsGdToIe)
1655*0eae32dcSDimitry Andric       addTpOffsetGotEntry(sym);
1656*0eae32dcSDimitry Andric   };
1657*0eae32dcSDimitry Andric   for (Symbol *sym : symtab->symbols())
1658*0eae32dcSDimitry Andric     fn(*sym);
1659*0eae32dcSDimitry Andric 
1660*0eae32dcSDimitry Andric   // Local symbols may need the aforementioned non-preemptible ifunc and GOT
1661*0eae32dcSDimitry Andric   // handling. They don't need regular PLT.
1662*0eae32dcSDimitry Andric   for (ELFFileBase *file : objectFiles)
1663*0eae32dcSDimitry Andric     for (Symbol *sym : cast<ELFFileBase>(file)->getLocalSymbols())
1664*0eae32dcSDimitry Andric       fn(*sym);
1665*0eae32dcSDimitry Andric }
1666*0eae32dcSDimitry Andric 
16670b57cec5SDimitry Andric static bool mergeCmp(const InputSection *a, const InputSection *b) {
16680b57cec5SDimitry Andric   // std::merge requires a strict weak ordering.
16690b57cec5SDimitry Andric   if (a->outSecOff < b->outSecOff)
16700b57cec5SDimitry Andric     return true;
16710b57cec5SDimitry Andric 
16720b57cec5SDimitry Andric   if (a->outSecOff == b->outSecOff) {
16730b57cec5SDimitry Andric     auto *ta = dyn_cast<ThunkSection>(a);
16740b57cec5SDimitry Andric     auto *tb = dyn_cast<ThunkSection>(b);
16750b57cec5SDimitry Andric 
16760b57cec5SDimitry Andric     // Check if Thunk is immediately before any specific Target
16770b57cec5SDimitry Andric     // InputSection for example Mips LA25 Thunks.
16780b57cec5SDimitry Andric     if (ta && ta->getTargetInputSection() == b)
16790b57cec5SDimitry Andric       return true;
16800b57cec5SDimitry Andric 
16810b57cec5SDimitry Andric     // Place Thunk Sections without specific targets before
16820b57cec5SDimitry Andric     // non-Thunk Sections.
16830b57cec5SDimitry Andric     if (ta && !tb && !ta->getTargetInputSection())
16840b57cec5SDimitry Andric       return true;
16850b57cec5SDimitry Andric   }
16860b57cec5SDimitry Andric 
16870b57cec5SDimitry Andric   return false;
16880b57cec5SDimitry Andric }
16890b57cec5SDimitry Andric 
16900b57cec5SDimitry Andric // Call Fn on every executable InputSection accessed via the linker script
16910b57cec5SDimitry Andric // InputSectionDescription::Sections.
16920b57cec5SDimitry Andric static void forEachInputSectionDescription(
16930b57cec5SDimitry Andric     ArrayRef<OutputSection *> outputSections,
16940b57cec5SDimitry Andric     llvm::function_ref<void(OutputSection *, InputSectionDescription *)> fn) {
16950b57cec5SDimitry Andric   for (OutputSection *os : outputSections) {
16960b57cec5SDimitry Andric     if (!(os->flags & SHF_ALLOC) || !(os->flags & SHF_EXECINSTR))
16970b57cec5SDimitry Andric       continue;
16984824e7fdSDimitry Andric     for (SectionCommand *bc : os->commands)
16990b57cec5SDimitry Andric       if (auto *isd = dyn_cast<InputSectionDescription>(bc))
17000b57cec5SDimitry Andric         fn(os, isd);
17010b57cec5SDimitry Andric   }
17020b57cec5SDimitry Andric }
17030b57cec5SDimitry Andric 
17040b57cec5SDimitry Andric // Thunk Implementation
17050b57cec5SDimitry Andric //
17060b57cec5SDimitry Andric // Thunks (sometimes called stubs, veneers or branch islands) are small pieces
17070b57cec5SDimitry Andric // of code that the linker inserts inbetween a caller and a callee. The thunks
17080b57cec5SDimitry Andric // are added at link time rather than compile time as the decision on whether
17090b57cec5SDimitry Andric // a thunk is needed, such as the caller and callee being out of range, can only
17100b57cec5SDimitry Andric // be made at link time.
17110b57cec5SDimitry Andric //
17120b57cec5SDimitry Andric // It is straightforward to tell given the current state of the program when a
17130b57cec5SDimitry Andric // thunk is needed for a particular call. The more difficult part is that
17140b57cec5SDimitry Andric // the thunk needs to be placed in the program such that the caller can reach
17150b57cec5SDimitry Andric // the thunk and the thunk can reach the callee; furthermore, adding thunks to
17160b57cec5SDimitry Andric // the program alters addresses, which can mean more thunks etc.
17170b57cec5SDimitry Andric //
17180b57cec5SDimitry Andric // In lld we have a synthetic ThunkSection that can hold many Thunks.
17190b57cec5SDimitry Andric // The decision to have a ThunkSection act as a container means that we can
17200b57cec5SDimitry Andric // more easily handle the most common case of a single block of contiguous
17210b57cec5SDimitry Andric // Thunks by inserting just a single ThunkSection.
17220b57cec5SDimitry Andric //
17230b57cec5SDimitry Andric // The implementation of Thunks in lld is split across these areas
17240b57cec5SDimitry Andric // Relocations.cpp : Framework for creating and placing thunks
17250b57cec5SDimitry Andric // Thunks.cpp : The code generated for each supported thunk
17260b57cec5SDimitry Andric // Target.cpp : Target specific hooks that the framework uses to decide when
17270b57cec5SDimitry Andric //              a thunk is used
17280b57cec5SDimitry Andric // Synthetic.cpp : Implementation of ThunkSection
17290b57cec5SDimitry Andric // Writer.cpp : Iteratively call framework until no more Thunks added
17300b57cec5SDimitry Andric //
17310b57cec5SDimitry Andric // Thunk placement requirements:
17320b57cec5SDimitry Andric // Mips LA25 thunks. These must be placed immediately before the callee section
17330b57cec5SDimitry Andric // We can assume that the caller is in range of the Thunk. These are modelled
17340b57cec5SDimitry Andric // by Thunks that return the section they must precede with
17350b57cec5SDimitry Andric // getTargetInputSection().
17360b57cec5SDimitry Andric //
17370b57cec5SDimitry Andric // ARM interworking and range extension thunks. These thunks must be placed
17380b57cec5SDimitry Andric // within range of the caller. All implemented ARM thunks can always reach the
17390b57cec5SDimitry Andric // callee as they use an indirect jump via a register that has no range
17400b57cec5SDimitry Andric // restrictions.
17410b57cec5SDimitry Andric //
17420b57cec5SDimitry Andric // Thunk placement algorithm:
17430b57cec5SDimitry Andric // For Mips LA25 ThunkSections; the placement is explicit, it has to be before
17440b57cec5SDimitry Andric // getTargetInputSection().
17450b57cec5SDimitry Andric //
17460b57cec5SDimitry Andric // For thunks that must be placed within range of the caller there are many
17470b57cec5SDimitry Andric // possible choices given that the maximum range from the caller is usually
17480b57cec5SDimitry Andric // much larger than the average InputSection size. Desirable properties include:
17490b57cec5SDimitry Andric // - Maximize reuse of thunks by multiple callers
17500b57cec5SDimitry Andric // - Minimize number of ThunkSections to simplify insertion
17510b57cec5SDimitry Andric // - Handle impact of already added Thunks on addresses
17520b57cec5SDimitry Andric // - Simple to understand and implement
17530b57cec5SDimitry Andric //
17540b57cec5SDimitry Andric // In lld for the first pass, we pre-create one or more ThunkSections per
17550b57cec5SDimitry Andric // InputSectionDescription at Target specific intervals. A ThunkSection is
17560b57cec5SDimitry Andric // placed so that the estimated end of the ThunkSection is within range of the
17570b57cec5SDimitry Andric // start of the InputSectionDescription or the previous ThunkSection. For
17580b57cec5SDimitry Andric // example:
17590b57cec5SDimitry Andric // InputSectionDescription
17600b57cec5SDimitry Andric // Section 0
17610b57cec5SDimitry Andric // ...
17620b57cec5SDimitry Andric // Section N
17630b57cec5SDimitry Andric // ThunkSection 0
17640b57cec5SDimitry Andric // Section N + 1
17650b57cec5SDimitry Andric // ...
17660b57cec5SDimitry Andric // Section N + K
17670b57cec5SDimitry Andric // Thunk Section 1
17680b57cec5SDimitry Andric //
17690b57cec5SDimitry Andric // The intention is that we can add a Thunk to a ThunkSection that is well
17700b57cec5SDimitry Andric // spaced enough to service a number of callers without having to do a lot
17710b57cec5SDimitry Andric // of work. An important principle is that it is not an error if a Thunk cannot
17720b57cec5SDimitry Andric // be placed in a pre-created ThunkSection; when this happens we create a new
17730b57cec5SDimitry Andric // ThunkSection placed next to the caller. This allows us to handle the vast
17740b57cec5SDimitry Andric // majority of thunks simply, but also handle rare cases where the branch range
17750b57cec5SDimitry Andric // is smaller than the target specific spacing.
17760b57cec5SDimitry Andric //
17770b57cec5SDimitry Andric // The algorithm is expected to create all the thunks that are needed in a
17780b57cec5SDimitry Andric // single pass, with a small number of programs needing a second pass due to
17790b57cec5SDimitry Andric // the insertion of thunks in the first pass increasing the offset between
17800b57cec5SDimitry Andric // callers and callees that were only just in range.
17810b57cec5SDimitry Andric //
17820b57cec5SDimitry Andric // A consequence of allowing new ThunkSections to be created outside of the
17830b57cec5SDimitry Andric // pre-created ThunkSections is that in rare cases calls to Thunks that were in
17840b57cec5SDimitry Andric // range in pass K, are out of range in some pass > K due to the insertion of
17850b57cec5SDimitry Andric // more Thunks in between the caller and callee. When this happens we retarget
17860b57cec5SDimitry Andric // the relocation back to the original target and create another Thunk.
17870b57cec5SDimitry Andric 
17880b57cec5SDimitry Andric // Remove ThunkSections that are empty, this should only be the initial set
17890b57cec5SDimitry Andric // precreated on pass 0.
17900b57cec5SDimitry Andric 
17910b57cec5SDimitry Andric // Insert the Thunks for OutputSection OS into their designated place
17920b57cec5SDimitry Andric // in the Sections vector, and recalculate the InputSection output section
17930b57cec5SDimitry Andric // offsets.
17940b57cec5SDimitry Andric // This may invalidate any output section offsets stored outside of InputSection
17950b57cec5SDimitry Andric void ThunkCreator::mergeThunks(ArrayRef<OutputSection *> outputSections) {
17960b57cec5SDimitry Andric   forEachInputSectionDescription(
17970b57cec5SDimitry Andric       outputSections, [&](OutputSection *os, InputSectionDescription *isd) {
17980b57cec5SDimitry Andric         if (isd->thunkSections.empty())
17990b57cec5SDimitry Andric           return;
18000b57cec5SDimitry Andric 
18010b57cec5SDimitry Andric         // Remove any zero sized precreated Thunks.
18020b57cec5SDimitry Andric         llvm::erase_if(isd->thunkSections,
18030b57cec5SDimitry Andric                        [](const std::pair<ThunkSection *, uint32_t> &ts) {
18040b57cec5SDimitry Andric                          return ts.first->getSize() == 0;
18050b57cec5SDimitry Andric                        });
18060b57cec5SDimitry Andric 
18070b57cec5SDimitry Andric         // ISD->ThunkSections contains all created ThunkSections, including
18080b57cec5SDimitry Andric         // those inserted in previous passes. Extract the Thunks created this
18090b57cec5SDimitry Andric         // pass and order them in ascending outSecOff.
18100b57cec5SDimitry Andric         std::vector<ThunkSection *> newThunks;
1811480093f4SDimitry Andric         for (std::pair<ThunkSection *, uint32_t> ts : isd->thunkSections)
18120b57cec5SDimitry Andric           if (ts.second == pass)
18130b57cec5SDimitry Andric             newThunks.push_back(ts.first);
18140b57cec5SDimitry Andric         llvm::stable_sort(newThunks,
18150b57cec5SDimitry Andric                           [](const ThunkSection *a, const ThunkSection *b) {
18160b57cec5SDimitry Andric                             return a->outSecOff < b->outSecOff;
18170b57cec5SDimitry Andric                           });
18180b57cec5SDimitry Andric 
18190b57cec5SDimitry Andric         // Merge sorted vectors of Thunks and InputSections by outSecOff
18200b57cec5SDimitry Andric         std::vector<InputSection *> tmp;
18210b57cec5SDimitry Andric         tmp.reserve(isd->sections.size() + newThunks.size());
18220b57cec5SDimitry Andric 
18230b57cec5SDimitry Andric         std::merge(isd->sections.begin(), isd->sections.end(),
18240b57cec5SDimitry Andric                    newThunks.begin(), newThunks.end(), std::back_inserter(tmp),
18250b57cec5SDimitry Andric                    mergeCmp);
18260b57cec5SDimitry Andric 
18270b57cec5SDimitry Andric         isd->sections = std::move(tmp);
18280b57cec5SDimitry Andric       });
18290b57cec5SDimitry Andric }
18300b57cec5SDimitry Andric 
18310b57cec5SDimitry Andric // Find or create a ThunkSection within the InputSectionDescription (ISD) that
18320b57cec5SDimitry Andric // is in range of Src. An ISD maps to a range of InputSections described by a
18330b57cec5SDimitry Andric // linker script section pattern such as { .text .text.* }.
1834fe6060f1SDimitry Andric ThunkSection *ThunkCreator::getISDThunkSec(OutputSection *os,
1835fe6060f1SDimitry Andric                                            InputSection *isec,
18360b57cec5SDimitry Andric                                            InputSectionDescription *isd,
1837fe6060f1SDimitry Andric                                            const Relocation &rel,
1838fe6060f1SDimitry Andric                                            uint64_t src) {
18390b57cec5SDimitry Andric   for (std::pair<ThunkSection *, uint32_t> tp : isd->thunkSections) {
18400b57cec5SDimitry Andric     ThunkSection *ts = tp.first;
1841fe6060f1SDimitry Andric     uint64_t tsBase = os->addr + ts->outSecOff + rel.addend;
1842fe6060f1SDimitry Andric     uint64_t tsLimit = tsBase + ts->getSize() + rel.addend;
1843fe6060f1SDimitry Andric     if (target->inBranchRange(rel.type, src,
1844fe6060f1SDimitry Andric                               (src > tsLimit) ? tsBase : tsLimit))
18450b57cec5SDimitry Andric       return ts;
18460b57cec5SDimitry Andric   }
18470b57cec5SDimitry Andric 
18480b57cec5SDimitry Andric   // No suitable ThunkSection exists. This can happen when there is a branch
18490b57cec5SDimitry Andric   // with lower range than the ThunkSection spacing or when there are too
18500b57cec5SDimitry Andric   // many Thunks. Create a new ThunkSection as close to the InputSection as
18510b57cec5SDimitry Andric   // possible. Error if InputSection is so large we cannot place ThunkSection
18520b57cec5SDimitry Andric   // anywhere in Range.
18530b57cec5SDimitry Andric   uint64_t thunkSecOff = isec->outSecOff;
1854fe6060f1SDimitry Andric   if (!target->inBranchRange(rel.type, src,
1855fe6060f1SDimitry Andric                              os->addr + thunkSecOff + rel.addend)) {
18560b57cec5SDimitry Andric     thunkSecOff = isec->outSecOff + isec->getSize();
1857fe6060f1SDimitry Andric     if (!target->inBranchRange(rel.type, src,
1858fe6060f1SDimitry Andric                                os->addr + thunkSecOff + rel.addend))
18590b57cec5SDimitry Andric       fatal("InputSection too large for range extension thunk " +
18600b57cec5SDimitry Andric             isec->getObjMsg(src - (os->addr + isec->outSecOff)));
18610b57cec5SDimitry Andric   }
18620b57cec5SDimitry Andric   return addThunkSection(os, isd, thunkSecOff);
18630b57cec5SDimitry Andric }
18640b57cec5SDimitry Andric 
18650b57cec5SDimitry Andric // Add a Thunk that needs to be placed in a ThunkSection that immediately
18660b57cec5SDimitry Andric // precedes its Target.
18670b57cec5SDimitry Andric ThunkSection *ThunkCreator::getISThunkSec(InputSection *isec) {
18680b57cec5SDimitry Andric   ThunkSection *ts = thunkedSections.lookup(isec);
18690b57cec5SDimitry Andric   if (ts)
18700b57cec5SDimitry Andric     return ts;
18710b57cec5SDimitry Andric 
18720b57cec5SDimitry Andric   // Find InputSectionRange within Target Output Section (TOS) that the
18730b57cec5SDimitry Andric   // InputSection (IS) that we need to precede is in.
18740b57cec5SDimitry Andric   OutputSection *tos = isec->getParent();
18754824e7fdSDimitry Andric   for (SectionCommand *bc : tos->commands) {
18760b57cec5SDimitry Andric     auto *isd = dyn_cast<InputSectionDescription>(bc);
18770b57cec5SDimitry Andric     if (!isd || isd->sections.empty())
18780b57cec5SDimitry Andric       continue;
18790b57cec5SDimitry Andric 
18800b57cec5SDimitry Andric     InputSection *first = isd->sections.front();
18810b57cec5SDimitry Andric     InputSection *last = isd->sections.back();
18820b57cec5SDimitry Andric 
18830b57cec5SDimitry Andric     if (isec->outSecOff < first->outSecOff || last->outSecOff < isec->outSecOff)
18840b57cec5SDimitry Andric       continue;
18850b57cec5SDimitry Andric 
18860b57cec5SDimitry Andric     ts = addThunkSection(tos, isd, isec->outSecOff);
18870b57cec5SDimitry Andric     thunkedSections[isec] = ts;
18880b57cec5SDimitry Andric     return ts;
18890b57cec5SDimitry Andric   }
18900b57cec5SDimitry Andric 
18910b57cec5SDimitry Andric   return nullptr;
18920b57cec5SDimitry Andric }
18930b57cec5SDimitry Andric 
18940b57cec5SDimitry Andric // Create one or more ThunkSections per OS that can be used to place Thunks.
18950b57cec5SDimitry Andric // We attempt to place the ThunkSections using the following desirable
18960b57cec5SDimitry Andric // properties:
18970b57cec5SDimitry Andric // - Within range of the maximum number of callers
18980b57cec5SDimitry Andric // - Minimise the number of ThunkSections
18990b57cec5SDimitry Andric //
19000b57cec5SDimitry Andric // We follow a simple but conservative heuristic to place ThunkSections at
19010b57cec5SDimitry Andric // offsets that are multiples of a Target specific branch range.
19020b57cec5SDimitry Andric // For an InputSectionDescription that is smaller than the range, a single
19030b57cec5SDimitry Andric // ThunkSection at the end of the range will do.
19040b57cec5SDimitry Andric //
19050b57cec5SDimitry Andric // For an InputSectionDescription that is more than twice the size of the range,
19060b57cec5SDimitry Andric // we place the last ThunkSection at range bytes from the end of the
19070b57cec5SDimitry Andric // InputSectionDescription in order to increase the likelihood that the
19080b57cec5SDimitry Andric // distance from a thunk to its target will be sufficiently small to
19090b57cec5SDimitry Andric // allow for the creation of a short thunk.
19100b57cec5SDimitry Andric void ThunkCreator::createInitialThunkSections(
19110b57cec5SDimitry Andric     ArrayRef<OutputSection *> outputSections) {
19120b57cec5SDimitry Andric   uint32_t thunkSectionSpacing = target->getThunkSectionSpacing();
19130b57cec5SDimitry Andric 
19140b57cec5SDimitry Andric   forEachInputSectionDescription(
19150b57cec5SDimitry Andric       outputSections, [&](OutputSection *os, InputSectionDescription *isd) {
19160b57cec5SDimitry Andric         if (isd->sections.empty())
19170b57cec5SDimitry Andric           return;
19180b57cec5SDimitry Andric 
19190b57cec5SDimitry Andric         uint32_t isdBegin = isd->sections.front()->outSecOff;
19200b57cec5SDimitry Andric         uint32_t isdEnd =
19210b57cec5SDimitry Andric             isd->sections.back()->outSecOff + isd->sections.back()->getSize();
19220b57cec5SDimitry Andric         uint32_t lastThunkLowerBound = -1;
19230b57cec5SDimitry Andric         if (isdEnd - isdBegin > thunkSectionSpacing * 2)
19240b57cec5SDimitry Andric           lastThunkLowerBound = isdEnd - thunkSectionSpacing;
19250b57cec5SDimitry Andric 
19260b57cec5SDimitry Andric         uint32_t isecLimit;
19270b57cec5SDimitry Andric         uint32_t prevIsecLimit = isdBegin;
19280b57cec5SDimitry Andric         uint32_t thunkUpperBound = isdBegin + thunkSectionSpacing;
19290b57cec5SDimitry Andric 
19300b57cec5SDimitry Andric         for (const InputSection *isec : isd->sections) {
19310b57cec5SDimitry Andric           isecLimit = isec->outSecOff + isec->getSize();
19320b57cec5SDimitry Andric           if (isecLimit > thunkUpperBound) {
19330b57cec5SDimitry Andric             addThunkSection(os, isd, prevIsecLimit);
19340b57cec5SDimitry Andric             thunkUpperBound = prevIsecLimit + thunkSectionSpacing;
19350b57cec5SDimitry Andric           }
19360b57cec5SDimitry Andric           if (isecLimit > lastThunkLowerBound)
19370b57cec5SDimitry Andric             break;
19380b57cec5SDimitry Andric           prevIsecLimit = isecLimit;
19390b57cec5SDimitry Andric         }
19400b57cec5SDimitry Andric         addThunkSection(os, isd, isecLimit);
19410b57cec5SDimitry Andric       });
19420b57cec5SDimitry Andric }
19430b57cec5SDimitry Andric 
19440b57cec5SDimitry Andric ThunkSection *ThunkCreator::addThunkSection(OutputSection *os,
19450b57cec5SDimitry Andric                                             InputSectionDescription *isd,
19460b57cec5SDimitry Andric                                             uint64_t off) {
19470b57cec5SDimitry Andric   auto *ts = make<ThunkSection>(os, off);
19480b57cec5SDimitry Andric   ts->partition = os->partition;
194913138422SDimitry Andric   if ((config->fixCortexA53Errata843419 || config->fixCortexA8) &&
195013138422SDimitry Andric       !isd->sections.empty()) {
195113138422SDimitry Andric     // The errata fixes are sensitive to addresses modulo 4 KiB. When we add
195213138422SDimitry Andric     // thunks we disturb the base addresses of sections placed after the thunks
195313138422SDimitry Andric     // this makes patches we have generated redundant, and may cause us to
195413138422SDimitry Andric     // generate more patches as different instructions are now in sensitive
195513138422SDimitry Andric     // locations. When we generate more patches we may force more branches to
195613138422SDimitry Andric     // go out of range, causing more thunks to be generated. In pathological
195713138422SDimitry Andric     // cases this can cause the address dependent content pass not to converge.
195813138422SDimitry Andric     // We fix this by rounding up the size of the ThunkSection to 4KiB, this
195913138422SDimitry Andric     // limits the insertion of a ThunkSection on the addresses modulo 4 KiB,
196013138422SDimitry Andric     // which means that adding Thunks to the section does not invalidate
196113138422SDimitry Andric     // errata patches for following code.
196213138422SDimitry Andric     // Rounding up the size to 4KiB has consequences for code-size and can
196313138422SDimitry Andric     // trip up linker script defined assertions. For example the linux kernel
196413138422SDimitry Andric     // has an assertion that what LLD represents as an InputSectionDescription
196513138422SDimitry Andric     // does not exceed 4 KiB even if the overall OutputSection is > 128 Mib.
196613138422SDimitry Andric     // We use the heuristic of rounding up the size when both of the following
196713138422SDimitry Andric     // conditions are true:
196813138422SDimitry Andric     // 1.) The OutputSection is larger than the ThunkSectionSpacing. This
196913138422SDimitry Andric     //     accounts for the case where no single InputSectionDescription is
197013138422SDimitry Andric     //     larger than the OutputSection size. This is conservative but simple.
197113138422SDimitry Andric     // 2.) The InputSectionDescription is larger than 4 KiB. This will prevent
197213138422SDimitry Andric     //     any assertion failures that an InputSectionDescription is < 4 KiB
197313138422SDimitry Andric     //     in size.
197413138422SDimitry Andric     uint64_t isdSize = isd->sections.back()->outSecOff +
197513138422SDimitry Andric                        isd->sections.back()->getSize() -
197613138422SDimitry Andric                        isd->sections.front()->outSecOff;
197713138422SDimitry Andric     if (os->size > target->getThunkSectionSpacing() && isdSize > 4096)
197813138422SDimitry Andric       ts->roundUpSizeForErrata = true;
197913138422SDimitry Andric   }
19800b57cec5SDimitry Andric   isd->thunkSections.push_back({ts, pass});
19810b57cec5SDimitry Andric   return ts;
19820b57cec5SDimitry Andric }
19830b57cec5SDimitry Andric 
19840b57cec5SDimitry Andric static bool isThunkSectionCompatible(InputSection *source,
19850b57cec5SDimitry Andric                                      SectionBase *target) {
19860b57cec5SDimitry Andric   // We can't reuse thunks in different loadable partitions because they might
19870b57cec5SDimitry Andric   // not be loaded. But partition 1 (the main partition) will always be loaded.
19880b57cec5SDimitry Andric   if (source->partition != target->partition)
19890b57cec5SDimitry Andric     return target->partition == 1;
19900b57cec5SDimitry Andric   return true;
19910b57cec5SDimitry Andric }
19920b57cec5SDimitry Andric 
1993480093f4SDimitry Andric static int64_t getPCBias(RelType type) {
1994480093f4SDimitry Andric   if (config->emachine != EM_ARM)
1995480093f4SDimitry Andric     return 0;
1996480093f4SDimitry Andric   switch (type) {
1997480093f4SDimitry Andric   case R_ARM_THM_JUMP19:
1998480093f4SDimitry Andric   case R_ARM_THM_JUMP24:
1999480093f4SDimitry Andric   case R_ARM_THM_CALL:
2000480093f4SDimitry Andric     return 4;
2001480093f4SDimitry Andric   default:
2002480093f4SDimitry Andric     return 8;
2003480093f4SDimitry Andric   }
2004480093f4SDimitry Andric }
2005480093f4SDimitry Andric 
20060b57cec5SDimitry Andric std::pair<Thunk *, bool> ThunkCreator::getThunk(InputSection *isec,
20070b57cec5SDimitry Andric                                                 Relocation &rel, uint64_t src) {
20080b57cec5SDimitry Andric   std::vector<Thunk *> *thunkVec = nullptr;
2009fe6060f1SDimitry Andric   // Arm and Thumb have a PC Bias of 8 and 4 respectively, this is cancelled
2010fe6060f1SDimitry Andric   // out in the relocation addend. We compensate for the PC bias so that
2011fe6060f1SDimitry Andric   // an Arm and Thumb relocation to the same destination get the same keyAddend,
2012fe6060f1SDimitry Andric   // which is usually 0.
20139b597132SPiotr Kubaj   const int64_t pcBias = getPCBias(rel.type);
20149b597132SPiotr Kubaj   const int64_t keyAddend = rel.addend + pcBias;
20150b57cec5SDimitry Andric 
2016480093f4SDimitry Andric   // We use a ((section, offset), addend) pair to find the thunk position if
2017480093f4SDimitry Andric   // possible so that we create only one thunk for aliased symbols or ICFed
2018480093f4SDimitry Andric   // sections. There may be multiple relocations sharing the same (section,
2019480093f4SDimitry Andric   // offset + addend) pair. We may revert the relocation back to its original
2020480093f4SDimitry Andric   // non-Thunk target, so we cannot fold offset + addend.
20210b57cec5SDimitry Andric   if (auto *d = dyn_cast<Defined>(rel.sym))
20220b57cec5SDimitry Andric     if (!d->isInPlt() && d->section)
2023*0eae32dcSDimitry Andric       thunkVec = &thunkedSymbolsBySectionAndAddend[{{d->section, d->value},
2024*0eae32dcSDimitry Andric                                                     keyAddend}];
20250b57cec5SDimitry Andric   if (!thunkVec)
2026fe6060f1SDimitry Andric     thunkVec = &thunkedSymbols[{rel.sym, keyAddend}];
20270b57cec5SDimitry Andric 
20280b57cec5SDimitry Andric   // Check existing Thunks for Sym to see if they can be reused
20290b57cec5SDimitry Andric   for (Thunk *t : *thunkVec)
20300b57cec5SDimitry Andric     if (isThunkSectionCompatible(isec, t->getThunkTargetSym()->section) &&
20310b57cec5SDimitry Andric         t->isCompatibleWith(*isec, rel) &&
2032480093f4SDimitry Andric         target->inBranchRange(rel.type, src,
20339b597132SPiotr Kubaj                               t->getThunkTargetSym()->getVA(-pcBias)))
20340b57cec5SDimitry Andric       return std::make_pair(t, false);
20350b57cec5SDimitry Andric 
20360b57cec5SDimitry Andric   // No existing compatible Thunk in range, create a new one
20370b57cec5SDimitry Andric   Thunk *t = addThunk(*isec, rel);
20380b57cec5SDimitry Andric   thunkVec->push_back(t);
20390b57cec5SDimitry Andric   return std::make_pair(t, true);
20400b57cec5SDimitry Andric }
20410b57cec5SDimitry Andric 
20420b57cec5SDimitry Andric // Return true if the relocation target is an in range Thunk.
20430b57cec5SDimitry Andric // Return false if the relocation is not to a Thunk. If the relocation target
20440b57cec5SDimitry Andric // was originally to a Thunk, but is no longer in range we revert the
20450b57cec5SDimitry Andric // relocation back to its original non-Thunk target.
20460b57cec5SDimitry Andric bool ThunkCreator::normalizeExistingThunk(Relocation &rel, uint64_t src) {
20470b57cec5SDimitry Andric   if (Thunk *t = thunks.lookup(rel.sym)) {
2048fe6060f1SDimitry Andric     if (target->inBranchRange(rel.type, src, rel.sym->getVA(rel.addend)))
20490b57cec5SDimitry Andric       return true;
20500b57cec5SDimitry Andric     rel.sym = &t->destination;
2051480093f4SDimitry Andric     rel.addend = t->addend;
20520b57cec5SDimitry Andric     if (rel.sym->isInPlt())
20530b57cec5SDimitry Andric       rel.expr = toPlt(rel.expr);
20540b57cec5SDimitry Andric   }
20550b57cec5SDimitry Andric   return false;
20560b57cec5SDimitry Andric }
20570b57cec5SDimitry Andric 
20580b57cec5SDimitry Andric // Process all relocations from the InputSections that have been assigned
20590b57cec5SDimitry Andric // to InputSectionDescriptions and redirect through Thunks if needed. The
20600b57cec5SDimitry Andric // function should be called iteratively until it returns false.
20610b57cec5SDimitry Andric //
20620b57cec5SDimitry Andric // PreConditions:
20630b57cec5SDimitry Andric // All InputSections that may need a Thunk are reachable from
20640b57cec5SDimitry Andric // OutputSectionCommands.
20650b57cec5SDimitry Andric //
20660b57cec5SDimitry Andric // All OutputSections have an address and all InputSections have an offset
20670b57cec5SDimitry Andric // within the OutputSection.
20680b57cec5SDimitry Andric //
20690b57cec5SDimitry Andric // The offsets between caller (relocation place) and callee
20700b57cec5SDimitry Andric // (relocation target) will not be modified outside of createThunks().
20710b57cec5SDimitry Andric //
20720b57cec5SDimitry Andric // PostConditions:
20730b57cec5SDimitry Andric // If return value is true then ThunkSections have been inserted into
20740b57cec5SDimitry Andric // OutputSections. All relocations that needed a Thunk based on the information
20750b57cec5SDimitry Andric // available to createThunks() on entry have been redirected to a Thunk. Note
20760b57cec5SDimitry Andric // that adding Thunks changes offsets between caller and callee so more Thunks
20770b57cec5SDimitry Andric // may be required.
20780b57cec5SDimitry Andric //
20790b57cec5SDimitry Andric // If return value is false then no more Thunks are needed, and createThunks has
20800b57cec5SDimitry Andric // made no changes. If the target requires range extension thunks, currently
20810b57cec5SDimitry Andric // ARM, then any future change in offset between caller and callee risks a
20820b57cec5SDimitry Andric // relocation out of range error.
20830b57cec5SDimitry Andric bool ThunkCreator::createThunks(ArrayRef<OutputSection *> outputSections) {
20840b57cec5SDimitry Andric   bool addressesChanged = false;
20850b57cec5SDimitry Andric 
20860b57cec5SDimitry Andric   if (pass == 0 && target->getThunkSectionSpacing())
20870b57cec5SDimitry Andric     createInitialThunkSections(outputSections);
20880b57cec5SDimitry Andric 
20890b57cec5SDimitry Andric   // Create all the Thunks and insert them into synthetic ThunkSections. The
20900b57cec5SDimitry Andric   // ThunkSections are later inserted back into InputSectionDescriptions.
20910b57cec5SDimitry Andric   // We separate the creation of ThunkSections from the insertion of the
20920b57cec5SDimitry Andric   // ThunkSections as ThunkSections are not always inserted into the same
20930b57cec5SDimitry Andric   // InputSectionDescription as the caller.
20940b57cec5SDimitry Andric   forEachInputSectionDescription(
20950b57cec5SDimitry Andric       outputSections, [&](OutputSection *os, InputSectionDescription *isd) {
20960b57cec5SDimitry Andric         for (InputSection *isec : isd->sections)
20970b57cec5SDimitry Andric           for (Relocation &rel : isec->relocations) {
20980b57cec5SDimitry Andric             uint64_t src = isec->getVA(rel.offset);
20990b57cec5SDimitry Andric 
21000b57cec5SDimitry Andric             // If we are a relocation to an existing Thunk, check if it is
21010b57cec5SDimitry Andric             // still in range. If not then Rel will be altered to point to its
21020b57cec5SDimitry Andric             // original target so another Thunk can be generated.
21030b57cec5SDimitry Andric             if (pass > 0 && normalizeExistingThunk(rel, src))
21040b57cec5SDimitry Andric               continue;
21050b57cec5SDimitry Andric 
21060b57cec5SDimitry Andric             if (!target->needsThunk(rel.expr, rel.type, isec->file, src,
2107480093f4SDimitry Andric                                     *rel.sym, rel.addend))
21080b57cec5SDimitry Andric               continue;
21090b57cec5SDimitry Andric 
21100b57cec5SDimitry Andric             Thunk *t;
21110b57cec5SDimitry Andric             bool isNew;
21120b57cec5SDimitry Andric             std::tie(t, isNew) = getThunk(isec, rel, src);
21130b57cec5SDimitry Andric 
21140b57cec5SDimitry Andric             if (isNew) {
21150b57cec5SDimitry Andric               // Find or create a ThunkSection for the new Thunk
21160b57cec5SDimitry Andric               ThunkSection *ts;
21170b57cec5SDimitry Andric               if (auto *tis = t->getTargetInputSection())
21180b57cec5SDimitry Andric                 ts = getISThunkSec(tis);
21190b57cec5SDimitry Andric               else
2120fe6060f1SDimitry Andric                 ts = getISDThunkSec(os, isec, isd, rel, src);
21210b57cec5SDimitry Andric               ts->addThunk(t);
21220b57cec5SDimitry Andric               thunks[t->getThunkTargetSym()] = t;
21230b57cec5SDimitry Andric             }
21240b57cec5SDimitry Andric 
21250b57cec5SDimitry Andric             // Redirect relocation to Thunk, we never go via the PLT to a Thunk
21260b57cec5SDimitry Andric             rel.sym = t->getThunkTargetSym();
21270b57cec5SDimitry Andric             rel.expr = fromPlt(rel.expr);
21280b57cec5SDimitry Andric 
212913138422SDimitry Andric             // On AArch64 and PPC, a jump/call relocation may be encoded as
2130480093f4SDimitry Andric             // STT_SECTION + non-zero addend, clear the addend after
2131480093f4SDimitry Andric             // redirection.
213213138422SDimitry Andric             if (config->emachine != EM_MIPS)
213313138422SDimitry Andric               rel.addend = -getPCBias(rel.type);
21340b57cec5SDimitry Andric           }
21350b57cec5SDimitry Andric 
21360b57cec5SDimitry Andric         for (auto &p : isd->thunkSections)
21370b57cec5SDimitry Andric           addressesChanged |= p.first->assignOffsets();
21380b57cec5SDimitry Andric       });
21390b57cec5SDimitry Andric 
21400b57cec5SDimitry Andric   for (auto &p : thunkedSections)
21410b57cec5SDimitry Andric     addressesChanged |= p.second->assignOffsets();
21420b57cec5SDimitry Andric 
21430b57cec5SDimitry Andric   // Merge all created synthetic ThunkSections back into OutputSection
21440b57cec5SDimitry Andric   mergeThunks(outputSections);
21450b57cec5SDimitry Andric   ++pass;
21460b57cec5SDimitry Andric   return addressesChanged;
21470b57cec5SDimitry Andric }
21480b57cec5SDimitry Andric 
21495ffd83dbSDimitry Andric // The following aid in the conversion of call x@GDPLT to call __tls_get_addr
21505ffd83dbSDimitry Andric // hexagonNeedsTLSSymbol scans for relocations would require a call to
21515ffd83dbSDimitry Andric // __tls_get_addr.
21525ffd83dbSDimitry Andric // hexagonTLSSymbolUpdate rebinds the relocation to __tls_get_addr.
21535ffd83dbSDimitry Andric bool elf::hexagonNeedsTLSSymbol(ArrayRef<OutputSection *> outputSections) {
21545ffd83dbSDimitry Andric   bool needTlsSymbol = false;
21555ffd83dbSDimitry Andric   forEachInputSectionDescription(
21565ffd83dbSDimitry Andric       outputSections, [&](OutputSection *os, InputSectionDescription *isd) {
21575ffd83dbSDimitry Andric         for (InputSection *isec : isd->sections)
21585ffd83dbSDimitry Andric           for (Relocation &rel : isec->relocations)
21595ffd83dbSDimitry Andric             if (rel.sym->type == llvm::ELF::STT_TLS && rel.expr == R_PLT_PC) {
21605ffd83dbSDimitry Andric               needTlsSymbol = true;
21615ffd83dbSDimitry Andric               return;
21625ffd83dbSDimitry Andric             }
21635ffd83dbSDimitry Andric       });
21645ffd83dbSDimitry Andric   return needTlsSymbol;
21655ffd83dbSDimitry Andric }
216685868e8aSDimitry Andric 
21675ffd83dbSDimitry Andric void elf::hexagonTLSSymbolUpdate(ArrayRef<OutputSection *> outputSections) {
21685ffd83dbSDimitry Andric   Symbol *sym = symtab->find("__tls_get_addr");
21695ffd83dbSDimitry Andric   if (!sym)
21705ffd83dbSDimitry Andric     return;
21715ffd83dbSDimitry Andric   bool needEntry = true;
21725ffd83dbSDimitry Andric   forEachInputSectionDescription(
21735ffd83dbSDimitry Andric       outputSections, [&](OutputSection *os, InputSectionDescription *isd) {
21745ffd83dbSDimitry Andric         for (InputSection *isec : isd->sections)
21755ffd83dbSDimitry Andric           for (Relocation &rel : isec->relocations)
21765ffd83dbSDimitry Andric             if (rel.sym->type == llvm::ELF::STT_TLS && rel.expr == R_PLT_PC) {
21775ffd83dbSDimitry Andric               if (needEntry) {
2178*0eae32dcSDimitry Andric                 addPltEntry(*in.plt, *in.gotPlt, *in.relaPlt, target->pltRel,
21795ffd83dbSDimitry Andric                             *sym);
21805ffd83dbSDimitry Andric                 needEntry = false;
21815ffd83dbSDimitry Andric               }
21825ffd83dbSDimitry Andric               rel.sym = sym;
21835ffd83dbSDimitry Andric             }
21845ffd83dbSDimitry Andric       });
21855ffd83dbSDimitry Andric }
21865ffd83dbSDimitry Andric 
21875ffd83dbSDimitry Andric template void elf::scanRelocations<ELF32LE>(InputSectionBase &);
21885ffd83dbSDimitry Andric template void elf::scanRelocations<ELF32BE>(InputSectionBase &);
21895ffd83dbSDimitry Andric template void elf::scanRelocations<ELF64LE>(InputSectionBase &);
21905ffd83dbSDimitry Andric template void elf::scanRelocations<ELF64BE>(InputSectionBase &);
21915ffd83dbSDimitry Andric template void elf::reportUndefinedSymbols<ELF32LE>();
21925ffd83dbSDimitry Andric template void elf::reportUndefinedSymbols<ELF32BE>();
21935ffd83dbSDimitry Andric template void elf::reportUndefinedSymbols<ELF64LE>();
21945ffd83dbSDimitry Andric template void elf::reportUndefinedSymbols<ELF64BE>();
2195