10b57cec5SDimitry Andric //===- Relocations.cpp ----------------------------------------------------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric // 90b57cec5SDimitry Andric // This file contains platform-independent functions to process relocations. 100b57cec5SDimitry Andric // I'll describe the overview of this file here. 110b57cec5SDimitry Andric // 120b57cec5SDimitry Andric // Simple relocations are easy to handle for the linker. For example, 130b57cec5SDimitry Andric // for R_X86_64_PC64 relocs, the linker just has to fix up locations 140b57cec5SDimitry Andric // with the relative offsets to the target symbols. It would just be 150b57cec5SDimitry Andric // reading records from relocation sections and applying them to output. 160b57cec5SDimitry Andric // 170b57cec5SDimitry Andric // But not all relocations are that easy to handle. For example, for 180b57cec5SDimitry Andric // R_386_GOTOFF relocs, the linker has to create new GOT entries for 190b57cec5SDimitry Andric // symbols if they don't exist, and fix up locations with GOT entry 200b57cec5SDimitry Andric // offsets from the beginning of GOT section. So there is more than 210b57cec5SDimitry Andric // fixing addresses in relocation processing. 220b57cec5SDimitry Andric // 230b57cec5SDimitry Andric // ELF defines a large number of complex relocations. 240b57cec5SDimitry Andric // 250b57cec5SDimitry Andric // The functions in this file analyze relocations and do whatever needs 260b57cec5SDimitry Andric // to be done. It includes, but not limited to, the following. 270b57cec5SDimitry Andric // 280b57cec5SDimitry Andric // - create GOT/PLT entries 290b57cec5SDimitry Andric // - create new relocations in .dynsym to let the dynamic linker resolve 300b57cec5SDimitry Andric // them at runtime (since ELF supports dynamic linking, not all 310b57cec5SDimitry Andric // relocations can be resolved at link-time) 320b57cec5SDimitry Andric // - create COPY relocs and reserve space in .bss 330b57cec5SDimitry Andric // - replace expensive relocs (in terms of runtime cost) with cheap ones 340b57cec5SDimitry Andric // - error out infeasible combinations such as PIC and non-relative relocs 350b57cec5SDimitry Andric // 360b57cec5SDimitry Andric // Note that the functions in this file don't actually apply relocations 370b57cec5SDimitry Andric // because it doesn't know about the output file nor the output file buffer. 380b57cec5SDimitry Andric // It instead stores Relocation objects to InputSection's Relocations 390b57cec5SDimitry Andric // vector to let it apply later in InputSection::writeTo. 400b57cec5SDimitry Andric // 410b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 420b57cec5SDimitry Andric 430b57cec5SDimitry Andric #include "Relocations.h" 440b57cec5SDimitry Andric #include "Config.h" 450b57cec5SDimitry Andric #include "LinkerScript.h" 460b57cec5SDimitry Andric #include "OutputSections.h" 470b57cec5SDimitry Andric #include "SymbolTable.h" 480b57cec5SDimitry Andric #include "Symbols.h" 490b57cec5SDimitry Andric #include "SyntheticSections.h" 500b57cec5SDimitry Andric #include "Target.h" 510b57cec5SDimitry Andric #include "Thunks.h" 520b57cec5SDimitry Andric #include "lld/Common/ErrorHandler.h" 530b57cec5SDimitry Andric #include "lld/Common/Memory.h" 540b57cec5SDimitry Andric #include "lld/Common/Strings.h" 550b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h" 56480093f4SDimitry Andric #include "llvm/Demangle/Demangle.h" 570b57cec5SDimitry Andric #include "llvm/Support/Endian.h" 580b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 590b57cec5SDimitry Andric #include <algorithm> 600b57cec5SDimitry Andric 610b57cec5SDimitry Andric using namespace llvm; 620b57cec5SDimitry Andric using namespace llvm::ELF; 630b57cec5SDimitry Andric using namespace llvm::object; 640b57cec5SDimitry Andric using namespace llvm::support::endian; 65*5ffd83dbSDimitry Andric using namespace lld; 66*5ffd83dbSDimitry Andric using namespace lld::elf; 670b57cec5SDimitry Andric 680b57cec5SDimitry Andric static Optional<std::string> getLinkerScriptLocation(const Symbol &sym) { 690b57cec5SDimitry Andric for (BaseCommand *base : script->sectionCommands) 700b57cec5SDimitry Andric if (auto *cmd = dyn_cast<SymbolAssignment>(base)) 710b57cec5SDimitry Andric if (cmd->sym == &sym) 720b57cec5SDimitry Andric return cmd->location; 730b57cec5SDimitry Andric return None; 740b57cec5SDimitry Andric } 750b57cec5SDimitry Andric 76*5ffd83dbSDimitry Andric static std::string getDefinedLocation(const Symbol &sym) { 77*5ffd83dbSDimitry Andric std::string msg = "\n>>> defined in "; 78*5ffd83dbSDimitry Andric if (sym.file) 79*5ffd83dbSDimitry Andric msg += toString(sym.file); 80*5ffd83dbSDimitry Andric else if (Optional<std::string> loc = getLinkerScriptLocation(sym)) 81*5ffd83dbSDimitry Andric msg += *loc; 82*5ffd83dbSDimitry Andric return msg; 83*5ffd83dbSDimitry Andric } 84*5ffd83dbSDimitry Andric 850b57cec5SDimitry Andric // Construct a message in the following format. 860b57cec5SDimitry Andric // 870b57cec5SDimitry Andric // >>> defined in /home/alice/src/foo.o 880b57cec5SDimitry Andric // >>> referenced by bar.c:12 (/home/alice/src/bar.c:12) 890b57cec5SDimitry Andric // >>> /home/alice/src/bar.o:(.text+0x1) 900b57cec5SDimitry Andric static std::string getLocation(InputSectionBase &s, const Symbol &sym, 910b57cec5SDimitry Andric uint64_t off) { 92*5ffd83dbSDimitry 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 99*5ffd83dbSDimitry Andric void elf::reportRangeError(uint8_t *loc, const Relocation &rel, const Twine &v, 100*5ffd83dbSDimitry Andric int64_t min, uint64_t max) { 101*5ffd83dbSDimitry Andric ErrorPlace errPlace = getErrorPlace(loc); 102*5ffd83dbSDimitry Andric std::string hint; 103*5ffd83dbSDimitry Andric if (rel.sym && !rel.sym->isLocal()) 104*5ffd83dbSDimitry Andric hint = "; references " + lld::toString(*rel.sym) + 105*5ffd83dbSDimitry Andric getDefinedLocation(*rel.sym); 106*5ffd83dbSDimitry Andric 107*5ffd83dbSDimitry Andric if (errPlace.isec && errPlace.isec->name.startswith(".debug")) 108*5ffd83dbSDimitry Andric hint += "; consider recompiling with -fdebug-types-section to reduce size " 109*5ffd83dbSDimitry Andric "of debug sections"; 110*5ffd83dbSDimitry Andric 111*5ffd83dbSDimitry Andric errorOrWarn(errPlace.loc + "relocation " + lld::toString(rel.type) + 112*5ffd83dbSDimitry Andric " out of range: " + v.str() + " is not in [" + Twine(min).str() + 113*5ffd83dbSDimitry Andric ", " + Twine(max).str() + "]" + hint); 114*5ffd83dbSDimitry Andric } 115*5ffd83dbSDimitry Andric 1160b57cec5SDimitry Andric namespace { 1170b57cec5SDimitry Andric // Build a bitmask with one bit set for each RelExpr. 1180b57cec5SDimitry Andric // 1190b57cec5SDimitry Andric // Constexpr function arguments can't be used in static asserts, so we 1200b57cec5SDimitry Andric // use template arguments to build the mask. 1210b57cec5SDimitry Andric // But function template partial specializations don't exist (needed 1220b57cec5SDimitry Andric // for base case of the recursion), so we need a dummy struct. 1230b57cec5SDimitry Andric template <RelExpr... Exprs> struct RelExprMaskBuilder { 1240b57cec5SDimitry Andric static inline uint64_t build() { return 0; } 1250b57cec5SDimitry Andric }; 1260b57cec5SDimitry Andric 1270b57cec5SDimitry Andric // Specialization for recursive case. 1280b57cec5SDimitry Andric template <RelExpr Head, RelExpr... Tail> 1290b57cec5SDimitry Andric struct RelExprMaskBuilder<Head, Tail...> { 1300b57cec5SDimitry Andric static inline uint64_t build() { 1310b57cec5SDimitry Andric static_assert(0 <= Head && Head < 64, 1320b57cec5SDimitry Andric "RelExpr is too large for 64-bit mask!"); 1330b57cec5SDimitry Andric return (uint64_t(1) << Head) | RelExprMaskBuilder<Tail...>::build(); 1340b57cec5SDimitry Andric } 1350b57cec5SDimitry Andric }; 1360b57cec5SDimitry Andric } // namespace 1370b57cec5SDimitry Andric 1380b57cec5SDimitry Andric // Return true if `Expr` is one of `Exprs`. 1390b57cec5SDimitry Andric // There are fewer than 64 RelExpr's, so we can represent any set of 1400b57cec5SDimitry Andric // RelExpr's as a constant bit mask and test for membership with a 1410b57cec5SDimitry Andric // couple cheap bitwise operations. 1420b57cec5SDimitry Andric template <RelExpr... Exprs> bool oneof(RelExpr expr) { 1430b57cec5SDimitry Andric assert(0 <= expr && (int)expr < 64 && 1440b57cec5SDimitry Andric "RelExpr is too large for 64-bit mask!"); 1450b57cec5SDimitry Andric return (uint64_t(1) << expr) & RelExprMaskBuilder<Exprs...>::build(); 1460b57cec5SDimitry Andric } 1470b57cec5SDimitry Andric 1480b57cec5SDimitry Andric // This function is similar to the `handleTlsRelocation`. MIPS does not 1490b57cec5SDimitry Andric // support any relaxations for TLS relocations so by factoring out MIPS 1500b57cec5SDimitry Andric // handling in to the separate function we can simplify the code and do not 1510b57cec5SDimitry Andric // pollute other `handleTlsRelocation` by MIPS `ifs` statements. 1520b57cec5SDimitry Andric // Mips has a custom MipsGotSection that handles the writing of GOT entries 1530b57cec5SDimitry Andric // without dynamic relocations. 1540b57cec5SDimitry Andric static unsigned handleMipsTlsRelocation(RelType type, Symbol &sym, 1550b57cec5SDimitry Andric InputSectionBase &c, uint64_t offset, 1560b57cec5SDimitry Andric int64_t addend, RelExpr expr) { 1570b57cec5SDimitry Andric if (expr == R_MIPS_TLSLD) { 1580b57cec5SDimitry Andric in.mipsGot->addTlsIndex(*c.file); 1590b57cec5SDimitry Andric c.relocations.push_back({expr, type, offset, addend, &sym}); 1600b57cec5SDimitry Andric return 1; 1610b57cec5SDimitry Andric } 1620b57cec5SDimitry Andric if (expr == R_MIPS_TLSGD) { 1630b57cec5SDimitry Andric in.mipsGot->addDynTlsEntry(*c.file, sym); 1640b57cec5SDimitry Andric c.relocations.push_back({expr, type, offset, addend, &sym}); 1650b57cec5SDimitry Andric return 1; 1660b57cec5SDimitry Andric } 1670b57cec5SDimitry Andric return 0; 1680b57cec5SDimitry Andric } 1690b57cec5SDimitry Andric 1700b57cec5SDimitry Andric // Notes about General Dynamic and Local Dynamic TLS models below. They may 1710b57cec5SDimitry Andric // require the generation of a pair of GOT entries that have associated dynamic 1720b57cec5SDimitry Andric // relocations. The pair of GOT entries created are of the form GOT[e0] Module 1730b57cec5SDimitry Andric // Index (Used to find pointer to TLS block at run-time) GOT[e1] Offset of 1740b57cec5SDimitry Andric // symbol in TLS block. 1750b57cec5SDimitry Andric // 1760b57cec5SDimitry Andric // Returns the number of relocations processed. 1770b57cec5SDimitry Andric template <class ELFT> 1780b57cec5SDimitry Andric static unsigned 1790b57cec5SDimitry Andric handleTlsRelocation(RelType type, Symbol &sym, InputSectionBase &c, 1800b57cec5SDimitry Andric typename ELFT::uint offset, int64_t addend, RelExpr expr) { 1810b57cec5SDimitry Andric if (!sym.isTls()) 1820b57cec5SDimitry Andric return 0; 1830b57cec5SDimitry Andric 1840b57cec5SDimitry Andric if (config->emachine == EM_MIPS) 1850b57cec5SDimitry Andric return handleMipsTlsRelocation(type, sym, c, offset, addend, expr); 1860b57cec5SDimitry Andric 1870b57cec5SDimitry Andric if (oneof<R_AARCH64_TLSDESC_PAGE, R_TLSDESC, R_TLSDESC_CALL, R_TLSDESC_PC>( 1880b57cec5SDimitry Andric expr) && 1890b57cec5SDimitry Andric config->shared) { 1900b57cec5SDimitry Andric if (in.got->addDynTlsEntry(sym)) { 1910b57cec5SDimitry Andric uint64_t off = in.got->getGlobalDynOffset(sym); 1920b57cec5SDimitry Andric mainPart->relaDyn->addReloc( 1930b57cec5SDimitry Andric {target->tlsDescRel, in.got, off, !sym.isPreemptible, &sym, 0}); 1940b57cec5SDimitry Andric } 1950b57cec5SDimitry Andric if (expr != R_TLSDESC_CALL) 1960b57cec5SDimitry Andric c.relocations.push_back({expr, type, offset, addend, &sym}); 1970b57cec5SDimitry Andric return 1; 1980b57cec5SDimitry Andric } 1990b57cec5SDimitry Andric 200*5ffd83dbSDimitry Andric bool toExecRelax = !config->shared && config->emachine != EM_ARM && 201480093f4SDimitry Andric config->emachine != EM_HEXAGON && 202480093f4SDimitry Andric config->emachine != EM_RISCV; 2030b57cec5SDimitry Andric 2040b57cec5SDimitry Andric // If we are producing an executable and the symbol is non-preemptable, it 2050b57cec5SDimitry Andric // must be defined and the code sequence can be relaxed to use Local-Exec. 2060b57cec5SDimitry Andric // 2070b57cec5SDimitry Andric // ARM and RISC-V do not support any relaxations for TLS relocations, however, 2080b57cec5SDimitry Andric // we can omit the DTPMOD dynamic relocations and resolve them at link time 2090b57cec5SDimitry Andric // because them are always 1. This may be necessary for static linking as 2100b57cec5SDimitry Andric // DTPMOD may not be expected at load time. 2110b57cec5SDimitry Andric bool isLocalInExecutable = !sym.isPreemptible && !config->shared; 2120b57cec5SDimitry Andric 2130b57cec5SDimitry Andric // Local Dynamic is for access to module local TLS variables, while still 2140b57cec5SDimitry Andric // being suitable for being dynamically loaded via dlopen. GOT[e0] is the 2150b57cec5SDimitry Andric // module index, with a special value of 0 for the current module. GOT[e1] is 2160b57cec5SDimitry Andric // unused. There only needs to be one module index entry. 2170b57cec5SDimitry Andric if (oneof<R_TLSLD_GOT, R_TLSLD_GOTPLT, R_TLSLD_PC, R_TLSLD_HINT>( 2180b57cec5SDimitry Andric expr)) { 2190b57cec5SDimitry Andric // Local-Dynamic relocs can be relaxed to Local-Exec. 220*5ffd83dbSDimitry Andric if (toExecRelax) { 2210b57cec5SDimitry Andric c.relocations.push_back( 2220b57cec5SDimitry Andric {target->adjustRelaxExpr(type, nullptr, R_RELAX_TLS_LD_TO_LE), type, 2230b57cec5SDimitry Andric offset, addend, &sym}); 2240b57cec5SDimitry Andric return target->getTlsGdRelaxSkip(type); 2250b57cec5SDimitry Andric } 2260b57cec5SDimitry Andric if (expr == R_TLSLD_HINT) 2270b57cec5SDimitry Andric return 1; 2280b57cec5SDimitry Andric if (in.got->addTlsIndex()) { 2290b57cec5SDimitry Andric if (isLocalInExecutable) 2300b57cec5SDimitry Andric in.got->relocations.push_back( 2310b57cec5SDimitry Andric {R_ADDEND, target->symbolicRel, in.got->getTlsIndexOff(), 1, &sym}); 2320b57cec5SDimitry Andric else 2330b57cec5SDimitry Andric mainPart->relaDyn->addReloc(target->tlsModuleIndexRel, in.got, 2340b57cec5SDimitry Andric in.got->getTlsIndexOff(), nullptr); 2350b57cec5SDimitry Andric } 2360b57cec5SDimitry Andric c.relocations.push_back({expr, type, offset, addend, &sym}); 2370b57cec5SDimitry Andric return 1; 2380b57cec5SDimitry Andric } 2390b57cec5SDimitry Andric 2400b57cec5SDimitry Andric // Local-Dynamic relocs can be relaxed to Local-Exec. 241*5ffd83dbSDimitry Andric if (expr == R_DTPREL && toExecRelax) { 2420b57cec5SDimitry Andric c.relocations.push_back( 2430b57cec5SDimitry Andric {target->adjustRelaxExpr(type, nullptr, R_RELAX_TLS_LD_TO_LE), type, 2440b57cec5SDimitry Andric offset, addend, &sym}); 2450b57cec5SDimitry Andric return 1; 2460b57cec5SDimitry Andric } 2470b57cec5SDimitry Andric 2480b57cec5SDimitry Andric // Local-Dynamic sequence where offset of tls variable relative to dynamic 2490b57cec5SDimitry Andric // thread pointer is stored in the got. This cannot be relaxed to Local-Exec. 2500b57cec5SDimitry Andric if (expr == R_TLSLD_GOT_OFF) { 2510b57cec5SDimitry Andric if (!sym.isInGot()) { 2520b57cec5SDimitry Andric in.got->addEntry(sym); 2530b57cec5SDimitry Andric uint64_t off = sym.getGotOffset(); 2540b57cec5SDimitry Andric in.got->relocations.push_back( 2550b57cec5SDimitry Andric {R_ABS, target->tlsOffsetRel, off, 0, &sym}); 2560b57cec5SDimitry Andric } 2570b57cec5SDimitry Andric c.relocations.push_back({expr, type, offset, addend, &sym}); 2580b57cec5SDimitry Andric return 1; 2590b57cec5SDimitry Andric } 2600b57cec5SDimitry Andric 2610b57cec5SDimitry Andric if (oneof<R_AARCH64_TLSDESC_PAGE, R_TLSDESC, R_TLSDESC_CALL, R_TLSDESC_PC, 2620b57cec5SDimitry Andric R_TLSGD_GOT, R_TLSGD_GOTPLT, R_TLSGD_PC>(expr)) { 263*5ffd83dbSDimitry Andric if (!toExecRelax) { 2640b57cec5SDimitry Andric if (in.got->addDynTlsEntry(sym)) { 2650b57cec5SDimitry Andric uint64_t off = in.got->getGlobalDynOffset(sym); 2660b57cec5SDimitry Andric 2670b57cec5SDimitry Andric if (isLocalInExecutable) 2680b57cec5SDimitry Andric // Write one to the GOT slot. 2690b57cec5SDimitry Andric in.got->relocations.push_back( 2700b57cec5SDimitry Andric {R_ADDEND, target->symbolicRel, off, 1, &sym}); 2710b57cec5SDimitry Andric else 2720b57cec5SDimitry Andric mainPart->relaDyn->addReloc(target->tlsModuleIndexRel, in.got, off, &sym); 2730b57cec5SDimitry Andric 2740b57cec5SDimitry Andric // If the symbol is preemptible we need the dynamic linker to write 2750b57cec5SDimitry Andric // the offset too. 2760b57cec5SDimitry Andric uint64_t offsetOff = off + config->wordsize; 2770b57cec5SDimitry Andric if (sym.isPreemptible) 2780b57cec5SDimitry Andric mainPart->relaDyn->addReloc(target->tlsOffsetRel, in.got, offsetOff, 2790b57cec5SDimitry Andric &sym); 2800b57cec5SDimitry Andric else 2810b57cec5SDimitry Andric in.got->relocations.push_back( 2820b57cec5SDimitry Andric {R_ABS, target->tlsOffsetRel, offsetOff, 0, &sym}); 2830b57cec5SDimitry Andric } 2840b57cec5SDimitry Andric c.relocations.push_back({expr, type, offset, addend, &sym}); 2850b57cec5SDimitry Andric return 1; 2860b57cec5SDimitry Andric } 2870b57cec5SDimitry Andric 2880b57cec5SDimitry Andric // Global-Dynamic relocs can be relaxed to Initial-Exec or Local-Exec 2890b57cec5SDimitry Andric // depending on the symbol being locally defined or not. 2900b57cec5SDimitry Andric if (sym.isPreemptible) { 2910b57cec5SDimitry Andric c.relocations.push_back( 2920b57cec5SDimitry Andric {target->adjustRelaxExpr(type, nullptr, R_RELAX_TLS_GD_TO_IE), type, 2930b57cec5SDimitry Andric offset, addend, &sym}); 2940b57cec5SDimitry Andric if (!sym.isInGot()) { 2950b57cec5SDimitry Andric in.got->addEntry(sym); 2960b57cec5SDimitry Andric mainPart->relaDyn->addReloc(target->tlsGotRel, in.got, sym.getGotOffset(), 2970b57cec5SDimitry Andric &sym); 2980b57cec5SDimitry Andric } 2990b57cec5SDimitry Andric } else { 3000b57cec5SDimitry Andric c.relocations.push_back( 3010b57cec5SDimitry Andric {target->adjustRelaxExpr(type, nullptr, R_RELAX_TLS_GD_TO_LE), type, 3020b57cec5SDimitry Andric offset, addend, &sym}); 3030b57cec5SDimitry Andric } 3040b57cec5SDimitry Andric return target->getTlsGdRelaxSkip(type); 3050b57cec5SDimitry Andric } 3060b57cec5SDimitry Andric 3070b57cec5SDimitry Andric // Initial-Exec relocs can be relaxed to Local-Exec if the symbol is locally 3080b57cec5SDimitry Andric // defined. 3090b57cec5SDimitry Andric if (oneof<R_GOT, R_GOTPLT, R_GOT_PC, R_AARCH64_GOT_PAGE_PC, R_GOT_OFF, 3100b57cec5SDimitry Andric R_TLSIE_HINT>(expr) && 311*5ffd83dbSDimitry Andric toExecRelax && isLocalInExecutable) { 3120b57cec5SDimitry Andric c.relocations.push_back({R_RELAX_TLS_IE_TO_LE, type, offset, addend, &sym}); 3130b57cec5SDimitry Andric return 1; 3140b57cec5SDimitry Andric } 3150b57cec5SDimitry Andric 3160b57cec5SDimitry Andric if (expr == R_TLSIE_HINT) 3170b57cec5SDimitry Andric return 1; 3180b57cec5SDimitry Andric return 0; 3190b57cec5SDimitry Andric } 3200b57cec5SDimitry Andric 3210b57cec5SDimitry Andric static RelType getMipsPairType(RelType type, bool isLocal) { 3220b57cec5SDimitry Andric switch (type) { 3230b57cec5SDimitry Andric case R_MIPS_HI16: 3240b57cec5SDimitry Andric return R_MIPS_LO16; 3250b57cec5SDimitry Andric case R_MIPS_GOT16: 3260b57cec5SDimitry Andric // In case of global symbol, the R_MIPS_GOT16 relocation does not 3270b57cec5SDimitry Andric // have a pair. Each global symbol has a unique entry in the GOT 3280b57cec5SDimitry Andric // and a corresponding instruction with help of the R_MIPS_GOT16 3290b57cec5SDimitry Andric // relocation loads an address of the symbol. In case of local 3300b57cec5SDimitry Andric // symbol, the R_MIPS_GOT16 relocation creates a GOT entry to hold 3310b57cec5SDimitry Andric // the high 16 bits of the symbol's value. A paired R_MIPS_LO16 3320b57cec5SDimitry Andric // relocations handle low 16 bits of the address. That allows 3330b57cec5SDimitry Andric // to allocate only one GOT entry for every 64 KBytes of local data. 3340b57cec5SDimitry Andric return isLocal ? R_MIPS_LO16 : R_MIPS_NONE; 3350b57cec5SDimitry Andric case R_MICROMIPS_GOT16: 3360b57cec5SDimitry Andric return isLocal ? R_MICROMIPS_LO16 : R_MIPS_NONE; 3370b57cec5SDimitry Andric case R_MIPS_PCHI16: 3380b57cec5SDimitry Andric return R_MIPS_PCLO16; 3390b57cec5SDimitry Andric case R_MICROMIPS_HI16: 3400b57cec5SDimitry Andric return R_MICROMIPS_LO16; 3410b57cec5SDimitry Andric default: 3420b57cec5SDimitry Andric return R_MIPS_NONE; 3430b57cec5SDimitry Andric } 3440b57cec5SDimitry Andric } 3450b57cec5SDimitry Andric 3460b57cec5SDimitry Andric // True if non-preemptable symbol always has the same value regardless of where 3470b57cec5SDimitry Andric // the DSO is loaded. 3480b57cec5SDimitry Andric static bool isAbsolute(const Symbol &sym) { 3490b57cec5SDimitry Andric if (sym.isUndefWeak()) 3500b57cec5SDimitry Andric return true; 3510b57cec5SDimitry Andric if (const auto *dr = dyn_cast<Defined>(&sym)) 3520b57cec5SDimitry Andric return dr->section == nullptr; // Absolute symbol. 3530b57cec5SDimitry Andric return false; 3540b57cec5SDimitry Andric } 3550b57cec5SDimitry Andric 3560b57cec5SDimitry Andric static bool isAbsoluteValue(const Symbol &sym) { 3570b57cec5SDimitry Andric return isAbsolute(sym) || sym.isTls(); 3580b57cec5SDimitry Andric } 3590b57cec5SDimitry Andric 3600b57cec5SDimitry Andric // Returns true if Expr refers a PLT entry. 3610b57cec5SDimitry Andric static bool needsPlt(RelExpr expr) { 3620b57cec5SDimitry Andric return oneof<R_PLT_PC, R_PPC32_PLTREL, R_PPC64_CALL_PLT, R_PLT>(expr); 3630b57cec5SDimitry Andric } 3640b57cec5SDimitry Andric 3650b57cec5SDimitry Andric // Returns true if Expr refers a GOT entry. Note that this function 3660b57cec5SDimitry Andric // returns false for TLS variables even though they need GOT, because 3670b57cec5SDimitry Andric // TLS variables uses GOT differently than the regular variables. 3680b57cec5SDimitry Andric static bool needsGot(RelExpr expr) { 36985868e8aSDimitry Andric return oneof<R_GOT, R_GOT_OFF, R_MIPS_GOT_LOCAL_PAGE, R_MIPS_GOT_OFF, 37085868e8aSDimitry Andric R_MIPS_GOT_OFF32, R_AARCH64_GOT_PAGE_PC, R_GOT_PC, R_GOTPLT>( 37185868e8aSDimitry Andric expr); 3720b57cec5SDimitry Andric } 3730b57cec5SDimitry Andric 3740b57cec5SDimitry Andric // True if this expression is of the form Sym - X, where X is a position in the 3750b57cec5SDimitry Andric // file (PC, or GOT for example). 3760b57cec5SDimitry Andric static bool isRelExpr(RelExpr expr) { 3770b57cec5SDimitry Andric return oneof<R_PC, R_GOTREL, R_GOTPLTREL, R_MIPS_GOTREL, R_PPC64_CALL, 3780b57cec5SDimitry Andric R_PPC64_RELAX_TOC, R_AARCH64_PAGE_PC, R_RELAX_GOT_PC, 3790b57cec5SDimitry Andric R_RISCV_PC_INDIRECT>(expr); 3800b57cec5SDimitry Andric } 3810b57cec5SDimitry Andric 3820b57cec5SDimitry Andric // Returns true if a given relocation can be computed at link-time. 3830b57cec5SDimitry Andric // 3840b57cec5SDimitry Andric // For instance, we know the offset from a relocation to its target at 3850b57cec5SDimitry Andric // link-time if the relocation is PC-relative and refers a 3860b57cec5SDimitry Andric // non-interposable function in the same executable. This function 3870b57cec5SDimitry Andric // will return true for such relocation. 3880b57cec5SDimitry Andric // 3890b57cec5SDimitry Andric // If this function returns false, that means we need to emit a 3900b57cec5SDimitry Andric // dynamic relocation so that the relocation will be fixed at load-time. 3910b57cec5SDimitry Andric static bool isStaticLinkTimeConstant(RelExpr e, RelType type, const Symbol &sym, 3920b57cec5SDimitry Andric InputSectionBase &s, uint64_t relOff) { 3930b57cec5SDimitry Andric // These expressions always compute a constant 39485868e8aSDimitry Andric if (oneof<R_DTPREL, R_GOTPLT, R_GOT_OFF, R_TLSLD_GOT_OFF, 3950b57cec5SDimitry Andric R_MIPS_GOT_LOCAL_PAGE, R_MIPS_GOTREL, R_MIPS_GOT_OFF, 3960b57cec5SDimitry Andric R_MIPS_GOT_OFF32, R_MIPS_GOT_GP_PC, R_MIPS_TLSGD, 3970b57cec5SDimitry Andric R_AARCH64_GOT_PAGE_PC, R_GOT_PC, R_GOTONLY_PC, R_GOTPLTONLY_PC, 3980b57cec5SDimitry Andric R_PLT_PC, R_TLSGD_GOT, R_TLSGD_GOTPLT, R_TLSGD_PC, R_PPC32_PLTREL, 3990b57cec5SDimitry Andric R_PPC64_CALL_PLT, R_PPC64_RELAX_TOC, R_RISCV_ADD, R_TLSDESC_CALL, 400480093f4SDimitry Andric R_TLSDESC_PC, R_AARCH64_TLSDESC_PAGE, R_TLSLD_HINT, R_TLSIE_HINT>( 401480093f4SDimitry Andric e)) 4020b57cec5SDimitry Andric return true; 4030b57cec5SDimitry Andric 4040b57cec5SDimitry Andric // These never do, except if the entire file is position dependent or if 4050b57cec5SDimitry Andric // only the low bits are used. 4060b57cec5SDimitry Andric if (e == R_GOT || e == R_PLT || e == R_TLSDESC) 4070b57cec5SDimitry Andric return target->usesOnlyLowPageBits(type) || !config->isPic; 4080b57cec5SDimitry Andric 4090b57cec5SDimitry Andric if (sym.isPreemptible) 4100b57cec5SDimitry Andric return false; 4110b57cec5SDimitry Andric if (!config->isPic) 4120b57cec5SDimitry Andric return true; 4130b57cec5SDimitry Andric 4140b57cec5SDimitry Andric // The size of a non preemptible symbol is a constant. 4150b57cec5SDimitry Andric if (e == R_SIZE) 4160b57cec5SDimitry Andric return true; 4170b57cec5SDimitry Andric 4180b57cec5SDimitry Andric // For the target and the relocation, we want to know if they are 4190b57cec5SDimitry Andric // absolute or relative. 4200b57cec5SDimitry Andric bool absVal = isAbsoluteValue(sym); 4210b57cec5SDimitry Andric bool relE = isRelExpr(e); 4220b57cec5SDimitry Andric if (absVal && !relE) 4230b57cec5SDimitry Andric return true; 4240b57cec5SDimitry Andric if (!absVal && relE) 4250b57cec5SDimitry Andric return true; 4260b57cec5SDimitry Andric if (!absVal && !relE) 4270b57cec5SDimitry Andric return target->usesOnlyLowPageBits(type); 4280b57cec5SDimitry Andric 4290b57cec5SDimitry Andric assert(absVal && relE); 4300b57cec5SDimitry Andric 43155e4f9d5SDimitry Andric // Allow R_PLT_PC (optimized to R_PC here) to a hidden undefined weak symbol 43255e4f9d5SDimitry Andric // in PIC mode. This is a little strange, but it allows us to link function 43355e4f9d5SDimitry Andric // calls to such symbols (e.g. glibc/stdlib/exit.c:__run_exit_handlers). 43455e4f9d5SDimitry Andric // Normally such a call will be guarded with a comparison, which will load a 43555e4f9d5SDimitry Andric // zero from the GOT. 43655e4f9d5SDimitry Andric if (sym.isUndefWeak()) 43755e4f9d5SDimitry Andric return true; 43855e4f9d5SDimitry Andric 4390b57cec5SDimitry Andric // We set the final symbols values for linker script defined symbols later. 4400b57cec5SDimitry Andric // They always can be computed as a link time constant. 4410b57cec5SDimitry Andric if (sym.scriptDefined) 4420b57cec5SDimitry Andric return true; 4430b57cec5SDimitry Andric 4440b57cec5SDimitry Andric error("relocation " + toString(type) + " cannot refer to absolute symbol: " + 4450b57cec5SDimitry Andric toString(sym) + getLocation(s, sym, relOff)); 4460b57cec5SDimitry Andric return true; 4470b57cec5SDimitry Andric } 4480b57cec5SDimitry Andric 4490b57cec5SDimitry Andric static RelExpr toPlt(RelExpr expr) { 4500b57cec5SDimitry Andric switch (expr) { 4510b57cec5SDimitry Andric case R_PPC64_CALL: 4520b57cec5SDimitry Andric return R_PPC64_CALL_PLT; 4530b57cec5SDimitry Andric case R_PC: 4540b57cec5SDimitry Andric return R_PLT_PC; 4550b57cec5SDimitry Andric case R_ABS: 4560b57cec5SDimitry Andric return R_PLT; 4570b57cec5SDimitry Andric default: 4580b57cec5SDimitry Andric return expr; 4590b57cec5SDimitry Andric } 4600b57cec5SDimitry Andric } 4610b57cec5SDimitry Andric 4620b57cec5SDimitry Andric static RelExpr fromPlt(RelExpr expr) { 4630b57cec5SDimitry Andric // We decided not to use a plt. Optimize a reference to the plt to a 4640b57cec5SDimitry Andric // reference to the symbol itself. 4650b57cec5SDimitry Andric switch (expr) { 4660b57cec5SDimitry Andric case R_PLT_PC: 4670b57cec5SDimitry Andric case R_PPC32_PLTREL: 4680b57cec5SDimitry Andric return R_PC; 4690b57cec5SDimitry Andric case R_PPC64_CALL_PLT: 4700b57cec5SDimitry Andric return R_PPC64_CALL; 4710b57cec5SDimitry Andric case R_PLT: 4720b57cec5SDimitry Andric return R_ABS; 4730b57cec5SDimitry Andric default: 4740b57cec5SDimitry Andric return expr; 4750b57cec5SDimitry Andric } 4760b57cec5SDimitry Andric } 4770b57cec5SDimitry Andric 4780b57cec5SDimitry Andric // Returns true if a given shared symbol is in a read-only segment in a DSO. 4790b57cec5SDimitry Andric template <class ELFT> static bool isReadOnly(SharedSymbol &ss) { 4800b57cec5SDimitry Andric using Elf_Phdr = typename ELFT::Phdr; 4810b57cec5SDimitry Andric 4820b57cec5SDimitry Andric // Determine if the symbol is read-only by scanning the DSO's program headers. 4830b57cec5SDimitry Andric const SharedFile &file = ss.getFile(); 4840b57cec5SDimitry Andric for (const Elf_Phdr &phdr : 4850b57cec5SDimitry Andric check(file.template getObj<ELFT>().program_headers())) 4860b57cec5SDimitry Andric if ((phdr.p_type == ELF::PT_LOAD || phdr.p_type == ELF::PT_GNU_RELRO) && 4870b57cec5SDimitry Andric !(phdr.p_flags & ELF::PF_W) && ss.value >= phdr.p_vaddr && 4880b57cec5SDimitry Andric ss.value < phdr.p_vaddr + phdr.p_memsz) 4890b57cec5SDimitry Andric return true; 4900b57cec5SDimitry Andric return false; 4910b57cec5SDimitry Andric } 4920b57cec5SDimitry Andric 4930b57cec5SDimitry Andric // Returns symbols at the same offset as a given symbol, including SS itself. 4940b57cec5SDimitry Andric // 4950b57cec5SDimitry Andric // If two or more symbols are at the same offset, and at least one of 4960b57cec5SDimitry Andric // them are copied by a copy relocation, all of them need to be copied. 4970b57cec5SDimitry Andric // Otherwise, they would refer to different places at runtime. 4980b57cec5SDimitry Andric template <class ELFT> 4990b57cec5SDimitry Andric static SmallSet<SharedSymbol *, 4> getSymbolsAt(SharedSymbol &ss) { 5000b57cec5SDimitry Andric using Elf_Sym = typename ELFT::Sym; 5010b57cec5SDimitry Andric 5020b57cec5SDimitry Andric SharedFile &file = ss.getFile(); 5030b57cec5SDimitry Andric 5040b57cec5SDimitry Andric SmallSet<SharedSymbol *, 4> ret; 5050b57cec5SDimitry Andric for (const Elf_Sym &s : file.template getGlobalELFSyms<ELFT>()) { 5060b57cec5SDimitry Andric if (s.st_shndx == SHN_UNDEF || s.st_shndx == SHN_ABS || 5070b57cec5SDimitry Andric s.getType() == STT_TLS || s.st_value != ss.value) 5080b57cec5SDimitry Andric continue; 5090b57cec5SDimitry Andric StringRef name = check(s.getName(file.getStringTable())); 5100b57cec5SDimitry Andric Symbol *sym = symtab->find(name); 5110b57cec5SDimitry Andric if (auto *alias = dyn_cast_or_null<SharedSymbol>(sym)) 5120b57cec5SDimitry Andric ret.insert(alias); 5130b57cec5SDimitry Andric } 5140b57cec5SDimitry Andric return ret; 5150b57cec5SDimitry Andric } 5160b57cec5SDimitry Andric 5170b57cec5SDimitry Andric // When a symbol is copy relocated or we create a canonical plt entry, it is 5180b57cec5SDimitry Andric // effectively a defined symbol. In the case of copy relocation the symbol is 5190b57cec5SDimitry Andric // in .bss and in the case of a canonical plt entry it is in .plt. This function 5200b57cec5SDimitry Andric // replaces the existing symbol with a Defined pointing to the appropriate 5210b57cec5SDimitry Andric // location. 5220b57cec5SDimitry Andric static void replaceWithDefined(Symbol &sym, SectionBase *sec, uint64_t value, 5230b57cec5SDimitry Andric uint64_t size) { 5240b57cec5SDimitry Andric Symbol old = sym; 5250b57cec5SDimitry Andric 5260b57cec5SDimitry Andric sym.replace(Defined{sym.file, sym.getName(), sym.binding, sym.stOther, 5270b57cec5SDimitry Andric sym.type, value, size, sec}); 5280b57cec5SDimitry Andric 5290b57cec5SDimitry Andric sym.pltIndex = old.pltIndex; 5300b57cec5SDimitry Andric sym.gotIndex = old.gotIndex; 5310b57cec5SDimitry Andric sym.verdefIndex = old.verdefIndex; 5320b57cec5SDimitry Andric sym.exportDynamic = true; 5330b57cec5SDimitry Andric sym.isUsedInRegularObj = true; 5340b57cec5SDimitry Andric } 5350b57cec5SDimitry Andric 5360b57cec5SDimitry Andric // Reserve space in .bss or .bss.rel.ro for copy relocation. 5370b57cec5SDimitry Andric // 5380b57cec5SDimitry Andric // The copy relocation is pretty much a hack. If you use a copy relocation 5390b57cec5SDimitry Andric // in your program, not only the symbol name but the symbol's size, RW/RO 5400b57cec5SDimitry Andric // bit and alignment become part of the ABI. In addition to that, if the 5410b57cec5SDimitry Andric // symbol has aliases, the aliases become part of the ABI. That's subtle, 5420b57cec5SDimitry Andric // but if you violate that implicit ABI, that can cause very counter- 5430b57cec5SDimitry Andric // intuitive consequences. 5440b57cec5SDimitry Andric // 5450b57cec5SDimitry Andric // So, what is the copy relocation? It's for linking non-position 5460b57cec5SDimitry Andric // independent code to DSOs. In an ideal world, all references to data 5470b57cec5SDimitry Andric // exported by DSOs should go indirectly through GOT. But if object files 5480b57cec5SDimitry Andric // are compiled as non-PIC, all data references are direct. There is no 5490b57cec5SDimitry Andric // way for the linker to transform the code to use GOT, as machine 5500b57cec5SDimitry Andric // instructions are already set in stone in object files. This is where 5510b57cec5SDimitry Andric // the copy relocation takes a role. 5520b57cec5SDimitry Andric // 5530b57cec5SDimitry Andric // A copy relocation instructs the dynamic linker to copy data from a DSO 5540b57cec5SDimitry Andric // to a specified address (which is usually in .bss) at load-time. If the 5550b57cec5SDimitry Andric // static linker (that's us) finds a direct data reference to a DSO 5560b57cec5SDimitry Andric // symbol, it creates a copy relocation, so that the symbol can be 5570b57cec5SDimitry Andric // resolved as if it were in .bss rather than in a DSO. 5580b57cec5SDimitry Andric // 5590b57cec5SDimitry Andric // As you can see in this function, we create a copy relocation for the 5600b57cec5SDimitry Andric // dynamic linker, and the relocation contains not only symbol name but 561480093f4SDimitry Andric // various other information about the symbol. So, such attributes become a 5620b57cec5SDimitry Andric // part of the ABI. 5630b57cec5SDimitry Andric // 5640b57cec5SDimitry Andric // Note for application developers: I can give you a piece of advice if 5650b57cec5SDimitry Andric // you are writing a shared library. You probably should export only 5660b57cec5SDimitry Andric // functions from your library. You shouldn't export variables. 5670b57cec5SDimitry Andric // 5680b57cec5SDimitry Andric // As an example what can happen when you export variables without knowing 5690b57cec5SDimitry Andric // the semantics of copy relocations, assume that you have an exported 5700b57cec5SDimitry Andric // variable of type T. It is an ABI-breaking change to add new members at 5710b57cec5SDimitry Andric // end of T even though doing that doesn't change the layout of the 5720b57cec5SDimitry Andric // existing members. That's because the space for the new members are not 5730b57cec5SDimitry Andric // reserved in .bss unless you recompile the main program. That means they 5740b57cec5SDimitry Andric // are likely to overlap with other data that happens to be laid out next 5750b57cec5SDimitry Andric // to the variable in .bss. This kind of issue is sometimes very hard to 576480093f4SDimitry Andric // debug. What's a solution? Instead of exporting a variable V from a DSO, 5770b57cec5SDimitry Andric // define an accessor getV(). 5780b57cec5SDimitry Andric template <class ELFT> static void addCopyRelSymbol(SharedSymbol &ss) { 5790b57cec5SDimitry Andric // Copy relocation against zero-sized symbol doesn't make sense. 5800b57cec5SDimitry Andric uint64_t symSize = ss.getSize(); 5810b57cec5SDimitry Andric if (symSize == 0 || ss.alignment == 0) 5820b57cec5SDimitry Andric fatal("cannot create a copy relocation for symbol " + toString(ss)); 5830b57cec5SDimitry Andric 5840b57cec5SDimitry Andric // See if this symbol is in a read-only segment. If so, preserve the symbol's 5850b57cec5SDimitry Andric // memory protection by reserving space in the .bss.rel.ro section. 5860b57cec5SDimitry Andric bool isRO = isReadOnly<ELFT>(ss); 5870b57cec5SDimitry Andric BssSection *sec = 5880b57cec5SDimitry Andric make<BssSection>(isRO ? ".bss.rel.ro" : ".bss", symSize, ss.alignment); 58985868e8aSDimitry Andric OutputSection *osec = (isRO ? in.bssRelRo : in.bss)->getParent(); 59085868e8aSDimitry Andric 59185868e8aSDimitry Andric // At this point, sectionBases has been migrated to sections. Append sec to 59285868e8aSDimitry Andric // sections. 59385868e8aSDimitry Andric if (osec->sectionCommands.empty() || 59485868e8aSDimitry Andric !isa<InputSectionDescription>(osec->sectionCommands.back())) 59585868e8aSDimitry Andric osec->sectionCommands.push_back(make<InputSectionDescription>("")); 59685868e8aSDimitry Andric auto *isd = cast<InputSectionDescription>(osec->sectionCommands.back()); 59785868e8aSDimitry Andric isd->sections.push_back(sec); 59885868e8aSDimitry Andric osec->commitSection(sec); 5990b57cec5SDimitry Andric 6000b57cec5SDimitry Andric // Look through the DSO's dynamic symbol table for aliases and create a 6010b57cec5SDimitry Andric // dynamic symbol for each one. This causes the copy relocation to correctly 6020b57cec5SDimitry Andric // interpose any aliases. 6030b57cec5SDimitry Andric for (SharedSymbol *sym : getSymbolsAt<ELFT>(ss)) 6040b57cec5SDimitry Andric replaceWithDefined(*sym, sec, 0, sym->size); 6050b57cec5SDimitry Andric 6060b57cec5SDimitry Andric mainPart->relaDyn->addReloc(target->copyRel, sec, 0, &ss); 6070b57cec5SDimitry Andric } 6080b57cec5SDimitry Andric 6090b57cec5SDimitry Andric // MIPS has an odd notion of "paired" relocations to calculate addends. 6100b57cec5SDimitry Andric // For example, if a relocation is of R_MIPS_HI16, there must be a 6110b57cec5SDimitry Andric // R_MIPS_LO16 relocation after that, and an addend is calculated using 6120b57cec5SDimitry Andric // the two relocations. 6130b57cec5SDimitry Andric template <class ELFT, class RelTy> 6140b57cec5SDimitry Andric static int64_t computeMipsAddend(const RelTy &rel, const RelTy *end, 6150b57cec5SDimitry Andric InputSectionBase &sec, RelExpr expr, 6160b57cec5SDimitry Andric bool isLocal) { 6170b57cec5SDimitry Andric if (expr == R_MIPS_GOTREL && isLocal) 6180b57cec5SDimitry Andric return sec.getFile<ELFT>()->mipsGp0; 6190b57cec5SDimitry Andric 6200b57cec5SDimitry Andric // The ABI says that the paired relocation is used only for REL. 6210b57cec5SDimitry Andric // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 6220b57cec5SDimitry Andric if (RelTy::IsRela) 6230b57cec5SDimitry Andric return 0; 6240b57cec5SDimitry Andric 6250b57cec5SDimitry Andric RelType type = rel.getType(config->isMips64EL); 6260b57cec5SDimitry Andric uint32_t pairTy = getMipsPairType(type, isLocal); 6270b57cec5SDimitry Andric if (pairTy == R_MIPS_NONE) 6280b57cec5SDimitry Andric return 0; 6290b57cec5SDimitry Andric 6300b57cec5SDimitry Andric const uint8_t *buf = sec.data().data(); 6310b57cec5SDimitry Andric uint32_t symIndex = rel.getSymbol(config->isMips64EL); 6320b57cec5SDimitry Andric 6330b57cec5SDimitry Andric // To make things worse, paired relocations might not be contiguous in 6340b57cec5SDimitry Andric // the relocation table, so we need to do linear search. *sigh* 6350b57cec5SDimitry Andric for (const RelTy *ri = &rel; ri != end; ++ri) 6360b57cec5SDimitry Andric if (ri->getType(config->isMips64EL) == pairTy && 6370b57cec5SDimitry Andric ri->getSymbol(config->isMips64EL) == symIndex) 6380b57cec5SDimitry Andric return target->getImplicitAddend(buf + ri->r_offset, pairTy); 6390b57cec5SDimitry Andric 6400b57cec5SDimitry Andric warn("can't find matching " + toString(pairTy) + " relocation for " + 6410b57cec5SDimitry Andric toString(type)); 6420b57cec5SDimitry Andric return 0; 6430b57cec5SDimitry Andric } 6440b57cec5SDimitry Andric 6450b57cec5SDimitry Andric // Returns an addend of a given relocation. If it is RELA, an addend 6460b57cec5SDimitry Andric // is in a relocation itself. If it is REL, we need to read it from an 6470b57cec5SDimitry Andric // input section. 6480b57cec5SDimitry Andric template <class ELFT, class RelTy> 6490b57cec5SDimitry Andric static int64_t computeAddend(const RelTy &rel, const RelTy *end, 6500b57cec5SDimitry Andric InputSectionBase &sec, RelExpr expr, 6510b57cec5SDimitry Andric bool isLocal) { 6520b57cec5SDimitry Andric int64_t addend; 6530b57cec5SDimitry Andric RelType type = rel.getType(config->isMips64EL); 6540b57cec5SDimitry Andric 6550b57cec5SDimitry Andric if (RelTy::IsRela) { 6560b57cec5SDimitry Andric addend = getAddend<ELFT>(rel); 6570b57cec5SDimitry Andric } else { 6580b57cec5SDimitry Andric const uint8_t *buf = sec.data().data(); 6590b57cec5SDimitry Andric addend = target->getImplicitAddend(buf + rel.r_offset, type); 6600b57cec5SDimitry Andric } 6610b57cec5SDimitry Andric 6620b57cec5SDimitry Andric if (config->emachine == EM_PPC64 && config->isPic && type == R_PPC64_TOC) 6630b57cec5SDimitry Andric addend += getPPC64TocBase(); 6640b57cec5SDimitry Andric if (config->emachine == EM_MIPS) 6650b57cec5SDimitry Andric addend += computeMipsAddend<ELFT>(rel, end, sec, expr, isLocal); 6660b57cec5SDimitry Andric 6670b57cec5SDimitry Andric return addend; 6680b57cec5SDimitry Andric } 6690b57cec5SDimitry Andric 6700b57cec5SDimitry Andric // Custom error message if Sym is defined in a discarded section. 6710b57cec5SDimitry Andric template <class ELFT> 6720b57cec5SDimitry Andric static std::string maybeReportDiscarded(Undefined &sym) { 6730b57cec5SDimitry Andric auto *file = dyn_cast_or_null<ObjFile<ELFT>>(sym.file); 6740b57cec5SDimitry Andric if (!file || !sym.discardedSecIdx || 6750b57cec5SDimitry Andric file->getSections()[sym.discardedSecIdx] != &InputSection::discarded) 6760b57cec5SDimitry Andric return ""; 6770b57cec5SDimitry Andric ArrayRef<Elf_Shdr_Impl<ELFT>> objSections = 6780b57cec5SDimitry Andric CHECK(file->getObj().sections(), file); 6790b57cec5SDimitry Andric 6800b57cec5SDimitry Andric std::string msg; 6810b57cec5SDimitry Andric if (sym.type == ELF::STT_SECTION) { 6820b57cec5SDimitry Andric msg = "relocation refers to a discarded section: "; 6830b57cec5SDimitry Andric msg += CHECK( 6840b57cec5SDimitry Andric file->getObj().getSectionName(&objSections[sym.discardedSecIdx]), file); 6850b57cec5SDimitry Andric } else { 6860b57cec5SDimitry Andric msg = "relocation refers to a symbol in a discarded section: " + 6870b57cec5SDimitry Andric toString(sym); 6880b57cec5SDimitry Andric } 6890b57cec5SDimitry Andric msg += "\n>>> defined in " + toString(file); 6900b57cec5SDimitry Andric 6910b57cec5SDimitry Andric Elf_Shdr_Impl<ELFT> elfSec = objSections[sym.discardedSecIdx - 1]; 6920b57cec5SDimitry Andric if (elfSec.sh_type != SHT_GROUP) 6930b57cec5SDimitry Andric return msg; 6940b57cec5SDimitry Andric 6950b57cec5SDimitry Andric // If the discarded section is a COMDAT. 6960b57cec5SDimitry Andric StringRef signature = file->getShtGroupSignature(objSections, elfSec); 6970b57cec5SDimitry Andric if (const InputFile *prevailing = 6980b57cec5SDimitry Andric symtab->comdatGroups.lookup(CachedHashStringRef(signature))) 6990b57cec5SDimitry Andric msg += "\n>>> section group signature: " + signature.str() + 7000b57cec5SDimitry Andric "\n>>> prevailing definition is in " + toString(prevailing); 7010b57cec5SDimitry Andric return msg; 7020b57cec5SDimitry Andric } 7030b57cec5SDimitry Andric 7040b57cec5SDimitry Andric // Undefined diagnostics are collected in a vector and emitted once all of 7050b57cec5SDimitry Andric // them are known, so that some postprocessing on the list of undefined symbols 7060b57cec5SDimitry Andric // can happen before lld emits diagnostics. 7070b57cec5SDimitry Andric struct UndefinedDiag { 7080b57cec5SDimitry Andric Symbol *sym; 7090b57cec5SDimitry Andric struct Loc { 7100b57cec5SDimitry Andric InputSectionBase *sec; 7110b57cec5SDimitry Andric uint64_t offset; 7120b57cec5SDimitry Andric }; 7130b57cec5SDimitry Andric std::vector<Loc> locs; 7140b57cec5SDimitry Andric bool isWarning; 7150b57cec5SDimitry Andric }; 7160b57cec5SDimitry Andric 7170b57cec5SDimitry Andric static std::vector<UndefinedDiag> undefs; 7180b57cec5SDimitry Andric 719480093f4SDimitry Andric // Check whether the definition name def is a mangled function name that matches 720480093f4SDimitry Andric // the reference name ref. 721480093f4SDimitry Andric static bool canSuggestExternCForCXX(StringRef ref, StringRef def) { 722480093f4SDimitry Andric llvm::ItaniumPartialDemangler d; 723480093f4SDimitry Andric std::string name = def.str(); 724480093f4SDimitry Andric if (d.partialDemangle(name.c_str())) 725480093f4SDimitry Andric return false; 726480093f4SDimitry Andric char *buf = d.getFunctionName(nullptr, nullptr); 727480093f4SDimitry Andric if (!buf) 728480093f4SDimitry Andric return false; 729480093f4SDimitry Andric bool ret = ref == buf; 730480093f4SDimitry Andric free(buf); 731480093f4SDimitry Andric return ret; 732480093f4SDimitry Andric } 733480093f4SDimitry Andric 73485868e8aSDimitry Andric // Suggest an alternative spelling of an "undefined symbol" diagnostic. Returns 73585868e8aSDimitry Andric // the suggested symbol, which is either in the symbol table, or in the same 73685868e8aSDimitry Andric // file of sym. 737480093f4SDimitry Andric template <class ELFT> 738480093f4SDimitry Andric static const Symbol *getAlternativeSpelling(const Undefined &sym, 739480093f4SDimitry Andric std::string &pre_hint, 740480093f4SDimitry Andric std::string &post_hint) { 74185868e8aSDimitry Andric DenseMap<StringRef, const Symbol *> map; 742480093f4SDimitry Andric if (auto *file = dyn_cast_or_null<ObjFile<ELFT>>(sym.file)) { 743480093f4SDimitry Andric // If sym is a symbol defined in a discarded section, maybeReportDiscarded() 744480093f4SDimitry Andric // will give an error. Don't suggest an alternative spelling. 745480093f4SDimitry Andric if (file && sym.discardedSecIdx != 0 && 746480093f4SDimitry Andric file->getSections()[sym.discardedSecIdx] == &InputSection::discarded) 747480093f4SDimitry Andric return nullptr; 748480093f4SDimitry Andric 749480093f4SDimitry Andric // Build a map of local defined symbols. 75085868e8aSDimitry Andric for (const Symbol *s : sym.file->getSymbols()) 75185868e8aSDimitry Andric if (s->isLocal() && s->isDefined()) 75285868e8aSDimitry Andric map.try_emplace(s->getName(), s); 75385868e8aSDimitry Andric } 75485868e8aSDimitry Andric 75585868e8aSDimitry Andric auto suggest = [&](StringRef newName) -> const Symbol * { 75685868e8aSDimitry Andric // If defined locally. 75785868e8aSDimitry Andric if (const Symbol *s = map.lookup(newName)) 75885868e8aSDimitry Andric return s; 75985868e8aSDimitry Andric 76085868e8aSDimitry Andric // If in the symbol table and not undefined. 76185868e8aSDimitry Andric if (const Symbol *s = symtab->find(newName)) 76285868e8aSDimitry Andric if (!s->isUndefined()) 76385868e8aSDimitry Andric return s; 76485868e8aSDimitry Andric 76585868e8aSDimitry Andric return nullptr; 76685868e8aSDimitry Andric }; 76785868e8aSDimitry Andric 76885868e8aSDimitry Andric // This loop enumerates all strings of Levenshtein distance 1 as typo 76985868e8aSDimitry Andric // correction candidates and suggests the one that exists as a non-undefined 77085868e8aSDimitry Andric // symbol. 77185868e8aSDimitry Andric StringRef name = sym.getName(); 77285868e8aSDimitry Andric for (size_t i = 0, e = name.size(); i != e + 1; ++i) { 77385868e8aSDimitry Andric // Insert a character before name[i]. 77485868e8aSDimitry Andric std::string newName = (name.substr(0, i) + "0" + name.substr(i)).str(); 77585868e8aSDimitry Andric for (char c = '0'; c <= 'z'; ++c) { 77685868e8aSDimitry Andric newName[i] = c; 77785868e8aSDimitry Andric if (const Symbol *s = suggest(newName)) 77885868e8aSDimitry Andric return s; 77985868e8aSDimitry Andric } 78085868e8aSDimitry Andric if (i == e) 78185868e8aSDimitry Andric break; 78285868e8aSDimitry Andric 78385868e8aSDimitry Andric // Substitute name[i]. 784*5ffd83dbSDimitry Andric newName = std::string(name); 78585868e8aSDimitry Andric for (char c = '0'; c <= 'z'; ++c) { 78685868e8aSDimitry Andric newName[i] = c; 78785868e8aSDimitry Andric if (const Symbol *s = suggest(newName)) 78885868e8aSDimitry Andric return s; 78985868e8aSDimitry Andric } 79085868e8aSDimitry Andric 79185868e8aSDimitry Andric // Transpose name[i] and name[i+1]. This is of edit distance 2 but it is 79285868e8aSDimitry Andric // common. 79385868e8aSDimitry Andric if (i + 1 < e) { 79485868e8aSDimitry Andric newName[i] = name[i + 1]; 79585868e8aSDimitry Andric newName[i + 1] = name[i]; 79685868e8aSDimitry Andric if (const Symbol *s = suggest(newName)) 79785868e8aSDimitry Andric return s; 79885868e8aSDimitry Andric } 79985868e8aSDimitry Andric 80085868e8aSDimitry Andric // Delete name[i]. 80185868e8aSDimitry Andric newName = (name.substr(0, i) + name.substr(i + 1)).str(); 80285868e8aSDimitry Andric if (const Symbol *s = suggest(newName)) 80385868e8aSDimitry Andric return s; 80485868e8aSDimitry Andric } 80585868e8aSDimitry Andric 806480093f4SDimitry Andric // Case mismatch, e.g. Foo vs FOO. 807480093f4SDimitry Andric for (auto &it : map) 808480093f4SDimitry Andric if (name.equals_lower(it.first)) 809480093f4SDimitry Andric return it.second; 810480093f4SDimitry Andric for (Symbol *sym : symtab->symbols()) 811480093f4SDimitry Andric if (!sym->isUndefined() && name.equals_lower(sym->getName())) 812480093f4SDimitry Andric return sym; 813480093f4SDimitry Andric 814480093f4SDimitry Andric // The reference may be a mangled name while the definition is not. Suggest a 815480093f4SDimitry Andric // missing extern "C". 816480093f4SDimitry Andric if (name.startswith("_Z")) { 817480093f4SDimitry Andric std::string buf = name.str(); 818480093f4SDimitry Andric llvm::ItaniumPartialDemangler d; 819480093f4SDimitry Andric if (!d.partialDemangle(buf.c_str())) 820480093f4SDimitry Andric if (char *buf = d.getFunctionName(nullptr, nullptr)) { 821480093f4SDimitry Andric const Symbol *s = suggest(buf); 822480093f4SDimitry Andric free(buf); 823480093f4SDimitry Andric if (s) { 824480093f4SDimitry Andric pre_hint = ": extern \"C\" "; 825480093f4SDimitry Andric return s; 826480093f4SDimitry Andric } 827480093f4SDimitry Andric } 828480093f4SDimitry Andric } else { 829480093f4SDimitry Andric const Symbol *s = nullptr; 830480093f4SDimitry Andric for (auto &it : map) 831480093f4SDimitry Andric if (canSuggestExternCForCXX(name, it.first)) { 832480093f4SDimitry Andric s = it.second; 833480093f4SDimitry Andric break; 834480093f4SDimitry Andric } 835480093f4SDimitry Andric if (!s) 836480093f4SDimitry Andric for (Symbol *sym : symtab->symbols()) 837480093f4SDimitry Andric if (canSuggestExternCForCXX(name, sym->getName())) { 838480093f4SDimitry Andric s = sym; 839480093f4SDimitry Andric break; 840480093f4SDimitry Andric } 841480093f4SDimitry Andric if (s) { 842480093f4SDimitry Andric pre_hint = " to declare "; 843480093f4SDimitry Andric post_hint = " as extern \"C\"?"; 844480093f4SDimitry Andric return s; 845480093f4SDimitry Andric } 846480093f4SDimitry Andric } 847480093f4SDimitry Andric 84885868e8aSDimitry Andric return nullptr; 84985868e8aSDimitry Andric } 85085868e8aSDimitry Andric 8510b57cec5SDimitry Andric template <class ELFT> 85285868e8aSDimitry Andric static void reportUndefinedSymbol(const UndefinedDiag &undef, 85385868e8aSDimitry Andric bool correctSpelling) { 8540b57cec5SDimitry Andric Symbol &sym = *undef.sym; 8550b57cec5SDimitry Andric 8560b57cec5SDimitry Andric auto visibility = [&]() -> std::string { 8570b57cec5SDimitry Andric switch (sym.visibility) { 8580b57cec5SDimitry Andric case STV_INTERNAL: 8590b57cec5SDimitry Andric return "internal "; 8600b57cec5SDimitry Andric case STV_HIDDEN: 8610b57cec5SDimitry Andric return "hidden "; 8620b57cec5SDimitry Andric case STV_PROTECTED: 8630b57cec5SDimitry Andric return "protected "; 8640b57cec5SDimitry Andric default: 8650b57cec5SDimitry Andric return ""; 8660b57cec5SDimitry Andric } 8670b57cec5SDimitry Andric }; 8680b57cec5SDimitry Andric 8690b57cec5SDimitry Andric std::string msg = maybeReportDiscarded<ELFT>(cast<Undefined>(sym)); 8700b57cec5SDimitry Andric if (msg.empty()) 8710b57cec5SDimitry Andric msg = "undefined " + visibility() + "symbol: " + toString(sym); 8720b57cec5SDimitry Andric 873*5ffd83dbSDimitry Andric const size_t maxUndefReferences = 3; 8740b57cec5SDimitry Andric size_t i = 0; 8750b57cec5SDimitry Andric for (UndefinedDiag::Loc l : undef.locs) { 8760b57cec5SDimitry Andric if (i >= maxUndefReferences) 8770b57cec5SDimitry Andric break; 8780b57cec5SDimitry Andric InputSectionBase &sec = *l.sec; 8790b57cec5SDimitry Andric uint64_t offset = l.offset; 8800b57cec5SDimitry Andric 8810b57cec5SDimitry Andric msg += "\n>>> referenced by "; 8820b57cec5SDimitry Andric std::string src = sec.getSrcMsg(sym, offset); 8830b57cec5SDimitry Andric if (!src.empty()) 8840b57cec5SDimitry Andric msg += src + "\n>>> "; 8850b57cec5SDimitry Andric msg += sec.getObjMsg(offset); 8860b57cec5SDimitry Andric i++; 8870b57cec5SDimitry Andric } 8880b57cec5SDimitry Andric 8890b57cec5SDimitry Andric if (i < undef.locs.size()) 8900b57cec5SDimitry Andric msg += ("\n>>> referenced " + Twine(undef.locs.size() - i) + " more times") 8910b57cec5SDimitry Andric .str(); 8920b57cec5SDimitry Andric 893480093f4SDimitry Andric if (correctSpelling) { 894480093f4SDimitry Andric std::string pre_hint = ": ", post_hint; 895480093f4SDimitry Andric if (const Symbol *corrected = getAlternativeSpelling<ELFT>( 896480093f4SDimitry Andric cast<Undefined>(sym), pre_hint, post_hint)) { 897480093f4SDimitry Andric msg += "\n>>> did you mean" + pre_hint + toString(*corrected) + post_hint; 89885868e8aSDimitry Andric if (corrected->file) 89985868e8aSDimitry Andric msg += "\n>>> defined in: " + toString(corrected->file); 90085868e8aSDimitry Andric } 901480093f4SDimitry Andric } 90285868e8aSDimitry Andric 9030b57cec5SDimitry Andric if (sym.getName().startswith("_ZTV")) 904*5ffd83dbSDimitry Andric msg += 905*5ffd83dbSDimitry Andric "\n>>> the vtable symbol may be undefined because the class is missing " 9060b57cec5SDimitry Andric "its key function (see https://lld.llvm.org/missingkeyfunction)"; 9070b57cec5SDimitry Andric 9080b57cec5SDimitry Andric if (undef.isWarning) 9090b57cec5SDimitry Andric warn(msg); 9100b57cec5SDimitry Andric else 9110b57cec5SDimitry Andric error(msg); 9120b57cec5SDimitry Andric } 9130b57cec5SDimitry Andric 914*5ffd83dbSDimitry Andric template <class ELFT> void elf::reportUndefinedSymbols() { 9150b57cec5SDimitry Andric // Find the first "undefined symbol" diagnostic for each diagnostic, and 9160b57cec5SDimitry Andric // collect all "referenced from" lines at the first diagnostic. 9170b57cec5SDimitry Andric DenseMap<Symbol *, UndefinedDiag *> firstRef; 9180b57cec5SDimitry Andric for (UndefinedDiag &undef : undefs) { 9190b57cec5SDimitry Andric assert(undef.locs.size() == 1); 9200b57cec5SDimitry Andric if (UndefinedDiag *canon = firstRef.lookup(undef.sym)) { 9210b57cec5SDimitry Andric canon->locs.push_back(undef.locs[0]); 9220b57cec5SDimitry Andric undef.locs.clear(); 9230b57cec5SDimitry Andric } else 9240b57cec5SDimitry Andric firstRef[undef.sym] = &undef; 9250b57cec5SDimitry Andric } 9260b57cec5SDimitry Andric 92785868e8aSDimitry Andric // Enable spell corrector for the first 2 diagnostics. 92885868e8aSDimitry Andric for (auto it : enumerate(undefs)) 92985868e8aSDimitry Andric if (!it.value().locs.empty()) 93085868e8aSDimitry Andric reportUndefinedSymbol<ELFT>(it.value(), it.index() < 2); 9310b57cec5SDimitry Andric undefs.clear(); 9320b57cec5SDimitry Andric } 9330b57cec5SDimitry Andric 9340b57cec5SDimitry Andric // Report an undefined symbol if necessary. 9350b57cec5SDimitry Andric // Returns true if the undefined symbol will produce an error message. 9360b57cec5SDimitry Andric static bool maybeReportUndefined(Symbol &sym, InputSectionBase &sec, 9370b57cec5SDimitry Andric uint64_t offset) { 9380b57cec5SDimitry Andric if (!sym.isUndefined() || sym.isWeak()) 9390b57cec5SDimitry Andric return false; 9400b57cec5SDimitry Andric 94185868e8aSDimitry Andric bool canBeExternal = !sym.isLocal() && sym.visibility == STV_DEFAULT; 9420b57cec5SDimitry Andric if (config->unresolvedSymbols == UnresolvedPolicy::Ignore && canBeExternal) 9430b57cec5SDimitry Andric return false; 9440b57cec5SDimitry Andric 9450b57cec5SDimitry Andric // clang (as of 2019-06-12) / gcc (as of 8.2.1) PPC64 may emit a .rela.toc 9460b57cec5SDimitry Andric // which references a switch table in a discarded .rodata/.text section. The 9470b57cec5SDimitry Andric // .toc and the .rela.toc are incorrectly not placed in the comdat. The ELF 9480b57cec5SDimitry Andric // spec says references from outside the group to a STB_LOCAL symbol are not 9490b57cec5SDimitry Andric // allowed. Work around the bug. 9505a0c326fSDimitry Andric // 9515a0c326fSDimitry Andric // PPC32 .got2 is similar but cannot be fixed. Multiple .got2 is infeasible 9525a0c326fSDimitry Andric // because .LC0-.LTOC is not representable if the two labels are in different 9535a0c326fSDimitry Andric // .got2 9545a0c326fSDimitry Andric if (cast<Undefined>(sym).discardedSecIdx != 0 && 9555a0c326fSDimitry Andric (sec.name == ".got2" || sec.name == ".toc")) 9560b57cec5SDimitry Andric return false; 9570b57cec5SDimitry Andric 9580b57cec5SDimitry Andric bool isWarning = 9590b57cec5SDimitry Andric (config->unresolvedSymbols == UnresolvedPolicy::Warn && canBeExternal) || 9600b57cec5SDimitry Andric config->noinhibitExec; 9610b57cec5SDimitry Andric undefs.push_back({&sym, {{&sec, offset}}, isWarning}); 9620b57cec5SDimitry Andric return !isWarning; 9630b57cec5SDimitry Andric } 9640b57cec5SDimitry Andric 9650b57cec5SDimitry Andric // MIPS N32 ABI treats series of successive relocations with the same offset 9660b57cec5SDimitry Andric // as a single relocation. The similar approach used by N64 ABI, but this ABI 9670b57cec5SDimitry Andric // packs all relocations into the single relocation record. Here we emulate 9680b57cec5SDimitry Andric // this for the N32 ABI. Iterate over relocation with the same offset and put 9690b57cec5SDimitry Andric // theirs types into the single bit-set. 9700b57cec5SDimitry Andric template <class RelTy> static RelType getMipsN32RelType(RelTy *&rel, RelTy *end) { 9710b57cec5SDimitry Andric RelType type = 0; 9720b57cec5SDimitry Andric uint64_t offset = rel->r_offset; 9730b57cec5SDimitry Andric 9740b57cec5SDimitry Andric int n = 0; 9750b57cec5SDimitry Andric while (rel != end && rel->r_offset == offset) 9760b57cec5SDimitry Andric type |= (rel++)->getType(config->isMips64EL) << (8 * n++); 9770b57cec5SDimitry Andric return type; 9780b57cec5SDimitry Andric } 9790b57cec5SDimitry Andric 9800b57cec5SDimitry Andric // .eh_frame sections are mergeable input sections, so their input 9810b57cec5SDimitry Andric // offsets are not linearly mapped to output section. For each input 9820b57cec5SDimitry Andric // offset, we need to find a section piece containing the offset and 9830b57cec5SDimitry Andric // add the piece's base address to the input offset to compute the 9840b57cec5SDimitry Andric // output offset. That isn't cheap. 9850b57cec5SDimitry Andric // 9860b57cec5SDimitry Andric // This class is to speed up the offset computation. When we process 9870b57cec5SDimitry Andric // relocations, we access offsets in the monotonically increasing 9880b57cec5SDimitry Andric // order. So we can optimize for that access pattern. 9890b57cec5SDimitry Andric // 9900b57cec5SDimitry Andric // For sections other than .eh_frame, this class doesn't do anything. 9910b57cec5SDimitry Andric namespace { 9920b57cec5SDimitry Andric class OffsetGetter { 9930b57cec5SDimitry Andric public: 9940b57cec5SDimitry Andric explicit OffsetGetter(InputSectionBase &sec) { 9950b57cec5SDimitry Andric if (auto *eh = dyn_cast<EhInputSection>(&sec)) 9960b57cec5SDimitry Andric pieces = eh->pieces; 9970b57cec5SDimitry Andric } 9980b57cec5SDimitry Andric 9990b57cec5SDimitry Andric // Translates offsets in input sections to offsets in output sections. 10000b57cec5SDimitry Andric // Given offset must increase monotonically. We assume that Piece is 10010b57cec5SDimitry Andric // sorted by inputOff. 10020b57cec5SDimitry Andric uint64_t get(uint64_t off) { 10030b57cec5SDimitry Andric if (pieces.empty()) 10040b57cec5SDimitry Andric return off; 10050b57cec5SDimitry Andric 10060b57cec5SDimitry Andric while (i != pieces.size() && pieces[i].inputOff + pieces[i].size <= off) 10070b57cec5SDimitry Andric ++i; 10080b57cec5SDimitry Andric if (i == pieces.size()) 10090b57cec5SDimitry Andric fatal(".eh_frame: relocation is not in any piece"); 10100b57cec5SDimitry Andric 10110b57cec5SDimitry Andric // Pieces must be contiguous, so there must be no holes in between. 10120b57cec5SDimitry Andric assert(pieces[i].inputOff <= off && "Relocation not in any piece"); 10130b57cec5SDimitry Andric 10140b57cec5SDimitry Andric // Offset -1 means that the piece is dead (i.e. garbage collected). 10150b57cec5SDimitry Andric if (pieces[i].outputOff == -1) 10160b57cec5SDimitry Andric return -1; 10170b57cec5SDimitry Andric return pieces[i].outputOff + off - pieces[i].inputOff; 10180b57cec5SDimitry Andric } 10190b57cec5SDimitry Andric 10200b57cec5SDimitry Andric private: 10210b57cec5SDimitry Andric ArrayRef<EhSectionPiece> pieces; 10220b57cec5SDimitry Andric size_t i = 0; 10230b57cec5SDimitry Andric }; 10240b57cec5SDimitry Andric } // namespace 10250b57cec5SDimitry Andric 10260b57cec5SDimitry Andric static void addRelativeReloc(InputSectionBase *isec, uint64_t offsetInSec, 10270b57cec5SDimitry Andric Symbol *sym, int64_t addend, RelExpr expr, 10280b57cec5SDimitry Andric RelType type) { 10290b57cec5SDimitry Andric Partition &part = isec->getPartition(); 10300b57cec5SDimitry Andric 10310b57cec5SDimitry Andric // Add a relative relocation. If relrDyn section is enabled, and the 10320b57cec5SDimitry Andric // relocation offset is guaranteed to be even, add the relocation to 10330b57cec5SDimitry Andric // the relrDyn section, otherwise add it to the relaDyn section. 10340b57cec5SDimitry Andric // relrDyn sections don't support odd offsets. Also, relrDyn sections 10350b57cec5SDimitry Andric // don't store the addend values, so we must write it to the relocated 10360b57cec5SDimitry Andric // address. 10370b57cec5SDimitry Andric if (part.relrDyn && isec->alignment >= 2 && offsetInSec % 2 == 0) { 10380b57cec5SDimitry Andric isec->relocations.push_back({expr, type, offsetInSec, addend, sym}); 10390b57cec5SDimitry Andric part.relrDyn->relocs.push_back({isec, offsetInSec}); 10400b57cec5SDimitry Andric return; 10410b57cec5SDimitry Andric } 10420b57cec5SDimitry Andric part.relaDyn->addReloc(target->relativeRel, isec, offsetInSec, sym, addend, 10430b57cec5SDimitry Andric expr, type); 10440b57cec5SDimitry Andric } 10450b57cec5SDimitry Andric 1046480093f4SDimitry Andric template <class PltSection, class GotPltSection> 10470b57cec5SDimitry Andric static void addPltEntry(PltSection *plt, GotPltSection *gotPlt, 10480b57cec5SDimitry Andric RelocationBaseSection *rel, RelType type, Symbol &sym) { 1049480093f4SDimitry Andric plt->addEntry(sym); 10500b57cec5SDimitry Andric gotPlt->addEntry(sym); 10510b57cec5SDimitry Andric rel->addReloc( 10520b57cec5SDimitry Andric {type, gotPlt, sym.getGotPltOffset(), !sym.isPreemptible, &sym, 0}); 10530b57cec5SDimitry Andric } 10540b57cec5SDimitry Andric 10550b57cec5SDimitry Andric static void addGotEntry(Symbol &sym) { 10560b57cec5SDimitry Andric in.got->addEntry(sym); 10570b57cec5SDimitry Andric 10580b57cec5SDimitry Andric RelExpr expr = sym.isTls() ? R_TLS : R_ABS; 10590b57cec5SDimitry Andric uint64_t off = sym.getGotOffset(); 10600b57cec5SDimitry Andric 10610b57cec5SDimitry Andric // If a GOT slot value can be calculated at link-time, which is now, 10620b57cec5SDimitry Andric // we can just fill that out. 10630b57cec5SDimitry Andric // 10640b57cec5SDimitry Andric // (We don't actually write a value to a GOT slot right now, but we 10650b57cec5SDimitry Andric // add a static relocation to a Relocations vector so that 10660b57cec5SDimitry Andric // InputSection::relocate will do the work for us. We may be able 10670b57cec5SDimitry Andric // to just write a value now, but it is a TODO.) 10680b57cec5SDimitry Andric bool isLinkTimeConstant = 10690b57cec5SDimitry Andric !sym.isPreemptible && (!config->isPic || isAbsolute(sym)); 10700b57cec5SDimitry Andric if (isLinkTimeConstant) { 10710b57cec5SDimitry Andric in.got->relocations.push_back({expr, target->symbolicRel, off, 0, &sym}); 10720b57cec5SDimitry Andric return; 10730b57cec5SDimitry Andric } 10740b57cec5SDimitry Andric 10750b57cec5SDimitry Andric // Otherwise, we emit a dynamic relocation to .rel[a].dyn so that 10760b57cec5SDimitry Andric // the GOT slot will be fixed at load-time. 10770b57cec5SDimitry Andric if (!sym.isTls() && !sym.isPreemptible && config->isPic && !isAbsolute(sym)) { 10780b57cec5SDimitry Andric addRelativeReloc(in.got, off, &sym, 0, R_ABS, target->symbolicRel); 10790b57cec5SDimitry Andric return; 10800b57cec5SDimitry Andric } 10810b57cec5SDimitry Andric mainPart->relaDyn->addReloc( 10820b57cec5SDimitry Andric sym.isTls() ? target->tlsGotRel : target->gotRel, in.got, off, &sym, 0, 10830b57cec5SDimitry Andric sym.isPreemptible ? R_ADDEND : R_ABS, target->symbolicRel); 10840b57cec5SDimitry Andric } 10850b57cec5SDimitry Andric 10860b57cec5SDimitry Andric // Return true if we can define a symbol in the executable that 10870b57cec5SDimitry Andric // contains the value/function of a symbol defined in a shared 10880b57cec5SDimitry Andric // library. 10890b57cec5SDimitry Andric static bool canDefineSymbolInExecutable(Symbol &sym) { 10900b57cec5SDimitry Andric // If the symbol has default visibility the symbol defined in the 10910b57cec5SDimitry Andric // executable will preempt it. 10920b57cec5SDimitry Andric // Note that we want the visibility of the shared symbol itself, not 10930b57cec5SDimitry Andric // the visibility of the symbol in the output file we are producing. That is 10940b57cec5SDimitry Andric // why we use Sym.stOther. 10950b57cec5SDimitry Andric if ((sym.stOther & 0x3) == STV_DEFAULT) 10960b57cec5SDimitry Andric return true; 10970b57cec5SDimitry Andric 10980b57cec5SDimitry Andric // If we are allowed to break address equality of functions, defining 10990b57cec5SDimitry Andric // a plt entry will allow the program to call the function in the 11000b57cec5SDimitry Andric // .so, but the .so and the executable will no agree on the address 11010b57cec5SDimitry Andric // of the function. Similar logic for objects. 11020b57cec5SDimitry Andric return ((sym.isFunc() && config->ignoreFunctionAddressEquality) || 11030b57cec5SDimitry Andric (sym.isObject() && config->ignoreDataAddressEquality)); 11040b57cec5SDimitry Andric } 11050b57cec5SDimitry Andric 11060b57cec5SDimitry Andric // The reason we have to do this early scan is as follows 11070b57cec5SDimitry Andric // * To mmap the output file, we need to know the size 11080b57cec5SDimitry Andric // * For that, we need to know how many dynamic relocs we will have. 11090b57cec5SDimitry Andric // It might be possible to avoid this by outputting the file with write: 11100b57cec5SDimitry Andric // * Write the allocated output sections, computing addresses. 11110b57cec5SDimitry Andric // * Apply relocations, recording which ones require a dynamic reloc. 11120b57cec5SDimitry Andric // * Write the dynamic relocations. 11130b57cec5SDimitry Andric // * Write the rest of the file. 11140b57cec5SDimitry Andric // This would have some drawbacks. For example, we would only know if .rela.dyn 11150b57cec5SDimitry Andric // is needed after applying relocations. If it is, it will go after rw and rx 11160b57cec5SDimitry Andric // sections. Given that it is ro, we will need an extra PT_LOAD. This 11170b57cec5SDimitry Andric // complicates things for the dynamic linker and means we would have to reserve 11180b57cec5SDimitry Andric // space for the extra PT_LOAD even if we end up not using it. 11190b57cec5SDimitry Andric template <class ELFT, class RelTy> 11200b57cec5SDimitry Andric static void processRelocAux(InputSectionBase &sec, RelExpr expr, RelType type, 11210b57cec5SDimitry Andric uint64_t offset, Symbol &sym, const RelTy &rel, 11220b57cec5SDimitry Andric int64_t addend) { 11230b57cec5SDimitry Andric // If the relocation is known to be a link-time constant, we know no dynamic 11240b57cec5SDimitry Andric // relocation will be created, pass the control to relocateAlloc() or 11250b57cec5SDimitry Andric // relocateNonAlloc() to resolve it. 11260b57cec5SDimitry Andric // 11270b57cec5SDimitry Andric // The behavior of an undefined weak reference is implementation defined. If 11280b57cec5SDimitry Andric // the relocation is to a weak undef, and we are producing an executable, let 11290b57cec5SDimitry Andric // relocate{,Non}Alloc() resolve it. 11300b57cec5SDimitry Andric if (isStaticLinkTimeConstant(expr, type, sym, sec, offset) || 11310b57cec5SDimitry Andric (!config->shared && sym.isUndefWeak())) { 11320b57cec5SDimitry Andric sec.relocations.push_back({expr, type, offset, addend, &sym}); 11330b57cec5SDimitry Andric return; 11340b57cec5SDimitry Andric } 11350b57cec5SDimitry Andric 11360b57cec5SDimitry Andric bool canWrite = (sec.flags & SHF_WRITE) || !config->zText; 11370b57cec5SDimitry Andric if (canWrite) { 11380b57cec5SDimitry Andric RelType rel = target->getDynRel(type); 11390b57cec5SDimitry Andric if (expr == R_GOT || (rel == target->symbolicRel && !sym.isPreemptible)) { 11400b57cec5SDimitry Andric addRelativeReloc(&sec, offset, &sym, addend, expr, type); 11410b57cec5SDimitry Andric return; 11420b57cec5SDimitry Andric } else if (rel != 0) { 11430b57cec5SDimitry Andric if (config->emachine == EM_MIPS && rel == target->symbolicRel) 11440b57cec5SDimitry Andric rel = target->relativeRel; 11450b57cec5SDimitry Andric sec.getPartition().relaDyn->addReloc(rel, &sec, offset, &sym, addend, 11460b57cec5SDimitry Andric R_ADDEND, type); 11470b57cec5SDimitry Andric 11480b57cec5SDimitry Andric // MIPS ABI turns using of GOT and dynamic relocations inside out. 11490b57cec5SDimitry Andric // While regular ABI uses dynamic relocations to fill up GOT entries 11500b57cec5SDimitry Andric // MIPS ABI requires dynamic linker to fills up GOT entries using 11510b57cec5SDimitry Andric // specially sorted dynamic symbol table. This affects even dynamic 11520b57cec5SDimitry Andric // relocations against symbols which do not require GOT entries 11530b57cec5SDimitry Andric // creation explicitly, i.e. do not have any GOT-relocations. So if 11540b57cec5SDimitry Andric // a preemptible symbol has a dynamic relocation we anyway have 11550b57cec5SDimitry Andric // to create a GOT entry for it. 11560b57cec5SDimitry Andric // If a non-preemptible symbol has a dynamic relocation against it, 11570b57cec5SDimitry Andric // dynamic linker takes it st_value, adds offset and writes down 11580b57cec5SDimitry Andric // result of the dynamic relocation. In case of preemptible symbol 11590b57cec5SDimitry Andric // dynamic linker performs symbol resolution, writes the symbol value 11600b57cec5SDimitry Andric // to the GOT entry and reads the GOT entry when it needs to perform 11610b57cec5SDimitry Andric // a dynamic relocation. 11620b57cec5SDimitry Andric // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19 11630b57cec5SDimitry Andric if (config->emachine == EM_MIPS) 11640b57cec5SDimitry Andric in.mipsGot->addEntry(*sec.file, sym, addend, expr); 11650b57cec5SDimitry Andric return; 11660b57cec5SDimitry Andric } 11670b57cec5SDimitry Andric } 11680b57cec5SDimitry Andric 116985868e8aSDimitry Andric // When producing an executable, we can perform copy relocations (for 117085868e8aSDimitry Andric // STT_OBJECT) and canonical PLT (for STT_FUNC). 117185868e8aSDimitry Andric if (!config->shared) { 11720b57cec5SDimitry Andric if (!canDefineSymbolInExecutable(sym)) { 117385868e8aSDimitry Andric errorOrWarn("cannot preempt symbol: " + toString(sym) + 11740b57cec5SDimitry Andric getLocation(sec, sym, offset)); 11750b57cec5SDimitry Andric return; 11760b57cec5SDimitry Andric } 11770b57cec5SDimitry Andric 11780b57cec5SDimitry Andric if (sym.isObject()) { 11790b57cec5SDimitry Andric // Produce a copy relocation. 11800b57cec5SDimitry Andric if (auto *ss = dyn_cast<SharedSymbol>(&sym)) { 11810b57cec5SDimitry Andric if (!config->zCopyreloc) 11820b57cec5SDimitry Andric error("unresolvable relocation " + toString(type) + 11830b57cec5SDimitry Andric " against symbol '" + toString(*ss) + 11840b57cec5SDimitry Andric "'; recompile with -fPIC or remove '-z nocopyreloc'" + 11850b57cec5SDimitry Andric getLocation(sec, sym, offset)); 11860b57cec5SDimitry Andric addCopyRelSymbol<ELFT>(*ss); 11870b57cec5SDimitry Andric } 11880b57cec5SDimitry Andric sec.relocations.push_back({expr, type, offset, addend, &sym}); 11890b57cec5SDimitry Andric return; 11900b57cec5SDimitry Andric } 11910b57cec5SDimitry Andric 11920b57cec5SDimitry Andric // This handles a non PIC program call to function in a shared library. In 11930b57cec5SDimitry Andric // an ideal world, we could just report an error saying the relocation can 11940b57cec5SDimitry Andric // overflow at runtime. In the real world with glibc, crt1.o has a 11950b57cec5SDimitry Andric // R_X86_64_PC32 pointing to libc.so. 11960b57cec5SDimitry Andric // 11970b57cec5SDimitry Andric // The general idea on how to handle such cases is to create a PLT entry and 11980b57cec5SDimitry Andric // use that as the function value. 11990b57cec5SDimitry Andric // 12000b57cec5SDimitry Andric // For the static linking part, we just return a plt expr and everything 12010b57cec5SDimitry Andric // else will use the PLT entry as the address. 12020b57cec5SDimitry Andric // 12030b57cec5SDimitry Andric // The remaining problem is making sure pointer equality still works. We 12040b57cec5SDimitry Andric // need the help of the dynamic linker for that. We let it know that we have 12050b57cec5SDimitry Andric // a direct reference to a so symbol by creating an undefined symbol with a 12060b57cec5SDimitry Andric // non zero st_value. Seeing that, the dynamic linker resolves the symbol to 12070b57cec5SDimitry Andric // the value of the symbol we created. This is true even for got entries, so 12080b57cec5SDimitry Andric // pointer equality is maintained. To avoid an infinite loop, the only entry 12090b57cec5SDimitry Andric // that points to the real function is a dedicated got entry used by the 12100b57cec5SDimitry Andric // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT, 12110b57cec5SDimitry Andric // R_386_JMP_SLOT, etc). 12120b57cec5SDimitry Andric 12130b57cec5SDimitry Andric // For position independent executable on i386, the plt entry requires ebx 12140b57cec5SDimitry Andric // to be set. This causes two problems: 12150b57cec5SDimitry Andric // * If some code has a direct reference to a function, it was probably 12160b57cec5SDimitry Andric // compiled without -fPIE/-fPIC and doesn't maintain ebx. 12170b57cec5SDimitry Andric // * If a library definition gets preempted to the executable, it will have 12180b57cec5SDimitry Andric // the wrong ebx value. 121985868e8aSDimitry Andric if (sym.isFunc()) { 12200b57cec5SDimitry Andric if (config->pie && config->emachine == EM_386) 12210b57cec5SDimitry Andric errorOrWarn("symbol '" + toString(sym) + 12220b57cec5SDimitry Andric "' cannot be preempted; recompile with -fPIE" + 12230b57cec5SDimitry Andric getLocation(sec, sym, offset)); 12240b57cec5SDimitry Andric if (!sym.isInPlt()) 1225480093f4SDimitry Andric addPltEntry(in.plt, in.gotPlt, in.relaPlt, target->pltRel, sym); 122613138422SDimitry Andric if (!sym.isDefined()) { 12270b57cec5SDimitry Andric replaceWithDefined( 12280b57cec5SDimitry Andric sym, in.plt, 12290b57cec5SDimitry Andric target->pltHeaderSize + target->pltEntrySize * sym.pltIndex, 0); 123013138422SDimitry Andric if (config->emachine == EM_PPC) { 123113138422SDimitry Andric // PPC32 canonical PLT entries are at the beginning of .glink 123213138422SDimitry Andric cast<Defined>(sym).value = in.plt->headerSize; 123313138422SDimitry Andric in.plt->headerSize += 16; 123492c0d181SDimitry Andric cast<PPC32GlinkSection>(in.plt)->canonical_plts.push_back(&sym); 123513138422SDimitry Andric } 123613138422SDimitry Andric } 12370b57cec5SDimitry Andric sym.needsPltAddr = true; 12380b57cec5SDimitry Andric sec.relocations.push_back({expr, type, offset, addend, &sym}); 12390b57cec5SDimitry Andric return; 12400b57cec5SDimitry Andric } 124185868e8aSDimitry Andric } 124285868e8aSDimitry Andric 124385868e8aSDimitry Andric if (config->isPic) { 124485868e8aSDimitry Andric if (!canWrite && !isRelExpr(expr)) 124585868e8aSDimitry Andric errorOrWarn( 124685868e8aSDimitry Andric "can't create dynamic relocation " + toString(type) + " against " + 124785868e8aSDimitry Andric (sym.getName().empty() ? "local symbol" 124885868e8aSDimitry Andric : "symbol: " + toString(sym)) + 124985868e8aSDimitry Andric " in readonly segment; recompile object files with -fPIC " 125085868e8aSDimitry Andric "or pass '-Wl,-z,notext' to allow text relocations in the output" + 125185868e8aSDimitry Andric getLocation(sec, sym, offset)); 125285868e8aSDimitry Andric else 125385868e8aSDimitry Andric errorOrWarn( 125485868e8aSDimitry Andric "relocation " + toString(type) + " cannot be used against " + 125585868e8aSDimitry Andric (sym.getName().empty() ? "local symbol" : "symbol " + toString(sym)) + 125685868e8aSDimitry Andric "; recompile with -fPIC" + getLocation(sec, sym, offset)); 125785868e8aSDimitry Andric return; 125885868e8aSDimitry Andric } 12590b57cec5SDimitry Andric 12600b57cec5SDimitry Andric errorOrWarn("symbol '" + toString(sym) + "' has no type" + 12610b57cec5SDimitry Andric getLocation(sec, sym, offset)); 12620b57cec5SDimitry Andric } 12630b57cec5SDimitry Andric 12640b57cec5SDimitry Andric template <class ELFT, class RelTy> 12650b57cec5SDimitry Andric static void scanReloc(InputSectionBase &sec, OffsetGetter &getOffset, RelTy *&i, 12660b57cec5SDimitry Andric RelTy *end) { 12670b57cec5SDimitry Andric const RelTy &rel = *i; 12680b57cec5SDimitry Andric uint32_t symIndex = rel.getSymbol(config->isMips64EL); 12690b57cec5SDimitry Andric Symbol &sym = sec.getFile<ELFT>()->getSymbol(symIndex); 12700b57cec5SDimitry Andric RelType type; 12710b57cec5SDimitry Andric 12720b57cec5SDimitry Andric // Deal with MIPS oddity. 12730b57cec5SDimitry Andric if (config->mipsN32Abi) { 12740b57cec5SDimitry Andric type = getMipsN32RelType(i, end); 12750b57cec5SDimitry Andric } else { 12760b57cec5SDimitry Andric type = rel.getType(config->isMips64EL); 12770b57cec5SDimitry Andric ++i; 12780b57cec5SDimitry Andric } 12790b57cec5SDimitry Andric 12800b57cec5SDimitry Andric // Get an offset in an output section this relocation is applied to. 12810b57cec5SDimitry Andric uint64_t offset = getOffset.get(rel.r_offset); 12820b57cec5SDimitry Andric if (offset == uint64_t(-1)) 12830b57cec5SDimitry Andric return; 12840b57cec5SDimitry Andric 12850b57cec5SDimitry Andric // Error if the target symbol is undefined. Symbol index 0 may be used by 12860b57cec5SDimitry Andric // marker relocations, e.g. R_*_NONE and R_ARM_V4BX. Don't error on them. 128785868e8aSDimitry Andric if (symIndex != 0 && maybeReportUndefined(sym, sec, rel.r_offset)) 12880b57cec5SDimitry Andric return; 12890b57cec5SDimitry Andric 12900b57cec5SDimitry Andric const uint8_t *relocatedAddr = sec.data().begin() + rel.r_offset; 12910b57cec5SDimitry Andric RelExpr expr = target->getRelExpr(type, sym, relocatedAddr); 12920b57cec5SDimitry Andric 1293480093f4SDimitry Andric // Ignore R_*_NONE and other marker relocations. 1294480093f4SDimitry Andric if (expr == R_NONE) 12950b57cec5SDimitry Andric return; 12960b57cec5SDimitry Andric 12970b57cec5SDimitry Andric if (sym.isGnuIFunc() && !config->zText && config->warnIfuncTextrel) { 12980b57cec5SDimitry Andric warn("using ifunc symbols when text relocations are allowed may produce " 12990b57cec5SDimitry Andric "a binary that will segfault, if the object file is linked with " 13000b57cec5SDimitry Andric "old version of glibc (glibc 2.28 and earlier). If this applies to " 13010b57cec5SDimitry Andric "you, consider recompiling the object files without -fPIC and " 13020b57cec5SDimitry Andric "without -Wl,-z,notext option. Use -no-warn-ifunc-textrel to " 13030b57cec5SDimitry Andric "turn off this warning." + 13040b57cec5SDimitry Andric getLocation(sec, sym, offset)); 13050b57cec5SDimitry Andric } 13060b57cec5SDimitry Andric 13070b57cec5SDimitry Andric // Read an addend. 13080b57cec5SDimitry Andric int64_t addend = computeAddend<ELFT>(rel, end, sec, expr, sym.isLocal()); 13090b57cec5SDimitry Andric 1310*5ffd83dbSDimitry Andric if (config->emachine == EM_PPC64) { 1311*5ffd83dbSDimitry Andric // We can separate the small code model relocations into 2 categories: 1312*5ffd83dbSDimitry Andric // 1) Those that access the compiler generated .toc sections. 1313*5ffd83dbSDimitry Andric // 2) Those that access the linker allocated got entries. 1314*5ffd83dbSDimitry Andric // lld allocates got entries to symbols on demand. Since we don't try to 1315*5ffd83dbSDimitry Andric // sort the got entries in any way, we don't have to track which objects 1316*5ffd83dbSDimitry Andric // have got-based small code model relocs. The .toc sections get placed 1317*5ffd83dbSDimitry Andric // after the end of the linker allocated .got section and we do sort those 1318*5ffd83dbSDimitry Andric // so sections addressed with small code model relocations come first. 1319*5ffd83dbSDimitry Andric if (isPPC64SmallCodeModelTocReloc(type)) 1320*5ffd83dbSDimitry Andric sec.file->ppc64SmallCodeModelTocRelocs = true; 1321*5ffd83dbSDimitry Andric 1322*5ffd83dbSDimitry Andric // Record the TOC entry (.toc + addend) as not relaxable. See the comment in 1323*5ffd83dbSDimitry Andric // InputSectionBase::relocateAlloc(). 1324*5ffd83dbSDimitry Andric if (type == R_PPC64_TOC16_LO && sym.isSection() && isa<Defined>(sym) && 1325*5ffd83dbSDimitry Andric cast<Defined>(sym).section->name == ".toc") 1326*5ffd83dbSDimitry Andric ppc64noTocRelax.insert({&sym, addend}); 1327*5ffd83dbSDimitry Andric } 1328*5ffd83dbSDimitry Andric 13290b57cec5SDimitry Andric // Relax relocations. 13300b57cec5SDimitry Andric // 13310b57cec5SDimitry Andric // If we know that a PLT entry will be resolved within the same ELF module, we 13320b57cec5SDimitry Andric // can skip PLT access and directly jump to the destination function. For 1333480093f4SDimitry Andric // example, if we are linking a main executable, all dynamic symbols that can 13340b57cec5SDimitry Andric // be resolved within the executable will actually be resolved that way at 1335480093f4SDimitry Andric // runtime, because the main executable is always at the beginning of a search 13360b57cec5SDimitry Andric // list. We can leverage that fact. 13370b57cec5SDimitry Andric if (!sym.isPreemptible && (!sym.isGnuIFunc() || config->zIfuncNoplt)) { 13380b57cec5SDimitry Andric if (expr == R_GOT_PC && !isAbsoluteValue(sym)) { 13390b57cec5SDimitry Andric expr = target->adjustRelaxExpr(type, relocatedAddr, expr); 13400b57cec5SDimitry Andric } else { 134113138422SDimitry Andric // The 0x8000 bit of r_addend of R_PPC_PLTREL24 is used to choose call 134213138422SDimitry Andric // stub type. It should be ignored if optimized to R_PC. 13430b57cec5SDimitry Andric if (config->emachine == EM_PPC && expr == R_PPC32_PLTREL) 134413138422SDimitry Andric addend &= ~0x8000; 1345*5ffd83dbSDimitry Andric // R_HEX_GD_PLT_B22_PCREL (call a@GDPLT) is transformed into 1346*5ffd83dbSDimitry Andric // call __tls_get_addr even if the symbol is non-preemptible. 1347*5ffd83dbSDimitry Andric if (!(config->emachine == EM_HEXAGON && 1348*5ffd83dbSDimitry Andric (type == R_HEX_GD_PLT_B22_PCREL || 1349*5ffd83dbSDimitry Andric type == R_HEX_GD_PLT_B22_PCREL_X || 1350*5ffd83dbSDimitry Andric type == R_HEX_GD_PLT_B32_PCREL_X))) 13510b57cec5SDimitry Andric expr = fromPlt(expr); 13520b57cec5SDimitry Andric } 13530b57cec5SDimitry Andric } 13540b57cec5SDimitry Andric 13550b57cec5SDimitry Andric // If the relocation does not emit a GOT or GOTPLT entry but its computation 13560b57cec5SDimitry Andric // uses their addresses, we need GOT or GOTPLT to be created. 13570b57cec5SDimitry Andric // 13580b57cec5SDimitry Andric // The 4 types that relative GOTPLT are all x86 and x86-64 specific. 13590b57cec5SDimitry Andric if (oneof<R_GOTPLTONLY_PC, R_GOTPLTREL, R_GOTPLT, R_TLSGD_GOTPLT>(expr)) { 13600b57cec5SDimitry Andric in.gotPlt->hasGotPltOffRel = true; 13610b57cec5SDimitry Andric } else if (oneof<R_GOTONLY_PC, R_GOTREL, R_PPC64_TOCBASE, R_PPC64_RELAX_TOC>( 13620b57cec5SDimitry Andric expr)) { 13630b57cec5SDimitry Andric in.got->hasGotOffRel = true; 13640b57cec5SDimitry Andric } 13650b57cec5SDimitry Andric 13660b57cec5SDimitry Andric // Process some TLS relocations, including relaxing TLS relocations. 13670b57cec5SDimitry Andric // Note that this function does not handle all TLS relocations. 13680b57cec5SDimitry Andric if (unsigned processed = 13690b57cec5SDimitry Andric handleTlsRelocation<ELFT>(type, sym, sec, offset, addend, expr)) { 13700b57cec5SDimitry Andric i += (processed - 1); 13710b57cec5SDimitry Andric return; 13720b57cec5SDimitry Andric } 13730b57cec5SDimitry Andric 13740b57cec5SDimitry Andric // We were asked not to generate PLT entries for ifuncs. Instead, pass the 13750b57cec5SDimitry Andric // direct relocation on through. 13760b57cec5SDimitry Andric if (sym.isGnuIFunc() && config->zIfuncNoplt) { 13770b57cec5SDimitry Andric sym.exportDynamic = true; 13780b57cec5SDimitry Andric mainPart->relaDyn->addReloc(type, &sec, offset, &sym, addend, R_ADDEND, type); 13790b57cec5SDimitry Andric return; 13800b57cec5SDimitry Andric } 13810b57cec5SDimitry Andric 13820b57cec5SDimitry Andric // Non-preemptible ifuncs require special handling. First, handle the usual 13830b57cec5SDimitry Andric // case where the symbol isn't one of these. 13840b57cec5SDimitry Andric if (!sym.isGnuIFunc() || sym.isPreemptible) { 13850b57cec5SDimitry Andric // If a relocation needs PLT, we create PLT and GOTPLT slots for the symbol. 13860b57cec5SDimitry Andric if (needsPlt(expr) && !sym.isInPlt()) 1387480093f4SDimitry Andric addPltEntry(in.plt, in.gotPlt, in.relaPlt, target->pltRel, sym); 13880b57cec5SDimitry Andric 13890b57cec5SDimitry Andric // Create a GOT slot if a relocation needs GOT. 13900b57cec5SDimitry Andric if (needsGot(expr)) { 13910b57cec5SDimitry Andric if (config->emachine == EM_MIPS) { 13920b57cec5SDimitry Andric // MIPS ABI has special rules to process GOT entries and doesn't 13930b57cec5SDimitry Andric // require relocation entries for them. A special case is TLS 13940b57cec5SDimitry Andric // relocations. In that case dynamic loader applies dynamic 13950b57cec5SDimitry Andric // relocations to initialize TLS GOT entries. 13960b57cec5SDimitry Andric // See "Global Offset Table" in Chapter 5 in the following document 13970b57cec5SDimitry Andric // for detailed description: 13980b57cec5SDimitry Andric // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 13990b57cec5SDimitry Andric in.mipsGot->addEntry(*sec.file, sym, addend, expr); 14000b57cec5SDimitry Andric } else if (!sym.isInGot()) { 14010b57cec5SDimitry Andric addGotEntry(sym); 14020b57cec5SDimitry Andric } 14030b57cec5SDimitry Andric } 14040b57cec5SDimitry Andric } else { 14050b57cec5SDimitry Andric // Handle a reference to a non-preemptible ifunc. These are special in a 14060b57cec5SDimitry Andric // few ways: 14070b57cec5SDimitry Andric // 14080b57cec5SDimitry Andric // - Unlike most non-preemptible symbols, non-preemptible ifuncs do not have 14090b57cec5SDimitry Andric // a fixed value. But assuming that all references to the ifunc are 14100b57cec5SDimitry Andric // GOT-generating or PLT-generating, the handling of an ifunc is 14110b57cec5SDimitry Andric // relatively straightforward. We create a PLT entry in Iplt, which is 14120b57cec5SDimitry Andric // usually at the end of .plt, which makes an indirect call using a 14130b57cec5SDimitry Andric // matching GOT entry in igotPlt, which is usually at the end of .got.plt. 14140b57cec5SDimitry Andric // The GOT entry is relocated using an IRELATIVE relocation in relaIplt, 14150b57cec5SDimitry Andric // which is usually at the end of .rela.plt. Unlike most relocations in 14160b57cec5SDimitry Andric // .rela.plt, which may be evaluated lazily without -z now, dynamic 14170b57cec5SDimitry Andric // loaders evaluate IRELATIVE relocs eagerly, which means that for 14180b57cec5SDimitry Andric // IRELATIVE relocs only, GOT-generating relocations can point directly to 14190b57cec5SDimitry Andric // .got.plt without requiring a separate GOT entry. 14200b57cec5SDimitry Andric // 14210b57cec5SDimitry Andric // - Despite the fact that an ifunc does not have a fixed value, compilers 14220b57cec5SDimitry Andric // that are not passed -fPIC will assume that they do, and will emit 14230b57cec5SDimitry Andric // direct (non-GOT-generating, non-PLT-generating) relocations to the 14240b57cec5SDimitry Andric // symbol. This means that if a direct relocation to the symbol is 14250b57cec5SDimitry Andric // seen, the linker must set a value for the symbol, and this value must 14260b57cec5SDimitry Andric // be consistent no matter what type of reference is made to the symbol. 14270b57cec5SDimitry Andric // This can be done by creating a PLT entry for the symbol in the way 14280b57cec5SDimitry Andric // described above and making it canonical, that is, making all references 14290b57cec5SDimitry Andric // point to the PLT entry instead of the resolver. In lld we also store 14300b57cec5SDimitry Andric // the address of the PLT entry in the dynamic symbol table, which means 14310b57cec5SDimitry Andric // that the symbol will also have the same value in other modules. 14320b57cec5SDimitry Andric // Because the value loaded from the GOT needs to be consistent with 14330b57cec5SDimitry Andric // the value computed using a direct relocation, a non-preemptible ifunc 14340b57cec5SDimitry Andric // may end up with two GOT entries, one in .got.plt that points to the 14350b57cec5SDimitry Andric // address returned by the resolver and is used only by the PLT entry, 14360b57cec5SDimitry Andric // and another in .got that points to the PLT entry and is used by 14370b57cec5SDimitry Andric // GOT-generating relocations. 14380b57cec5SDimitry Andric // 14390b57cec5SDimitry Andric // - The fact that these symbols do not have a fixed value makes them an 14400b57cec5SDimitry Andric // exception to the general rule that a statically linked executable does 14410b57cec5SDimitry Andric // not require any form of dynamic relocation. To handle these relocations 14420b57cec5SDimitry Andric // correctly, the IRELATIVE relocations are stored in an array which a 14430b57cec5SDimitry Andric // statically linked executable's startup code must enumerate using the 14440b57cec5SDimitry Andric // linker-defined symbols __rela?_iplt_{start,end}. 14450b57cec5SDimitry Andric if (!sym.isInPlt()) { 14460b57cec5SDimitry Andric // Create PLT and GOTPLT slots for the symbol. 14470b57cec5SDimitry Andric sym.isInIplt = true; 14480b57cec5SDimitry Andric 14490b57cec5SDimitry Andric // Create a copy of the symbol to use as the target of the IRELATIVE 14500b57cec5SDimitry Andric // relocation in the igotPlt. This is in case we make the PLT canonical 14510b57cec5SDimitry Andric // later, which would overwrite the original symbol. 14520b57cec5SDimitry Andric // 14530b57cec5SDimitry Andric // FIXME: Creating a copy of the symbol here is a bit of a hack. All 14540b57cec5SDimitry Andric // that's really needed to create the IRELATIVE is the section and value, 14550b57cec5SDimitry Andric // so ideally we should just need to copy those. 14560b57cec5SDimitry Andric auto *directSym = make<Defined>(cast<Defined>(sym)); 1457480093f4SDimitry Andric addPltEntry(in.iplt, in.igotPlt, in.relaIplt, target->iRelativeRel, 14580b57cec5SDimitry Andric *directSym); 14590b57cec5SDimitry Andric sym.pltIndex = directSym->pltIndex; 14600b57cec5SDimitry Andric } 14610b57cec5SDimitry Andric if (needsGot(expr)) { 14620b57cec5SDimitry Andric // Redirect GOT accesses to point to the Igot. 14630b57cec5SDimitry Andric // 14640b57cec5SDimitry Andric // This field is also used to keep track of whether we ever needed a GOT 14650b57cec5SDimitry Andric // entry. If we did and we make the PLT canonical later, we'll need to 14660b57cec5SDimitry Andric // create a GOT entry pointing to the PLT entry for Sym. 14670b57cec5SDimitry Andric sym.gotInIgot = true; 14680b57cec5SDimitry Andric } else if (!needsPlt(expr)) { 14690b57cec5SDimitry Andric // Make the ifunc's PLT entry canonical by changing the value of its 14700b57cec5SDimitry Andric // symbol to redirect all references to point to it. 14710b57cec5SDimitry Andric auto &d = cast<Defined>(sym); 14720b57cec5SDimitry Andric d.section = in.iplt; 1473480093f4SDimitry Andric d.value = sym.pltIndex * target->ipltEntrySize; 14740b57cec5SDimitry Andric d.size = 0; 14750b57cec5SDimitry Andric // It's important to set the symbol type here so that dynamic loaders 14760b57cec5SDimitry Andric // don't try to call the PLT as if it were an ifunc resolver. 14770b57cec5SDimitry Andric d.type = STT_FUNC; 14780b57cec5SDimitry Andric 14790b57cec5SDimitry Andric if (sym.gotInIgot) { 14800b57cec5SDimitry Andric // We previously encountered a GOT generating reference that we 14810b57cec5SDimitry Andric // redirected to the Igot. Now that the PLT entry is canonical we must 14820b57cec5SDimitry Andric // clear the redirection to the Igot and add a GOT entry. As we've 14830b57cec5SDimitry Andric // changed the symbol type to STT_FUNC future GOT generating references 14840b57cec5SDimitry Andric // will naturally use this GOT entry. 14850b57cec5SDimitry Andric // 14860b57cec5SDimitry Andric // We don't need to worry about creating a MIPS GOT here because ifuncs 14870b57cec5SDimitry Andric // aren't a thing on MIPS. 14880b57cec5SDimitry Andric sym.gotInIgot = false; 14890b57cec5SDimitry Andric addGotEntry(sym); 14900b57cec5SDimitry Andric } 14910b57cec5SDimitry Andric } 14920b57cec5SDimitry Andric } 14930b57cec5SDimitry Andric 14940b57cec5SDimitry Andric processRelocAux<ELFT>(sec, expr, type, offset, sym, rel, addend); 14950b57cec5SDimitry Andric } 14960b57cec5SDimitry Andric 14970b57cec5SDimitry Andric template <class ELFT, class RelTy> 14980b57cec5SDimitry Andric static void scanRelocs(InputSectionBase &sec, ArrayRef<RelTy> rels) { 14990b57cec5SDimitry Andric OffsetGetter getOffset(sec); 15000b57cec5SDimitry Andric 15010b57cec5SDimitry Andric // Not all relocations end up in Sec.Relocations, but a lot do. 15020b57cec5SDimitry Andric sec.relocations.reserve(rels.size()); 15030b57cec5SDimitry Andric 15040b57cec5SDimitry Andric for (auto i = rels.begin(), end = rels.end(); i != end;) 15050b57cec5SDimitry Andric scanReloc<ELFT>(sec, getOffset, i, end); 15060b57cec5SDimitry Andric 15070b57cec5SDimitry Andric // Sort relocations by offset for more efficient searching for 15080b57cec5SDimitry Andric // R_RISCV_PCREL_HI20 and R_PPC64_ADDR64. 15090b57cec5SDimitry Andric if (config->emachine == EM_RISCV || 15100b57cec5SDimitry Andric (config->emachine == EM_PPC64 && sec.name == ".toc")) 15110b57cec5SDimitry Andric llvm::stable_sort(sec.relocations, 15120b57cec5SDimitry Andric [](const Relocation &lhs, const Relocation &rhs) { 15130b57cec5SDimitry Andric return lhs.offset < rhs.offset; 15140b57cec5SDimitry Andric }); 15150b57cec5SDimitry Andric } 15160b57cec5SDimitry Andric 1517*5ffd83dbSDimitry Andric template <class ELFT> void elf::scanRelocations(InputSectionBase &s) { 15180b57cec5SDimitry Andric if (s.areRelocsRela) 15190b57cec5SDimitry Andric scanRelocs<ELFT>(s, s.relas<ELFT>()); 15200b57cec5SDimitry Andric else 15210b57cec5SDimitry Andric scanRelocs<ELFT>(s, s.rels<ELFT>()); 15220b57cec5SDimitry Andric } 15230b57cec5SDimitry Andric 15240b57cec5SDimitry Andric static bool mergeCmp(const InputSection *a, const InputSection *b) { 15250b57cec5SDimitry Andric // std::merge requires a strict weak ordering. 15260b57cec5SDimitry Andric if (a->outSecOff < b->outSecOff) 15270b57cec5SDimitry Andric return true; 15280b57cec5SDimitry Andric 15290b57cec5SDimitry Andric if (a->outSecOff == b->outSecOff) { 15300b57cec5SDimitry Andric auto *ta = dyn_cast<ThunkSection>(a); 15310b57cec5SDimitry Andric auto *tb = dyn_cast<ThunkSection>(b); 15320b57cec5SDimitry Andric 15330b57cec5SDimitry Andric // Check if Thunk is immediately before any specific Target 15340b57cec5SDimitry Andric // InputSection for example Mips LA25 Thunks. 15350b57cec5SDimitry Andric if (ta && ta->getTargetInputSection() == b) 15360b57cec5SDimitry Andric return true; 15370b57cec5SDimitry Andric 15380b57cec5SDimitry Andric // Place Thunk Sections without specific targets before 15390b57cec5SDimitry Andric // non-Thunk Sections. 15400b57cec5SDimitry Andric if (ta && !tb && !ta->getTargetInputSection()) 15410b57cec5SDimitry Andric return true; 15420b57cec5SDimitry Andric } 15430b57cec5SDimitry Andric 15440b57cec5SDimitry Andric return false; 15450b57cec5SDimitry Andric } 15460b57cec5SDimitry Andric 15470b57cec5SDimitry Andric // Call Fn on every executable InputSection accessed via the linker script 15480b57cec5SDimitry Andric // InputSectionDescription::Sections. 15490b57cec5SDimitry Andric static void forEachInputSectionDescription( 15500b57cec5SDimitry Andric ArrayRef<OutputSection *> outputSections, 15510b57cec5SDimitry Andric llvm::function_ref<void(OutputSection *, InputSectionDescription *)> fn) { 15520b57cec5SDimitry Andric for (OutputSection *os : outputSections) { 15530b57cec5SDimitry Andric if (!(os->flags & SHF_ALLOC) || !(os->flags & SHF_EXECINSTR)) 15540b57cec5SDimitry Andric continue; 15550b57cec5SDimitry Andric for (BaseCommand *bc : os->sectionCommands) 15560b57cec5SDimitry Andric if (auto *isd = dyn_cast<InputSectionDescription>(bc)) 15570b57cec5SDimitry Andric fn(os, isd); 15580b57cec5SDimitry Andric } 15590b57cec5SDimitry Andric } 15600b57cec5SDimitry Andric 15610b57cec5SDimitry Andric // Thunk Implementation 15620b57cec5SDimitry Andric // 15630b57cec5SDimitry Andric // Thunks (sometimes called stubs, veneers or branch islands) are small pieces 15640b57cec5SDimitry Andric // of code that the linker inserts inbetween a caller and a callee. The thunks 15650b57cec5SDimitry Andric // are added at link time rather than compile time as the decision on whether 15660b57cec5SDimitry Andric // a thunk is needed, such as the caller and callee being out of range, can only 15670b57cec5SDimitry Andric // be made at link time. 15680b57cec5SDimitry Andric // 15690b57cec5SDimitry Andric // It is straightforward to tell given the current state of the program when a 15700b57cec5SDimitry Andric // thunk is needed for a particular call. The more difficult part is that 15710b57cec5SDimitry Andric // the thunk needs to be placed in the program such that the caller can reach 15720b57cec5SDimitry Andric // the thunk and the thunk can reach the callee; furthermore, adding thunks to 15730b57cec5SDimitry Andric // the program alters addresses, which can mean more thunks etc. 15740b57cec5SDimitry Andric // 15750b57cec5SDimitry Andric // In lld we have a synthetic ThunkSection that can hold many Thunks. 15760b57cec5SDimitry Andric // The decision to have a ThunkSection act as a container means that we can 15770b57cec5SDimitry Andric // more easily handle the most common case of a single block of contiguous 15780b57cec5SDimitry Andric // Thunks by inserting just a single ThunkSection. 15790b57cec5SDimitry Andric // 15800b57cec5SDimitry Andric // The implementation of Thunks in lld is split across these areas 15810b57cec5SDimitry Andric // Relocations.cpp : Framework for creating and placing thunks 15820b57cec5SDimitry Andric // Thunks.cpp : The code generated for each supported thunk 15830b57cec5SDimitry Andric // Target.cpp : Target specific hooks that the framework uses to decide when 15840b57cec5SDimitry Andric // a thunk is used 15850b57cec5SDimitry Andric // Synthetic.cpp : Implementation of ThunkSection 15860b57cec5SDimitry Andric // Writer.cpp : Iteratively call framework until no more Thunks added 15870b57cec5SDimitry Andric // 15880b57cec5SDimitry Andric // Thunk placement requirements: 15890b57cec5SDimitry Andric // Mips LA25 thunks. These must be placed immediately before the callee section 15900b57cec5SDimitry Andric // We can assume that the caller is in range of the Thunk. These are modelled 15910b57cec5SDimitry Andric // by Thunks that return the section they must precede with 15920b57cec5SDimitry Andric // getTargetInputSection(). 15930b57cec5SDimitry Andric // 15940b57cec5SDimitry Andric // ARM interworking and range extension thunks. These thunks must be placed 15950b57cec5SDimitry Andric // within range of the caller. All implemented ARM thunks can always reach the 15960b57cec5SDimitry Andric // callee as they use an indirect jump via a register that has no range 15970b57cec5SDimitry Andric // restrictions. 15980b57cec5SDimitry Andric // 15990b57cec5SDimitry Andric // Thunk placement algorithm: 16000b57cec5SDimitry Andric // For Mips LA25 ThunkSections; the placement is explicit, it has to be before 16010b57cec5SDimitry Andric // getTargetInputSection(). 16020b57cec5SDimitry Andric // 16030b57cec5SDimitry Andric // For thunks that must be placed within range of the caller there are many 16040b57cec5SDimitry Andric // possible choices given that the maximum range from the caller is usually 16050b57cec5SDimitry Andric // much larger than the average InputSection size. Desirable properties include: 16060b57cec5SDimitry Andric // - Maximize reuse of thunks by multiple callers 16070b57cec5SDimitry Andric // - Minimize number of ThunkSections to simplify insertion 16080b57cec5SDimitry Andric // - Handle impact of already added Thunks on addresses 16090b57cec5SDimitry Andric // - Simple to understand and implement 16100b57cec5SDimitry Andric // 16110b57cec5SDimitry Andric // In lld for the first pass, we pre-create one or more ThunkSections per 16120b57cec5SDimitry Andric // InputSectionDescription at Target specific intervals. A ThunkSection is 16130b57cec5SDimitry Andric // placed so that the estimated end of the ThunkSection is within range of the 16140b57cec5SDimitry Andric // start of the InputSectionDescription or the previous ThunkSection. For 16150b57cec5SDimitry Andric // example: 16160b57cec5SDimitry Andric // InputSectionDescription 16170b57cec5SDimitry Andric // Section 0 16180b57cec5SDimitry Andric // ... 16190b57cec5SDimitry Andric // Section N 16200b57cec5SDimitry Andric // ThunkSection 0 16210b57cec5SDimitry Andric // Section N + 1 16220b57cec5SDimitry Andric // ... 16230b57cec5SDimitry Andric // Section N + K 16240b57cec5SDimitry Andric // Thunk Section 1 16250b57cec5SDimitry Andric // 16260b57cec5SDimitry Andric // The intention is that we can add a Thunk to a ThunkSection that is well 16270b57cec5SDimitry Andric // spaced enough to service a number of callers without having to do a lot 16280b57cec5SDimitry Andric // of work. An important principle is that it is not an error if a Thunk cannot 16290b57cec5SDimitry Andric // be placed in a pre-created ThunkSection; when this happens we create a new 16300b57cec5SDimitry Andric // ThunkSection placed next to the caller. This allows us to handle the vast 16310b57cec5SDimitry Andric // majority of thunks simply, but also handle rare cases where the branch range 16320b57cec5SDimitry Andric // is smaller than the target specific spacing. 16330b57cec5SDimitry Andric // 16340b57cec5SDimitry Andric // The algorithm is expected to create all the thunks that are needed in a 16350b57cec5SDimitry Andric // single pass, with a small number of programs needing a second pass due to 16360b57cec5SDimitry Andric // the insertion of thunks in the first pass increasing the offset between 16370b57cec5SDimitry Andric // callers and callees that were only just in range. 16380b57cec5SDimitry Andric // 16390b57cec5SDimitry Andric // A consequence of allowing new ThunkSections to be created outside of the 16400b57cec5SDimitry Andric // pre-created ThunkSections is that in rare cases calls to Thunks that were in 16410b57cec5SDimitry Andric // range in pass K, are out of range in some pass > K due to the insertion of 16420b57cec5SDimitry Andric // more Thunks in between the caller and callee. When this happens we retarget 16430b57cec5SDimitry Andric // the relocation back to the original target and create another Thunk. 16440b57cec5SDimitry Andric 16450b57cec5SDimitry Andric // Remove ThunkSections that are empty, this should only be the initial set 16460b57cec5SDimitry Andric // precreated on pass 0. 16470b57cec5SDimitry Andric 16480b57cec5SDimitry Andric // Insert the Thunks for OutputSection OS into their designated place 16490b57cec5SDimitry Andric // in the Sections vector, and recalculate the InputSection output section 16500b57cec5SDimitry Andric // offsets. 16510b57cec5SDimitry Andric // This may invalidate any output section offsets stored outside of InputSection 16520b57cec5SDimitry Andric void ThunkCreator::mergeThunks(ArrayRef<OutputSection *> outputSections) { 16530b57cec5SDimitry Andric forEachInputSectionDescription( 16540b57cec5SDimitry Andric outputSections, [&](OutputSection *os, InputSectionDescription *isd) { 16550b57cec5SDimitry Andric if (isd->thunkSections.empty()) 16560b57cec5SDimitry Andric return; 16570b57cec5SDimitry Andric 16580b57cec5SDimitry Andric // Remove any zero sized precreated Thunks. 16590b57cec5SDimitry Andric llvm::erase_if(isd->thunkSections, 16600b57cec5SDimitry Andric [](const std::pair<ThunkSection *, uint32_t> &ts) { 16610b57cec5SDimitry Andric return ts.first->getSize() == 0; 16620b57cec5SDimitry Andric }); 16630b57cec5SDimitry Andric 16640b57cec5SDimitry Andric // ISD->ThunkSections contains all created ThunkSections, including 16650b57cec5SDimitry Andric // those inserted in previous passes. Extract the Thunks created this 16660b57cec5SDimitry Andric // pass and order them in ascending outSecOff. 16670b57cec5SDimitry Andric std::vector<ThunkSection *> newThunks; 1668480093f4SDimitry Andric for (std::pair<ThunkSection *, uint32_t> ts : isd->thunkSections) 16690b57cec5SDimitry Andric if (ts.second == pass) 16700b57cec5SDimitry Andric newThunks.push_back(ts.first); 16710b57cec5SDimitry Andric llvm::stable_sort(newThunks, 16720b57cec5SDimitry Andric [](const ThunkSection *a, const ThunkSection *b) { 16730b57cec5SDimitry Andric return a->outSecOff < b->outSecOff; 16740b57cec5SDimitry Andric }); 16750b57cec5SDimitry Andric 16760b57cec5SDimitry Andric // Merge sorted vectors of Thunks and InputSections by outSecOff 16770b57cec5SDimitry Andric std::vector<InputSection *> tmp; 16780b57cec5SDimitry Andric tmp.reserve(isd->sections.size() + newThunks.size()); 16790b57cec5SDimitry Andric 16800b57cec5SDimitry Andric std::merge(isd->sections.begin(), isd->sections.end(), 16810b57cec5SDimitry Andric newThunks.begin(), newThunks.end(), std::back_inserter(tmp), 16820b57cec5SDimitry Andric mergeCmp); 16830b57cec5SDimitry Andric 16840b57cec5SDimitry Andric isd->sections = std::move(tmp); 16850b57cec5SDimitry Andric }); 16860b57cec5SDimitry Andric } 16870b57cec5SDimitry Andric 16880b57cec5SDimitry Andric // Find or create a ThunkSection within the InputSectionDescription (ISD) that 16890b57cec5SDimitry Andric // is in range of Src. An ISD maps to a range of InputSections described by a 16900b57cec5SDimitry Andric // linker script section pattern such as { .text .text.* }. 16910b57cec5SDimitry Andric ThunkSection *ThunkCreator::getISDThunkSec(OutputSection *os, InputSection *isec, 16920b57cec5SDimitry Andric InputSectionDescription *isd, 16930b57cec5SDimitry Andric uint32_t type, uint64_t src) { 16940b57cec5SDimitry Andric for (std::pair<ThunkSection *, uint32_t> tp : isd->thunkSections) { 16950b57cec5SDimitry Andric ThunkSection *ts = tp.first; 16960b57cec5SDimitry Andric uint64_t tsBase = os->addr + ts->outSecOff; 16970b57cec5SDimitry Andric uint64_t tsLimit = tsBase + ts->getSize(); 16980b57cec5SDimitry Andric if (target->inBranchRange(type, src, (src > tsLimit) ? tsBase : tsLimit)) 16990b57cec5SDimitry Andric return ts; 17000b57cec5SDimitry Andric } 17010b57cec5SDimitry Andric 17020b57cec5SDimitry Andric // No suitable ThunkSection exists. This can happen when there is a branch 17030b57cec5SDimitry Andric // with lower range than the ThunkSection spacing or when there are too 17040b57cec5SDimitry Andric // many Thunks. Create a new ThunkSection as close to the InputSection as 17050b57cec5SDimitry Andric // possible. Error if InputSection is so large we cannot place ThunkSection 17060b57cec5SDimitry Andric // anywhere in Range. 17070b57cec5SDimitry Andric uint64_t thunkSecOff = isec->outSecOff; 17080b57cec5SDimitry Andric if (!target->inBranchRange(type, src, os->addr + thunkSecOff)) { 17090b57cec5SDimitry Andric thunkSecOff = isec->outSecOff + isec->getSize(); 17100b57cec5SDimitry Andric if (!target->inBranchRange(type, src, os->addr + thunkSecOff)) 17110b57cec5SDimitry Andric fatal("InputSection too large for range extension thunk " + 17120b57cec5SDimitry Andric isec->getObjMsg(src - (os->addr + isec->outSecOff))); 17130b57cec5SDimitry Andric } 17140b57cec5SDimitry Andric return addThunkSection(os, isd, thunkSecOff); 17150b57cec5SDimitry Andric } 17160b57cec5SDimitry Andric 17170b57cec5SDimitry Andric // Add a Thunk that needs to be placed in a ThunkSection that immediately 17180b57cec5SDimitry Andric // precedes its Target. 17190b57cec5SDimitry Andric ThunkSection *ThunkCreator::getISThunkSec(InputSection *isec) { 17200b57cec5SDimitry Andric ThunkSection *ts = thunkedSections.lookup(isec); 17210b57cec5SDimitry Andric if (ts) 17220b57cec5SDimitry Andric return ts; 17230b57cec5SDimitry Andric 17240b57cec5SDimitry Andric // Find InputSectionRange within Target Output Section (TOS) that the 17250b57cec5SDimitry Andric // InputSection (IS) that we need to precede is in. 17260b57cec5SDimitry Andric OutputSection *tos = isec->getParent(); 17270b57cec5SDimitry Andric for (BaseCommand *bc : tos->sectionCommands) { 17280b57cec5SDimitry Andric auto *isd = dyn_cast<InputSectionDescription>(bc); 17290b57cec5SDimitry Andric if (!isd || isd->sections.empty()) 17300b57cec5SDimitry Andric continue; 17310b57cec5SDimitry Andric 17320b57cec5SDimitry Andric InputSection *first = isd->sections.front(); 17330b57cec5SDimitry Andric InputSection *last = isd->sections.back(); 17340b57cec5SDimitry Andric 17350b57cec5SDimitry Andric if (isec->outSecOff < first->outSecOff || last->outSecOff < isec->outSecOff) 17360b57cec5SDimitry Andric continue; 17370b57cec5SDimitry Andric 17380b57cec5SDimitry Andric ts = addThunkSection(tos, isd, isec->outSecOff); 17390b57cec5SDimitry Andric thunkedSections[isec] = ts; 17400b57cec5SDimitry Andric return ts; 17410b57cec5SDimitry Andric } 17420b57cec5SDimitry Andric 17430b57cec5SDimitry Andric return nullptr; 17440b57cec5SDimitry Andric } 17450b57cec5SDimitry Andric 17460b57cec5SDimitry Andric // Create one or more ThunkSections per OS that can be used to place Thunks. 17470b57cec5SDimitry Andric // We attempt to place the ThunkSections using the following desirable 17480b57cec5SDimitry Andric // properties: 17490b57cec5SDimitry Andric // - Within range of the maximum number of callers 17500b57cec5SDimitry Andric // - Minimise the number of ThunkSections 17510b57cec5SDimitry Andric // 17520b57cec5SDimitry Andric // We follow a simple but conservative heuristic to place ThunkSections at 17530b57cec5SDimitry Andric // offsets that are multiples of a Target specific branch range. 17540b57cec5SDimitry Andric // For an InputSectionDescription that is smaller than the range, a single 17550b57cec5SDimitry Andric // ThunkSection at the end of the range will do. 17560b57cec5SDimitry Andric // 17570b57cec5SDimitry Andric // For an InputSectionDescription that is more than twice the size of the range, 17580b57cec5SDimitry Andric // we place the last ThunkSection at range bytes from the end of the 17590b57cec5SDimitry Andric // InputSectionDescription in order to increase the likelihood that the 17600b57cec5SDimitry Andric // distance from a thunk to its target will be sufficiently small to 17610b57cec5SDimitry Andric // allow for the creation of a short thunk. 17620b57cec5SDimitry Andric void ThunkCreator::createInitialThunkSections( 17630b57cec5SDimitry Andric ArrayRef<OutputSection *> outputSections) { 17640b57cec5SDimitry Andric uint32_t thunkSectionSpacing = target->getThunkSectionSpacing(); 17650b57cec5SDimitry Andric 17660b57cec5SDimitry Andric forEachInputSectionDescription( 17670b57cec5SDimitry Andric outputSections, [&](OutputSection *os, InputSectionDescription *isd) { 17680b57cec5SDimitry Andric if (isd->sections.empty()) 17690b57cec5SDimitry Andric return; 17700b57cec5SDimitry Andric 17710b57cec5SDimitry Andric uint32_t isdBegin = isd->sections.front()->outSecOff; 17720b57cec5SDimitry Andric uint32_t isdEnd = 17730b57cec5SDimitry Andric isd->sections.back()->outSecOff + isd->sections.back()->getSize(); 17740b57cec5SDimitry Andric uint32_t lastThunkLowerBound = -1; 17750b57cec5SDimitry Andric if (isdEnd - isdBegin > thunkSectionSpacing * 2) 17760b57cec5SDimitry Andric lastThunkLowerBound = isdEnd - thunkSectionSpacing; 17770b57cec5SDimitry Andric 17780b57cec5SDimitry Andric uint32_t isecLimit; 17790b57cec5SDimitry Andric uint32_t prevIsecLimit = isdBegin; 17800b57cec5SDimitry Andric uint32_t thunkUpperBound = isdBegin + thunkSectionSpacing; 17810b57cec5SDimitry Andric 17820b57cec5SDimitry Andric for (const InputSection *isec : isd->sections) { 17830b57cec5SDimitry Andric isecLimit = isec->outSecOff + isec->getSize(); 17840b57cec5SDimitry Andric if (isecLimit > thunkUpperBound) { 17850b57cec5SDimitry Andric addThunkSection(os, isd, prevIsecLimit); 17860b57cec5SDimitry Andric thunkUpperBound = prevIsecLimit + thunkSectionSpacing; 17870b57cec5SDimitry Andric } 17880b57cec5SDimitry Andric if (isecLimit > lastThunkLowerBound) 17890b57cec5SDimitry Andric break; 17900b57cec5SDimitry Andric prevIsecLimit = isecLimit; 17910b57cec5SDimitry Andric } 17920b57cec5SDimitry Andric addThunkSection(os, isd, isecLimit); 17930b57cec5SDimitry Andric }); 17940b57cec5SDimitry Andric } 17950b57cec5SDimitry Andric 17960b57cec5SDimitry Andric ThunkSection *ThunkCreator::addThunkSection(OutputSection *os, 17970b57cec5SDimitry Andric InputSectionDescription *isd, 17980b57cec5SDimitry Andric uint64_t off) { 17990b57cec5SDimitry Andric auto *ts = make<ThunkSection>(os, off); 18000b57cec5SDimitry Andric ts->partition = os->partition; 180113138422SDimitry Andric if ((config->fixCortexA53Errata843419 || config->fixCortexA8) && 180213138422SDimitry Andric !isd->sections.empty()) { 180313138422SDimitry Andric // The errata fixes are sensitive to addresses modulo 4 KiB. When we add 180413138422SDimitry Andric // thunks we disturb the base addresses of sections placed after the thunks 180513138422SDimitry Andric // this makes patches we have generated redundant, and may cause us to 180613138422SDimitry Andric // generate more patches as different instructions are now in sensitive 180713138422SDimitry Andric // locations. When we generate more patches we may force more branches to 180813138422SDimitry Andric // go out of range, causing more thunks to be generated. In pathological 180913138422SDimitry Andric // cases this can cause the address dependent content pass not to converge. 181013138422SDimitry Andric // We fix this by rounding up the size of the ThunkSection to 4KiB, this 181113138422SDimitry Andric // limits the insertion of a ThunkSection on the addresses modulo 4 KiB, 181213138422SDimitry Andric // which means that adding Thunks to the section does not invalidate 181313138422SDimitry Andric // errata patches for following code. 181413138422SDimitry Andric // Rounding up the size to 4KiB has consequences for code-size and can 181513138422SDimitry Andric // trip up linker script defined assertions. For example the linux kernel 181613138422SDimitry Andric // has an assertion that what LLD represents as an InputSectionDescription 181713138422SDimitry Andric // does not exceed 4 KiB even if the overall OutputSection is > 128 Mib. 181813138422SDimitry Andric // We use the heuristic of rounding up the size when both of the following 181913138422SDimitry Andric // conditions are true: 182013138422SDimitry Andric // 1.) The OutputSection is larger than the ThunkSectionSpacing. This 182113138422SDimitry Andric // accounts for the case where no single InputSectionDescription is 182213138422SDimitry Andric // larger than the OutputSection size. This is conservative but simple. 182313138422SDimitry Andric // 2.) The InputSectionDescription is larger than 4 KiB. This will prevent 182413138422SDimitry Andric // any assertion failures that an InputSectionDescription is < 4 KiB 182513138422SDimitry Andric // in size. 182613138422SDimitry Andric uint64_t isdSize = isd->sections.back()->outSecOff + 182713138422SDimitry Andric isd->sections.back()->getSize() - 182813138422SDimitry Andric isd->sections.front()->outSecOff; 182913138422SDimitry Andric if (os->size > target->getThunkSectionSpacing() && isdSize > 4096) 183013138422SDimitry Andric ts->roundUpSizeForErrata = true; 183113138422SDimitry Andric } 18320b57cec5SDimitry Andric isd->thunkSections.push_back({ts, pass}); 18330b57cec5SDimitry Andric return ts; 18340b57cec5SDimitry Andric } 18350b57cec5SDimitry Andric 18360b57cec5SDimitry Andric static bool isThunkSectionCompatible(InputSection *source, 18370b57cec5SDimitry Andric SectionBase *target) { 18380b57cec5SDimitry Andric // We can't reuse thunks in different loadable partitions because they might 18390b57cec5SDimitry Andric // not be loaded. But partition 1 (the main partition) will always be loaded. 18400b57cec5SDimitry Andric if (source->partition != target->partition) 18410b57cec5SDimitry Andric return target->partition == 1; 18420b57cec5SDimitry Andric return true; 18430b57cec5SDimitry Andric } 18440b57cec5SDimitry Andric 1845480093f4SDimitry Andric static int64_t getPCBias(RelType type) { 1846480093f4SDimitry Andric if (config->emachine != EM_ARM) 1847480093f4SDimitry Andric return 0; 1848480093f4SDimitry Andric switch (type) { 1849480093f4SDimitry Andric case R_ARM_THM_JUMP19: 1850480093f4SDimitry Andric case R_ARM_THM_JUMP24: 1851480093f4SDimitry Andric case R_ARM_THM_CALL: 1852480093f4SDimitry Andric return 4; 1853480093f4SDimitry Andric default: 1854480093f4SDimitry Andric return 8; 1855480093f4SDimitry Andric } 1856480093f4SDimitry Andric } 1857480093f4SDimitry Andric 18580b57cec5SDimitry Andric std::pair<Thunk *, bool> ThunkCreator::getThunk(InputSection *isec, 18590b57cec5SDimitry Andric Relocation &rel, uint64_t src) { 18600b57cec5SDimitry Andric std::vector<Thunk *> *thunkVec = nullptr; 1861480093f4SDimitry Andric int64_t addend = rel.addend + getPCBias(rel.type); 18620b57cec5SDimitry Andric 1863480093f4SDimitry Andric // We use a ((section, offset), addend) pair to find the thunk position if 1864480093f4SDimitry Andric // possible so that we create only one thunk for aliased symbols or ICFed 1865480093f4SDimitry Andric // sections. There may be multiple relocations sharing the same (section, 1866480093f4SDimitry Andric // offset + addend) pair. We may revert the relocation back to its original 1867480093f4SDimitry Andric // non-Thunk target, so we cannot fold offset + addend. 18680b57cec5SDimitry Andric if (auto *d = dyn_cast<Defined>(rel.sym)) 18690b57cec5SDimitry Andric if (!d->isInPlt() && d->section) 1870480093f4SDimitry Andric thunkVec = &thunkedSymbolsBySectionAndAddend[{ 1871480093f4SDimitry Andric {d->section->repl, d->value}, addend}]; 18720b57cec5SDimitry Andric if (!thunkVec) 1873480093f4SDimitry Andric thunkVec = &thunkedSymbols[{rel.sym, addend}]; 18740b57cec5SDimitry Andric 18750b57cec5SDimitry Andric // Check existing Thunks for Sym to see if they can be reused 18760b57cec5SDimitry Andric for (Thunk *t : *thunkVec) 18770b57cec5SDimitry Andric if (isThunkSectionCompatible(isec, t->getThunkTargetSym()->section) && 18780b57cec5SDimitry Andric t->isCompatibleWith(*isec, rel) && 1879480093f4SDimitry Andric target->inBranchRange(rel.type, src, 1880480093f4SDimitry Andric t->getThunkTargetSym()->getVA(rel.addend) + 1881480093f4SDimitry Andric getPCBias(rel.type))) 18820b57cec5SDimitry Andric return std::make_pair(t, false); 18830b57cec5SDimitry Andric 18840b57cec5SDimitry Andric // No existing compatible Thunk in range, create a new one 18850b57cec5SDimitry Andric Thunk *t = addThunk(*isec, rel); 18860b57cec5SDimitry Andric thunkVec->push_back(t); 18870b57cec5SDimitry Andric return std::make_pair(t, true); 18880b57cec5SDimitry Andric } 18890b57cec5SDimitry Andric 18900b57cec5SDimitry Andric // Return true if the relocation target is an in range Thunk. 18910b57cec5SDimitry Andric // Return false if the relocation is not to a Thunk. If the relocation target 18920b57cec5SDimitry Andric // was originally to a Thunk, but is no longer in range we revert the 18930b57cec5SDimitry Andric // relocation back to its original non-Thunk target. 18940b57cec5SDimitry Andric bool ThunkCreator::normalizeExistingThunk(Relocation &rel, uint64_t src) { 18950b57cec5SDimitry Andric if (Thunk *t = thunks.lookup(rel.sym)) { 1896480093f4SDimitry Andric if (target->inBranchRange(rel.type, src, 1897480093f4SDimitry Andric rel.sym->getVA(rel.addend) + getPCBias(rel.type))) 18980b57cec5SDimitry Andric return true; 18990b57cec5SDimitry Andric rel.sym = &t->destination; 1900480093f4SDimitry Andric rel.addend = t->addend; 19010b57cec5SDimitry Andric if (rel.sym->isInPlt()) 19020b57cec5SDimitry Andric rel.expr = toPlt(rel.expr); 19030b57cec5SDimitry Andric } 19040b57cec5SDimitry Andric return false; 19050b57cec5SDimitry Andric } 19060b57cec5SDimitry Andric 19070b57cec5SDimitry Andric // Process all relocations from the InputSections that have been assigned 19080b57cec5SDimitry Andric // to InputSectionDescriptions and redirect through Thunks if needed. The 19090b57cec5SDimitry Andric // function should be called iteratively until it returns false. 19100b57cec5SDimitry Andric // 19110b57cec5SDimitry Andric // PreConditions: 19120b57cec5SDimitry Andric // All InputSections that may need a Thunk are reachable from 19130b57cec5SDimitry Andric // OutputSectionCommands. 19140b57cec5SDimitry Andric // 19150b57cec5SDimitry Andric // All OutputSections have an address and all InputSections have an offset 19160b57cec5SDimitry Andric // within the OutputSection. 19170b57cec5SDimitry Andric // 19180b57cec5SDimitry Andric // The offsets between caller (relocation place) and callee 19190b57cec5SDimitry Andric // (relocation target) will not be modified outside of createThunks(). 19200b57cec5SDimitry Andric // 19210b57cec5SDimitry Andric // PostConditions: 19220b57cec5SDimitry Andric // If return value is true then ThunkSections have been inserted into 19230b57cec5SDimitry Andric // OutputSections. All relocations that needed a Thunk based on the information 19240b57cec5SDimitry Andric // available to createThunks() on entry have been redirected to a Thunk. Note 19250b57cec5SDimitry Andric // that adding Thunks changes offsets between caller and callee so more Thunks 19260b57cec5SDimitry Andric // may be required. 19270b57cec5SDimitry Andric // 19280b57cec5SDimitry Andric // If return value is false then no more Thunks are needed, and createThunks has 19290b57cec5SDimitry Andric // made no changes. If the target requires range extension thunks, currently 19300b57cec5SDimitry Andric // ARM, then any future change in offset between caller and callee risks a 19310b57cec5SDimitry Andric // relocation out of range error. 19320b57cec5SDimitry Andric bool ThunkCreator::createThunks(ArrayRef<OutputSection *> outputSections) { 19330b57cec5SDimitry Andric bool addressesChanged = false; 19340b57cec5SDimitry Andric 19350b57cec5SDimitry Andric if (pass == 0 && target->getThunkSectionSpacing()) 19360b57cec5SDimitry Andric createInitialThunkSections(outputSections); 19370b57cec5SDimitry Andric 19380b57cec5SDimitry Andric // Create all the Thunks and insert them into synthetic ThunkSections. The 19390b57cec5SDimitry Andric // ThunkSections are later inserted back into InputSectionDescriptions. 19400b57cec5SDimitry Andric // We separate the creation of ThunkSections from the insertion of the 19410b57cec5SDimitry Andric // ThunkSections as ThunkSections are not always inserted into the same 19420b57cec5SDimitry Andric // InputSectionDescription as the caller. 19430b57cec5SDimitry Andric forEachInputSectionDescription( 19440b57cec5SDimitry Andric outputSections, [&](OutputSection *os, InputSectionDescription *isd) { 19450b57cec5SDimitry Andric for (InputSection *isec : isd->sections) 19460b57cec5SDimitry Andric for (Relocation &rel : isec->relocations) { 19470b57cec5SDimitry Andric uint64_t src = isec->getVA(rel.offset); 19480b57cec5SDimitry Andric 19490b57cec5SDimitry Andric // If we are a relocation to an existing Thunk, check if it is 19500b57cec5SDimitry Andric // still in range. If not then Rel will be altered to point to its 19510b57cec5SDimitry Andric // original target so another Thunk can be generated. 19520b57cec5SDimitry Andric if (pass > 0 && normalizeExistingThunk(rel, src)) 19530b57cec5SDimitry Andric continue; 19540b57cec5SDimitry Andric 19550b57cec5SDimitry Andric if (!target->needsThunk(rel.expr, rel.type, isec->file, src, 1956480093f4SDimitry Andric *rel.sym, rel.addend)) 19570b57cec5SDimitry Andric continue; 19580b57cec5SDimitry Andric 19590b57cec5SDimitry Andric Thunk *t; 19600b57cec5SDimitry Andric bool isNew; 19610b57cec5SDimitry Andric std::tie(t, isNew) = getThunk(isec, rel, src); 19620b57cec5SDimitry Andric 19630b57cec5SDimitry Andric if (isNew) { 19640b57cec5SDimitry Andric // Find or create a ThunkSection for the new Thunk 19650b57cec5SDimitry Andric ThunkSection *ts; 19660b57cec5SDimitry Andric if (auto *tis = t->getTargetInputSection()) 19670b57cec5SDimitry Andric ts = getISThunkSec(tis); 19680b57cec5SDimitry Andric else 19690b57cec5SDimitry Andric ts = getISDThunkSec(os, isec, isd, rel.type, src); 19700b57cec5SDimitry Andric ts->addThunk(t); 19710b57cec5SDimitry Andric thunks[t->getThunkTargetSym()] = t; 19720b57cec5SDimitry Andric } 19730b57cec5SDimitry Andric 19740b57cec5SDimitry Andric // Redirect relocation to Thunk, we never go via the PLT to a Thunk 19750b57cec5SDimitry Andric rel.sym = t->getThunkTargetSym(); 19760b57cec5SDimitry Andric rel.expr = fromPlt(rel.expr); 19770b57cec5SDimitry Andric 197813138422SDimitry Andric // On AArch64 and PPC, a jump/call relocation may be encoded as 1979480093f4SDimitry Andric // STT_SECTION + non-zero addend, clear the addend after 1980480093f4SDimitry Andric // redirection. 198113138422SDimitry Andric if (config->emachine != EM_MIPS) 198213138422SDimitry Andric rel.addend = -getPCBias(rel.type); 19830b57cec5SDimitry Andric } 19840b57cec5SDimitry Andric 19850b57cec5SDimitry Andric for (auto &p : isd->thunkSections) 19860b57cec5SDimitry Andric addressesChanged |= p.first->assignOffsets(); 19870b57cec5SDimitry Andric }); 19880b57cec5SDimitry Andric 19890b57cec5SDimitry Andric for (auto &p : thunkedSections) 19900b57cec5SDimitry Andric addressesChanged |= p.second->assignOffsets(); 19910b57cec5SDimitry Andric 19920b57cec5SDimitry Andric // Merge all created synthetic ThunkSections back into OutputSection 19930b57cec5SDimitry Andric mergeThunks(outputSections); 19940b57cec5SDimitry Andric ++pass; 19950b57cec5SDimitry Andric return addressesChanged; 19960b57cec5SDimitry Andric } 19970b57cec5SDimitry Andric 1998*5ffd83dbSDimitry Andric // The following aid in the conversion of call x@GDPLT to call __tls_get_addr 1999*5ffd83dbSDimitry Andric // hexagonNeedsTLSSymbol scans for relocations would require a call to 2000*5ffd83dbSDimitry Andric // __tls_get_addr. 2001*5ffd83dbSDimitry Andric // hexagonTLSSymbolUpdate rebinds the relocation to __tls_get_addr. 2002*5ffd83dbSDimitry Andric bool elf::hexagonNeedsTLSSymbol(ArrayRef<OutputSection *> outputSections) { 2003*5ffd83dbSDimitry Andric bool needTlsSymbol = false; 2004*5ffd83dbSDimitry Andric forEachInputSectionDescription( 2005*5ffd83dbSDimitry Andric outputSections, [&](OutputSection *os, InputSectionDescription *isd) { 2006*5ffd83dbSDimitry Andric for (InputSection *isec : isd->sections) 2007*5ffd83dbSDimitry Andric for (Relocation &rel : isec->relocations) 2008*5ffd83dbSDimitry Andric if (rel.sym->type == llvm::ELF::STT_TLS && rel.expr == R_PLT_PC) { 2009*5ffd83dbSDimitry Andric needTlsSymbol = true; 2010*5ffd83dbSDimitry Andric return; 2011*5ffd83dbSDimitry Andric } 2012*5ffd83dbSDimitry Andric }); 2013*5ffd83dbSDimitry Andric return needTlsSymbol; 2014*5ffd83dbSDimitry Andric } 201585868e8aSDimitry Andric 2016*5ffd83dbSDimitry Andric void elf::hexagonTLSSymbolUpdate(ArrayRef<OutputSection *> outputSections) { 2017*5ffd83dbSDimitry Andric Symbol *sym = symtab->find("__tls_get_addr"); 2018*5ffd83dbSDimitry Andric if (!sym) 2019*5ffd83dbSDimitry Andric return; 2020*5ffd83dbSDimitry Andric bool needEntry = true; 2021*5ffd83dbSDimitry Andric forEachInputSectionDescription( 2022*5ffd83dbSDimitry Andric outputSections, [&](OutputSection *os, InputSectionDescription *isd) { 2023*5ffd83dbSDimitry Andric for (InputSection *isec : isd->sections) 2024*5ffd83dbSDimitry Andric for (Relocation &rel : isec->relocations) 2025*5ffd83dbSDimitry Andric if (rel.sym->type == llvm::ELF::STT_TLS && rel.expr == R_PLT_PC) { 2026*5ffd83dbSDimitry Andric if (needEntry) { 2027*5ffd83dbSDimitry Andric addPltEntry(in.plt, in.gotPlt, in.relaPlt, target->pltRel, 2028*5ffd83dbSDimitry Andric *sym); 2029*5ffd83dbSDimitry Andric needEntry = false; 2030*5ffd83dbSDimitry Andric } 2031*5ffd83dbSDimitry Andric rel.sym = sym; 2032*5ffd83dbSDimitry Andric } 2033*5ffd83dbSDimitry Andric }); 2034*5ffd83dbSDimitry Andric } 2035*5ffd83dbSDimitry Andric 2036*5ffd83dbSDimitry Andric template void elf::scanRelocations<ELF32LE>(InputSectionBase &); 2037*5ffd83dbSDimitry Andric template void elf::scanRelocations<ELF32BE>(InputSectionBase &); 2038*5ffd83dbSDimitry Andric template void elf::scanRelocations<ELF64LE>(InputSectionBase &); 2039*5ffd83dbSDimitry Andric template void elf::scanRelocations<ELF64BE>(InputSectionBase &); 2040*5ffd83dbSDimitry Andric template void elf::reportUndefinedSymbols<ELF32LE>(); 2041*5ffd83dbSDimitry Andric template void elf::reportUndefinedSymbols<ELF32BE>(); 2042*5ffd83dbSDimitry Andric template void elf::reportUndefinedSymbols<ELF64LE>(); 2043*5ffd83dbSDimitry Andric template void elf::reportUndefinedSymbols<ELF64BE>(); 2044