10b57cec5SDimitry Andric //===- Relocations.cpp ----------------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file contains platform-independent functions to process relocations.
100b57cec5SDimitry Andric // I'll describe the overview of this file here.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric // Simple relocations are easy to handle for the linker. For example,
130b57cec5SDimitry Andric // for R_X86_64_PC64 relocs, the linker just has to fix up locations
140b57cec5SDimitry Andric // with the relative offsets to the target symbols. It would just be
150b57cec5SDimitry Andric // reading records from relocation sections and applying them to output.
160b57cec5SDimitry Andric //
170b57cec5SDimitry Andric // But not all relocations are that easy to handle. For example, for
180b57cec5SDimitry Andric // R_386_GOTOFF relocs, the linker has to create new GOT entries for
190b57cec5SDimitry Andric // symbols if they don't exist, and fix up locations with GOT entry
200b57cec5SDimitry Andric // offsets from the beginning of GOT section. So there is more than
210b57cec5SDimitry Andric // fixing addresses in relocation processing.
220b57cec5SDimitry Andric //
230b57cec5SDimitry Andric // ELF defines a large number of complex relocations.
240b57cec5SDimitry Andric //
250b57cec5SDimitry Andric // The functions in this file analyze relocations and do whatever needs
260b57cec5SDimitry Andric // to be done. It includes, but not limited to, the following.
270b57cec5SDimitry Andric //
280b57cec5SDimitry Andric // - create GOT/PLT entries
290b57cec5SDimitry Andric // - create new relocations in .dynsym to let the dynamic linker resolve
300b57cec5SDimitry Andric // them at runtime (since ELF supports dynamic linking, not all
310b57cec5SDimitry Andric // relocations can be resolved at link-time)
320b57cec5SDimitry Andric // - create COPY relocs and reserve space in .bss
330b57cec5SDimitry Andric // - replace expensive relocs (in terms of runtime cost) with cheap ones
340b57cec5SDimitry Andric // - error out infeasible combinations such as PIC and non-relative relocs
350b57cec5SDimitry Andric //
360b57cec5SDimitry Andric // Note that the functions in this file don't actually apply relocations
370b57cec5SDimitry Andric // because it doesn't know about the output file nor the output file buffer.
380b57cec5SDimitry Andric // It instead stores Relocation objects to InputSection's Relocations
390b57cec5SDimitry Andric // vector to let it apply later in InputSection::writeTo.
400b57cec5SDimitry Andric //
410b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
420b57cec5SDimitry Andric
430b57cec5SDimitry Andric #include "Relocations.h"
440b57cec5SDimitry Andric #include "Config.h"
4581ad6265SDimitry Andric #include "InputFiles.h"
460b57cec5SDimitry Andric #include "LinkerScript.h"
470b57cec5SDimitry Andric #include "OutputSections.h"
480b57cec5SDimitry Andric #include "SymbolTable.h"
490b57cec5SDimitry Andric #include "Symbols.h"
500b57cec5SDimitry Andric #include "SyntheticSections.h"
510b57cec5SDimitry Andric #include "Target.h"
520b57cec5SDimitry Andric #include "Thunks.h"
530b57cec5SDimitry Andric #include "lld/Common/ErrorHandler.h"
540b57cec5SDimitry Andric #include "lld/Common/Memory.h"
550b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
565f757f3fSDimitry Andric #include "llvm/BinaryFormat/ELF.h"
57480093f4SDimitry Andric #include "llvm/Demangle/Demangle.h"
580b57cec5SDimitry Andric #include "llvm/Support/Endian.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
getLinkerScriptLocation(const Symbol & sym)68bdd1243dSDimitry Andric static std::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;
73bdd1243dSDimitry Andric return std::nullopt;
740b57cec5SDimitry Andric }
750b57cec5SDimitry Andric
getDefinedLocation(const Symbol & sym)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);
80bdd1243dSDimitry Andric if (std::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)
getLocation(InputSectionBase & s,const Symbol & sym,uint64_t off)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
reportRangeError(uint8_t * loc,const Relocation & rel,const Twine & v,int64_t min,uint64_t max)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;
10306c3fb27SDimitry Andric if (rel.sym) {
10406c3fb27SDimitry Andric if (!rel.sym->isSection())
10506c3fb27SDimitry Andric hint = "; references '" + lld::toString(*rel.sym) + '\'';
10606c3fb27SDimitry Andric else if (auto *d = dyn_cast<Defined>(rel.sym))
10706c3fb27SDimitry Andric hint = ("; references section '" + d->section->name + "'").str();
1087a6dacacSDimitry Andric
1097a6dacacSDimitry Andric if (config->emachine == EM_X86_64 && rel.type == R_X86_64_PC32 &&
1107a6dacacSDimitry Andric rel.sym->getOutputSection() &&
1117a6dacacSDimitry Andric (rel.sym->getOutputSection()->flags & SHF_X86_64_LARGE)) {
1127a6dacacSDimitry Andric hint += "; R_X86_64_PC32 should not reference a section marked "
1137a6dacacSDimitry Andric "SHF_X86_64_LARGE";
1147a6dacacSDimitry Andric }
11506c3fb27SDimitry Andric }
116349cc55cSDimitry Andric if (!errPlace.srcLoc.empty())
117349cc55cSDimitry Andric hint += "\n>>> referenced by " + errPlace.srcLoc;
11804eeddc0SDimitry Andric if (rel.sym && !rel.sym->isSection())
119349cc55cSDimitry Andric hint += getDefinedLocation(*rel.sym);
1205ffd83dbSDimitry Andric
12106c3fb27SDimitry Andric if (errPlace.isec && errPlace.isec->name.starts_with(".debug"))
1225ffd83dbSDimitry Andric hint += "; consider recompiling with -fdebug-types-section to reduce size "
1235ffd83dbSDimitry Andric "of debug sections";
1245ffd83dbSDimitry Andric
1255ffd83dbSDimitry Andric errorOrWarn(errPlace.loc + "relocation " + lld::toString(rel.type) +
1265ffd83dbSDimitry Andric " out of range: " + v.str() + " is not in [" + Twine(min).str() +
1275ffd83dbSDimitry Andric ", " + Twine(max).str() + "]" + hint);
1285ffd83dbSDimitry Andric }
1295ffd83dbSDimitry Andric
reportRangeError(uint8_t * loc,int64_t v,int n,const Symbol & sym,const Twine & msg)130e8d8bef9SDimitry Andric void elf::reportRangeError(uint8_t *loc, int64_t v, int n, const Symbol &sym,
131e8d8bef9SDimitry Andric const Twine &msg) {
132e8d8bef9SDimitry Andric ErrorPlace errPlace = getErrorPlace(loc);
133e8d8bef9SDimitry Andric std::string hint;
134e8d8bef9SDimitry Andric if (!sym.getName().empty())
13506c3fb27SDimitry Andric hint =
13606c3fb27SDimitry Andric "; references '" + lld::toString(sym) + '\'' + getDefinedLocation(sym);
137e8d8bef9SDimitry Andric errorOrWarn(errPlace.loc + msg + " is out of range: " + Twine(v) +
138e8d8bef9SDimitry Andric " is not in [" + Twine(llvm::minIntN(n)) + ", " +
139e8d8bef9SDimitry Andric Twine(llvm::maxIntN(n)) + "]" + hint);
140e8d8bef9SDimitry Andric }
141e8d8bef9SDimitry Andric
142349cc55cSDimitry Andric // Build a bitmask with one bit set for each 64 subset of RelExpr.
buildMask()143349cc55cSDimitry Andric static constexpr uint64_t buildMask() { return 0; }
1440b57cec5SDimitry Andric
145349cc55cSDimitry Andric template <typename... Tails>
buildMask(int head,Tails...tails)146349cc55cSDimitry Andric static constexpr uint64_t buildMask(int head, Tails... tails) {
147349cc55cSDimitry Andric return (0 <= head && head < 64 ? uint64_t(1) << head : 0) |
148349cc55cSDimitry Andric buildMask(tails...);
1490b57cec5SDimitry Andric }
1500b57cec5SDimitry Andric
1510b57cec5SDimitry Andric // Return true if `Expr` is one of `Exprs`.
152349cc55cSDimitry Andric // There are more than 64 but less than 128 RelExprs, so we divide the set of
153349cc55cSDimitry Andric // exprs into [0, 64) and [64, 128) and represent each range as a constant
154349cc55cSDimitry Andric // 64-bit mask. Then we decide which mask to test depending on the value of
155349cc55cSDimitry Andric // expr and use a simple shift and bitwise-and to test for membership.
oneof(RelExpr expr)156349cc55cSDimitry Andric template <RelExpr... Exprs> static bool oneof(RelExpr expr) {
157349cc55cSDimitry Andric assert(0 <= expr && (int)expr < 128 &&
158349cc55cSDimitry Andric "RelExpr is too large for 128-bit mask!");
1590b57cec5SDimitry Andric
160349cc55cSDimitry Andric if (expr >= 64)
161349cc55cSDimitry Andric return (uint64_t(1) << (expr - 64)) & buildMask((Exprs - 64)...);
162349cc55cSDimitry Andric return (uint64_t(1) << expr) & buildMask(Exprs...);
1630b57cec5SDimitry Andric }
1640b57cec5SDimitry Andric
getMipsPairType(RelType type,bool isLocal)1650b57cec5SDimitry Andric static RelType getMipsPairType(RelType type, bool isLocal) {
1660b57cec5SDimitry Andric switch (type) {
1670b57cec5SDimitry Andric case R_MIPS_HI16:
1680b57cec5SDimitry Andric return R_MIPS_LO16;
1690b57cec5SDimitry Andric case R_MIPS_GOT16:
1700b57cec5SDimitry Andric // In case of global symbol, the R_MIPS_GOT16 relocation does not
1710b57cec5SDimitry Andric // have a pair. Each global symbol has a unique entry in the GOT
1720b57cec5SDimitry Andric // and a corresponding instruction with help of the R_MIPS_GOT16
1730b57cec5SDimitry Andric // relocation loads an address of the symbol. In case of local
1740b57cec5SDimitry Andric // symbol, the R_MIPS_GOT16 relocation creates a GOT entry to hold
1750b57cec5SDimitry Andric // the high 16 bits of the symbol's value. A paired R_MIPS_LO16
1760b57cec5SDimitry Andric // relocations handle low 16 bits of the address. That allows
1770b57cec5SDimitry Andric // to allocate only one GOT entry for every 64 KBytes of local data.
1780b57cec5SDimitry Andric return isLocal ? R_MIPS_LO16 : R_MIPS_NONE;
1790b57cec5SDimitry Andric case R_MICROMIPS_GOT16:
1800b57cec5SDimitry Andric return isLocal ? R_MICROMIPS_LO16 : R_MIPS_NONE;
1810b57cec5SDimitry Andric case R_MIPS_PCHI16:
1820b57cec5SDimitry Andric return R_MIPS_PCLO16;
1830b57cec5SDimitry Andric case R_MICROMIPS_HI16:
1840b57cec5SDimitry Andric return R_MICROMIPS_LO16;
1850b57cec5SDimitry Andric default:
1860b57cec5SDimitry Andric return R_MIPS_NONE;
1870b57cec5SDimitry Andric }
1880b57cec5SDimitry Andric }
1890b57cec5SDimitry Andric
1900b57cec5SDimitry Andric // True if non-preemptable symbol always has the same value regardless of where
1910b57cec5SDimitry Andric // the DSO is loaded.
isAbsolute(const Symbol & sym)1920b57cec5SDimitry Andric static bool isAbsolute(const Symbol &sym) {
1930b57cec5SDimitry Andric if (sym.isUndefWeak())
1940b57cec5SDimitry Andric return true;
1950b57cec5SDimitry Andric if (const auto *dr = dyn_cast<Defined>(&sym))
1960b57cec5SDimitry Andric return dr->section == nullptr; // Absolute symbol.
1970b57cec5SDimitry Andric return false;
1980b57cec5SDimitry Andric }
1990b57cec5SDimitry Andric
isAbsoluteValue(const Symbol & sym)2000b57cec5SDimitry Andric static bool isAbsoluteValue(const Symbol &sym) {
2010b57cec5SDimitry Andric return isAbsolute(sym) || sym.isTls();
2020b57cec5SDimitry Andric }
2030b57cec5SDimitry Andric
2040b57cec5SDimitry Andric // Returns true if Expr refers a PLT entry.
needsPlt(RelExpr expr)2050b57cec5SDimitry Andric static bool needsPlt(RelExpr expr) {
20674626c16SDimitry Andric return oneof<R_PLT, R_PLT_PC, R_PLT_GOTREL, R_PLT_GOTPLT, R_GOTPLT_GOTREL,
20774626c16SDimitry Andric R_GOTPLT_PC, R_LOONGARCH_PLT_PAGE_PC, R_PPC32_PLTREL,
20874626c16SDimitry Andric R_PPC64_CALL_PLT>(expr);
2090b57cec5SDimitry Andric }
2100b57cec5SDimitry Andric
needsGot(RelExpr expr)2115f757f3fSDimitry Andric bool lld::elf::needsGot(RelExpr expr) {
21285868e8aSDimitry Andric return oneof<R_GOT, R_GOT_OFF, R_MIPS_GOT_LOCAL_PAGE, R_MIPS_GOT_OFF,
213e8d8bef9SDimitry Andric R_MIPS_GOT_OFF32, R_AARCH64_GOT_PAGE_PC, R_GOT_PC, R_GOTPLT,
21406c3fb27SDimitry Andric R_AARCH64_GOT_PAGE, R_LOONGARCH_GOT, R_LOONGARCH_GOT_PAGE_PC>(
21506c3fb27SDimitry Andric expr);
2160b57cec5SDimitry Andric }
2170b57cec5SDimitry Andric
2180b57cec5SDimitry Andric // True if this expression is of the form Sym - X, where X is a position in the
2190b57cec5SDimitry Andric // file (PC, or GOT for example).
isRelExpr(RelExpr expr)2200b57cec5SDimitry Andric static bool isRelExpr(RelExpr expr) {
2217a6dacacSDimitry Andric return oneof<R_PC, R_GOTREL, R_GOTPLTREL, R_ARM_PCA, R_MIPS_GOTREL,
2227a6dacacSDimitry Andric R_PPC64_CALL, R_PPC64_RELAX_TOC, R_AARCH64_PAGE_PC,
2237a6dacacSDimitry Andric R_RELAX_GOT_PC, R_RISCV_PC_INDIRECT, R_PPC64_RELAX_GOT_PC,
2247a6dacacSDimitry Andric R_LOONGARCH_PAGE_PC>(expr);
2250b57cec5SDimitry Andric }
2260b57cec5SDimitry Andric
toPlt(RelExpr expr)2270b57cec5SDimitry Andric static RelExpr toPlt(RelExpr expr) {
2280b57cec5SDimitry Andric switch (expr) {
22906c3fb27SDimitry Andric case R_LOONGARCH_PAGE_PC:
23006c3fb27SDimitry Andric return R_LOONGARCH_PLT_PAGE_PC;
2310b57cec5SDimitry Andric case R_PPC64_CALL:
2320b57cec5SDimitry Andric return R_PPC64_CALL_PLT;
2330b57cec5SDimitry Andric case R_PC:
2340b57cec5SDimitry Andric return R_PLT_PC;
2350b57cec5SDimitry Andric case R_ABS:
2360b57cec5SDimitry Andric return R_PLT;
23774626c16SDimitry Andric case R_GOTREL:
23874626c16SDimitry Andric return R_PLT_GOTREL;
2390b57cec5SDimitry Andric default:
2400b57cec5SDimitry Andric return expr;
2410b57cec5SDimitry Andric }
2420b57cec5SDimitry Andric }
2430b57cec5SDimitry Andric
fromPlt(RelExpr expr)2440b57cec5SDimitry Andric static RelExpr fromPlt(RelExpr expr) {
2450b57cec5SDimitry Andric // We decided not to use a plt. Optimize a reference to the plt to a
2460b57cec5SDimitry Andric // reference to the symbol itself.
2470b57cec5SDimitry Andric switch (expr) {
2480b57cec5SDimitry Andric case R_PLT_PC:
2490b57cec5SDimitry Andric case R_PPC32_PLTREL:
2500b57cec5SDimitry Andric return R_PC;
25106c3fb27SDimitry Andric case R_LOONGARCH_PLT_PAGE_PC:
25206c3fb27SDimitry Andric return R_LOONGARCH_PAGE_PC;
2530b57cec5SDimitry Andric case R_PPC64_CALL_PLT:
2540b57cec5SDimitry Andric return R_PPC64_CALL;
2550b57cec5SDimitry Andric case R_PLT:
2560b57cec5SDimitry Andric return R_ABS;
257349cc55cSDimitry Andric case R_PLT_GOTPLT:
258349cc55cSDimitry Andric return R_GOTPLTREL;
25974626c16SDimitry Andric case R_PLT_GOTREL:
26074626c16SDimitry Andric return R_GOTREL;
2610b57cec5SDimitry Andric default:
2620b57cec5SDimitry Andric return expr;
2630b57cec5SDimitry Andric }
2640b57cec5SDimitry Andric }
2650b57cec5SDimitry Andric
2660b57cec5SDimitry Andric // Returns true if a given shared symbol is in a read-only segment in a DSO.
isReadOnly(SharedSymbol & ss)2670b57cec5SDimitry Andric template <class ELFT> static bool isReadOnly(SharedSymbol &ss) {
2680b57cec5SDimitry Andric using Elf_Phdr = typename ELFT::Phdr;
2690b57cec5SDimitry Andric
2700b57cec5SDimitry Andric // Determine if the symbol is read-only by scanning the DSO's program headers.
27181ad6265SDimitry Andric const auto &file = cast<SharedFile>(*ss.file);
2720b57cec5SDimitry Andric for (const Elf_Phdr &phdr :
2730b57cec5SDimitry Andric check(file.template getObj<ELFT>().program_headers()))
2740b57cec5SDimitry Andric if ((phdr.p_type == ELF::PT_LOAD || phdr.p_type == ELF::PT_GNU_RELRO) &&
2750b57cec5SDimitry Andric !(phdr.p_flags & ELF::PF_W) && ss.value >= phdr.p_vaddr &&
2760b57cec5SDimitry Andric ss.value < phdr.p_vaddr + phdr.p_memsz)
2770b57cec5SDimitry Andric return true;
2780b57cec5SDimitry Andric return false;
2790b57cec5SDimitry Andric }
2800b57cec5SDimitry Andric
2810b57cec5SDimitry Andric // Returns symbols at the same offset as a given symbol, including SS itself.
2820b57cec5SDimitry Andric //
2830b57cec5SDimitry Andric // If two or more symbols are at the same offset, and at least one of
2840b57cec5SDimitry Andric // them are copied by a copy relocation, all of them need to be copied.
2850b57cec5SDimitry Andric // Otherwise, they would refer to different places at runtime.
2860b57cec5SDimitry Andric template <class ELFT>
getSymbolsAt(SharedSymbol & ss)2870b57cec5SDimitry Andric static SmallSet<SharedSymbol *, 4> getSymbolsAt(SharedSymbol &ss) {
2880b57cec5SDimitry Andric using Elf_Sym = typename ELFT::Sym;
2890b57cec5SDimitry Andric
29081ad6265SDimitry Andric const auto &file = cast<SharedFile>(*ss.file);
2910b57cec5SDimitry Andric
2920b57cec5SDimitry Andric SmallSet<SharedSymbol *, 4> ret;
2930b57cec5SDimitry Andric for (const Elf_Sym &s : file.template getGlobalELFSyms<ELFT>()) {
2940b57cec5SDimitry Andric if (s.st_shndx == SHN_UNDEF || s.st_shndx == SHN_ABS ||
2950b57cec5SDimitry Andric s.getType() == STT_TLS || s.st_value != ss.value)
2960b57cec5SDimitry Andric continue;
2970b57cec5SDimitry Andric StringRef name = check(s.getName(file.getStringTable()));
298bdd1243dSDimitry Andric Symbol *sym = symtab.find(name);
2990b57cec5SDimitry Andric if (auto *alias = dyn_cast_or_null<SharedSymbol>(sym))
3000b57cec5SDimitry Andric ret.insert(alias);
3010b57cec5SDimitry Andric }
3026e75b2fbSDimitry Andric
3036e75b2fbSDimitry Andric // The loop does not check SHT_GNU_verneed, so ret does not contain
3046e75b2fbSDimitry Andric // non-default version symbols. If ss has a non-default version, ret won't
3056e75b2fbSDimitry Andric // contain ss. Just add ss unconditionally. If a non-default version alias is
3066e75b2fbSDimitry Andric // separately copy relocated, it and ss will have different addresses.
3076e75b2fbSDimitry Andric // Fortunately this case is impractical and fails with GNU ld as well.
3086e75b2fbSDimitry Andric ret.insert(&ss);
3090b57cec5SDimitry Andric return ret;
3100b57cec5SDimitry Andric }
3110b57cec5SDimitry Andric
3120b57cec5SDimitry Andric // When a symbol is copy relocated or we create a canonical plt entry, it is
3130b57cec5SDimitry Andric // effectively a defined symbol. In the case of copy relocation the symbol is
3140b57cec5SDimitry Andric // in .bss and in the case of a canonical plt entry it is in .plt. This function
3150b57cec5SDimitry Andric // replaces the existing symbol with a Defined pointing to the appropriate
3160b57cec5SDimitry Andric // location.
replaceWithDefined(Symbol & sym,SectionBase & sec,uint64_t value,uint64_t size)3170eae32dcSDimitry Andric static void replaceWithDefined(Symbol &sym, SectionBase &sec, uint64_t value,
3180b57cec5SDimitry Andric uint64_t size) {
3190b57cec5SDimitry Andric Symbol old = sym;
320bdd1243dSDimitry Andric Defined(sym.file, StringRef(), sym.binding, sym.stOther, sym.type, value,
321bdd1243dSDimitry Andric size, &sec)
322bdd1243dSDimitry Andric .overwrite(sym);
3230b57cec5SDimitry Andric
3245f757f3fSDimitry Andric sym.versionId = old.versionId;
3250b57cec5SDimitry Andric sym.exportDynamic = true;
3260b57cec5SDimitry Andric sym.isUsedInRegularObj = true;
3270eae32dcSDimitry Andric // A copy relocated alias may need a GOT entry.
328bdd1243dSDimitry Andric sym.flags.store(old.flags.load(std::memory_order_relaxed) & NEEDS_GOT,
329bdd1243dSDimitry Andric std::memory_order_relaxed);
3300b57cec5SDimitry Andric }
3310b57cec5SDimitry Andric
3320b57cec5SDimitry Andric // Reserve space in .bss or .bss.rel.ro for copy relocation.
3330b57cec5SDimitry Andric //
3340b57cec5SDimitry Andric // The copy relocation is pretty much a hack. If you use a copy relocation
3350b57cec5SDimitry Andric // in your program, not only the symbol name but the symbol's size, RW/RO
3360b57cec5SDimitry Andric // bit and alignment become part of the ABI. In addition to that, if the
3370b57cec5SDimitry Andric // symbol has aliases, the aliases become part of the ABI. That's subtle,
3380b57cec5SDimitry Andric // but if you violate that implicit ABI, that can cause very counter-
3390b57cec5SDimitry Andric // intuitive consequences.
3400b57cec5SDimitry Andric //
3410b57cec5SDimitry Andric // So, what is the copy relocation? It's for linking non-position
3420b57cec5SDimitry Andric // independent code to DSOs. In an ideal world, all references to data
3430b57cec5SDimitry Andric // exported by DSOs should go indirectly through GOT. But if object files
3440b57cec5SDimitry Andric // are compiled as non-PIC, all data references are direct. There is no
3450b57cec5SDimitry Andric // way for the linker to transform the code to use GOT, as machine
3460b57cec5SDimitry Andric // instructions are already set in stone in object files. This is where
3470b57cec5SDimitry Andric // the copy relocation takes a role.
3480b57cec5SDimitry Andric //
3490b57cec5SDimitry Andric // A copy relocation instructs the dynamic linker to copy data from a DSO
3500b57cec5SDimitry Andric // to a specified address (which is usually in .bss) at load-time. If the
3510b57cec5SDimitry Andric // static linker (that's us) finds a direct data reference to a DSO
3520b57cec5SDimitry Andric // symbol, it creates a copy relocation, so that the symbol can be
3530b57cec5SDimitry Andric // resolved as if it were in .bss rather than in a DSO.
3540b57cec5SDimitry Andric //
3550b57cec5SDimitry Andric // As you can see in this function, we create a copy relocation for the
3560b57cec5SDimitry Andric // dynamic linker, and the relocation contains not only symbol name but
357480093f4SDimitry Andric // various other information about the symbol. So, such attributes become a
3580b57cec5SDimitry Andric // part of the ABI.
3590b57cec5SDimitry Andric //
3600b57cec5SDimitry Andric // Note for application developers: I can give you a piece of advice if
3610b57cec5SDimitry Andric // you are writing a shared library. You probably should export only
3620b57cec5SDimitry Andric // functions from your library. You shouldn't export variables.
3630b57cec5SDimitry Andric //
3640b57cec5SDimitry Andric // As an example what can happen when you export variables without knowing
3650b57cec5SDimitry Andric // the semantics of copy relocations, assume that you have an exported
3660b57cec5SDimitry Andric // variable of type T. It is an ABI-breaking change to add new members at
3670b57cec5SDimitry Andric // end of T even though doing that doesn't change the layout of the
3680b57cec5SDimitry Andric // existing members. That's because the space for the new members are not
3690b57cec5SDimitry Andric // reserved in .bss unless you recompile the main program. That means they
3700b57cec5SDimitry Andric // are likely to overlap with other data that happens to be laid out next
3710b57cec5SDimitry Andric // to the variable in .bss. This kind of issue is sometimes very hard to
372480093f4SDimitry Andric // debug. What's a solution? Instead of exporting a variable V from a DSO,
3730b57cec5SDimitry Andric // define an accessor getV().
addCopyRelSymbol(SharedSymbol & ss)37481ad6265SDimitry Andric template <class ELFT> static void addCopyRelSymbol(SharedSymbol &ss) {
3750b57cec5SDimitry Andric // Copy relocation against zero-sized symbol doesn't make sense.
3760b57cec5SDimitry Andric uint64_t symSize = ss.getSize();
3770b57cec5SDimitry Andric if (symSize == 0 || ss.alignment == 0)
3780b57cec5SDimitry Andric fatal("cannot create a copy relocation for symbol " + toString(ss));
3790b57cec5SDimitry Andric
3800b57cec5SDimitry Andric // See if this symbol is in a read-only segment. If so, preserve the symbol's
3810b57cec5SDimitry Andric // memory protection by reserving space in the .bss.rel.ro section.
3820b57cec5SDimitry Andric bool isRO = isReadOnly<ELFT>(ss);
3830b57cec5SDimitry Andric BssSection *sec =
3840b57cec5SDimitry Andric make<BssSection>(isRO ? ".bss.rel.ro" : ".bss", symSize, ss.alignment);
38585868e8aSDimitry Andric OutputSection *osec = (isRO ? in.bssRelRo : in.bss)->getParent();
38685868e8aSDimitry Andric
38785868e8aSDimitry Andric // At this point, sectionBases has been migrated to sections. Append sec to
38885868e8aSDimitry Andric // sections.
3894824e7fdSDimitry Andric if (osec->commands.empty() ||
3904824e7fdSDimitry Andric !isa<InputSectionDescription>(osec->commands.back()))
3914824e7fdSDimitry Andric osec->commands.push_back(make<InputSectionDescription>(""));
3924824e7fdSDimitry Andric auto *isd = cast<InputSectionDescription>(osec->commands.back());
39385868e8aSDimitry Andric isd->sections.push_back(sec);
39485868e8aSDimitry Andric osec->commitSection(sec);
3950b57cec5SDimitry Andric
3960b57cec5SDimitry Andric // Look through the DSO's dynamic symbol table for aliases and create a
3970b57cec5SDimitry Andric // dynamic symbol for each one. This causes the copy relocation to correctly
3980b57cec5SDimitry Andric // interpose any aliases.
3990b57cec5SDimitry Andric for (SharedSymbol *sym : getSymbolsAt<ELFT>(ss))
4000eae32dcSDimitry Andric replaceWithDefined(*sym, *sec, 0, sym->size);
4010b57cec5SDimitry Andric
4020eae32dcSDimitry Andric mainPart->relaDyn->addSymbolReloc(target->copyRel, *sec, 0, ss);
4030eae32dcSDimitry Andric }
4040eae32dcSDimitry Andric
40504eeddc0SDimitry Andric // .eh_frame sections are mergeable input sections, so their input
40604eeddc0SDimitry Andric // offsets are not linearly mapped to output section. For each input
40704eeddc0SDimitry Andric // offset, we need to find a section piece containing the offset and
40804eeddc0SDimitry Andric // add the piece's base address to the input offset to compute the
40904eeddc0SDimitry Andric // output offset. That isn't cheap.
41004eeddc0SDimitry Andric //
41104eeddc0SDimitry Andric // This class is to speed up the offset computation. When we process
41204eeddc0SDimitry Andric // relocations, we access offsets in the monotonically increasing
41304eeddc0SDimitry Andric // order. So we can optimize for that access pattern.
41404eeddc0SDimitry Andric //
41504eeddc0SDimitry Andric // For sections other than .eh_frame, this class doesn't do anything.
41604eeddc0SDimitry Andric namespace {
41704eeddc0SDimitry Andric class OffsetGetter {
41804eeddc0SDimitry Andric public:
419bdd1243dSDimitry Andric OffsetGetter() = default;
OffsetGetter(InputSectionBase & sec)42004eeddc0SDimitry Andric explicit OffsetGetter(InputSectionBase &sec) {
421bdd1243dSDimitry Andric if (auto *eh = dyn_cast<EhInputSection>(&sec)) {
422bdd1243dSDimitry Andric cies = eh->cies;
423bdd1243dSDimitry Andric fdes = eh->fdes;
424bdd1243dSDimitry Andric i = cies.begin();
425bdd1243dSDimitry Andric j = fdes.begin();
426bdd1243dSDimitry Andric }
42704eeddc0SDimitry Andric }
42804eeddc0SDimitry Andric
42904eeddc0SDimitry Andric // Translates offsets in input sections to offsets in output sections.
43004eeddc0SDimitry Andric // Given offset must increase monotonically. We assume that Piece is
43104eeddc0SDimitry Andric // sorted by inputOff.
get(uint64_t off)43204eeddc0SDimitry Andric uint64_t get(uint64_t off) {
433bdd1243dSDimitry Andric if (cies.empty())
43404eeddc0SDimitry Andric return off;
43504eeddc0SDimitry Andric
436bdd1243dSDimitry Andric while (j != fdes.end() && j->inputOff <= off)
437bdd1243dSDimitry Andric ++j;
438bdd1243dSDimitry Andric auto it = j;
439bdd1243dSDimitry Andric if (j == fdes.begin() || j[-1].inputOff + j[-1].size <= off) {
440bdd1243dSDimitry Andric while (i != cies.end() && i->inputOff <= off)
44104eeddc0SDimitry Andric ++i;
442bdd1243dSDimitry Andric if (i == cies.begin() || i[-1].inputOff + i[-1].size <= off)
44304eeddc0SDimitry Andric fatal(".eh_frame: relocation is not in any piece");
444bdd1243dSDimitry Andric it = i;
445bdd1243dSDimitry Andric }
44604eeddc0SDimitry Andric
44704eeddc0SDimitry Andric // Offset -1 means that the piece is dead (i.e. garbage collected).
448bdd1243dSDimitry Andric if (it[-1].outputOff == -1)
44904eeddc0SDimitry Andric return -1;
450bdd1243dSDimitry Andric return it[-1].outputOff + (off - it[-1].inputOff);
45104eeddc0SDimitry Andric }
45204eeddc0SDimitry Andric
45304eeddc0SDimitry Andric private:
454bdd1243dSDimitry Andric ArrayRef<EhSectionPiece> cies, fdes;
455bdd1243dSDimitry Andric ArrayRef<EhSectionPiece>::iterator i, j;
45604eeddc0SDimitry Andric };
45704eeddc0SDimitry Andric
45804eeddc0SDimitry Andric // This class encapsulates states needed to scan relocations for one
45904eeddc0SDimitry Andric // InputSectionBase.
46004eeddc0SDimitry Andric class RelocationScanner {
46104eeddc0SDimitry Andric public:
462*62987288SDimitry Andric template <class ELFT>
463*62987288SDimitry Andric void scanSection(InputSectionBase &s, bool isEH = false);
46404eeddc0SDimitry Andric
46504eeddc0SDimitry Andric private:
466bdd1243dSDimitry Andric InputSectionBase *sec;
46704eeddc0SDimitry Andric OffsetGetter getter;
46804eeddc0SDimitry Andric
46904eeddc0SDimitry Andric // End of relocations, used by Mips/PPC64.
47004eeddc0SDimitry Andric const void *end = nullptr;
47104eeddc0SDimitry Andric
47204eeddc0SDimitry Andric template <class RelTy> RelType getMipsN32RelType(RelTy *&rel) const;
47304eeddc0SDimitry Andric template <class ELFT, class RelTy>
47404eeddc0SDimitry Andric int64_t computeMipsAddend(const RelTy &rel, RelExpr expr, bool isLocal) const;
47504eeddc0SDimitry Andric bool isStaticLinkTimeConstant(RelExpr e, RelType type, const Symbol &sym,
47604eeddc0SDimitry Andric uint64_t relOff) const;
47704eeddc0SDimitry Andric void processAux(RelExpr expr, RelType type, uint64_t offset, Symbol &sym,
47804eeddc0SDimitry Andric int64_t addend) const;
47952418fc2SDimitry Andric template <class ELFT, class RelTy>
48052418fc2SDimitry Andric void scanOne(typename Relocs<RelTy>::const_iterator &i);
48152418fc2SDimitry Andric template <class ELFT, class RelTy> void scan(Relocs<RelTy> rels);
48204eeddc0SDimitry Andric };
48304eeddc0SDimitry Andric } // namespace
48404eeddc0SDimitry Andric
4850b57cec5SDimitry Andric // MIPS has an odd notion of "paired" relocations to calculate addends.
4860b57cec5SDimitry Andric // For example, if a relocation is of R_MIPS_HI16, there must be a
4870b57cec5SDimitry Andric // R_MIPS_LO16 relocation after that, and an addend is calculated using
4880b57cec5SDimitry Andric // the two relocations.
4890b57cec5SDimitry Andric template <class ELFT, class RelTy>
computeMipsAddend(const RelTy & rel,RelExpr expr,bool isLocal) const49004eeddc0SDimitry Andric int64_t RelocationScanner::computeMipsAddend(const RelTy &rel, RelExpr expr,
49104eeddc0SDimitry Andric bool isLocal) const {
4920b57cec5SDimitry Andric if (expr == R_MIPS_GOTREL && isLocal)
493bdd1243dSDimitry Andric return sec->getFile<ELFT>()->mipsGp0;
4940b57cec5SDimitry Andric
4950b57cec5SDimitry Andric // The ABI says that the paired relocation is used only for REL.
4960b57cec5SDimitry Andric // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
4970fca6ea1SDimitry Andric // This generalises to relocation types with implicit addends.
4980fca6ea1SDimitry Andric if (RelTy::HasAddend)
4990b57cec5SDimitry Andric return 0;
5000b57cec5SDimitry Andric
5010b57cec5SDimitry Andric RelType type = rel.getType(config->isMips64EL);
5020b57cec5SDimitry Andric uint32_t pairTy = getMipsPairType(type, isLocal);
5030b57cec5SDimitry Andric if (pairTy == R_MIPS_NONE)
5040b57cec5SDimitry Andric return 0;
5050b57cec5SDimitry Andric
506bdd1243dSDimitry Andric const uint8_t *buf = sec->content().data();
5070b57cec5SDimitry Andric uint32_t symIndex = rel.getSymbol(config->isMips64EL);
5080b57cec5SDimitry Andric
5090b57cec5SDimitry Andric // To make things worse, paired relocations might not be contiguous in
5100b57cec5SDimitry Andric // the relocation table, so we need to do linear search. *sigh*
51104eeddc0SDimitry Andric for (const RelTy *ri = &rel; ri != static_cast<const RelTy *>(end); ++ri)
5120b57cec5SDimitry Andric if (ri->getType(config->isMips64EL) == pairTy &&
5130b57cec5SDimitry Andric ri->getSymbol(config->isMips64EL) == symIndex)
514bdd1243dSDimitry Andric return target->getImplicitAddend(buf + ri->r_offset, pairTy);
5150b57cec5SDimitry Andric
5160b57cec5SDimitry Andric warn("can't find matching " + toString(pairTy) + " relocation for " +
5170b57cec5SDimitry Andric toString(type));
5180b57cec5SDimitry Andric return 0;
5190b57cec5SDimitry Andric }
5200b57cec5SDimitry Andric
5210b57cec5SDimitry Andric // Custom error message if Sym is defined in a discarded section.
5220b57cec5SDimitry Andric template <class ELFT>
maybeReportDiscarded(Undefined & sym)5230b57cec5SDimitry Andric static std::string maybeReportDiscarded(Undefined &sym) {
5240b57cec5SDimitry Andric auto *file = dyn_cast_or_null<ObjFile<ELFT>>(sym.file);
5255f757f3fSDimitry Andric if (!file || !sym.discardedSecIdx)
5260b57cec5SDimitry Andric return "";
5270eae32dcSDimitry Andric ArrayRef<typename ELFT::Shdr> objSections =
5280eae32dcSDimitry Andric file->template getELFShdrs<ELFT>();
5290b57cec5SDimitry Andric
5300b57cec5SDimitry Andric std::string msg;
5310b57cec5SDimitry Andric if (sym.type == ELF::STT_SECTION) {
5320b57cec5SDimitry Andric msg = "relocation refers to a discarded section: ";
5330b57cec5SDimitry Andric msg += CHECK(
534e8d8bef9SDimitry Andric file->getObj().getSectionName(objSections[sym.discardedSecIdx]), file);
5350b57cec5SDimitry Andric } else {
5360b57cec5SDimitry Andric msg = "relocation refers to a symbol in a discarded section: " +
5370b57cec5SDimitry Andric toString(sym);
5380b57cec5SDimitry Andric }
5390b57cec5SDimitry Andric msg += "\n>>> defined in " + toString(file);
5400b57cec5SDimitry Andric
5410b57cec5SDimitry Andric Elf_Shdr_Impl<ELFT> elfSec = objSections[sym.discardedSecIdx - 1];
5420b57cec5SDimitry Andric if (elfSec.sh_type != SHT_GROUP)
5430b57cec5SDimitry Andric return msg;
5440b57cec5SDimitry Andric
5450b57cec5SDimitry Andric // If the discarded section is a COMDAT.
5460b57cec5SDimitry Andric StringRef signature = file->getShtGroupSignature(objSections, elfSec);
5470b57cec5SDimitry Andric if (const InputFile *prevailing =
548bdd1243dSDimitry Andric symtab.comdatGroups.lookup(CachedHashStringRef(signature))) {
5490b57cec5SDimitry Andric msg += "\n>>> section group signature: " + signature.str() +
5500b57cec5SDimitry Andric "\n>>> prevailing definition is in " + toString(prevailing);
55181ad6265SDimitry Andric if (sym.nonPrevailing) {
55281ad6265SDimitry Andric msg += "\n>>> or the symbol in the prevailing group had STB_WEAK "
55381ad6265SDimitry Andric "binding and the symbol in a non-prevailing group had STB_GLOBAL "
55481ad6265SDimitry Andric "binding. Mixing groups with STB_WEAK and STB_GLOBAL binding "
55581ad6265SDimitry Andric "signature is not supported";
55681ad6265SDimitry Andric }
55781ad6265SDimitry Andric }
5580b57cec5SDimitry Andric return msg;
5590b57cec5SDimitry Andric }
5600b57cec5SDimitry Andric
56181ad6265SDimitry Andric namespace {
5620b57cec5SDimitry Andric // Undefined diagnostics are collected in a vector and emitted once all of
5630b57cec5SDimitry Andric // them are known, so that some postprocessing on the list of undefined symbols
5640b57cec5SDimitry Andric // can happen before lld emits diagnostics.
5650b57cec5SDimitry Andric struct UndefinedDiag {
56604eeddc0SDimitry Andric Undefined *sym;
5670b57cec5SDimitry Andric struct Loc {
5680b57cec5SDimitry Andric InputSectionBase *sec;
5690b57cec5SDimitry Andric uint64_t offset;
5700b57cec5SDimitry Andric };
5710b57cec5SDimitry Andric std::vector<Loc> locs;
5720b57cec5SDimitry Andric bool isWarning;
5730b57cec5SDimitry Andric };
5740b57cec5SDimitry Andric
57581ad6265SDimitry Andric std::vector<UndefinedDiag> undefs;
576bdd1243dSDimitry Andric std::mutex relocMutex;
57781ad6265SDimitry Andric }
5780b57cec5SDimitry Andric
579480093f4SDimitry Andric // Check whether the definition name def is a mangled function name that matches
580480093f4SDimitry Andric // the reference name ref.
canSuggestExternCForCXX(StringRef ref,StringRef def)581480093f4SDimitry Andric static bool canSuggestExternCForCXX(StringRef ref, StringRef def) {
582480093f4SDimitry Andric llvm::ItaniumPartialDemangler d;
583480093f4SDimitry Andric std::string name = def.str();
584480093f4SDimitry Andric if (d.partialDemangle(name.c_str()))
585480093f4SDimitry Andric return false;
586480093f4SDimitry Andric char *buf = d.getFunctionName(nullptr, nullptr);
587480093f4SDimitry Andric if (!buf)
588480093f4SDimitry Andric return false;
589480093f4SDimitry Andric bool ret = ref == buf;
590480093f4SDimitry Andric free(buf);
591480093f4SDimitry Andric return ret;
592480093f4SDimitry Andric }
593480093f4SDimitry Andric
59485868e8aSDimitry Andric // Suggest an alternative spelling of an "undefined symbol" diagnostic. Returns
59585868e8aSDimitry Andric // the suggested symbol, which is either in the symbol table, or in the same
59685868e8aSDimitry Andric // file of sym.
getAlternativeSpelling(const Undefined & sym,std::string & pre_hint,std::string & post_hint)597480093f4SDimitry Andric static const Symbol *getAlternativeSpelling(const Undefined &sym,
598480093f4SDimitry Andric std::string &pre_hint,
599480093f4SDimitry Andric std::string &post_hint) {
60085868e8aSDimitry Andric DenseMap<StringRef, const Symbol *> map;
60104eeddc0SDimitry Andric if (sym.file && sym.file->kind() == InputFile::ObjKind) {
60204eeddc0SDimitry Andric auto *file = cast<ELFFileBase>(sym.file);
603480093f4SDimitry Andric // If sym is a symbol defined in a discarded section, maybeReportDiscarded()
604480093f4SDimitry Andric // will give an error. Don't suggest an alternative spelling.
605480093f4SDimitry Andric if (file && sym.discardedSecIdx != 0 &&
606480093f4SDimitry Andric file->getSections()[sym.discardedSecIdx] == &InputSection::discarded)
607480093f4SDimitry Andric return nullptr;
608480093f4SDimitry Andric
609480093f4SDimitry Andric // Build a map of local defined symbols.
61085868e8aSDimitry Andric for (const Symbol *s : sym.file->getSymbols())
611fe6060f1SDimitry Andric if (s->isLocal() && s->isDefined() && !s->getName().empty())
61285868e8aSDimitry Andric map.try_emplace(s->getName(), s);
61385868e8aSDimitry Andric }
61485868e8aSDimitry Andric
61585868e8aSDimitry Andric auto suggest = [&](StringRef newName) -> const Symbol * {
61685868e8aSDimitry Andric // If defined locally.
61785868e8aSDimitry Andric if (const Symbol *s = map.lookup(newName))
61885868e8aSDimitry Andric return s;
61985868e8aSDimitry Andric
62085868e8aSDimitry Andric // If in the symbol table and not undefined.
621bdd1243dSDimitry Andric if (const Symbol *s = symtab.find(newName))
62285868e8aSDimitry Andric if (!s->isUndefined())
62385868e8aSDimitry Andric return s;
62485868e8aSDimitry Andric
62585868e8aSDimitry Andric return nullptr;
62685868e8aSDimitry Andric };
62785868e8aSDimitry Andric
62885868e8aSDimitry Andric // This loop enumerates all strings of Levenshtein distance 1 as typo
62985868e8aSDimitry Andric // correction candidates and suggests the one that exists as a non-undefined
63085868e8aSDimitry Andric // symbol.
63185868e8aSDimitry Andric StringRef name = sym.getName();
63285868e8aSDimitry Andric for (size_t i = 0, e = name.size(); i != e + 1; ++i) {
63385868e8aSDimitry Andric // Insert a character before name[i].
63485868e8aSDimitry Andric std::string newName = (name.substr(0, i) + "0" + name.substr(i)).str();
63585868e8aSDimitry Andric for (char c = '0'; c <= 'z'; ++c) {
63685868e8aSDimitry Andric newName[i] = c;
63785868e8aSDimitry Andric if (const Symbol *s = suggest(newName))
63885868e8aSDimitry Andric return s;
63985868e8aSDimitry Andric }
64085868e8aSDimitry Andric if (i == e)
64185868e8aSDimitry Andric break;
64285868e8aSDimitry Andric
64385868e8aSDimitry Andric // Substitute name[i].
6445ffd83dbSDimitry Andric newName = std::string(name);
64585868e8aSDimitry Andric for (char c = '0'; c <= 'z'; ++c) {
64685868e8aSDimitry Andric newName[i] = c;
64785868e8aSDimitry Andric if (const Symbol *s = suggest(newName))
64885868e8aSDimitry Andric return s;
64985868e8aSDimitry Andric }
65085868e8aSDimitry Andric
65185868e8aSDimitry Andric // Transpose name[i] and name[i+1]. This is of edit distance 2 but it is
65285868e8aSDimitry Andric // common.
65385868e8aSDimitry Andric if (i + 1 < e) {
65485868e8aSDimitry Andric newName[i] = name[i + 1];
65585868e8aSDimitry Andric newName[i + 1] = name[i];
65685868e8aSDimitry Andric if (const Symbol *s = suggest(newName))
65785868e8aSDimitry Andric return s;
65885868e8aSDimitry Andric }
65985868e8aSDimitry Andric
66085868e8aSDimitry Andric // Delete name[i].
66185868e8aSDimitry Andric newName = (name.substr(0, i) + name.substr(i + 1)).str();
66285868e8aSDimitry Andric if (const Symbol *s = suggest(newName))
66385868e8aSDimitry Andric return s;
66485868e8aSDimitry Andric }
66585868e8aSDimitry Andric
666480093f4SDimitry Andric // Case mismatch, e.g. Foo vs FOO.
667480093f4SDimitry Andric for (auto &it : map)
668fe6060f1SDimitry Andric if (name.equals_insensitive(it.first))
669480093f4SDimitry Andric return it.second;
670bdd1243dSDimitry Andric for (Symbol *sym : symtab.getSymbols())
671fe6060f1SDimitry Andric if (!sym->isUndefined() && name.equals_insensitive(sym->getName()))
672480093f4SDimitry Andric return sym;
673480093f4SDimitry Andric
674480093f4SDimitry Andric // The reference may be a mangled name while the definition is not. Suggest a
675480093f4SDimitry Andric // missing extern "C".
67606c3fb27SDimitry Andric if (name.starts_with("_Z")) {
677480093f4SDimitry Andric std::string buf = name.str();
678480093f4SDimitry Andric llvm::ItaniumPartialDemangler d;
679480093f4SDimitry Andric if (!d.partialDemangle(buf.c_str()))
680480093f4SDimitry Andric if (char *buf = d.getFunctionName(nullptr, nullptr)) {
681480093f4SDimitry Andric const Symbol *s = suggest(buf);
682480093f4SDimitry Andric free(buf);
683480093f4SDimitry Andric if (s) {
684480093f4SDimitry Andric pre_hint = ": extern \"C\" ";
685480093f4SDimitry Andric return s;
686480093f4SDimitry Andric }
687480093f4SDimitry Andric }
688480093f4SDimitry Andric } else {
689480093f4SDimitry Andric const Symbol *s = nullptr;
690480093f4SDimitry Andric for (auto &it : map)
691480093f4SDimitry Andric if (canSuggestExternCForCXX(name, it.first)) {
692480093f4SDimitry Andric s = it.second;
693480093f4SDimitry Andric break;
694480093f4SDimitry Andric }
695480093f4SDimitry Andric if (!s)
696bdd1243dSDimitry Andric for (Symbol *sym : symtab.getSymbols())
697480093f4SDimitry Andric if (canSuggestExternCForCXX(name, sym->getName())) {
698480093f4SDimitry Andric s = sym;
699480093f4SDimitry Andric break;
700480093f4SDimitry Andric }
701480093f4SDimitry Andric if (s) {
702480093f4SDimitry Andric pre_hint = " to declare ";
703480093f4SDimitry Andric post_hint = " as extern \"C\"?";
704480093f4SDimitry Andric return s;
705480093f4SDimitry Andric }
706480093f4SDimitry Andric }
707480093f4SDimitry Andric
70885868e8aSDimitry Andric return nullptr;
70985868e8aSDimitry Andric }
71085868e8aSDimitry Andric
reportUndefinedSymbol(const UndefinedDiag & undef,bool correctSpelling)71185868e8aSDimitry Andric static void reportUndefinedSymbol(const UndefinedDiag &undef,
71285868e8aSDimitry Andric bool correctSpelling) {
71304eeddc0SDimitry Andric Undefined &sym = *undef.sym;
7140b57cec5SDimitry Andric
7150b57cec5SDimitry Andric auto visibility = [&]() -> std::string {
716bdd1243dSDimitry Andric switch (sym.visibility()) {
7170b57cec5SDimitry Andric case STV_INTERNAL:
7180b57cec5SDimitry Andric return "internal ";
7190b57cec5SDimitry Andric case STV_HIDDEN:
7200b57cec5SDimitry Andric return "hidden ";
7210b57cec5SDimitry Andric case STV_PROTECTED:
7220b57cec5SDimitry Andric return "protected ";
7230b57cec5SDimitry Andric default:
7240b57cec5SDimitry Andric return "";
7250b57cec5SDimitry Andric }
7260b57cec5SDimitry Andric };
7270b57cec5SDimitry Andric
72881ad6265SDimitry Andric std::string msg;
72981ad6265SDimitry Andric switch (config->ekind) {
73081ad6265SDimitry Andric case ELF32LEKind:
73181ad6265SDimitry Andric msg = maybeReportDiscarded<ELF32LE>(sym);
73281ad6265SDimitry Andric break;
73381ad6265SDimitry Andric case ELF32BEKind:
73481ad6265SDimitry Andric msg = maybeReportDiscarded<ELF32BE>(sym);
73581ad6265SDimitry Andric break;
73681ad6265SDimitry Andric case ELF64LEKind:
73781ad6265SDimitry Andric msg = maybeReportDiscarded<ELF64LE>(sym);
73881ad6265SDimitry Andric break;
73981ad6265SDimitry Andric case ELF64BEKind:
74081ad6265SDimitry Andric msg = maybeReportDiscarded<ELF64BE>(sym);
74181ad6265SDimitry Andric break;
74281ad6265SDimitry Andric default:
74381ad6265SDimitry Andric llvm_unreachable("");
74481ad6265SDimitry Andric }
7450b57cec5SDimitry Andric if (msg.empty())
7460b57cec5SDimitry Andric msg = "undefined " + visibility() + "symbol: " + toString(sym);
7470b57cec5SDimitry Andric
7485ffd83dbSDimitry Andric const size_t maxUndefReferences = 3;
7490b57cec5SDimitry Andric size_t i = 0;
7500b57cec5SDimitry Andric for (UndefinedDiag::Loc l : undef.locs) {
7510b57cec5SDimitry Andric if (i >= maxUndefReferences)
7520b57cec5SDimitry Andric break;
7530b57cec5SDimitry Andric InputSectionBase &sec = *l.sec;
7540b57cec5SDimitry Andric uint64_t offset = l.offset;
7550b57cec5SDimitry Andric
7560b57cec5SDimitry Andric msg += "\n>>> referenced by ";
7575f757f3fSDimitry Andric // In the absence of line number information, utilize DW_TAG_variable (if
7585f757f3fSDimitry Andric // present) for the enclosing symbol (e.g. var in `int *a[] = {&undef};`).
7595f757f3fSDimitry Andric Symbol *enclosing = sec.getEnclosingSymbol(offset);
7605f757f3fSDimitry Andric std::string src = sec.getSrcMsg(enclosing ? *enclosing : sym, offset);
7610b57cec5SDimitry Andric if (!src.empty())
7620b57cec5SDimitry Andric msg += src + "\n>>> ";
7630b57cec5SDimitry Andric msg += sec.getObjMsg(offset);
7640b57cec5SDimitry Andric i++;
7650b57cec5SDimitry Andric }
7660b57cec5SDimitry Andric
7670b57cec5SDimitry Andric if (i < undef.locs.size())
7680b57cec5SDimitry Andric msg += ("\n>>> referenced " + Twine(undef.locs.size() - i) + " more times")
7690b57cec5SDimitry Andric .str();
7700b57cec5SDimitry Andric
771480093f4SDimitry Andric if (correctSpelling) {
772480093f4SDimitry Andric std::string pre_hint = ": ", post_hint;
77304eeddc0SDimitry Andric if (const Symbol *corrected =
77404eeddc0SDimitry Andric getAlternativeSpelling(sym, pre_hint, post_hint)) {
775480093f4SDimitry Andric msg += "\n>>> did you mean" + pre_hint + toString(*corrected) + post_hint;
77685868e8aSDimitry Andric if (corrected->file)
77785868e8aSDimitry Andric msg += "\n>>> defined in: " + toString(corrected->file);
77885868e8aSDimitry Andric }
779480093f4SDimitry Andric }
78085868e8aSDimitry Andric
78106c3fb27SDimitry Andric if (sym.getName().starts_with("_ZTV"))
7825ffd83dbSDimitry Andric msg +=
7835ffd83dbSDimitry Andric "\n>>> the vtable symbol may be undefined because the class is missing "
7840b57cec5SDimitry Andric "its key function (see https://lld.llvm.org/missingkeyfunction)";
7850eae32dcSDimitry Andric if (config->gcSections && config->zStartStopGC &&
78606c3fb27SDimitry Andric sym.getName().starts_with("__start_")) {
7870eae32dcSDimitry Andric msg += "\n>>> the encapsulation symbol needs to be retained under "
7880eae32dcSDimitry Andric "--gc-sections properly; consider -z nostart-stop-gc "
7890eae32dcSDimitry Andric "(see https://lld.llvm.org/ELF/start-stop-gc)";
7900eae32dcSDimitry Andric }
7910b57cec5SDimitry Andric
7920b57cec5SDimitry Andric if (undef.isWarning)
7930b57cec5SDimitry Andric warn(msg);
7940b57cec5SDimitry Andric else
795e8d8bef9SDimitry Andric error(msg, ErrorTag::SymbolNotFound, {sym.getName()});
7960b57cec5SDimitry Andric }
7970b57cec5SDimitry Andric
reportUndefinedSymbols()79881ad6265SDimitry Andric void elf::reportUndefinedSymbols() {
7990b57cec5SDimitry Andric // Find the first "undefined symbol" diagnostic for each diagnostic, and
8000b57cec5SDimitry Andric // collect all "referenced from" lines at the first diagnostic.
8010b57cec5SDimitry Andric DenseMap<Symbol *, UndefinedDiag *> firstRef;
8020b57cec5SDimitry Andric for (UndefinedDiag &undef : undefs) {
8030b57cec5SDimitry Andric assert(undef.locs.size() == 1);
8040b57cec5SDimitry Andric if (UndefinedDiag *canon = firstRef.lookup(undef.sym)) {
8050b57cec5SDimitry Andric canon->locs.push_back(undef.locs[0]);
8060b57cec5SDimitry Andric undef.locs.clear();
8070b57cec5SDimitry Andric } else
8080b57cec5SDimitry Andric firstRef[undef.sym] = &undef;
8090b57cec5SDimitry Andric }
8100b57cec5SDimitry Andric
81185868e8aSDimitry Andric // Enable spell corrector for the first 2 diagnostics.
812bdd1243dSDimitry Andric for (const auto &[i, undef] : llvm::enumerate(undefs))
813bdd1243dSDimitry Andric if (!undef.locs.empty())
814bdd1243dSDimitry Andric reportUndefinedSymbol(undef, i < 2);
8150b57cec5SDimitry Andric undefs.clear();
8160b57cec5SDimitry Andric }
8170b57cec5SDimitry Andric
8180b57cec5SDimitry Andric // Report an undefined symbol if necessary.
8190b57cec5SDimitry Andric // Returns true if the undefined symbol will produce an error message.
maybeReportUndefined(Undefined & sym,InputSectionBase & sec,uint64_t offset)82004eeddc0SDimitry Andric static bool maybeReportUndefined(Undefined &sym, InputSectionBase &sec,
8210b57cec5SDimitry Andric uint64_t offset) {
822bdd1243dSDimitry Andric std::lock_guard<std::mutex> lock(relocMutex);
823e8d8bef9SDimitry Andric // If versioned, issue an error (even if the symbol is weak) because we don't
824e8d8bef9SDimitry Andric // know the defining filename which is required to construct a Verneed entry.
82504eeddc0SDimitry Andric if (sym.hasVersionSuffix) {
826e8d8bef9SDimitry Andric undefs.push_back({&sym, {{&sec, offset}}, false});
827e8d8bef9SDimitry Andric return true;
828e8d8bef9SDimitry Andric }
829e8d8bef9SDimitry Andric if (sym.isWeak())
8300b57cec5SDimitry Andric return false;
8310b57cec5SDimitry Andric
832bdd1243dSDimitry Andric bool canBeExternal = !sym.isLocal() && sym.visibility() == STV_DEFAULT;
8330b57cec5SDimitry Andric if (config->unresolvedSymbols == UnresolvedPolicy::Ignore && canBeExternal)
8340b57cec5SDimitry Andric return false;
8350b57cec5SDimitry Andric
8360b57cec5SDimitry Andric // clang (as of 2019-06-12) / gcc (as of 8.2.1) PPC64 may emit a .rela.toc
8370b57cec5SDimitry Andric // which references a switch table in a discarded .rodata/.text section. The
8380b57cec5SDimitry Andric // .toc and the .rela.toc are incorrectly not placed in the comdat. The ELF
8390b57cec5SDimitry Andric // spec says references from outside the group to a STB_LOCAL symbol are not
8400b57cec5SDimitry Andric // allowed. Work around the bug.
8415a0c326fSDimitry Andric //
8425a0c326fSDimitry Andric // PPC32 .got2 is similar but cannot be fixed. Multiple .got2 is infeasible
8435a0c326fSDimitry Andric // because .LC0-.LTOC is not representable if the two labels are in different
8445a0c326fSDimitry Andric // .got2
84504eeddc0SDimitry Andric if (sym.discardedSecIdx != 0 && (sec.name == ".got2" || sec.name == ".toc"))
8460b57cec5SDimitry Andric return false;
8470b57cec5SDimitry Andric
8480b57cec5SDimitry Andric bool isWarning =
8490b57cec5SDimitry Andric (config->unresolvedSymbols == UnresolvedPolicy::Warn && canBeExternal) ||
8500b57cec5SDimitry Andric config->noinhibitExec;
8510b57cec5SDimitry Andric undefs.push_back({&sym, {{&sec, offset}}, isWarning});
8520b57cec5SDimitry Andric return !isWarning;
8530b57cec5SDimitry Andric }
8540b57cec5SDimitry Andric
8550b57cec5SDimitry Andric // MIPS N32 ABI treats series of successive relocations with the same offset
8560b57cec5SDimitry Andric // as a single relocation. The similar approach used by N64 ABI, but this ABI
8570b57cec5SDimitry Andric // packs all relocations into the single relocation record. Here we emulate
8580b57cec5SDimitry Andric // this for the N32 ABI. Iterate over relocation with the same offset and put
8590b57cec5SDimitry Andric // theirs types into the single bit-set.
86004eeddc0SDimitry Andric template <class RelTy>
getMipsN32RelType(RelTy * & rel) const86104eeddc0SDimitry Andric RelType RelocationScanner::getMipsN32RelType(RelTy *&rel) const {
8620b57cec5SDimitry Andric RelType type = 0;
8630b57cec5SDimitry Andric uint64_t offset = rel->r_offset;
8640b57cec5SDimitry Andric
8650b57cec5SDimitry Andric int n = 0;
86604eeddc0SDimitry Andric while (rel != static_cast<const RelTy *>(end) && rel->r_offset == offset)
8670b57cec5SDimitry Andric type |= (rel++)->getType(config->isMips64EL) << (8 * n++);
8680b57cec5SDimitry Andric return type;
8690b57cec5SDimitry Andric }
8700b57cec5SDimitry Andric
871bdd1243dSDimitry Andric template <bool shard = false>
addRelativeReloc(InputSectionBase & isec,uint64_t offsetInSec,Symbol & sym,int64_t addend,RelExpr expr,RelType type)8720eae32dcSDimitry Andric static void addRelativeReloc(InputSectionBase &isec, uint64_t offsetInSec,
873fe6060f1SDimitry Andric Symbol &sym, int64_t addend, RelExpr expr,
8740b57cec5SDimitry Andric RelType type) {
8750eae32dcSDimitry Andric Partition &part = isec.getPartition();
8760b57cec5SDimitry Andric
8775f757f3fSDimitry Andric if (sym.isTagged()) {
8785f757f3fSDimitry Andric std::lock_guard<std::mutex> lock(relocMutex);
8795f757f3fSDimitry Andric part.relaDyn->addRelativeReloc(target->relativeRel, isec, offsetInSec, sym,
8805f757f3fSDimitry Andric addend, type, expr);
8815f757f3fSDimitry Andric // With MTE globals, we always want to derive the address tag by `ldg`-ing
8825f757f3fSDimitry Andric // the symbol. When we have a RELATIVE relocation though, we no longer have
8835f757f3fSDimitry Andric // a reference to the symbol. Because of this, when we have an addend that
8845f757f3fSDimitry Andric // puts the result of the RELATIVE relocation out-of-bounds of the symbol
8855f757f3fSDimitry Andric // (e.g. the addend is outside of [0, sym.getSize()]), the AArch64 MemtagABI
8865f757f3fSDimitry Andric // says we should store the offset to the start of the symbol in the target
8875f757f3fSDimitry Andric // field. This is described in further detail in:
8885f757f3fSDimitry Andric // https://github.com/ARM-software/abi-aa/blob/main/memtagabielf64/memtagabielf64.rst#841extended-semantics-of-r_aarch64_relative
8895f757f3fSDimitry Andric if (addend < 0 || static_cast<uint64_t>(addend) >= sym.getSize())
8905f757f3fSDimitry Andric isec.relocations.push_back({expr, type, offsetInSec, addend, &sym});
8915f757f3fSDimitry Andric return;
8925f757f3fSDimitry Andric }
8935f757f3fSDimitry Andric
8940b57cec5SDimitry Andric // Add a relative relocation. If relrDyn section is enabled, and the
8950b57cec5SDimitry Andric // relocation offset is guaranteed to be even, add the relocation to
8960b57cec5SDimitry Andric // the relrDyn section, otherwise add it to the relaDyn section.
8970b57cec5SDimitry Andric // relrDyn sections don't support odd offsets. Also, relrDyn sections
8980b57cec5SDimitry Andric // don't store the addend values, so we must write it to the relocated
8990b57cec5SDimitry Andric // address.
900bdd1243dSDimitry Andric if (part.relrDyn && isec.addralign >= 2 && offsetInSec % 2 == 0) {
901bdd1243dSDimitry Andric isec.addReloc({expr, type, offsetInSec, addend, &sym});
902bdd1243dSDimitry Andric if (shard)
903bdd1243dSDimitry Andric part.relrDyn->relocsVec[parallel::getThreadIndex()].push_back(
9040fca6ea1SDimitry Andric {&isec, isec.relocs().size() - 1});
905bdd1243dSDimitry Andric else
9060fca6ea1SDimitry Andric part.relrDyn->relocs.push_back({&isec, isec.relocs().size() - 1});
9070b57cec5SDimitry Andric return;
9080b57cec5SDimitry Andric }
909bdd1243dSDimitry Andric part.relaDyn->addRelativeReloc<shard>(target->relativeRel, isec, offsetInSec,
910bdd1243dSDimitry Andric sym, addend, type, expr);
9110b57cec5SDimitry Andric }
9120b57cec5SDimitry Andric
913480093f4SDimitry Andric template <class PltSection, class GotPltSection>
addPltEntry(PltSection & plt,GotPltSection & gotPlt,RelocationBaseSection & rel,RelType type,Symbol & sym)9140eae32dcSDimitry Andric static void addPltEntry(PltSection &plt, GotPltSection &gotPlt,
9150eae32dcSDimitry Andric RelocationBaseSection &rel, RelType type, Symbol &sym) {
9160eae32dcSDimitry Andric plt.addEntry(sym);
9170eae32dcSDimitry Andric gotPlt.addEntry(sym);
9180eae32dcSDimitry Andric rel.addReloc({type, &gotPlt, sym.getGotPltOffset(),
919fe6060f1SDimitry Andric sym.isPreemptible ? DynamicReloc::AgainstSymbol
920fe6060f1SDimitry Andric : DynamicReloc::AddendOnlyWithTargetVA,
921fe6060f1SDimitry Andric sym, 0, R_ABS});
9220b57cec5SDimitry Andric }
9230b57cec5SDimitry Andric
addGotEntry(Symbol & sym)9245f757f3fSDimitry Andric void elf::addGotEntry(Symbol &sym) {
9250b57cec5SDimitry Andric in.got->addEntry(sym);
9260b57cec5SDimitry Andric uint64_t off = sym.getGotOffset();
9270b57cec5SDimitry Andric
928349cc55cSDimitry Andric // If preemptible, emit a GLOB_DAT relocation.
929349cc55cSDimitry Andric if (sym.isPreemptible) {
93004eeddc0SDimitry Andric mainPart->relaDyn->addReloc({target->gotRel, in.got.get(), off,
931349cc55cSDimitry Andric DynamicReloc::AgainstSymbol, sym, 0, R_ABS});
9320b57cec5SDimitry Andric return;
9330b57cec5SDimitry Andric }
9340b57cec5SDimitry Andric
935349cc55cSDimitry Andric // Otherwise, the value is either a link-time constant or the load base
936349cc55cSDimitry Andric // plus a constant.
937349cc55cSDimitry Andric if (!config->isPic || isAbsolute(sym))
938bdd1243dSDimitry Andric in.got->addConstant({R_ABS, target->symbolicRel, off, 0, &sym});
939349cc55cSDimitry Andric else
9400eae32dcSDimitry Andric addRelativeReloc(*in.got, off, sym, 0, R_ABS, target->symbolicRel);
941349cc55cSDimitry Andric }
942349cc55cSDimitry Andric
addTpOffsetGotEntry(Symbol & sym)943349cc55cSDimitry Andric static void addTpOffsetGotEntry(Symbol &sym) {
944349cc55cSDimitry Andric in.got->addEntry(sym);
945349cc55cSDimitry Andric uint64_t off = sym.getGotOffset();
94674626c16SDimitry Andric if (!sym.isPreemptible && !config->shared) {
947bdd1243dSDimitry Andric in.got->addConstant({R_TPREL, target->symbolicRel, off, 0, &sym});
9480b57cec5SDimitry Andric return;
9490b57cec5SDimitry Andric }
950fe6060f1SDimitry Andric mainPart->relaDyn->addAddendOnlyRelocIfNonPreemptible(
9510eae32dcSDimitry Andric target->tlsGotRel, *in.got, off, sym, target->symbolicRel);
9520b57cec5SDimitry Andric }
9530b57cec5SDimitry Andric
9540b57cec5SDimitry Andric // Return true if we can define a symbol in the executable that
9550b57cec5SDimitry Andric // contains the value/function of a symbol defined in a shared
9560b57cec5SDimitry Andric // library.
canDefineSymbolInExecutable(Symbol & sym)9570b57cec5SDimitry Andric static bool canDefineSymbolInExecutable(Symbol &sym) {
9580b57cec5SDimitry Andric // If the symbol has default visibility the symbol defined in the
9590b57cec5SDimitry Andric // executable will preempt it.
9600b57cec5SDimitry Andric // Note that we want the visibility of the shared symbol itself, not
961bdd1243dSDimitry Andric // the visibility of the symbol in the output file we are producing.
962bdd1243dSDimitry Andric if (!sym.dsoProtected)
9630b57cec5SDimitry Andric return true;
9640b57cec5SDimitry Andric
9650b57cec5SDimitry Andric // If we are allowed to break address equality of functions, defining
9660b57cec5SDimitry Andric // a plt entry will allow the program to call the function in the
9670b57cec5SDimitry Andric // .so, but the .so and the executable will no agree on the address
9680b57cec5SDimitry Andric // of the function. Similar logic for objects.
9690b57cec5SDimitry Andric return ((sym.isFunc() && config->ignoreFunctionAddressEquality) ||
9700b57cec5SDimitry Andric (sym.isObject() && config->ignoreDataAddressEquality));
9710b57cec5SDimitry Andric }
9720b57cec5SDimitry Andric
973349cc55cSDimitry Andric // Returns true if a given relocation can be computed at link-time.
97481ad6265SDimitry Andric // This only handles relocation types expected in processAux.
975349cc55cSDimitry Andric //
976349cc55cSDimitry Andric // For instance, we know the offset from a relocation to its target at
977349cc55cSDimitry Andric // link-time if the relocation is PC-relative and refers a
978349cc55cSDimitry Andric // non-interposable function in the same executable. This function
979349cc55cSDimitry Andric // will return true for such relocation.
980349cc55cSDimitry Andric //
981349cc55cSDimitry Andric // If this function returns false, that means we need to emit a
982349cc55cSDimitry Andric // dynamic relocation so that the relocation will be fixed at load-time.
isStaticLinkTimeConstant(RelExpr e,RelType type,const Symbol & sym,uint64_t relOff) const98304eeddc0SDimitry Andric bool RelocationScanner::isStaticLinkTimeConstant(RelExpr e, RelType type,
98404eeddc0SDimitry Andric const Symbol &sym,
98504eeddc0SDimitry Andric uint64_t relOff) const {
986349cc55cSDimitry Andric // These expressions always compute a constant
987753f127fSDimitry Andric if (oneof<R_GOTPLT, R_GOT_OFF, R_RELAX_HINT, R_MIPS_GOT_LOCAL_PAGE,
988753f127fSDimitry Andric R_MIPS_GOTREL, R_MIPS_GOT_OFF, R_MIPS_GOT_OFF32, R_MIPS_GOT_GP_PC,
989349cc55cSDimitry Andric R_AARCH64_GOT_PAGE_PC, R_GOT_PC, R_GOTONLY_PC, R_GOTPLTONLY_PC,
99074626c16SDimitry Andric R_PLT_PC, R_PLT_GOTREL, R_PLT_GOTPLT, R_GOTPLT_GOTREL, R_GOTPLT_PC,
99174626c16SDimitry Andric R_PPC32_PLTREL, R_PPC64_CALL_PLT, R_PPC64_RELAX_TOC, R_RISCV_ADD,
99274626c16SDimitry Andric R_AARCH64_GOT_PAGE, R_LOONGARCH_PLT_PAGE_PC, R_LOONGARCH_GOT,
99374626c16SDimitry Andric R_LOONGARCH_GOT_PAGE_PC>(e))
994349cc55cSDimitry Andric return true;
995349cc55cSDimitry Andric
996349cc55cSDimitry Andric // These never do, except if the entire file is position dependent or if
997349cc55cSDimitry Andric // only the low bits are used.
998349cc55cSDimitry Andric if (e == R_GOT || e == R_PLT)
999bdd1243dSDimitry Andric return target->usesOnlyLowPageBits(type) || !config->isPic;
1000349cc55cSDimitry Andric
10010fca6ea1SDimitry Andric // R_AARCH64_AUTH_ABS64 requires a dynamic relocation.
10020fca6ea1SDimitry Andric if (sym.isPreemptible || e == R_AARCH64_AUTH)
1003349cc55cSDimitry Andric return false;
1004349cc55cSDimitry Andric if (!config->isPic)
1005349cc55cSDimitry Andric return true;
1006349cc55cSDimitry Andric
10071db9f3b2SDimitry Andric // Constant when referencing a non-preemptible symbol.
10081db9f3b2SDimitry Andric if (e == R_SIZE || e == R_RISCV_LEB128)
1009349cc55cSDimitry Andric return true;
1010349cc55cSDimitry Andric
1011349cc55cSDimitry Andric // For the target and the relocation, we want to know if they are
1012349cc55cSDimitry Andric // absolute or relative.
1013349cc55cSDimitry Andric bool absVal = isAbsoluteValue(sym);
1014349cc55cSDimitry Andric bool relE = isRelExpr(e);
1015349cc55cSDimitry Andric if (absVal && !relE)
1016349cc55cSDimitry Andric return true;
1017349cc55cSDimitry Andric if (!absVal && relE)
1018349cc55cSDimitry Andric return true;
1019349cc55cSDimitry Andric if (!absVal && !relE)
1020bdd1243dSDimitry Andric return target->usesOnlyLowPageBits(type);
1021349cc55cSDimitry Andric
1022349cc55cSDimitry Andric assert(absVal && relE);
1023349cc55cSDimitry Andric
1024349cc55cSDimitry Andric // Allow R_PLT_PC (optimized to R_PC here) to a hidden undefined weak symbol
1025349cc55cSDimitry Andric // in PIC mode. This is a little strange, but it allows us to link function
1026349cc55cSDimitry Andric // calls to such symbols (e.g. glibc/stdlib/exit.c:__run_exit_handlers).
1027349cc55cSDimitry Andric // Normally such a call will be guarded with a comparison, which will load a
1028349cc55cSDimitry Andric // zero from the GOT.
1029349cc55cSDimitry Andric if (sym.isUndefWeak())
1030349cc55cSDimitry Andric return true;
1031349cc55cSDimitry Andric
1032349cc55cSDimitry Andric // We set the final symbols values for linker script defined symbols later.
1033349cc55cSDimitry Andric // They always can be computed as a link time constant.
1034349cc55cSDimitry Andric if (sym.scriptDefined)
1035349cc55cSDimitry Andric return true;
1036349cc55cSDimitry Andric
1037349cc55cSDimitry Andric error("relocation " + toString(type) + " cannot refer to absolute symbol: " +
1038bdd1243dSDimitry Andric toString(sym) + getLocation(*sec, sym, relOff));
1039349cc55cSDimitry Andric return true;
1040349cc55cSDimitry Andric }
1041349cc55cSDimitry Andric
10420b57cec5SDimitry Andric // The reason we have to do this early scan is as follows
10430b57cec5SDimitry Andric // * To mmap the output file, we need to know the size
10440b57cec5SDimitry Andric // * For that, we need to know how many dynamic relocs we will have.
10450b57cec5SDimitry Andric // It might be possible to avoid this by outputting the file with write:
10460b57cec5SDimitry Andric // * Write the allocated output sections, computing addresses.
10470b57cec5SDimitry Andric // * Apply relocations, recording which ones require a dynamic reloc.
10480b57cec5SDimitry Andric // * Write the dynamic relocations.
10490b57cec5SDimitry Andric // * Write the rest of the file.
10500b57cec5SDimitry Andric // This would have some drawbacks. For example, we would only know if .rela.dyn
10510b57cec5SDimitry Andric // is needed after applying relocations. If it is, it will go after rw and rx
10520b57cec5SDimitry Andric // sections. Given that it is ro, we will need an extra PT_LOAD. This
10530b57cec5SDimitry Andric // complicates things for the dynamic linker and means we would have to reserve
10540b57cec5SDimitry Andric // space for the extra PT_LOAD even if we end up not using it.
processAux(RelExpr expr,RelType type,uint64_t offset,Symbol & sym,int64_t addend) const105504eeddc0SDimitry Andric void RelocationScanner::processAux(RelExpr expr, RelType type, uint64_t offset,
105604eeddc0SDimitry Andric Symbol &sym, int64_t addend) const {
1057bdd1243dSDimitry Andric // If non-ifunc non-preemptible, change PLT to direct call and optimize GOT
1058bdd1243dSDimitry Andric // indirection.
1059bdd1243dSDimitry Andric const bool isIfunc = sym.isGnuIFunc();
1060bdd1243dSDimitry Andric if (!sym.isPreemptible && (!isIfunc || config->zIfuncNoplt)) {
1061bdd1243dSDimitry Andric if (expr != R_GOT_PC) {
1062bdd1243dSDimitry Andric // The 0x8000 bit of r_addend of R_PPC_PLTREL24 is used to choose call
1063bdd1243dSDimitry Andric // stub type. It should be ignored if optimized to R_PC.
1064bdd1243dSDimitry Andric if (config->emachine == EM_PPC && expr == R_PPC32_PLTREL)
1065bdd1243dSDimitry Andric addend &= ~0x8000;
1066bdd1243dSDimitry Andric // R_HEX_GD_PLT_B22_PCREL (call a@GDPLT) is transformed into
1067bdd1243dSDimitry Andric // call __tls_get_addr even if the symbol is non-preemptible.
1068bdd1243dSDimitry Andric if (!(config->emachine == EM_HEXAGON &&
1069bdd1243dSDimitry Andric (type == R_HEX_GD_PLT_B22_PCREL ||
1070bdd1243dSDimitry Andric type == R_HEX_GD_PLT_B22_PCREL_X ||
1071bdd1243dSDimitry Andric type == R_HEX_GD_PLT_B32_PCREL_X)))
1072bdd1243dSDimitry Andric expr = fromPlt(expr);
1073bdd1243dSDimitry Andric } else if (!isAbsoluteValue(sym)) {
1074bdd1243dSDimitry Andric expr =
1075bdd1243dSDimitry Andric target->adjustGotPcExpr(type, addend, sec->content().data() + offset);
10765f757f3fSDimitry Andric // If the target adjusted the expression to R_RELAX_GOT_PC, we may end up
10775f757f3fSDimitry Andric // needing the GOT if we can't relax everything.
10785f757f3fSDimitry Andric if (expr == R_RELAX_GOT_PC)
10795f757f3fSDimitry Andric in.got->hasGotOffRel.store(true, std::memory_order_relaxed);
1080bdd1243dSDimitry Andric }
1081bdd1243dSDimitry Andric }
1082bdd1243dSDimitry Andric
1083bdd1243dSDimitry Andric // We were asked not to generate PLT entries for ifuncs. Instead, pass the
1084bdd1243dSDimitry Andric // direct relocation on through.
1085bdd1243dSDimitry Andric if (LLVM_UNLIKELY(isIfunc) && config->zIfuncNoplt) {
1086bdd1243dSDimitry Andric std::lock_guard<std::mutex> lock(relocMutex);
1087bdd1243dSDimitry Andric sym.exportDynamic = true;
1088bdd1243dSDimitry Andric mainPart->relaDyn->addSymbolReloc(type, *sec, offset, sym, addend, type);
1089bdd1243dSDimitry Andric return;
1090bdd1243dSDimitry Andric }
1091bdd1243dSDimitry Andric
1092bdd1243dSDimitry Andric if (needsGot(expr)) {
1093bdd1243dSDimitry Andric if (config->emachine == EM_MIPS) {
1094bdd1243dSDimitry Andric // MIPS ABI has special rules to process GOT entries and doesn't
1095bdd1243dSDimitry Andric // require relocation entries for them. A special case is TLS
1096bdd1243dSDimitry Andric // relocations. In that case dynamic loader applies dynamic
1097bdd1243dSDimitry Andric // relocations to initialize TLS GOT entries.
1098bdd1243dSDimitry Andric // See "Global Offset Table" in Chapter 5 in the following document
1099bdd1243dSDimitry Andric // for detailed description:
1100bdd1243dSDimitry Andric // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1101bdd1243dSDimitry Andric in.mipsGot->addEntry(*sec->file, sym, addend, expr);
110206c3fb27SDimitry Andric } else if (!sym.isTls() || config->emachine != EM_LOONGARCH) {
110306c3fb27SDimitry Andric // Many LoongArch TLS relocs reuse the R_LOONGARCH_GOT type, in which
110406c3fb27SDimitry Andric // case the NEEDS_GOT flag shouldn't get set.
1105bdd1243dSDimitry Andric sym.setFlags(NEEDS_GOT);
1106bdd1243dSDimitry Andric }
1107bdd1243dSDimitry Andric } else if (needsPlt(expr)) {
1108bdd1243dSDimitry Andric sym.setFlags(NEEDS_PLT);
1109bdd1243dSDimitry Andric } else if (LLVM_UNLIKELY(isIfunc)) {
1110bdd1243dSDimitry Andric sym.setFlags(HAS_DIRECT_RELOC);
1111bdd1243dSDimitry Andric }
1112bdd1243dSDimitry Andric
11130b57cec5SDimitry Andric // If the relocation is known to be a link-time constant, we know no dynamic
11140b57cec5SDimitry Andric // relocation will be created, pass the control to relocateAlloc() or
11150b57cec5SDimitry Andric // relocateNonAlloc() to resolve it.
11160b57cec5SDimitry Andric //
1117fe6060f1SDimitry Andric // The behavior of an undefined weak reference is implementation defined. For
1118fe6060f1SDimitry Andric // non-link-time constants, we resolve relocations statically (let
1119fe6060f1SDimitry Andric // relocate{,Non}Alloc() resolve them) for -no-pie and try producing dynamic
1120fe6060f1SDimitry Andric // relocations for -pie and -shared.
1121fe6060f1SDimitry Andric //
1122fe6060f1SDimitry Andric // The general expectation of -no-pie static linking is that there is no
1123fe6060f1SDimitry Andric // dynamic relocation (except IRELATIVE). Emitting dynamic relocations for
1124fe6060f1SDimitry Andric // -shared matches the spirit of its -z undefs default. -pie has freedom on
1125fe6060f1SDimitry Andric // choices, and we choose dynamic relocations to be consistent with the
1126fe6060f1SDimitry Andric // handling of GOT-generating relocations.
112704eeddc0SDimitry Andric if (isStaticLinkTimeConstant(expr, type, sym, offset) ||
1128fe6060f1SDimitry Andric (!config->isPic && sym.isUndefWeak())) {
1129bdd1243dSDimitry Andric sec->addReloc({expr, type, offset, addend, &sym});
11300b57cec5SDimitry Andric return;
11310b57cec5SDimitry Andric }
11320b57cec5SDimitry Andric
11331ac55f4cSDimitry Andric // Use a simple -z notext rule that treats all sections except .eh_frame as
11341ac55f4cSDimitry Andric // writable. GNU ld does not produce dynamic relocations in .eh_frame (and our
11351ac55f4cSDimitry Andric // SectionBase::getOffset would incorrectly adjust the offset).
11361ac55f4cSDimitry Andric //
11371ac55f4cSDimitry Andric // For MIPS, we don't implement GNU ld's DW_EH_PE_absptr to DW_EH_PE_pcrel
11381ac55f4cSDimitry Andric // conversion. We still emit a dynamic relocation.
11391ac55f4cSDimitry Andric bool canWrite = (sec->flags & SHF_WRITE) ||
11401ac55f4cSDimitry Andric !(config->zText ||
11411ac55f4cSDimitry Andric (isa<EhInputSection>(sec) && config->emachine != EM_MIPS));
11420b57cec5SDimitry Andric if (canWrite) {
1143bdd1243dSDimitry Andric RelType rel = target->getDynRel(type);
114406c3fb27SDimitry Andric if (oneof<R_GOT, R_LOONGARCH_GOT>(expr) ||
114506c3fb27SDimitry Andric (rel == target->symbolicRel && !sym.isPreemptible)) {
1146bdd1243dSDimitry Andric addRelativeReloc<true>(*sec, offset, sym, addend, expr, type);
11470b57cec5SDimitry Andric return;
11480fca6ea1SDimitry Andric }
11490fca6ea1SDimitry Andric if (rel != 0) {
1150bdd1243dSDimitry Andric if (config->emachine == EM_MIPS && rel == target->symbolicRel)
1151bdd1243dSDimitry Andric rel = target->relativeRel;
1152bdd1243dSDimitry Andric std::lock_guard<std::mutex> lock(relocMutex);
11530fca6ea1SDimitry Andric Partition &part = sec->getPartition();
11540fca6ea1SDimitry Andric if (config->emachine == EM_AARCH64 && type == R_AARCH64_AUTH_ABS64) {
11550fca6ea1SDimitry Andric // For a preemptible symbol, we can't use a relative relocation. For an
11560fca6ea1SDimitry Andric // undefined symbol, we can't compute offset at link-time and use a
11570fca6ea1SDimitry Andric // relative relocation. Use a symbolic relocation instead.
11580fca6ea1SDimitry Andric if (sym.isPreemptible) {
11590fca6ea1SDimitry Andric part.relaDyn->addSymbolReloc(type, *sec, offset, sym, addend, type);
11600fca6ea1SDimitry Andric } else if (part.relrAuthDyn && sec->addralign >= 2 && offset % 2 == 0) {
11610fca6ea1SDimitry Andric // When symbol values are determined in
11620fca6ea1SDimitry Andric // finalizeAddressDependentContent, some .relr.auth.dyn relocations
11630fca6ea1SDimitry Andric // may be moved to .rela.dyn.
11640fca6ea1SDimitry Andric sec->addReloc({expr, type, offset, addend, &sym});
11650fca6ea1SDimitry Andric part.relrAuthDyn->relocs.push_back({sec, sec->relocs().size() - 1});
11660fca6ea1SDimitry Andric } else {
11670fca6ea1SDimitry Andric part.relaDyn->addReloc({R_AARCH64_AUTH_RELATIVE, sec, offset,
11680fca6ea1SDimitry Andric DynamicReloc::AddendOnlyWithTargetVA, sym,
11690fca6ea1SDimitry Andric addend, R_ABS});
11700fca6ea1SDimitry Andric }
11710fca6ea1SDimitry Andric return;
11720fca6ea1SDimitry Andric }
11730fca6ea1SDimitry Andric part.relaDyn->addSymbolReloc(rel, *sec, offset, sym, addend, type);
11740b57cec5SDimitry Andric
11750b57cec5SDimitry Andric // MIPS ABI turns using of GOT and dynamic relocations inside out.
11760b57cec5SDimitry Andric // While regular ABI uses dynamic relocations to fill up GOT entries
11770b57cec5SDimitry Andric // MIPS ABI requires dynamic linker to fills up GOT entries using
11780b57cec5SDimitry Andric // specially sorted dynamic symbol table. This affects even dynamic
11790b57cec5SDimitry Andric // relocations against symbols which do not require GOT entries
11800b57cec5SDimitry Andric // creation explicitly, i.e. do not have any GOT-relocations. So if
11810b57cec5SDimitry Andric // a preemptible symbol has a dynamic relocation we anyway have
11820b57cec5SDimitry Andric // to create a GOT entry for it.
11830b57cec5SDimitry Andric // If a non-preemptible symbol has a dynamic relocation against it,
11840b57cec5SDimitry Andric // dynamic linker takes it st_value, adds offset and writes down
11850b57cec5SDimitry Andric // result of the dynamic relocation. In case of preemptible symbol
11860b57cec5SDimitry Andric // dynamic linker performs symbol resolution, writes the symbol value
11870b57cec5SDimitry Andric // to the GOT entry and reads the GOT entry when it needs to perform
11880b57cec5SDimitry Andric // a dynamic relocation.
11890b57cec5SDimitry Andric // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19
11900b57cec5SDimitry Andric if (config->emachine == EM_MIPS)
1191bdd1243dSDimitry Andric in.mipsGot->addEntry(*sec->file, sym, addend, expr);
11920b57cec5SDimitry Andric return;
11930b57cec5SDimitry Andric }
11940b57cec5SDimitry Andric }
11950b57cec5SDimitry Andric
119685868e8aSDimitry Andric // When producing an executable, we can perform copy relocations (for
11975f757f3fSDimitry Andric // STT_OBJECT) and canonical PLT (for STT_FUNC) if sym is defined by a DSO.
11980fca6ea1SDimitry Andric // Copy relocations/canonical PLT entries are unsupported for
11990fca6ea1SDimitry Andric // R_AARCH64_AUTH_ABS64.
12000fca6ea1SDimitry Andric if (!config->shared && sym.isShared() &&
12010fca6ea1SDimitry Andric !(config->emachine == EM_AARCH64 && type == R_AARCH64_AUTH_ABS64)) {
12020b57cec5SDimitry Andric if (!canDefineSymbolInExecutable(sym)) {
120385868e8aSDimitry Andric errorOrWarn("cannot preempt symbol: " + toString(sym) +
1204bdd1243dSDimitry Andric getLocation(*sec, sym, offset));
12050b57cec5SDimitry Andric return;
12060b57cec5SDimitry Andric }
12070b57cec5SDimitry Andric
12080b57cec5SDimitry Andric if (sym.isObject()) {
12090b57cec5SDimitry Andric // Produce a copy relocation.
12100b57cec5SDimitry Andric if (auto *ss = dyn_cast<SharedSymbol>(&sym)) {
12110b57cec5SDimitry Andric if (!config->zCopyreloc)
12120b57cec5SDimitry Andric error("unresolvable relocation " + toString(type) +
12130b57cec5SDimitry Andric " against symbol '" + toString(*ss) +
12140b57cec5SDimitry Andric "'; recompile with -fPIC or remove '-z nocopyreloc'" +
1215bdd1243dSDimitry Andric getLocation(*sec, sym, offset));
1216bdd1243dSDimitry Andric sym.setFlags(NEEDS_COPY);
12170b57cec5SDimitry Andric }
1218bdd1243dSDimitry Andric sec->addReloc({expr, type, offset, addend, &sym});
12190b57cec5SDimitry Andric return;
12200b57cec5SDimitry Andric }
12210b57cec5SDimitry Andric
12220b57cec5SDimitry Andric // This handles a non PIC program call to function in a shared library. In
12230b57cec5SDimitry Andric // an ideal world, we could just report an error saying the relocation can
12240b57cec5SDimitry Andric // overflow at runtime. In the real world with glibc, crt1.o has a
12250b57cec5SDimitry Andric // R_X86_64_PC32 pointing to libc.so.
12260b57cec5SDimitry Andric //
12270b57cec5SDimitry Andric // The general idea on how to handle such cases is to create a PLT entry and
12280b57cec5SDimitry Andric // use that as the function value.
12290b57cec5SDimitry Andric //
12300b57cec5SDimitry Andric // For the static linking part, we just return a plt expr and everything
12310b57cec5SDimitry Andric // else will use the PLT entry as the address.
12320b57cec5SDimitry Andric //
12330b57cec5SDimitry Andric // The remaining problem is making sure pointer equality still works. We
12340b57cec5SDimitry Andric // need the help of the dynamic linker for that. We let it know that we have
12350b57cec5SDimitry Andric // a direct reference to a so symbol by creating an undefined symbol with a
12360b57cec5SDimitry Andric // non zero st_value. Seeing that, the dynamic linker resolves the symbol to
12370b57cec5SDimitry Andric // the value of the symbol we created. This is true even for got entries, so
12380b57cec5SDimitry Andric // pointer equality is maintained. To avoid an infinite loop, the only entry
12390b57cec5SDimitry Andric // that points to the real function is a dedicated got entry used by the
12400b57cec5SDimitry Andric // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT,
12410b57cec5SDimitry Andric // R_386_JMP_SLOT, etc).
12420b57cec5SDimitry Andric
12430b57cec5SDimitry Andric // For position independent executable on i386, the plt entry requires ebx
12440b57cec5SDimitry Andric // to be set. This causes two problems:
12450b57cec5SDimitry Andric // * If some code has a direct reference to a function, it was probably
12460b57cec5SDimitry Andric // compiled without -fPIE/-fPIC and doesn't maintain ebx.
12470b57cec5SDimitry Andric // * If a library definition gets preempted to the executable, it will have
12480b57cec5SDimitry Andric // the wrong ebx value.
124985868e8aSDimitry Andric if (sym.isFunc()) {
12500b57cec5SDimitry Andric if (config->pie && config->emachine == EM_386)
12510b57cec5SDimitry Andric errorOrWarn("symbol '" + toString(sym) +
12520b57cec5SDimitry Andric "' cannot be preempted; recompile with -fPIE" +
1253bdd1243dSDimitry Andric getLocation(*sec, sym, offset));
1254bdd1243dSDimitry Andric sym.setFlags(NEEDS_COPY | NEEDS_PLT);
1255bdd1243dSDimitry Andric sec->addReloc({expr, type, offset, addend, &sym});
12560b57cec5SDimitry Andric return;
12570b57cec5SDimitry Andric }
125885868e8aSDimitry Andric }
125985868e8aSDimitry Andric
1260349cc55cSDimitry Andric errorOrWarn("relocation " + toString(type) + " cannot be used against " +
126185868e8aSDimitry Andric (sym.getName().empty() ? "local symbol"
1262349cc55cSDimitry Andric : "symbol '" + toString(sym) + "'") +
1263bdd1243dSDimitry Andric "; recompile with -fPIC" + getLocation(*sec, sym, offset));
126485868e8aSDimitry Andric }
12650b57cec5SDimitry Andric
1266349cc55cSDimitry Andric // This function is similar to the `handleTlsRelocation`. MIPS does not
1267349cc55cSDimitry Andric // support any relaxations for TLS relocations so by factoring out MIPS
1268349cc55cSDimitry Andric // handling in to the separate function we can simplify the code and do not
1269349cc55cSDimitry Andric // pollute other `handleTlsRelocation` by MIPS `ifs` statements.
1270349cc55cSDimitry Andric // Mips has a custom MipsGotSection that handles the writing of GOT entries
1271349cc55cSDimitry Andric // without dynamic relocations.
handleMipsTlsRelocation(RelType type,Symbol & sym,InputSectionBase & c,uint64_t offset,int64_t addend,RelExpr expr)1272349cc55cSDimitry Andric static unsigned handleMipsTlsRelocation(RelType type, Symbol &sym,
1273349cc55cSDimitry Andric InputSectionBase &c, uint64_t offset,
1274349cc55cSDimitry Andric int64_t addend, RelExpr expr) {
1275349cc55cSDimitry Andric if (expr == R_MIPS_TLSLD) {
1276349cc55cSDimitry Andric in.mipsGot->addTlsIndex(*c.file);
1277bdd1243dSDimitry Andric c.addReloc({expr, type, offset, addend, &sym});
1278349cc55cSDimitry Andric return 1;
1279349cc55cSDimitry Andric }
1280349cc55cSDimitry Andric if (expr == R_MIPS_TLSGD) {
1281349cc55cSDimitry Andric in.mipsGot->addDynTlsEntry(*c.file, sym);
1282bdd1243dSDimitry Andric c.addReloc({expr, type, offset, addend, &sym});
1283349cc55cSDimitry Andric return 1;
1284349cc55cSDimitry Andric }
1285349cc55cSDimitry Andric return 0;
1286349cc55cSDimitry Andric }
1287349cc55cSDimitry Andric
1288349cc55cSDimitry Andric // Notes about General Dynamic and Local Dynamic TLS models below. They may
1289349cc55cSDimitry Andric // require the generation of a pair of GOT entries that have associated dynamic
1290349cc55cSDimitry Andric // relocations. The pair of GOT entries created are of the form GOT[e0] Module
1291349cc55cSDimitry Andric // Index (Used to find pointer to TLS block at run-time) GOT[e1] Offset of
1292349cc55cSDimitry Andric // symbol in TLS block.
1293349cc55cSDimitry Andric //
1294349cc55cSDimitry Andric // Returns the number of relocations processed.
handleTlsRelocation(RelType type,Symbol & sym,InputSectionBase & c,uint64_t offset,int64_t addend,RelExpr expr)129504eeddc0SDimitry Andric static unsigned handleTlsRelocation(RelType type, Symbol &sym,
129604eeddc0SDimitry Andric InputSectionBase &c, uint64_t offset,
129704eeddc0SDimitry Andric int64_t addend, RelExpr expr) {
1298bdd1243dSDimitry Andric if (expr == R_TPREL || expr == R_TPREL_NEG) {
1299bdd1243dSDimitry Andric if (config->shared) {
1300bdd1243dSDimitry Andric errorOrWarn("relocation " + toString(type) + " against " + toString(sym) +
1301bdd1243dSDimitry Andric " cannot be used with -shared" + getLocation(c, sym, offset));
1302bdd1243dSDimitry Andric return 1;
1303bdd1243dSDimitry Andric }
1304349cc55cSDimitry Andric return 0;
1305bdd1243dSDimitry Andric }
1306349cc55cSDimitry Andric
1307349cc55cSDimitry Andric if (config->emachine == EM_MIPS)
1308349cc55cSDimitry Andric return handleMipsTlsRelocation(type, sym, c, offset, addend, expr);
13090fca6ea1SDimitry Andric
13100fca6ea1SDimitry Andric // LoongArch does not yet implement transition from TLSDESC to LE/IE, so
13110fca6ea1SDimitry Andric // generate TLSDESC dynamic relocation for the dynamic linker to handle.
13120fca6ea1SDimitry Andric if (config->emachine == EM_LOONGARCH &&
131352418fc2SDimitry Andric oneof<R_LOONGARCH_TLSDESC_PAGE_PC, R_TLSDESC, R_TLSDESC_PC,
131452418fc2SDimitry Andric R_TLSDESC_CALL>(expr)) {
13150fca6ea1SDimitry Andric if (expr != R_TLSDESC_CALL) {
13160fca6ea1SDimitry Andric sym.setFlags(NEEDS_TLSDESC);
13170fca6ea1SDimitry Andric c.addReloc({expr, type, offset, addend, &sym});
13180fca6ea1SDimitry Andric }
13190fca6ea1SDimitry Andric return 1;
13200fca6ea1SDimitry Andric }
13210fca6ea1SDimitry Andric
1322b3edf446SDimitry Andric bool isRISCV = config->emachine == EM_RISCV;
1323349cc55cSDimitry Andric
1324349cc55cSDimitry Andric if (oneof<R_AARCH64_TLSDESC_PAGE, R_TLSDESC, R_TLSDESC_CALL, R_TLSDESC_PC,
1325349cc55cSDimitry Andric R_TLSDESC_GOTPLT>(expr) &&
1326349cc55cSDimitry Andric config->shared) {
1327b3edf446SDimitry Andric // R_RISCV_TLSDESC_{LOAD_LO12,ADD_LO12_I,CALL} reference a label. Do not
1328b3edf446SDimitry Andric // set NEEDS_TLSDESC on the label.
13290eae32dcSDimitry Andric if (expr != R_TLSDESC_CALL) {
1330b3edf446SDimitry Andric if (!isRISCV || type == R_RISCV_TLSDESC_HI20)
1331bdd1243dSDimitry Andric sym.setFlags(NEEDS_TLSDESC);
1332bdd1243dSDimitry Andric c.addReloc({expr, type, offset, addend, &sym});
13330eae32dcSDimitry Andric }
1334349cc55cSDimitry Andric return 1;
1335349cc55cSDimitry Andric }
1336349cc55cSDimitry Andric
133706c3fb27SDimitry Andric // ARM, Hexagon, LoongArch and RISC-V do not support GD/LD to IE/LE
1338b3edf446SDimitry Andric // optimizations.
1339b3edf446SDimitry Andric // RISC-V supports TLSDESC to IE/LE optimizations.
134006c3fb27SDimitry Andric // For PPC64, if the file has missing R_PPC64_TLSGD/R_PPC64_TLSLD, disable
1341b3edf446SDimitry Andric // optimization as well.
1342b3edf446SDimitry Andric bool execOptimize =
1343b3edf446SDimitry Andric !config->shared && config->emachine != EM_ARM &&
1344b3edf446SDimitry Andric config->emachine != EM_HEXAGON && config->emachine != EM_LOONGARCH &&
1345b3edf446SDimitry Andric !(isRISCV && expr != R_TLSDESC_PC && expr != R_TLSDESC_CALL) &&
1346349cc55cSDimitry Andric !c.file->ppc64DisableTLSRelax;
1347349cc55cSDimitry Andric
1348349cc55cSDimitry Andric // If we are producing an executable and the symbol is non-preemptable, it
1349b3edf446SDimitry Andric // must be defined and the code sequence can be optimized to use Local-Exec.
1350349cc55cSDimitry Andric //
1351349cc55cSDimitry Andric // ARM and RISC-V do not support any relaxations for TLS relocations, however,
1352349cc55cSDimitry Andric // we can omit the DTPMOD dynamic relocations and resolve them at link time
1353349cc55cSDimitry Andric // because them are always 1. This may be necessary for static linking as
1354349cc55cSDimitry Andric // DTPMOD may not be expected at load time.
1355349cc55cSDimitry Andric bool isLocalInExecutable = !sym.isPreemptible && !config->shared;
1356349cc55cSDimitry Andric
1357349cc55cSDimitry Andric // Local Dynamic is for access to module local TLS variables, while still
1358349cc55cSDimitry Andric // being suitable for being dynamically loaded via dlopen. GOT[e0] is the
1359349cc55cSDimitry Andric // module index, with a special value of 0 for the current module. GOT[e1] is
1360349cc55cSDimitry Andric // unused. There only needs to be one module index entry.
136106c3fb27SDimitry Andric if (oneof<R_TLSLD_GOT, R_TLSLD_GOTPLT, R_TLSLD_PC, R_TLSLD_HINT>(expr)) {
1362b3edf446SDimitry Andric // Local-Dynamic relocs can be optimized to Local-Exec.
1363b3edf446SDimitry Andric if (execOptimize) {
1364bdd1243dSDimitry Andric c.addReloc({target->adjustTlsExpr(type, R_RELAX_TLS_LD_TO_LE), type,
1365bdd1243dSDimitry Andric offset, addend, &sym});
1366349cc55cSDimitry Andric return target->getTlsGdRelaxSkip(type);
1367349cc55cSDimitry Andric }
1368349cc55cSDimitry Andric if (expr == R_TLSLD_HINT)
1369349cc55cSDimitry Andric return 1;
1370bdd1243dSDimitry Andric ctx.needsTlsLd.store(true, std::memory_order_relaxed);
1371bdd1243dSDimitry Andric c.addReloc({expr, type, offset, addend, &sym});
1372349cc55cSDimitry Andric return 1;
1373349cc55cSDimitry Andric }
1374349cc55cSDimitry Andric
1375b3edf446SDimitry Andric // Local-Dynamic relocs can be optimized to Local-Exec.
1376349cc55cSDimitry Andric if (expr == R_DTPREL) {
1377b3edf446SDimitry Andric if (execOptimize)
1378349cc55cSDimitry Andric expr = target->adjustTlsExpr(type, R_RELAX_TLS_LD_TO_LE);
1379bdd1243dSDimitry Andric c.addReloc({expr, type, offset, addend, &sym});
1380349cc55cSDimitry Andric return 1;
1381349cc55cSDimitry Andric }
1382349cc55cSDimitry Andric
1383349cc55cSDimitry Andric // Local-Dynamic sequence where offset of tls variable relative to dynamic
1384b3edf446SDimitry Andric // thread pointer is stored in the got. This cannot be optimized to
1385b3edf446SDimitry Andric // Local-Exec.
1386349cc55cSDimitry Andric if (expr == R_TLSLD_GOT_OFF) {
1387bdd1243dSDimitry Andric sym.setFlags(NEEDS_GOT_DTPREL);
1388bdd1243dSDimitry Andric c.addReloc({expr, type, offset, addend, &sym});
1389349cc55cSDimitry Andric return 1;
1390349cc55cSDimitry Andric }
1391349cc55cSDimitry Andric
1392349cc55cSDimitry Andric if (oneof<R_AARCH64_TLSDESC_PAGE, R_TLSDESC, R_TLSDESC_CALL, R_TLSDESC_PC,
139306c3fb27SDimitry Andric R_TLSDESC_GOTPLT, R_TLSGD_GOT, R_TLSGD_GOTPLT, R_TLSGD_PC,
139406c3fb27SDimitry Andric R_LOONGARCH_TLSGD_PAGE_PC>(expr)) {
1395b3edf446SDimitry Andric if (!execOptimize) {
1396bdd1243dSDimitry Andric sym.setFlags(NEEDS_TLSGD);
1397bdd1243dSDimitry Andric c.addReloc({expr, type, offset, addend, &sym});
1398349cc55cSDimitry Andric return 1;
1399349cc55cSDimitry Andric }
1400349cc55cSDimitry Andric
1401b3edf446SDimitry Andric // Global-Dynamic/TLSDESC can be optimized to Initial-Exec or Local-Exec
1402349cc55cSDimitry Andric // depending on the symbol being locally defined or not.
1403b3edf446SDimitry Andric //
1404b3edf446SDimitry Andric // R_RISCV_TLSDESC_{LOAD_LO12,ADD_LO12_I,CALL} reference a non-preemptible
14050fca6ea1SDimitry Andric // label, so TLSDESC=>IE will be categorized as R_RELAX_TLS_GD_TO_LE. We fix
14060fca6ea1SDimitry Andric // the categorization in RISCV::relocateAlloc.
1407349cc55cSDimitry Andric if (sym.isPreemptible) {
1408bdd1243dSDimitry Andric sym.setFlags(NEEDS_TLSGD_TO_IE);
1409bdd1243dSDimitry Andric c.addReloc({target->adjustTlsExpr(type, R_RELAX_TLS_GD_TO_IE), type,
1410bdd1243dSDimitry Andric offset, addend, &sym});
1411349cc55cSDimitry Andric } else {
1412bdd1243dSDimitry Andric c.addReloc({target->adjustTlsExpr(type, R_RELAX_TLS_GD_TO_LE), type,
1413bdd1243dSDimitry Andric offset, addend, &sym});
1414349cc55cSDimitry Andric }
1415349cc55cSDimitry Andric return target->getTlsGdRelaxSkip(type);
1416349cc55cSDimitry Andric }
1417349cc55cSDimitry Andric
141806c3fb27SDimitry Andric if (oneof<R_GOT, R_GOTPLT, R_GOT_PC, R_AARCH64_GOT_PAGE_PC,
141906c3fb27SDimitry Andric R_LOONGARCH_GOT_PAGE_PC, R_GOT_OFF, R_TLSIE_HINT>(expr)) {
1420bdd1243dSDimitry Andric ctx.hasTlsIe.store(true, std::memory_order_relaxed);
1421b3edf446SDimitry Andric // Initial-Exec relocs can be optimized to Local-Exec if the symbol is
142274626c16SDimitry Andric // locally defined. This is not supported on SystemZ.
142374626c16SDimitry Andric if (execOptimize && isLocalInExecutable && config->emachine != EM_S390) {
1424bdd1243dSDimitry Andric c.addReloc({R_RELAX_TLS_IE_TO_LE, type, offset, addend, &sym});
1425349cc55cSDimitry Andric } else if (expr != R_TLSIE_HINT) {
1426bdd1243dSDimitry Andric sym.setFlags(NEEDS_TLSIE);
1427349cc55cSDimitry Andric // R_GOT needs a relative relocation for PIC on i386 and Hexagon.
1428349cc55cSDimitry Andric if (expr == R_GOT && config->isPic && !target->usesOnlyLowPageBits(type))
1429bdd1243dSDimitry Andric addRelativeReloc<true>(c, offset, sym, addend, expr, type);
1430349cc55cSDimitry Andric else
1431bdd1243dSDimitry Andric c.addReloc({expr, type, offset, addend, &sym});
1432349cc55cSDimitry Andric }
1433349cc55cSDimitry Andric return 1;
1434349cc55cSDimitry Andric }
1435349cc55cSDimitry Andric
1436349cc55cSDimitry Andric return 0;
14370b57cec5SDimitry Andric }
14380b57cec5SDimitry Andric
143952418fc2SDimitry Andric template <class ELFT, class RelTy>
scanOne(typename Relocs<RelTy>::const_iterator & i)144052418fc2SDimitry Andric void RelocationScanner::scanOne(typename Relocs<RelTy>::const_iterator &i) {
14410b57cec5SDimitry Andric const RelTy &rel = *i;
14420b57cec5SDimitry Andric uint32_t symIndex = rel.getSymbol(config->isMips64EL);
1443bdd1243dSDimitry Andric Symbol &sym = sec->getFile<ELFT>()->getSymbol(symIndex);
14440b57cec5SDimitry Andric RelType type;
144552418fc2SDimitry Andric if constexpr (ELFT::Is64Bits || RelTy::IsCrel) {
14460fca6ea1SDimitry Andric type = rel.getType(config->isMips64EL);
14470fca6ea1SDimitry Andric ++i;
14480fca6ea1SDimitry Andric } else {
144952418fc2SDimitry Andric // CREL is unsupported for MIPS N32.
14500b57cec5SDimitry Andric if (config->mipsN32Abi) {
145104eeddc0SDimitry Andric type = getMipsN32RelType(i);
14520b57cec5SDimitry Andric } else {
14530b57cec5SDimitry Andric type = rel.getType(config->isMips64EL);
14540b57cec5SDimitry Andric ++i;
14550b57cec5SDimitry Andric }
14560fca6ea1SDimitry Andric }
14570b57cec5SDimitry Andric // Get an offset in an output section this relocation is applied to.
145804eeddc0SDimitry Andric uint64_t offset = getter.get(rel.r_offset);
14590b57cec5SDimitry Andric if (offset == uint64_t(-1))
14600b57cec5SDimitry Andric return;
14610b57cec5SDimitry Andric
1462bdd1243dSDimitry Andric RelExpr expr = target->getRelExpr(type, sym, sec->content().data() + offset);
14630fca6ea1SDimitry Andric int64_t addend = RelTy::HasAddend
1464bdd1243dSDimitry Andric ? getAddend<ELFT>(rel)
1465bdd1243dSDimitry Andric : target->getImplicitAddend(
1466bdd1243dSDimitry Andric sec->content().data() + rel.r_offset, type);
1467bdd1243dSDimitry Andric if (LLVM_UNLIKELY(config->emachine == EM_MIPS))
1468bdd1243dSDimitry Andric addend += computeMipsAddend<ELFT>(rel, expr, sym.isLocal());
1469bdd1243dSDimitry Andric else if (config->emachine == EM_PPC64 && config->isPic && type == R_PPC64_TOC)
1470bdd1243dSDimitry Andric addend += getPPC64TocBase();
14710b57cec5SDimitry Andric
1472480093f4SDimitry Andric // Ignore R_*_NONE and other marker relocations.
1473480093f4SDimitry Andric if (expr == R_NONE)
14740b57cec5SDimitry Andric return;
14750b57cec5SDimitry Andric
1476bdd1243dSDimitry Andric // Error if the target symbol is undefined. Symbol index 0 may be used by
1477bdd1243dSDimitry Andric // marker relocations, e.g. R_*_NONE and R_ARM_V4BX. Don't error on them.
1478bdd1243dSDimitry Andric if (sym.isUndefined() && symIndex != 0 &&
1479bdd1243dSDimitry Andric maybeReportUndefined(cast<Undefined>(sym), *sec, offset))
1480bdd1243dSDimitry Andric return;
14810b57cec5SDimitry Andric
14825ffd83dbSDimitry Andric if (config->emachine == EM_PPC64) {
14835ffd83dbSDimitry Andric // We can separate the small code model relocations into 2 categories:
14845ffd83dbSDimitry Andric // 1) Those that access the compiler generated .toc sections.
14855ffd83dbSDimitry Andric // 2) Those that access the linker allocated got entries.
14865ffd83dbSDimitry Andric // lld allocates got entries to symbols on demand. Since we don't try to
14875ffd83dbSDimitry Andric // sort the got entries in any way, we don't have to track which objects
14885ffd83dbSDimitry Andric // have got-based small code model relocs. The .toc sections get placed
14895ffd83dbSDimitry Andric // after the end of the linker allocated .got section and we do sort those
14905ffd83dbSDimitry Andric // so sections addressed with small code model relocations come first.
1491349cc55cSDimitry Andric if (type == R_PPC64_TOC16 || type == R_PPC64_TOC16_DS)
1492bdd1243dSDimitry Andric sec->file->ppc64SmallCodeModelTocRelocs = true;
14935ffd83dbSDimitry Andric
14945ffd83dbSDimitry Andric // Record the TOC entry (.toc + addend) as not relaxable. See the comment in
14955ffd83dbSDimitry Andric // InputSectionBase::relocateAlloc().
14965ffd83dbSDimitry Andric if (type == R_PPC64_TOC16_LO && sym.isSection() && isa<Defined>(sym) &&
14975ffd83dbSDimitry Andric cast<Defined>(sym).section->name == ".toc")
14985ffd83dbSDimitry Andric ppc64noTocRelax.insert({&sym, addend});
1499e8d8bef9SDimitry Andric
1500e8d8bef9SDimitry Andric if ((type == R_PPC64_TLSGD && expr == R_TLSDESC_CALL) ||
1501e8d8bef9SDimitry Andric (type == R_PPC64_TLSLD && expr == R_TLSLD_HINT)) {
150252418fc2SDimitry Andric // Skip the error check for CREL, which does not set `end`.
150352418fc2SDimitry Andric if constexpr (!RelTy::IsCrel) {
1504e8d8bef9SDimitry Andric if (i == end) {
1505e8d8bef9SDimitry Andric errorOrWarn("R_PPC64_TLSGD/R_PPC64_TLSLD may not be the last "
1506e8d8bef9SDimitry Andric "relocation" +
1507bdd1243dSDimitry Andric getLocation(*sec, sym, offset));
1508e8d8bef9SDimitry Andric return;
1509e8d8bef9SDimitry Andric }
151052418fc2SDimitry Andric }
1511e8d8bef9SDimitry Andric
151252418fc2SDimitry Andric // Offset the 4-byte aligned R_PPC64_TLSGD by one byte in the NOTOC
151352418fc2SDimitry Andric // case, so we can discern it later from the toc-case.
1514e8d8bef9SDimitry Andric if (i->getType(/*isMips64EL=*/false) == R_PPC64_REL24_NOTOC)
1515e8d8bef9SDimitry Andric ++offset;
1516e8d8bef9SDimitry Andric }
15175ffd83dbSDimitry Andric }
15185ffd83dbSDimitry Andric
15190b57cec5SDimitry Andric // If the relocation does not emit a GOT or GOTPLT entry but its computation
15200b57cec5SDimitry Andric // uses their addresses, we need GOT or GOTPLT to be created.
15210b57cec5SDimitry Andric //
1522349cc55cSDimitry Andric // The 5 types that relative GOTPLT are all x86 and x86-64 specific.
1523349cc55cSDimitry Andric if (oneof<R_GOTPLTONLY_PC, R_GOTPLTREL, R_GOTPLT, R_PLT_GOTPLT,
1524349cc55cSDimitry Andric R_TLSDESC_GOTPLT, R_TLSGD_GOTPLT>(expr)) {
1525bdd1243dSDimitry Andric in.gotPlt->hasGotPltOffRel.store(true, std::memory_order_relaxed);
15260eae32dcSDimitry Andric } else if (oneof<R_GOTONLY_PC, R_GOTREL, R_PPC32_PLTREL, R_PPC64_TOCBASE,
15270eae32dcSDimitry Andric R_PPC64_RELAX_TOC>(expr)) {
1528bdd1243dSDimitry Andric in.got->hasGotOffRel.store(true, std::memory_order_relaxed);
15290b57cec5SDimitry Andric }
15300b57cec5SDimitry Andric
1531b3edf446SDimitry Andric // Process TLS relocations, including TLS optimizations. Note that
153204eeddc0SDimitry Andric // R_TPREL and R_TPREL_NEG relocations are resolved in processAux.
15333a079333SDimitry Andric //
15343a079333SDimitry Andric // Some RISCV TLSDESC relocations reference a local NOTYPE symbol,
15353a079333SDimitry Andric // but we need to process them in handleTlsRelocation.
15363a079333SDimitry Andric if (sym.isTls() || oneof<R_TLSDESC_PC, R_TLSDESC_CALL>(expr)) {
1537bdd1243dSDimitry Andric if (unsigned processed =
1538bdd1243dSDimitry Andric handleTlsRelocation(type, sym, *sec, offset, addend, expr)) {
1539bdd1243dSDimitry Andric i += processed - 1;
1540e8d8bef9SDimitry Andric return;
1541e8d8bef9SDimitry Andric }
15420b57cec5SDimitry Andric }
15430b57cec5SDimitry Andric
154404eeddc0SDimitry Andric processAux(expr, type, offset, sym, addend);
15450b57cec5SDimitry Andric }
15460b57cec5SDimitry Andric
1547e8d8bef9SDimitry Andric // R_PPC64_TLSGD/R_PPC64_TLSLD is required to mark `bl __tls_get_addr` for
1548e8d8bef9SDimitry Andric // General Dynamic/Local Dynamic code sequences. If a GD/LD GOT relocation is
1549e8d8bef9SDimitry Andric // found but no R_PPC64_TLSGD/R_PPC64_TLSLD is seen, we assume that the
1550e8d8bef9SDimitry Andric // instructions are generated by very old IBM XL compilers. Work around the
1551e8d8bef9SDimitry Andric // issue by disabling GD/LD to IE/LE relaxation.
1552e8d8bef9SDimitry Andric template <class RelTy>
checkPPC64TLSRelax(InputSectionBase & sec,Relocs<RelTy> rels)155352418fc2SDimitry Andric static void checkPPC64TLSRelax(InputSectionBase &sec, Relocs<RelTy> rels) {
1554e8d8bef9SDimitry Andric // Skip if sec is synthetic (sec.file is null) or if sec has been marked.
1555e8d8bef9SDimitry Andric if (!sec.file || sec.file->ppc64DisableTLSRelax)
1556e8d8bef9SDimitry Andric return;
1557e8d8bef9SDimitry Andric bool hasGDLD = false;
1558e8d8bef9SDimitry Andric for (const RelTy &rel : rels) {
1559e8d8bef9SDimitry Andric RelType type = rel.getType(false);
1560e8d8bef9SDimitry Andric switch (type) {
1561e8d8bef9SDimitry Andric case R_PPC64_TLSGD:
1562e8d8bef9SDimitry Andric case R_PPC64_TLSLD:
1563e8d8bef9SDimitry Andric return; // Found a marker
1564e8d8bef9SDimitry Andric case R_PPC64_GOT_TLSGD16:
1565e8d8bef9SDimitry Andric case R_PPC64_GOT_TLSGD16_HA:
1566e8d8bef9SDimitry Andric case R_PPC64_GOT_TLSGD16_HI:
1567e8d8bef9SDimitry Andric case R_PPC64_GOT_TLSGD16_LO:
1568e8d8bef9SDimitry Andric case R_PPC64_GOT_TLSLD16:
1569e8d8bef9SDimitry Andric case R_PPC64_GOT_TLSLD16_HA:
1570e8d8bef9SDimitry Andric case R_PPC64_GOT_TLSLD16_HI:
1571e8d8bef9SDimitry Andric case R_PPC64_GOT_TLSLD16_LO:
1572e8d8bef9SDimitry Andric hasGDLD = true;
1573e8d8bef9SDimitry Andric break;
1574e8d8bef9SDimitry Andric }
1575e8d8bef9SDimitry Andric }
1576e8d8bef9SDimitry Andric if (hasGDLD) {
1577e8d8bef9SDimitry Andric sec.file->ppc64DisableTLSRelax = true;
1578e8d8bef9SDimitry Andric warn(toString(sec.file) +
1579e8d8bef9SDimitry Andric ": disable TLS relaxation due to R_PPC64_GOT_TLS* relocations without "
1580e8d8bef9SDimitry Andric "R_PPC64_TLSGD/R_PPC64_TLSLD relocations");
1581e8d8bef9SDimitry Andric }
1582e8d8bef9SDimitry Andric }
1583e8d8bef9SDimitry Andric
15840b57cec5SDimitry Andric template <class ELFT, class RelTy>
scan(Relocs<RelTy> rels)158552418fc2SDimitry Andric void RelocationScanner::scan(Relocs<RelTy> rels) {
1586bdd1243dSDimitry Andric // Not all relocations end up in Sec->Relocations, but a lot do.
1587bdd1243dSDimitry Andric sec->relocations.reserve(rels.size());
15880b57cec5SDimitry Andric
1589e8d8bef9SDimitry Andric if (config->emachine == EM_PPC64)
1590bdd1243dSDimitry Andric checkPPC64TLSRelax<RelTy>(*sec, rels);
1591e8d8bef9SDimitry Andric
1592fe6060f1SDimitry Andric // For EhInputSection, OffsetGetter expects the relocations to be sorted by
1593fe6060f1SDimitry Andric // r_offset. In rare cases (.eh_frame pieces are reordered by a linker
1594fe6060f1SDimitry Andric // script), the relocations may be unordered.
159574626c16SDimitry Andric // On SystemZ, all sections need to be sorted by r_offset, to allow TLS
159674626c16SDimitry Andric // relaxation to be handled correctly - see SystemZ::getTlsGdRelaxSkip.
1597fe6060f1SDimitry Andric SmallVector<RelTy, 0> storage;
159874626c16SDimitry Andric if (isa<EhInputSection>(sec) || config->emachine == EM_S390)
1599fe6060f1SDimitry Andric rels = sortRels(rels, storage);
1600fe6060f1SDimitry Andric
160152418fc2SDimitry Andric if constexpr (RelTy::IsCrel) {
160252418fc2SDimitry Andric for (auto i = rels.begin(); i != rels.end();)
160352418fc2SDimitry Andric scanOne<ELFT, RelTy>(i);
160452418fc2SDimitry Andric } else {
160552418fc2SDimitry Andric // The non-CREL code path has additional check for PPC64 TLS.
160604eeddc0SDimitry Andric end = static_cast<const void *>(rels.end());
160704eeddc0SDimitry Andric for (auto i = rels.begin(); i != end;)
160852418fc2SDimitry Andric scanOne<ELFT, RelTy>(i);
160952418fc2SDimitry Andric }
16100b57cec5SDimitry Andric
16110b57cec5SDimitry Andric // Sort relocations by offset for more efficient searching for
16120b57cec5SDimitry Andric // R_RISCV_PCREL_HI20 and R_PPC64_ADDR64.
16130b57cec5SDimitry Andric if (config->emachine == EM_RISCV ||
1614bdd1243dSDimitry Andric (config->emachine == EM_PPC64 && sec->name == ".toc"))
1615bdd1243dSDimitry Andric llvm::stable_sort(sec->relocs(),
16160b57cec5SDimitry Andric [](const Relocation &lhs, const Relocation &rhs) {
16170b57cec5SDimitry Andric return lhs.offset < rhs.offset;
16180b57cec5SDimitry Andric });
16190b57cec5SDimitry Andric }
16200b57cec5SDimitry Andric
1621*62987288SDimitry Andric template <class ELFT>
scanSection(InputSectionBase & s,bool isEH)1622*62987288SDimitry Andric void RelocationScanner::scanSection(InputSectionBase &s, bool isEH) {
1623bdd1243dSDimitry Andric sec = &s;
1624bdd1243dSDimitry Andric getter = OffsetGetter(s);
1625*62987288SDimitry Andric const RelsOrRelas<ELFT> rels = s.template relsOrRelas<ELFT>(!isEH);
162652418fc2SDimitry Andric if (rels.areRelocsCrel())
162752418fc2SDimitry Andric scan<ELFT>(rels.crels);
162852418fc2SDimitry Andric else if (rels.areRelocsRel())
1629bdd1243dSDimitry Andric scan<ELFT>(rels.rels);
16300b57cec5SDimitry Andric else
1631bdd1243dSDimitry Andric scan<ELFT>(rels.relas);
16320b57cec5SDimitry Andric }
16330b57cec5SDimitry Andric
scanRelocations()1634bdd1243dSDimitry Andric template <class ELFT> void elf::scanRelocations() {
1635bdd1243dSDimitry Andric // Scan all relocations. Each relocation goes through a series of tests to
1636bdd1243dSDimitry Andric // determine if it needs special treatment, such as creating GOT, PLT,
1637bdd1243dSDimitry Andric // copy relocations, etc. Note that relocations for non-alloc sections are
1638bdd1243dSDimitry Andric // directly processed by InputSection::relocateNonAlloc.
1639bdd1243dSDimitry Andric
1640bdd1243dSDimitry Andric // Deterministic parallellism needs sorting relocations which is unsuitable
1641bdd1243dSDimitry Andric // for -z nocombreloc. MIPS and PPC64 use global states which are not suitable
1642bdd1243dSDimitry Andric // for parallelism.
1643bdd1243dSDimitry Andric bool serial = !config->zCombreloc || config->emachine == EM_MIPS ||
1644bdd1243dSDimitry Andric config->emachine == EM_PPC64;
1645bdd1243dSDimitry Andric parallel::TaskGroup tg;
164654521a2fSDimitry Andric auto outerFn = [&]() {
1647bdd1243dSDimitry Andric for (ELFFileBase *f : ctx.objectFiles) {
1648bdd1243dSDimitry Andric auto fn = [f]() {
1649bdd1243dSDimitry Andric RelocationScanner scanner;
1650bdd1243dSDimitry Andric for (InputSectionBase *s : f->getSections()) {
1651bdd1243dSDimitry Andric if (s && s->kind() == SectionBase::Regular && s->isLive() &&
1652bdd1243dSDimitry Andric (s->flags & SHF_ALLOC) &&
1653bdd1243dSDimitry Andric !(s->type == SHT_ARM_EXIDX && config->emachine == EM_ARM))
1654bdd1243dSDimitry Andric scanner.template scanSection<ELFT>(*s);
1655bdd1243dSDimitry Andric }
1656bdd1243dSDimitry Andric };
165754521a2fSDimitry Andric if (serial)
165854521a2fSDimitry Andric fn();
165954521a2fSDimitry Andric else
166054521a2fSDimitry Andric tg.spawn(fn);
1661bdd1243dSDimitry Andric }
166254521a2fSDimitry Andric auto scanEH = [] {
1663bdd1243dSDimitry Andric RelocationScanner scanner;
1664bdd1243dSDimitry Andric for (Partition &part : partitions) {
1665bdd1243dSDimitry Andric for (EhInputSection *sec : part.ehFrame->sections)
1666bdd1243dSDimitry Andric scanner.template scanSection<ELFT>(*sec);
1667bdd1243dSDimitry Andric if (part.armExidx && part.armExidx->isLive())
1668bdd1243dSDimitry Andric for (InputSection *sec : part.armExidx->exidxSections)
16695f757f3fSDimitry Andric if (sec->isLive())
1670bdd1243dSDimitry Andric scanner.template scanSection<ELFT>(*sec);
1671bdd1243dSDimitry Andric }
167254521a2fSDimitry Andric };
167354521a2fSDimitry Andric if (serial)
167454521a2fSDimitry Andric scanEH();
167554521a2fSDimitry Andric else
167654521a2fSDimitry Andric tg.spawn(scanEH);
167754521a2fSDimitry Andric };
167854521a2fSDimitry Andric // If `serial` is true, call `spawn` to ensure that `scanner` runs in a thread
167954521a2fSDimitry Andric // with valid getThreadIndex().
168054521a2fSDimitry Andric if (serial)
168154521a2fSDimitry Andric tg.spawn(outerFn);
168254521a2fSDimitry Andric else
168354521a2fSDimitry Andric outerFn();
1684bdd1243dSDimitry Andric }
1685bdd1243dSDimitry Andric
handleNonPreemptibleIfunc(Symbol & sym,uint16_t flags)1686bdd1243dSDimitry Andric static bool handleNonPreemptibleIfunc(Symbol &sym, uint16_t flags) {
16870eae32dcSDimitry Andric // Handle a reference to a non-preemptible ifunc. These are special in a
16880eae32dcSDimitry Andric // few ways:
16890eae32dcSDimitry Andric //
16900eae32dcSDimitry Andric // - Unlike most non-preemptible symbols, non-preemptible ifuncs do not have
16910eae32dcSDimitry Andric // a fixed value. But assuming that all references to the ifunc are
16920eae32dcSDimitry Andric // GOT-generating or PLT-generating, the handling of an ifunc is
16930eae32dcSDimitry Andric // relatively straightforward. We create a PLT entry in Iplt, which is
16940eae32dcSDimitry Andric // usually at the end of .plt, which makes an indirect call using a
16950eae32dcSDimitry Andric // matching GOT entry in igotPlt, which is usually at the end of .got.plt.
16960fca6ea1SDimitry Andric // The GOT entry is relocated using an IRELATIVE relocation in relaDyn,
16970fca6ea1SDimitry Andric // which is usually at the end of .rela.dyn.
16980eae32dcSDimitry Andric //
16990eae32dcSDimitry Andric // - Despite the fact that an ifunc does not have a fixed value, compilers
17000eae32dcSDimitry Andric // that are not passed -fPIC will assume that they do, and will emit
17010eae32dcSDimitry Andric // direct (non-GOT-generating, non-PLT-generating) relocations to the
17020eae32dcSDimitry Andric // symbol. This means that if a direct relocation to the symbol is
17030eae32dcSDimitry Andric // seen, the linker must set a value for the symbol, and this value must
17040eae32dcSDimitry Andric // be consistent no matter what type of reference is made to the symbol.
17050eae32dcSDimitry Andric // This can be done by creating a PLT entry for the symbol in the way
17060eae32dcSDimitry Andric // described above and making it canonical, that is, making all references
17070eae32dcSDimitry Andric // point to the PLT entry instead of the resolver. In lld we also store
17080eae32dcSDimitry Andric // the address of the PLT entry in the dynamic symbol table, which means
17090eae32dcSDimitry Andric // that the symbol will also have the same value in other modules.
17100eae32dcSDimitry Andric // Because the value loaded from the GOT needs to be consistent with
17110eae32dcSDimitry Andric // the value computed using a direct relocation, a non-preemptible ifunc
17120eae32dcSDimitry Andric // may end up with two GOT entries, one in .got.plt that points to the
17130eae32dcSDimitry Andric // address returned by the resolver and is used only by the PLT entry,
17140eae32dcSDimitry Andric // and another in .got that points to the PLT entry and is used by
17150eae32dcSDimitry Andric // GOT-generating relocations.
17160eae32dcSDimitry Andric //
17170eae32dcSDimitry Andric // - The fact that these symbols do not have a fixed value makes them an
17180eae32dcSDimitry Andric // exception to the general rule that a statically linked executable does
17190eae32dcSDimitry Andric // not require any form of dynamic relocation. To handle these relocations
17200eae32dcSDimitry Andric // correctly, the IRELATIVE relocations are stored in an array which a
17210eae32dcSDimitry Andric // statically linked executable's startup code must enumerate using the
17220eae32dcSDimitry Andric // linker-defined symbols __rela?_iplt_{start,end}.
17230eae32dcSDimitry Andric if (!sym.isGnuIFunc() || sym.isPreemptible || config->zIfuncNoplt)
17240eae32dcSDimitry Andric return false;
17250eae32dcSDimitry Andric // Skip unreferenced non-preemptible ifunc.
1726bdd1243dSDimitry Andric if (!(flags & (NEEDS_GOT | NEEDS_PLT | HAS_DIRECT_RELOC)))
17270eae32dcSDimitry Andric return true;
17280eae32dcSDimitry Andric
17290eae32dcSDimitry Andric sym.isInIplt = true;
17300eae32dcSDimitry Andric
17310eae32dcSDimitry Andric // Create an Iplt and the associated IRELATIVE relocation pointing to the
17320eae32dcSDimitry Andric // original section/value pairs. For non-GOT non-PLT relocation case below, we
17330eae32dcSDimitry Andric // may alter section/value, so create a copy of the symbol to make
17340eae32dcSDimitry Andric // section/value fixed.
17350fca6ea1SDimitry Andric //
17360fca6ea1SDimitry Andric // Prior to Android V, there was a bug that caused RELR relocations to be
17370fca6ea1SDimitry Andric // applied after packed relocations. This meant that resolvers referenced by
17380fca6ea1SDimitry Andric // IRELATIVE relocations in the packed relocation section would read
17390fca6ea1SDimitry Andric // unrelocated globals with RELR relocations when
17400fca6ea1SDimitry Andric // --pack-relative-relocs=android+relr is enabled. Work around this by placing
17410fca6ea1SDimitry Andric // IRELATIVE in .rela.plt.
17420eae32dcSDimitry Andric auto *directSym = makeDefined(cast<Defined>(sym));
174304eeddc0SDimitry Andric directSym->allocateAux();
17440fca6ea1SDimitry Andric auto &dyn = config->androidPackDynRelocs ? *in.relaPlt : *mainPart->relaDyn;
17450fca6ea1SDimitry Andric addPltEntry(*in.iplt, *in.igotPlt, dyn, target->iRelativeRel, *directSym);
174604eeddc0SDimitry Andric sym.allocateAux();
174704eeddc0SDimitry Andric symAux.back().pltIdx = symAux[directSym->auxIdx].pltIdx;
17480eae32dcSDimitry Andric
1749bdd1243dSDimitry Andric if (flags & HAS_DIRECT_RELOC) {
17500eae32dcSDimitry Andric // Change the value to the IPLT and redirect all references to it.
17510eae32dcSDimitry Andric auto &d = cast<Defined>(sym);
175204eeddc0SDimitry Andric d.section = in.iplt.get();
175304eeddc0SDimitry Andric d.value = d.getPltIdx() * target->ipltEntrySize;
17540eae32dcSDimitry Andric d.size = 0;
17550eae32dcSDimitry Andric // It's important to set the symbol type here so that dynamic loaders
17560eae32dcSDimitry Andric // don't try to call the PLT as if it were an ifunc resolver.
17570eae32dcSDimitry Andric d.type = STT_FUNC;
17580eae32dcSDimitry Andric
1759bdd1243dSDimitry Andric if (flags & NEEDS_GOT)
17600eae32dcSDimitry Andric addGotEntry(sym);
1761bdd1243dSDimitry Andric } else if (flags & NEEDS_GOT) {
17620eae32dcSDimitry Andric // Redirect GOT accesses to point to the Igot.
17630eae32dcSDimitry Andric sym.gotInIgot = true;
17640eae32dcSDimitry Andric }
17650eae32dcSDimitry Andric return true;
17660eae32dcSDimitry Andric }
17670eae32dcSDimitry Andric
postScanRelocations()17680eae32dcSDimitry Andric void elf::postScanRelocations() {
17690eae32dcSDimitry Andric auto fn = [](Symbol &sym) {
1770bdd1243dSDimitry Andric auto flags = sym.flags.load(std::memory_order_relaxed);
1771bdd1243dSDimitry Andric if (handleNonPreemptibleIfunc(sym, flags))
17720eae32dcSDimitry Andric return;
17735f757f3fSDimitry Andric
17745f757f3fSDimitry Andric if (sym.isTagged() && sym.isDefined())
17751db9f3b2SDimitry Andric mainPart->memtagGlobalDescriptors->addSymbol(sym);
17765f757f3fSDimitry Andric
177704eeddc0SDimitry Andric if (!sym.needsDynReloc())
177804eeddc0SDimitry Andric return;
177904eeddc0SDimitry Andric sym.allocateAux();
178004eeddc0SDimitry Andric
1781bdd1243dSDimitry Andric if (flags & NEEDS_GOT)
17820eae32dcSDimitry Andric addGotEntry(sym);
1783bdd1243dSDimitry Andric if (flags & NEEDS_PLT)
17840eae32dcSDimitry Andric addPltEntry(*in.plt, *in.gotPlt, *in.relaPlt, target->pltRel, sym);
1785bdd1243dSDimitry Andric if (flags & NEEDS_COPY) {
17860eae32dcSDimitry Andric if (sym.isObject()) {
178781ad6265SDimitry Andric invokeELFT(addCopyRelSymbol, cast<SharedSymbol>(sym));
1788bdd1243dSDimitry Andric // NEEDS_COPY is cleared for sym and its aliases so that in
1789bdd1243dSDimitry Andric // later iterations aliases won't cause redundant copies.
1790bdd1243dSDimitry Andric assert(!sym.hasFlag(NEEDS_COPY));
17910eae32dcSDimitry Andric } else {
1792bdd1243dSDimitry Andric assert(sym.isFunc() && sym.hasFlag(NEEDS_PLT));
17930eae32dcSDimitry Andric if (!sym.isDefined()) {
179404eeddc0SDimitry Andric replaceWithDefined(sym, *in.plt,
179504eeddc0SDimitry Andric target->pltHeaderSize +
179604eeddc0SDimitry Andric target->pltEntrySize * sym.getPltIdx(),
179704eeddc0SDimitry Andric 0);
1798bdd1243dSDimitry Andric sym.setFlags(NEEDS_COPY);
17990eae32dcSDimitry Andric if (config->emachine == EM_PPC) {
18000eae32dcSDimitry Andric // PPC32 canonical PLT entries are at the beginning of .glink
18010eae32dcSDimitry Andric cast<Defined>(sym).value = in.plt->headerSize;
18020eae32dcSDimitry Andric in.plt->headerSize += 16;
18030eae32dcSDimitry Andric cast<PPC32GlinkSection>(*in.plt).canonical_plts.push_back(&sym);
18040eae32dcSDimitry Andric }
18050eae32dcSDimitry Andric }
18060eae32dcSDimitry Andric }
18070eae32dcSDimitry Andric }
18080eae32dcSDimitry Andric
18090eae32dcSDimitry Andric if (!sym.isTls())
18100eae32dcSDimitry Andric return;
18110eae32dcSDimitry Andric bool isLocalInExecutable = !sym.isPreemptible && !config->shared;
1812bdd1243dSDimitry Andric GotSection *got = in.got.get();
18130eae32dcSDimitry Andric
1814bdd1243dSDimitry Andric if (flags & NEEDS_TLSDESC) {
1815bdd1243dSDimitry Andric got->addTlsDescEntry(sym);
18160eae32dcSDimitry Andric mainPart->relaDyn->addAddendOnlyRelocIfNonPreemptible(
1817bdd1243dSDimitry Andric target->tlsDescRel, *got, got->getTlsDescOffset(sym), sym,
18180eae32dcSDimitry Andric target->tlsDescRel);
18190eae32dcSDimitry Andric }
1820bdd1243dSDimitry Andric if (flags & NEEDS_TLSGD) {
1821bdd1243dSDimitry Andric got->addDynTlsEntry(sym);
1822bdd1243dSDimitry Andric uint64_t off = got->getGlobalDynOffset(sym);
18230eae32dcSDimitry Andric if (isLocalInExecutable)
18240eae32dcSDimitry Andric // Write one to the GOT slot.
1825bdd1243dSDimitry Andric got->addConstant({R_ADDEND, target->symbolicRel, off, 1, &sym});
18260eae32dcSDimitry Andric else
1827bdd1243dSDimitry Andric mainPart->relaDyn->addSymbolReloc(target->tlsModuleIndexRel, *got, off,
1828bdd1243dSDimitry Andric sym);
18290eae32dcSDimitry Andric
18300eae32dcSDimitry Andric // If the symbol is preemptible we need the dynamic linker to write
18310eae32dcSDimitry Andric // the offset too.
18320eae32dcSDimitry Andric uint64_t offsetOff = off + config->wordsize;
18330eae32dcSDimitry Andric if (sym.isPreemptible)
1834bdd1243dSDimitry Andric mainPart->relaDyn->addSymbolReloc(target->tlsOffsetRel, *got, offsetOff,
1835bdd1243dSDimitry Andric sym);
18360eae32dcSDimitry Andric else
1837bdd1243dSDimitry Andric got->addConstant({R_ABS, target->tlsOffsetRel, offsetOff, 0, &sym});
18380eae32dcSDimitry Andric }
1839bdd1243dSDimitry Andric if (flags & NEEDS_TLSGD_TO_IE) {
1840bdd1243dSDimitry Andric got->addEntry(sym);
1841bdd1243dSDimitry Andric mainPart->relaDyn->addSymbolReloc(target->tlsGotRel, *got,
18420eae32dcSDimitry Andric sym.getGotOffset(), sym);
18430eae32dcSDimitry Andric }
1844bdd1243dSDimitry Andric if (flags & NEEDS_GOT_DTPREL) {
1845bdd1243dSDimitry Andric got->addEntry(sym);
1846bdd1243dSDimitry Andric got->addConstant(
18470eae32dcSDimitry Andric {R_ABS, target->tlsOffsetRel, sym.getGotOffset(), 0, &sym});
18480eae32dcSDimitry Andric }
18490eae32dcSDimitry Andric
1850bdd1243dSDimitry Andric if ((flags & NEEDS_TLSIE) && !(flags & NEEDS_TLSGD_TO_IE))
18510eae32dcSDimitry Andric addTpOffsetGotEntry(sym);
18520eae32dcSDimitry Andric };
185304eeddc0SDimitry Andric
1854bdd1243dSDimitry Andric GotSection *got = in.got.get();
1855bdd1243dSDimitry Andric if (ctx.needsTlsLd.load(std::memory_order_relaxed) && got->addTlsIndex()) {
18567a6dacacSDimitry Andric static Undefined dummy(ctx.internalFile, "", STB_LOCAL, 0, 0);
185781ad6265SDimitry Andric if (config->shared)
185881ad6265SDimitry Andric mainPart->relaDyn->addReloc(
1859bdd1243dSDimitry Andric {target->tlsModuleIndexRel, got, got->getTlsIndexOff()});
186081ad6265SDimitry Andric else
1861bdd1243dSDimitry Andric got->addConstant(
1862bdd1243dSDimitry Andric {R_ADDEND, target->symbolicRel, got->getTlsIndexOff(), 1, &dummy});
186381ad6265SDimitry Andric }
186481ad6265SDimitry Andric
1865bdd1243dSDimitry Andric assert(symAux.size() == 1);
1866bdd1243dSDimitry Andric for (Symbol *sym : symtab.getSymbols())
18670eae32dcSDimitry Andric fn(*sym);
18680eae32dcSDimitry Andric
18690eae32dcSDimitry Andric // Local symbols may need the aforementioned non-preemptible ifunc and GOT
18700eae32dcSDimitry Andric // handling. They don't need regular PLT.
1871bdd1243dSDimitry Andric for (ELFFileBase *file : ctx.objectFiles)
187204eeddc0SDimitry Andric for (Symbol *sym : file->getLocalSymbols())
18730eae32dcSDimitry Andric fn(*sym);
18740eae32dcSDimitry Andric }
18750eae32dcSDimitry Andric
mergeCmp(const InputSection * a,const InputSection * b)18760b57cec5SDimitry Andric static bool mergeCmp(const InputSection *a, const InputSection *b) {
18770b57cec5SDimitry Andric // std::merge requires a strict weak ordering.
18780b57cec5SDimitry Andric if (a->outSecOff < b->outSecOff)
18790b57cec5SDimitry Andric return true;
18800b57cec5SDimitry Andric
188161cfbce3SDimitry Andric // FIXME dyn_cast<ThunkSection> is non-null for any SyntheticSection.
188261cfbce3SDimitry Andric if (a->outSecOff == b->outSecOff && a != b) {
18830b57cec5SDimitry Andric auto *ta = dyn_cast<ThunkSection>(a);
18840b57cec5SDimitry Andric auto *tb = dyn_cast<ThunkSection>(b);
18850b57cec5SDimitry Andric
18860b57cec5SDimitry Andric // Check if Thunk is immediately before any specific Target
18870b57cec5SDimitry Andric // InputSection for example Mips LA25 Thunks.
18880b57cec5SDimitry Andric if (ta && ta->getTargetInputSection() == b)
18890b57cec5SDimitry Andric return true;
18900b57cec5SDimitry Andric
18910b57cec5SDimitry Andric // Place Thunk Sections without specific targets before
18920b57cec5SDimitry Andric // non-Thunk Sections.
18930b57cec5SDimitry Andric if (ta && !tb && !ta->getTargetInputSection())
18940b57cec5SDimitry Andric return true;
18950b57cec5SDimitry Andric }
18960b57cec5SDimitry Andric
18970b57cec5SDimitry Andric return false;
18980b57cec5SDimitry Andric }
18990b57cec5SDimitry Andric
19000b57cec5SDimitry Andric // Call Fn on every executable InputSection accessed via the linker script
19010b57cec5SDimitry Andric // InputSectionDescription::Sections.
forEachInputSectionDescription(ArrayRef<OutputSection * > outputSections,llvm::function_ref<void (OutputSection *,InputSectionDescription *)> fn)19020b57cec5SDimitry Andric static void forEachInputSectionDescription(
19030b57cec5SDimitry Andric ArrayRef<OutputSection *> outputSections,
19040b57cec5SDimitry Andric llvm::function_ref<void(OutputSection *, InputSectionDescription *)> fn) {
19050b57cec5SDimitry Andric for (OutputSection *os : outputSections) {
19060b57cec5SDimitry Andric if (!(os->flags & SHF_ALLOC) || !(os->flags & SHF_EXECINSTR))
19070b57cec5SDimitry Andric continue;
19084824e7fdSDimitry Andric for (SectionCommand *bc : os->commands)
19090b57cec5SDimitry Andric if (auto *isd = dyn_cast<InputSectionDescription>(bc))
19100b57cec5SDimitry Andric fn(os, isd);
19110b57cec5SDimitry Andric }
19120b57cec5SDimitry Andric }
19130b57cec5SDimitry Andric
19140b57cec5SDimitry Andric // Thunk Implementation
19150b57cec5SDimitry Andric //
19160b57cec5SDimitry Andric // Thunks (sometimes called stubs, veneers or branch islands) are small pieces
19170b57cec5SDimitry Andric // of code that the linker inserts inbetween a caller and a callee. The thunks
19180b57cec5SDimitry Andric // are added at link time rather than compile time as the decision on whether
19190b57cec5SDimitry Andric // a thunk is needed, such as the caller and callee being out of range, can only
19200b57cec5SDimitry Andric // be made at link time.
19210b57cec5SDimitry Andric //
19220b57cec5SDimitry Andric // It is straightforward to tell given the current state of the program when a
19230b57cec5SDimitry Andric // thunk is needed for a particular call. The more difficult part is that
19240b57cec5SDimitry Andric // the thunk needs to be placed in the program such that the caller can reach
19250b57cec5SDimitry Andric // the thunk and the thunk can reach the callee; furthermore, adding thunks to
19260b57cec5SDimitry Andric // the program alters addresses, which can mean more thunks etc.
19270b57cec5SDimitry Andric //
19280b57cec5SDimitry Andric // In lld we have a synthetic ThunkSection that can hold many Thunks.
19290b57cec5SDimitry Andric // The decision to have a ThunkSection act as a container means that we can
19300b57cec5SDimitry Andric // more easily handle the most common case of a single block of contiguous
19310b57cec5SDimitry Andric // Thunks by inserting just a single ThunkSection.
19320b57cec5SDimitry Andric //
19330b57cec5SDimitry Andric // The implementation of Thunks in lld is split across these areas
19340b57cec5SDimitry Andric // Relocations.cpp : Framework for creating and placing thunks
19350b57cec5SDimitry Andric // Thunks.cpp : The code generated for each supported thunk
19360b57cec5SDimitry Andric // Target.cpp : Target specific hooks that the framework uses to decide when
19370b57cec5SDimitry Andric // a thunk is used
19380b57cec5SDimitry Andric // Synthetic.cpp : Implementation of ThunkSection
19390b57cec5SDimitry Andric // Writer.cpp : Iteratively call framework until no more Thunks added
19400b57cec5SDimitry Andric //
19410b57cec5SDimitry Andric // Thunk placement requirements:
19420b57cec5SDimitry Andric // Mips LA25 thunks. These must be placed immediately before the callee section
19430b57cec5SDimitry Andric // We can assume that the caller is in range of the Thunk. These are modelled
19440b57cec5SDimitry Andric // by Thunks that return the section they must precede with
19450b57cec5SDimitry Andric // getTargetInputSection().
19460b57cec5SDimitry Andric //
19470b57cec5SDimitry Andric // ARM interworking and range extension thunks. These thunks must be placed
19480b57cec5SDimitry Andric // within range of the caller. All implemented ARM thunks can always reach the
19490b57cec5SDimitry Andric // callee as they use an indirect jump via a register that has no range
19500b57cec5SDimitry Andric // restrictions.
19510b57cec5SDimitry Andric //
19520b57cec5SDimitry Andric // Thunk placement algorithm:
19530b57cec5SDimitry Andric // For Mips LA25 ThunkSections; the placement is explicit, it has to be before
19540b57cec5SDimitry Andric // getTargetInputSection().
19550b57cec5SDimitry Andric //
19560b57cec5SDimitry Andric // For thunks that must be placed within range of the caller there are many
19570b57cec5SDimitry Andric // possible choices given that the maximum range from the caller is usually
19580b57cec5SDimitry Andric // much larger than the average InputSection size. Desirable properties include:
19590b57cec5SDimitry Andric // - Maximize reuse of thunks by multiple callers
19600b57cec5SDimitry Andric // - Minimize number of ThunkSections to simplify insertion
19610b57cec5SDimitry Andric // - Handle impact of already added Thunks on addresses
19620b57cec5SDimitry Andric // - Simple to understand and implement
19630b57cec5SDimitry Andric //
19640b57cec5SDimitry Andric // In lld for the first pass, we pre-create one or more ThunkSections per
19650b57cec5SDimitry Andric // InputSectionDescription at Target specific intervals. A ThunkSection is
19660b57cec5SDimitry Andric // placed so that the estimated end of the ThunkSection is within range of the
19670b57cec5SDimitry Andric // start of the InputSectionDescription or the previous ThunkSection. For
19680b57cec5SDimitry Andric // example:
19690b57cec5SDimitry Andric // InputSectionDescription
19700b57cec5SDimitry Andric // Section 0
19710b57cec5SDimitry Andric // ...
19720b57cec5SDimitry Andric // Section N
19730b57cec5SDimitry Andric // ThunkSection 0
19740b57cec5SDimitry Andric // Section N + 1
19750b57cec5SDimitry Andric // ...
19760b57cec5SDimitry Andric // Section N + K
19770b57cec5SDimitry Andric // Thunk Section 1
19780b57cec5SDimitry Andric //
19790b57cec5SDimitry Andric // The intention is that we can add a Thunk to a ThunkSection that is well
19800b57cec5SDimitry Andric // spaced enough to service a number of callers without having to do a lot
19810b57cec5SDimitry Andric // of work. An important principle is that it is not an error if a Thunk cannot
19820b57cec5SDimitry Andric // be placed in a pre-created ThunkSection; when this happens we create a new
19830b57cec5SDimitry Andric // ThunkSection placed next to the caller. This allows us to handle the vast
19840b57cec5SDimitry Andric // majority of thunks simply, but also handle rare cases where the branch range
19850b57cec5SDimitry Andric // is smaller than the target specific spacing.
19860b57cec5SDimitry Andric //
19870b57cec5SDimitry Andric // The algorithm is expected to create all the thunks that are needed in a
19880b57cec5SDimitry Andric // single pass, with a small number of programs needing a second pass due to
19890b57cec5SDimitry Andric // the insertion of thunks in the first pass increasing the offset between
19900b57cec5SDimitry Andric // callers and callees that were only just in range.
19910b57cec5SDimitry Andric //
19920b57cec5SDimitry Andric // A consequence of allowing new ThunkSections to be created outside of the
19930b57cec5SDimitry Andric // pre-created ThunkSections is that in rare cases calls to Thunks that were in
19940b57cec5SDimitry Andric // range in pass K, are out of range in some pass > K due to the insertion of
19950b57cec5SDimitry Andric // more Thunks in between the caller and callee. When this happens we retarget
19960b57cec5SDimitry Andric // the relocation back to the original target and create another Thunk.
19970b57cec5SDimitry Andric
19980b57cec5SDimitry Andric // Remove ThunkSections that are empty, this should only be the initial set
19990b57cec5SDimitry Andric // precreated on pass 0.
20000b57cec5SDimitry Andric
20010b57cec5SDimitry Andric // Insert the Thunks for OutputSection OS into their designated place
20020b57cec5SDimitry Andric // in the Sections vector, and recalculate the InputSection output section
20030b57cec5SDimitry Andric // offsets.
20040b57cec5SDimitry Andric // This may invalidate any output section offsets stored outside of InputSection
mergeThunks(ArrayRef<OutputSection * > outputSections)20050b57cec5SDimitry Andric void ThunkCreator::mergeThunks(ArrayRef<OutputSection *> outputSections) {
20060b57cec5SDimitry Andric forEachInputSectionDescription(
20070b57cec5SDimitry Andric outputSections, [&](OutputSection *os, InputSectionDescription *isd) {
20080b57cec5SDimitry Andric if (isd->thunkSections.empty())
20090b57cec5SDimitry Andric return;
20100b57cec5SDimitry Andric
20110b57cec5SDimitry Andric // Remove any zero sized precreated Thunks.
20120b57cec5SDimitry Andric llvm::erase_if(isd->thunkSections,
20130b57cec5SDimitry Andric [](const std::pair<ThunkSection *, uint32_t> &ts) {
20140b57cec5SDimitry Andric return ts.first->getSize() == 0;
20150b57cec5SDimitry Andric });
20160b57cec5SDimitry Andric
20170b57cec5SDimitry Andric // ISD->ThunkSections contains all created ThunkSections, including
20180b57cec5SDimitry Andric // those inserted in previous passes. Extract the Thunks created this
20190b57cec5SDimitry Andric // pass and order them in ascending outSecOff.
20200b57cec5SDimitry Andric std::vector<ThunkSection *> newThunks;
2021480093f4SDimitry Andric for (std::pair<ThunkSection *, uint32_t> ts : isd->thunkSections)
20220b57cec5SDimitry Andric if (ts.second == pass)
20230b57cec5SDimitry Andric newThunks.push_back(ts.first);
20240b57cec5SDimitry Andric llvm::stable_sort(newThunks,
20250b57cec5SDimitry Andric [](const ThunkSection *a, const ThunkSection *b) {
20260b57cec5SDimitry Andric return a->outSecOff < b->outSecOff;
20270b57cec5SDimitry Andric });
20280b57cec5SDimitry Andric
20290b57cec5SDimitry Andric // Merge sorted vectors of Thunks and InputSections by outSecOff
203004eeddc0SDimitry Andric SmallVector<InputSection *, 0> tmp;
20310b57cec5SDimitry Andric tmp.reserve(isd->sections.size() + newThunks.size());
20320b57cec5SDimitry Andric
20330b57cec5SDimitry Andric std::merge(isd->sections.begin(), isd->sections.end(),
20340b57cec5SDimitry Andric newThunks.begin(), newThunks.end(), std::back_inserter(tmp),
20350b57cec5SDimitry Andric mergeCmp);
20360b57cec5SDimitry Andric
20370b57cec5SDimitry Andric isd->sections = std::move(tmp);
20380b57cec5SDimitry Andric });
20390b57cec5SDimitry Andric }
20400b57cec5SDimitry Andric
getPCBias(RelType type)204181ad6265SDimitry Andric static int64_t getPCBias(RelType type) {
204281ad6265SDimitry Andric if (config->emachine != EM_ARM)
204381ad6265SDimitry Andric return 0;
204481ad6265SDimitry Andric switch (type) {
204581ad6265SDimitry Andric case R_ARM_THM_JUMP19:
204681ad6265SDimitry Andric case R_ARM_THM_JUMP24:
204781ad6265SDimitry Andric case R_ARM_THM_CALL:
204881ad6265SDimitry Andric return 4;
204981ad6265SDimitry Andric default:
205081ad6265SDimitry Andric return 8;
205181ad6265SDimitry Andric }
205281ad6265SDimitry Andric }
205381ad6265SDimitry Andric
20540b57cec5SDimitry Andric // Find or create a ThunkSection within the InputSectionDescription (ISD) that
20550b57cec5SDimitry Andric // is in range of Src. An ISD maps to a range of InputSections described by a
20560b57cec5SDimitry Andric // linker script section pattern such as { .text .text.* }.
getISDThunkSec(OutputSection * os,InputSection * isec,InputSectionDescription * isd,const Relocation & rel,uint64_t src)2057fe6060f1SDimitry Andric ThunkSection *ThunkCreator::getISDThunkSec(OutputSection *os,
2058fe6060f1SDimitry Andric InputSection *isec,
20590b57cec5SDimitry Andric InputSectionDescription *isd,
2060fe6060f1SDimitry Andric const Relocation &rel,
2061fe6060f1SDimitry Andric uint64_t src) {
206281ad6265SDimitry Andric // See the comment in getThunk for -pcBias below.
206381ad6265SDimitry Andric const int64_t pcBias = getPCBias(rel.type);
20640b57cec5SDimitry Andric for (std::pair<ThunkSection *, uint32_t> tp : isd->thunkSections) {
20650b57cec5SDimitry Andric ThunkSection *ts = tp.first;
206681ad6265SDimitry Andric uint64_t tsBase = os->addr + ts->outSecOff - pcBias;
206781ad6265SDimitry Andric uint64_t tsLimit = tsBase + ts->getSize();
2068fe6060f1SDimitry Andric if (target->inBranchRange(rel.type, src,
2069fe6060f1SDimitry Andric (src > tsLimit) ? tsBase : tsLimit))
20700b57cec5SDimitry Andric return ts;
20710b57cec5SDimitry Andric }
20720b57cec5SDimitry Andric
20730b57cec5SDimitry Andric // No suitable ThunkSection exists. This can happen when there is a branch
20740b57cec5SDimitry Andric // with lower range than the ThunkSection spacing or when there are too
20750b57cec5SDimitry Andric // many Thunks. Create a new ThunkSection as close to the InputSection as
20760b57cec5SDimitry Andric // possible. Error if InputSection is so large we cannot place ThunkSection
20770b57cec5SDimitry Andric // anywhere in Range.
20780b57cec5SDimitry Andric uint64_t thunkSecOff = isec->outSecOff;
2079fe6060f1SDimitry Andric if (!target->inBranchRange(rel.type, src,
2080fe6060f1SDimitry Andric os->addr + thunkSecOff + rel.addend)) {
20810b57cec5SDimitry Andric thunkSecOff = isec->outSecOff + isec->getSize();
2082fe6060f1SDimitry Andric if (!target->inBranchRange(rel.type, src,
2083fe6060f1SDimitry Andric os->addr + thunkSecOff + rel.addend))
20840b57cec5SDimitry Andric fatal("InputSection too large for range extension thunk " +
20850b57cec5SDimitry Andric isec->getObjMsg(src - (os->addr + isec->outSecOff)));
20860b57cec5SDimitry Andric }
20870b57cec5SDimitry Andric return addThunkSection(os, isd, thunkSecOff);
20880b57cec5SDimitry Andric }
20890b57cec5SDimitry Andric
20900b57cec5SDimitry Andric // Add a Thunk that needs to be placed in a ThunkSection that immediately
20910b57cec5SDimitry Andric // precedes its Target.
getISThunkSec(InputSection * isec)20920b57cec5SDimitry Andric ThunkSection *ThunkCreator::getISThunkSec(InputSection *isec) {
20930b57cec5SDimitry Andric ThunkSection *ts = thunkedSections.lookup(isec);
20940b57cec5SDimitry Andric if (ts)
20950b57cec5SDimitry Andric return ts;
20960b57cec5SDimitry Andric
20970b57cec5SDimitry Andric // Find InputSectionRange within Target Output Section (TOS) that the
20980b57cec5SDimitry Andric // InputSection (IS) that we need to precede is in.
20990b57cec5SDimitry Andric OutputSection *tos = isec->getParent();
21004824e7fdSDimitry Andric for (SectionCommand *bc : tos->commands) {
21010b57cec5SDimitry Andric auto *isd = dyn_cast<InputSectionDescription>(bc);
21020b57cec5SDimitry Andric if (!isd || isd->sections.empty())
21030b57cec5SDimitry Andric continue;
21040b57cec5SDimitry Andric
21050b57cec5SDimitry Andric InputSection *first = isd->sections.front();
21060b57cec5SDimitry Andric InputSection *last = isd->sections.back();
21070b57cec5SDimitry Andric
21080b57cec5SDimitry Andric if (isec->outSecOff < first->outSecOff || last->outSecOff < isec->outSecOff)
21090b57cec5SDimitry Andric continue;
21100b57cec5SDimitry Andric
21110b57cec5SDimitry Andric ts = addThunkSection(tos, isd, isec->outSecOff);
21120b57cec5SDimitry Andric thunkedSections[isec] = ts;
21130b57cec5SDimitry Andric return ts;
21140b57cec5SDimitry Andric }
21150b57cec5SDimitry Andric
21160b57cec5SDimitry Andric return nullptr;
21170b57cec5SDimitry Andric }
21180b57cec5SDimitry Andric
21190b57cec5SDimitry Andric // Create one or more ThunkSections per OS that can be used to place Thunks.
21200b57cec5SDimitry Andric // We attempt to place the ThunkSections using the following desirable
21210b57cec5SDimitry Andric // properties:
21220b57cec5SDimitry Andric // - Within range of the maximum number of callers
21230b57cec5SDimitry Andric // - Minimise the number of ThunkSections
21240b57cec5SDimitry Andric //
21250b57cec5SDimitry Andric // We follow a simple but conservative heuristic to place ThunkSections at
21260b57cec5SDimitry Andric // offsets that are multiples of a Target specific branch range.
21270b57cec5SDimitry Andric // For an InputSectionDescription that is smaller than the range, a single
21280b57cec5SDimitry Andric // ThunkSection at the end of the range will do.
21290b57cec5SDimitry Andric //
21300b57cec5SDimitry Andric // For an InputSectionDescription that is more than twice the size of the range,
21310b57cec5SDimitry Andric // we place the last ThunkSection at range bytes from the end of the
21320b57cec5SDimitry Andric // InputSectionDescription in order to increase the likelihood that the
21330b57cec5SDimitry Andric // distance from a thunk to its target will be sufficiently small to
21340b57cec5SDimitry Andric // allow for the creation of a short thunk.
createInitialThunkSections(ArrayRef<OutputSection * > outputSections)21350b57cec5SDimitry Andric void ThunkCreator::createInitialThunkSections(
21360b57cec5SDimitry Andric ArrayRef<OutputSection *> outputSections) {
21370b57cec5SDimitry Andric uint32_t thunkSectionSpacing = target->getThunkSectionSpacing();
21380b57cec5SDimitry Andric
21390b57cec5SDimitry Andric forEachInputSectionDescription(
21400b57cec5SDimitry Andric outputSections, [&](OutputSection *os, InputSectionDescription *isd) {
21410b57cec5SDimitry Andric if (isd->sections.empty())
21420b57cec5SDimitry Andric return;
21430b57cec5SDimitry Andric
21440b57cec5SDimitry Andric uint32_t isdBegin = isd->sections.front()->outSecOff;
21450b57cec5SDimitry Andric uint32_t isdEnd =
21460b57cec5SDimitry Andric isd->sections.back()->outSecOff + isd->sections.back()->getSize();
21470b57cec5SDimitry Andric uint32_t lastThunkLowerBound = -1;
21480b57cec5SDimitry Andric if (isdEnd - isdBegin > thunkSectionSpacing * 2)
21490b57cec5SDimitry Andric lastThunkLowerBound = isdEnd - thunkSectionSpacing;
21500b57cec5SDimitry Andric
21510b57cec5SDimitry Andric uint32_t isecLimit;
21520b57cec5SDimitry Andric uint32_t prevIsecLimit = isdBegin;
21530b57cec5SDimitry Andric uint32_t thunkUpperBound = isdBegin + thunkSectionSpacing;
21540b57cec5SDimitry Andric
21550b57cec5SDimitry Andric for (const InputSection *isec : isd->sections) {
21560b57cec5SDimitry Andric isecLimit = isec->outSecOff + isec->getSize();
21570b57cec5SDimitry Andric if (isecLimit > thunkUpperBound) {
21580b57cec5SDimitry Andric addThunkSection(os, isd, prevIsecLimit);
21590b57cec5SDimitry Andric thunkUpperBound = prevIsecLimit + thunkSectionSpacing;
21600b57cec5SDimitry Andric }
21610b57cec5SDimitry Andric if (isecLimit > lastThunkLowerBound)
21620b57cec5SDimitry Andric break;
21630b57cec5SDimitry Andric prevIsecLimit = isecLimit;
21640b57cec5SDimitry Andric }
21650b57cec5SDimitry Andric addThunkSection(os, isd, isecLimit);
21660b57cec5SDimitry Andric });
21670b57cec5SDimitry Andric }
21680b57cec5SDimitry Andric
addThunkSection(OutputSection * os,InputSectionDescription * isd,uint64_t off)21690b57cec5SDimitry Andric ThunkSection *ThunkCreator::addThunkSection(OutputSection *os,
21700b57cec5SDimitry Andric InputSectionDescription *isd,
21710b57cec5SDimitry Andric uint64_t off) {
21720b57cec5SDimitry Andric auto *ts = make<ThunkSection>(os, off);
21730b57cec5SDimitry Andric ts->partition = os->partition;
217413138422SDimitry Andric if ((config->fixCortexA53Errata843419 || config->fixCortexA8) &&
217513138422SDimitry Andric !isd->sections.empty()) {
217613138422SDimitry Andric // The errata fixes are sensitive to addresses modulo 4 KiB. When we add
217713138422SDimitry Andric // thunks we disturb the base addresses of sections placed after the thunks
217813138422SDimitry Andric // this makes patches we have generated redundant, and may cause us to
217913138422SDimitry Andric // generate more patches as different instructions are now in sensitive
218013138422SDimitry Andric // locations. When we generate more patches we may force more branches to
218113138422SDimitry Andric // go out of range, causing more thunks to be generated. In pathological
218213138422SDimitry Andric // cases this can cause the address dependent content pass not to converge.
218313138422SDimitry Andric // We fix this by rounding up the size of the ThunkSection to 4KiB, this
218413138422SDimitry Andric // limits the insertion of a ThunkSection on the addresses modulo 4 KiB,
218513138422SDimitry Andric // which means that adding Thunks to the section does not invalidate
218613138422SDimitry Andric // errata patches for following code.
218713138422SDimitry Andric // Rounding up the size to 4KiB has consequences for code-size and can
218813138422SDimitry Andric // trip up linker script defined assertions. For example the linux kernel
218913138422SDimitry Andric // has an assertion that what LLD represents as an InputSectionDescription
219013138422SDimitry Andric // does not exceed 4 KiB even if the overall OutputSection is > 128 Mib.
219113138422SDimitry Andric // We use the heuristic of rounding up the size when both of the following
219213138422SDimitry Andric // conditions are true:
219313138422SDimitry Andric // 1.) The OutputSection is larger than the ThunkSectionSpacing. This
219413138422SDimitry Andric // accounts for the case where no single InputSectionDescription is
219513138422SDimitry Andric // larger than the OutputSection size. This is conservative but simple.
219613138422SDimitry Andric // 2.) The InputSectionDescription is larger than 4 KiB. This will prevent
219713138422SDimitry Andric // any assertion failures that an InputSectionDescription is < 4 KiB
219813138422SDimitry Andric // in size.
219913138422SDimitry Andric uint64_t isdSize = isd->sections.back()->outSecOff +
220013138422SDimitry Andric isd->sections.back()->getSize() -
220113138422SDimitry Andric isd->sections.front()->outSecOff;
220213138422SDimitry Andric if (os->size > target->getThunkSectionSpacing() && isdSize > 4096)
220313138422SDimitry Andric ts->roundUpSizeForErrata = true;
220413138422SDimitry Andric }
22050b57cec5SDimitry Andric isd->thunkSections.push_back({ts, pass});
22060b57cec5SDimitry Andric return ts;
22070b57cec5SDimitry Andric }
22080b57cec5SDimitry Andric
isThunkSectionCompatible(InputSection * source,SectionBase * target)22090b57cec5SDimitry Andric static bool isThunkSectionCompatible(InputSection *source,
22100b57cec5SDimitry Andric SectionBase *target) {
22110b57cec5SDimitry Andric // We can't reuse thunks in different loadable partitions because they might
22120b57cec5SDimitry Andric // not be loaded. But partition 1 (the main partition) will always be loaded.
22130b57cec5SDimitry Andric if (source->partition != target->partition)
22140b57cec5SDimitry Andric return target->partition == 1;
22150b57cec5SDimitry Andric return true;
22160b57cec5SDimitry Andric }
22170b57cec5SDimitry Andric
getThunk(InputSection * isec,Relocation & rel,uint64_t src)22180b57cec5SDimitry Andric std::pair<Thunk *, bool> ThunkCreator::getThunk(InputSection *isec,
22190b57cec5SDimitry Andric Relocation &rel, uint64_t src) {
22200b57cec5SDimitry Andric std::vector<Thunk *> *thunkVec = nullptr;
2221fe6060f1SDimitry Andric // Arm and Thumb have a PC Bias of 8 and 4 respectively, this is cancelled
2222fe6060f1SDimitry Andric // out in the relocation addend. We compensate for the PC bias so that
2223fe6060f1SDimitry Andric // an Arm and Thumb relocation to the same destination get the same keyAddend,
2224fe6060f1SDimitry Andric // which is usually 0.
22259b597132SPiotr Kubaj const int64_t pcBias = getPCBias(rel.type);
22269b597132SPiotr Kubaj const int64_t keyAddend = rel.addend + pcBias;
22270b57cec5SDimitry Andric
2228480093f4SDimitry Andric // We use a ((section, offset), addend) pair to find the thunk position if
2229480093f4SDimitry Andric // possible so that we create only one thunk for aliased symbols or ICFed
2230480093f4SDimitry Andric // sections. There may be multiple relocations sharing the same (section,
2231480093f4SDimitry Andric // offset + addend) pair. We may revert the relocation back to its original
2232480093f4SDimitry Andric // non-Thunk target, so we cannot fold offset + addend.
22330b57cec5SDimitry Andric if (auto *d = dyn_cast<Defined>(rel.sym))
22340b57cec5SDimitry Andric if (!d->isInPlt() && d->section)
22350eae32dcSDimitry Andric thunkVec = &thunkedSymbolsBySectionAndAddend[{{d->section, d->value},
22360eae32dcSDimitry Andric keyAddend}];
22370b57cec5SDimitry Andric if (!thunkVec)
2238fe6060f1SDimitry Andric thunkVec = &thunkedSymbols[{rel.sym, keyAddend}];
22390b57cec5SDimitry Andric
22400b57cec5SDimitry Andric // Check existing Thunks for Sym to see if they can be reused
22410b57cec5SDimitry Andric for (Thunk *t : *thunkVec)
22420b57cec5SDimitry Andric if (isThunkSectionCompatible(isec, t->getThunkTargetSym()->section) &&
22430b57cec5SDimitry Andric t->isCompatibleWith(*isec, rel) &&
2244480093f4SDimitry Andric target->inBranchRange(rel.type, src,
22459b597132SPiotr Kubaj t->getThunkTargetSym()->getVA(-pcBias)))
22460b57cec5SDimitry Andric return std::make_pair(t, false);
22470b57cec5SDimitry Andric
22480b57cec5SDimitry Andric // No existing compatible Thunk in range, create a new one
22490b57cec5SDimitry Andric Thunk *t = addThunk(*isec, rel);
22500b57cec5SDimitry Andric thunkVec->push_back(t);
22510b57cec5SDimitry Andric return std::make_pair(t, true);
22520b57cec5SDimitry Andric }
22530b57cec5SDimitry Andric
22540b57cec5SDimitry Andric // Return true if the relocation target is an in range Thunk.
22550b57cec5SDimitry Andric // Return false if the relocation is not to a Thunk. If the relocation target
22560b57cec5SDimitry Andric // was originally to a Thunk, but is no longer in range we revert the
22570b57cec5SDimitry Andric // relocation back to its original non-Thunk target.
normalizeExistingThunk(Relocation & rel,uint64_t src)22580b57cec5SDimitry Andric bool ThunkCreator::normalizeExistingThunk(Relocation &rel, uint64_t src) {
22590b57cec5SDimitry Andric if (Thunk *t = thunks.lookup(rel.sym)) {
2260fe6060f1SDimitry Andric if (target->inBranchRange(rel.type, src, rel.sym->getVA(rel.addend)))
22610b57cec5SDimitry Andric return true;
22620b57cec5SDimitry Andric rel.sym = &t->destination;
2263480093f4SDimitry Andric rel.addend = t->addend;
22640b57cec5SDimitry Andric if (rel.sym->isInPlt())
22650b57cec5SDimitry Andric rel.expr = toPlt(rel.expr);
22660b57cec5SDimitry Andric }
22670b57cec5SDimitry Andric return false;
22680b57cec5SDimitry Andric }
22690b57cec5SDimitry Andric
22700b57cec5SDimitry Andric // Process all relocations from the InputSections that have been assigned
22710b57cec5SDimitry Andric // to InputSectionDescriptions and redirect through Thunks if needed. The
22720b57cec5SDimitry Andric // function should be called iteratively until it returns false.
22730b57cec5SDimitry Andric //
22740b57cec5SDimitry Andric // PreConditions:
22750b57cec5SDimitry Andric // All InputSections that may need a Thunk are reachable from
22760b57cec5SDimitry Andric // OutputSectionCommands.
22770b57cec5SDimitry Andric //
22780b57cec5SDimitry Andric // All OutputSections have an address and all InputSections have an offset
22790b57cec5SDimitry Andric // within the OutputSection.
22800b57cec5SDimitry Andric //
22810b57cec5SDimitry Andric // The offsets between caller (relocation place) and callee
22820b57cec5SDimitry Andric // (relocation target) will not be modified outside of createThunks().
22830b57cec5SDimitry Andric //
22840b57cec5SDimitry Andric // PostConditions:
22850b57cec5SDimitry Andric // If return value is true then ThunkSections have been inserted into
22860b57cec5SDimitry Andric // OutputSections. All relocations that needed a Thunk based on the information
22870b57cec5SDimitry Andric // available to createThunks() on entry have been redirected to a Thunk. Note
22880b57cec5SDimitry Andric // that adding Thunks changes offsets between caller and callee so more Thunks
22890b57cec5SDimitry Andric // may be required.
22900b57cec5SDimitry Andric //
22910b57cec5SDimitry Andric // If return value is false then no more Thunks are needed, and createThunks has
22920b57cec5SDimitry Andric // made no changes. If the target requires range extension thunks, currently
22930b57cec5SDimitry Andric // ARM, then any future change in offset between caller and callee risks a
22940b57cec5SDimitry Andric // relocation out of range error.
createThunks(uint32_t pass,ArrayRef<OutputSection * > outputSections)2295753f127fSDimitry Andric bool ThunkCreator::createThunks(uint32_t pass,
2296753f127fSDimitry Andric ArrayRef<OutputSection *> outputSections) {
2297753f127fSDimitry Andric this->pass = pass;
22980b57cec5SDimitry Andric bool addressesChanged = false;
22990b57cec5SDimitry Andric
23000b57cec5SDimitry Andric if (pass == 0 && target->getThunkSectionSpacing())
23010b57cec5SDimitry Andric createInitialThunkSections(outputSections);
23020b57cec5SDimitry Andric
23030b57cec5SDimitry Andric // Create all the Thunks and insert them into synthetic ThunkSections. The
23040b57cec5SDimitry Andric // ThunkSections are later inserted back into InputSectionDescriptions.
23050b57cec5SDimitry Andric // We separate the creation of ThunkSections from the insertion of the
23060b57cec5SDimitry Andric // ThunkSections as ThunkSections are not always inserted into the same
23070b57cec5SDimitry Andric // InputSectionDescription as the caller.
23080b57cec5SDimitry Andric forEachInputSectionDescription(
23090b57cec5SDimitry Andric outputSections, [&](OutputSection *os, InputSectionDescription *isd) {
23100b57cec5SDimitry Andric for (InputSection *isec : isd->sections)
2311bdd1243dSDimitry Andric for (Relocation &rel : isec->relocs()) {
23120b57cec5SDimitry Andric uint64_t src = isec->getVA(rel.offset);
23130b57cec5SDimitry Andric
23140b57cec5SDimitry Andric // If we are a relocation to an existing Thunk, check if it is
23150b57cec5SDimitry Andric // still in range. If not then Rel will be altered to point to its
23160b57cec5SDimitry Andric // original target so another Thunk can be generated.
23170b57cec5SDimitry Andric if (pass > 0 && normalizeExistingThunk(rel, src))
23180b57cec5SDimitry Andric continue;
23190b57cec5SDimitry Andric
23200b57cec5SDimitry Andric if (!target->needsThunk(rel.expr, rel.type, isec->file, src,
2321480093f4SDimitry Andric *rel.sym, rel.addend))
23220b57cec5SDimitry Andric continue;
23230b57cec5SDimitry Andric
23240b57cec5SDimitry Andric Thunk *t;
23250b57cec5SDimitry Andric bool isNew;
23260b57cec5SDimitry Andric std::tie(t, isNew) = getThunk(isec, rel, src);
23270b57cec5SDimitry Andric
23280b57cec5SDimitry Andric if (isNew) {
23290b57cec5SDimitry Andric // Find or create a ThunkSection for the new Thunk
23300b57cec5SDimitry Andric ThunkSection *ts;
23310b57cec5SDimitry Andric if (auto *tis = t->getTargetInputSection())
23320b57cec5SDimitry Andric ts = getISThunkSec(tis);
23330b57cec5SDimitry Andric else
2334fe6060f1SDimitry Andric ts = getISDThunkSec(os, isec, isd, rel, src);
23350b57cec5SDimitry Andric ts->addThunk(t);
23360b57cec5SDimitry Andric thunks[t->getThunkTargetSym()] = t;
23370b57cec5SDimitry Andric }
23380b57cec5SDimitry Andric
23390b57cec5SDimitry Andric // Redirect relocation to Thunk, we never go via the PLT to a Thunk
23400b57cec5SDimitry Andric rel.sym = t->getThunkTargetSym();
23410b57cec5SDimitry Andric rel.expr = fromPlt(rel.expr);
23420b57cec5SDimitry Andric
234313138422SDimitry Andric // On AArch64 and PPC, a jump/call relocation may be encoded as
2344480093f4SDimitry Andric // STT_SECTION + non-zero addend, clear the addend after
2345480093f4SDimitry Andric // redirection.
234613138422SDimitry Andric if (config->emachine != EM_MIPS)
234713138422SDimitry Andric rel.addend = -getPCBias(rel.type);
23480b57cec5SDimitry Andric }
23490b57cec5SDimitry Andric
23500b57cec5SDimitry Andric for (auto &p : isd->thunkSections)
23510b57cec5SDimitry Andric addressesChanged |= p.first->assignOffsets();
23520b57cec5SDimitry Andric });
23530b57cec5SDimitry Andric
23540b57cec5SDimitry Andric for (auto &p : thunkedSections)
23550b57cec5SDimitry Andric addressesChanged |= p.second->assignOffsets();
23560b57cec5SDimitry Andric
23570b57cec5SDimitry Andric // Merge all created synthetic ThunkSections back into OutputSection
23580b57cec5SDimitry Andric mergeThunks(outputSections);
23590b57cec5SDimitry Andric return addressesChanged;
23600b57cec5SDimitry Andric }
23610b57cec5SDimitry Andric
23625ffd83dbSDimitry Andric // The following aid in the conversion of call x@GDPLT to call __tls_get_addr
23635ffd83dbSDimitry Andric // hexagonNeedsTLSSymbol scans for relocations would require a call to
23645ffd83dbSDimitry Andric // __tls_get_addr.
23655ffd83dbSDimitry Andric // hexagonTLSSymbolUpdate rebinds the relocation to __tls_get_addr.
hexagonNeedsTLSSymbol(ArrayRef<OutputSection * > outputSections)23665ffd83dbSDimitry Andric bool elf::hexagonNeedsTLSSymbol(ArrayRef<OutputSection *> outputSections) {
23675ffd83dbSDimitry Andric bool needTlsSymbol = false;
23685ffd83dbSDimitry Andric forEachInputSectionDescription(
23695ffd83dbSDimitry Andric outputSections, [&](OutputSection *os, InputSectionDescription *isd) {
23705ffd83dbSDimitry Andric for (InputSection *isec : isd->sections)
2371bdd1243dSDimitry Andric for (Relocation &rel : isec->relocs())
23725ffd83dbSDimitry Andric if (rel.sym->type == llvm::ELF::STT_TLS && rel.expr == R_PLT_PC) {
23735ffd83dbSDimitry Andric needTlsSymbol = true;
23745ffd83dbSDimitry Andric return;
23755ffd83dbSDimitry Andric }
23765ffd83dbSDimitry Andric });
23775ffd83dbSDimitry Andric return needTlsSymbol;
23785ffd83dbSDimitry Andric }
237985868e8aSDimitry Andric
hexagonTLSSymbolUpdate(ArrayRef<OutputSection * > outputSections)23805ffd83dbSDimitry Andric void elf::hexagonTLSSymbolUpdate(ArrayRef<OutputSection *> outputSections) {
2381bdd1243dSDimitry Andric Symbol *sym = symtab.find("__tls_get_addr");
23825ffd83dbSDimitry Andric if (!sym)
23835ffd83dbSDimitry Andric return;
23845ffd83dbSDimitry Andric bool needEntry = true;
23855ffd83dbSDimitry Andric forEachInputSectionDescription(
23865ffd83dbSDimitry Andric outputSections, [&](OutputSection *os, InputSectionDescription *isd) {
23875ffd83dbSDimitry Andric for (InputSection *isec : isd->sections)
2388bdd1243dSDimitry Andric for (Relocation &rel : isec->relocs())
23895ffd83dbSDimitry Andric if (rel.sym->type == llvm::ELF::STT_TLS && rel.expr == R_PLT_PC) {
23905ffd83dbSDimitry Andric if (needEntry) {
239104eeddc0SDimitry Andric sym->allocateAux();
23920eae32dcSDimitry Andric addPltEntry(*in.plt, *in.gotPlt, *in.relaPlt, target->pltRel,
23935ffd83dbSDimitry Andric *sym);
23945ffd83dbSDimitry Andric needEntry = false;
23955ffd83dbSDimitry Andric }
23965ffd83dbSDimitry Andric rel.sym = sym;
23975ffd83dbSDimitry Andric }
23985ffd83dbSDimitry Andric });
23995ffd83dbSDimitry Andric }
24005ffd83dbSDimitry Andric
matchesRefTo(const NoCrossRefCommand & cmd,StringRef osec)24010fca6ea1SDimitry Andric static bool matchesRefTo(const NoCrossRefCommand &cmd, StringRef osec) {
24020fca6ea1SDimitry Andric if (cmd.toFirst)
24030fca6ea1SDimitry Andric return cmd.outputSections[0] == osec;
24040fca6ea1SDimitry Andric return llvm::is_contained(cmd.outputSections, osec);
24050fca6ea1SDimitry Andric }
24060fca6ea1SDimitry Andric
24070fca6ea1SDimitry Andric template <class ELFT, class Rels>
scanCrossRefs(const NoCrossRefCommand & cmd,OutputSection * osec,InputSection * sec,Rels rels)24080fca6ea1SDimitry Andric static void scanCrossRefs(const NoCrossRefCommand &cmd, OutputSection *osec,
24090fca6ea1SDimitry Andric InputSection *sec, Rels rels) {
24100fca6ea1SDimitry Andric for (const auto &r : rels) {
24110fca6ea1SDimitry Andric Symbol &sym = sec->file->getSymbol(r.getSymbol(config->isMips64EL));
24120fca6ea1SDimitry Andric // A legal cross-reference is when the destination output section is
24130fca6ea1SDimitry Andric // nullptr, osec for a self-reference, or a section that is described by the
24140fca6ea1SDimitry Andric // NOCROSSREFS/NOCROSSREFS_TO command.
24150fca6ea1SDimitry Andric auto *dstOsec = sym.getOutputSection();
24160fca6ea1SDimitry Andric if (!dstOsec || dstOsec == osec || !matchesRefTo(cmd, dstOsec->name))
24170fca6ea1SDimitry Andric continue;
24180fca6ea1SDimitry Andric
24190fca6ea1SDimitry Andric std::string toSymName;
24200fca6ea1SDimitry Andric if (!sym.isSection())
24210fca6ea1SDimitry Andric toSymName = toString(sym);
24220fca6ea1SDimitry Andric else if (auto *d = dyn_cast<Defined>(&sym))
24230fca6ea1SDimitry Andric toSymName = d->section->name;
24240fca6ea1SDimitry Andric errorOrWarn(sec->getLocation(r.r_offset) +
24250fca6ea1SDimitry Andric ": prohibited cross reference from '" + osec->name + "' to '" +
24260fca6ea1SDimitry Andric toSymName + "' in '" + dstOsec->name + "'");
24270fca6ea1SDimitry Andric }
24280fca6ea1SDimitry Andric }
24290fca6ea1SDimitry Andric
24300fca6ea1SDimitry Andric // For each output section described by at least one NOCROSSREFS(_TO) command,
24310fca6ea1SDimitry Andric // scan relocations from its input sections for prohibited cross references.
checkNoCrossRefs()24320fca6ea1SDimitry Andric template <class ELFT> void elf::checkNoCrossRefs() {
24330fca6ea1SDimitry Andric for (OutputSection *osec : outputSections) {
24340fca6ea1SDimitry Andric for (const NoCrossRefCommand &noxref : script->noCrossRefs) {
24350fca6ea1SDimitry Andric if (!llvm::is_contained(noxref.outputSections, osec->name) ||
24360fca6ea1SDimitry Andric (noxref.toFirst && noxref.outputSections[0] == osec->name))
24370fca6ea1SDimitry Andric continue;
24380fca6ea1SDimitry Andric for (SectionCommand *cmd : osec->commands) {
24390fca6ea1SDimitry Andric auto *isd = dyn_cast<InputSectionDescription>(cmd);
24400fca6ea1SDimitry Andric if (!isd)
24410fca6ea1SDimitry Andric continue;
24420fca6ea1SDimitry Andric parallelForEach(isd->sections, [&](InputSection *sec) {
244352418fc2SDimitry Andric invokeOnRelocs(*sec, scanCrossRefs<ELFT>, noxref, osec, sec);
24440fca6ea1SDimitry Andric });
24450fca6ea1SDimitry Andric }
24460fca6ea1SDimitry Andric }
24470fca6ea1SDimitry Andric }
24480fca6ea1SDimitry Andric }
24490fca6ea1SDimitry Andric
2450bdd1243dSDimitry Andric template void elf::scanRelocations<ELF32LE>();
2451bdd1243dSDimitry Andric template void elf::scanRelocations<ELF32BE>();
2452bdd1243dSDimitry Andric template void elf::scanRelocations<ELF64LE>();
2453bdd1243dSDimitry Andric template void elf::scanRelocations<ELF64BE>();
24540fca6ea1SDimitry Andric
24550fca6ea1SDimitry Andric template void elf::checkNoCrossRefs<ELF32LE>();
24560fca6ea1SDimitry Andric template void elf::checkNoCrossRefs<ELF32BE>();
24570fca6ea1SDimitry Andric template void elf::checkNoCrossRefs<ELF64LE>();
24580fca6ea1SDimitry Andric template void elf::checkNoCrossRefs<ELF64BE>();
2459