xref: /freebsd/contrib/llvm-project/lld/ELF/Relocations.cpp (revision 0b57cec536236d46e3dba9bd041533462f33dbb7)
1*0b57cec5SDimitry Andric //===- Relocations.cpp ----------------------------------------------------===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric // This file contains platform-independent functions to process relocations.
10*0b57cec5SDimitry Andric // I'll describe the overview of this file here.
11*0b57cec5SDimitry Andric //
12*0b57cec5SDimitry Andric // Simple relocations are easy to handle for the linker. For example,
13*0b57cec5SDimitry Andric // for R_X86_64_PC64 relocs, the linker just has to fix up locations
14*0b57cec5SDimitry Andric // with the relative offsets to the target symbols. It would just be
15*0b57cec5SDimitry Andric // reading records from relocation sections and applying them to output.
16*0b57cec5SDimitry Andric //
17*0b57cec5SDimitry Andric // But not all relocations are that easy to handle. For example, for
18*0b57cec5SDimitry Andric // R_386_GOTOFF relocs, the linker has to create new GOT entries for
19*0b57cec5SDimitry Andric // symbols if they don't exist, and fix up locations with GOT entry
20*0b57cec5SDimitry Andric // offsets from the beginning of GOT section. So there is more than
21*0b57cec5SDimitry Andric // fixing addresses in relocation processing.
22*0b57cec5SDimitry Andric //
23*0b57cec5SDimitry Andric // ELF defines a large number of complex relocations.
24*0b57cec5SDimitry Andric //
25*0b57cec5SDimitry Andric // The functions in this file analyze relocations and do whatever needs
26*0b57cec5SDimitry Andric // to be done. It includes, but not limited to, the following.
27*0b57cec5SDimitry Andric //
28*0b57cec5SDimitry Andric //  - create GOT/PLT entries
29*0b57cec5SDimitry Andric //  - create new relocations in .dynsym to let the dynamic linker resolve
30*0b57cec5SDimitry Andric //    them at runtime (since ELF supports dynamic linking, not all
31*0b57cec5SDimitry Andric //    relocations can be resolved at link-time)
32*0b57cec5SDimitry Andric //  - create COPY relocs and reserve space in .bss
33*0b57cec5SDimitry Andric //  - replace expensive relocs (in terms of runtime cost) with cheap ones
34*0b57cec5SDimitry Andric //  - error out infeasible combinations such as PIC and non-relative relocs
35*0b57cec5SDimitry Andric //
36*0b57cec5SDimitry Andric // Note that the functions in this file don't actually apply relocations
37*0b57cec5SDimitry Andric // because it doesn't know about the output file nor the output file buffer.
38*0b57cec5SDimitry Andric // It instead stores Relocation objects to InputSection's Relocations
39*0b57cec5SDimitry Andric // vector to let it apply later in InputSection::writeTo.
40*0b57cec5SDimitry Andric //
41*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
42*0b57cec5SDimitry Andric 
43*0b57cec5SDimitry Andric #include "Relocations.h"
44*0b57cec5SDimitry Andric #include "Config.h"
45*0b57cec5SDimitry Andric #include "LinkerScript.h"
46*0b57cec5SDimitry Andric #include "OutputSections.h"
47*0b57cec5SDimitry Andric #include "SymbolTable.h"
48*0b57cec5SDimitry Andric #include "Symbols.h"
49*0b57cec5SDimitry Andric #include "SyntheticSections.h"
50*0b57cec5SDimitry Andric #include "Target.h"
51*0b57cec5SDimitry Andric #include "Thunks.h"
52*0b57cec5SDimitry Andric #include "lld/Common/ErrorHandler.h"
53*0b57cec5SDimitry Andric #include "lld/Common/Memory.h"
54*0b57cec5SDimitry Andric #include "lld/Common/Strings.h"
55*0b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
56*0b57cec5SDimitry Andric #include "llvm/Support/Endian.h"
57*0b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
58*0b57cec5SDimitry Andric #include <algorithm>
59*0b57cec5SDimitry Andric 
60*0b57cec5SDimitry Andric using namespace llvm;
61*0b57cec5SDimitry Andric using namespace llvm::ELF;
62*0b57cec5SDimitry Andric using namespace llvm::object;
63*0b57cec5SDimitry Andric using namespace llvm::support::endian;
64*0b57cec5SDimitry Andric 
65*0b57cec5SDimitry Andric using namespace lld;
66*0b57cec5SDimitry Andric using namespace lld::elf;
67*0b57cec5SDimitry Andric 
68*0b57cec5SDimitry Andric static Optional<std::string> getLinkerScriptLocation(const Symbol &sym) {
69*0b57cec5SDimitry Andric   for (BaseCommand *base : script->sectionCommands)
70*0b57cec5SDimitry Andric     if (auto *cmd = dyn_cast<SymbolAssignment>(base))
71*0b57cec5SDimitry Andric       if (cmd->sym == &sym)
72*0b57cec5SDimitry Andric         return cmd->location;
73*0b57cec5SDimitry Andric   return None;
74*0b57cec5SDimitry Andric }
75*0b57cec5SDimitry Andric 
76*0b57cec5SDimitry Andric // Construct a message in the following format.
77*0b57cec5SDimitry Andric //
78*0b57cec5SDimitry Andric // >>> defined in /home/alice/src/foo.o
79*0b57cec5SDimitry Andric // >>> referenced by bar.c:12 (/home/alice/src/bar.c:12)
80*0b57cec5SDimitry Andric // >>>               /home/alice/src/bar.o:(.text+0x1)
81*0b57cec5SDimitry Andric static std::string getLocation(InputSectionBase &s, const Symbol &sym,
82*0b57cec5SDimitry Andric                                uint64_t off) {
83*0b57cec5SDimitry Andric   std::string msg = "\n>>> defined in ";
84*0b57cec5SDimitry Andric   if (sym.file)
85*0b57cec5SDimitry Andric     msg += toString(sym.file);
86*0b57cec5SDimitry Andric   else if (Optional<std::string> loc = getLinkerScriptLocation(sym))
87*0b57cec5SDimitry Andric     msg += *loc;
88*0b57cec5SDimitry Andric 
89*0b57cec5SDimitry Andric   msg += "\n>>> referenced by ";
90*0b57cec5SDimitry Andric   std::string src = s.getSrcMsg(sym, off);
91*0b57cec5SDimitry Andric   if (!src.empty())
92*0b57cec5SDimitry Andric     msg += src + "\n>>>               ";
93*0b57cec5SDimitry Andric   return msg + s.getObjMsg(off);
94*0b57cec5SDimitry Andric }
95*0b57cec5SDimitry Andric 
96*0b57cec5SDimitry Andric namespace {
97*0b57cec5SDimitry Andric // Build a bitmask with one bit set for each RelExpr.
98*0b57cec5SDimitry Andric //
99*0b57cec5SDimitry Andric // Constexpr function arguments can't be used in static asserts, so we
100*0b57cec5SDimitry Andric // use template arguments to build the mask.
101*0b57cec5SDimitry Andric // But function template partial specializations don't exist (needed
102*0b57cec5SDimitry Andric // for base case of the recursion), so we need a dummy struct.
103*0b57cec5SDimitry Andric template <RelExpr... Exprs> struct RelExprMaskBuilder {
104*0b57cec5SDimitry Andric   static inline uint64_t build() { return 0; }
105*0b57cec5SDimitry Andric };
106*0b57cec5SDimitry Andric 
107*0b57cec5SDimitry Andric // Specialization for recursive case.
108*0b57cec5SDimitry Andric template <RelExpr Head, RelExpr... Tail>
109*0b57cec5SDimitry Andric struct RelExprMaskBuilder<Head, Tail...> {
110*0b57cec5SDimitry Andric   static inline uint64_t build() {
111*0b57cec5SDimitry Andric     static_assert(0 <= Head && Head < 64,
112*0b57cec5SDimitry Andric                   "RelExpr is too large for 64-bit mask!");
113*0b57cec5SDimitry Andric     return (uint64_t(1) << Head) | RelExprMaskBuilder<Tail...>::build();
114*0b57cec5SDimitry Andric   }
115*0b57cec5SDimitry Andric };
116*0b57cec5SDimitry Andric } // namespace
117*0b57cec5SDimitry Andric 
118*0b57cec5SDimitry Andric // Return true if `Expr` is one of `Exprs`.
119*0b57cec5SDimitry Andric // There are fewer than 64 RelExpr's, so we can represent any set of
120*0b57cec5SDimitry Andric // RelExpr's as a constant bit mask and test for membership with a
121*0b57cec5SDimitry Andric // couple cheap bitwise operations.
122*0b57cec5SDimitry Andric template <RelExpr... Exprs> bool oneof(RelExpr expr) {
123*0b57cec5SDimitry Andric   assert(0 <= expr && (int)expr < 64 &&
124*0b57cec5SDimitry Andric          "RelExpr is too large for 64-bit mask!");
125*0b57cec5SDimitry Andric   return (uint64_t(1) << expr) & RelExprMaskBuilder<Exprs...>::build();
126*0b57cec5SDimitry Andric }
127*0b57cec5SDimitry Andric 
128*0b57cec5SDimitry Andric // This function is similar to the `handleTlsRelocation`. MIPS does not
129*0b57cec5SDimitry Andric // support any relaxations for TLS relocations so by factoring out MIPS
130*0b57cec5SDimitry Andric // handling in to the separate function we can simplify the code and do not
131*0b57cec5SDimitry Andric // pollute other `handleTlsRelocation` by MIPS `ifs` statements.
132*0b57cec5SDimitry Andric // Mips has a custom MipsGotSection that handles the writing of GOT entries
133*0b57cec5SDimitry Andric // without dynamic relocations.
134*0b57cec5SDimitry Andric static unsigned handleMipsTlsRelocation(RelType type, Symbol &sym,
135*0b57cec5SDimitry Andric                                         InputSectionBase &c, uint64_t offset,
136*0b57cec5SDimitry Andric                                         int64_t addend, RelExpr expr) {
137*0b57cec5SDimitry Andric   if (expr == R_MIPS_TLSLD) {
138*0b57cec5SDimitry Andric     in.mipsGot->addTlsIndex(*c.file);
139*0b57cec5SDimitry Andric     c.relocations.push_back({expr, type, offset, addend, &sym});
140*0b57cec5SDimitry Andric     return 1;
141*0b57cec5SDimitry Andric   }
142*0b57cec5SDimitry Andric   if (expr == R_MIPS_TLSGD) {
143*0b57cec5SDimitry Andric     in.mipsGot->addDynTlsEntry(*c.file, sym);
144*0b57cec5SDimitry Andric     c.relocations.push_back({expr, type, offset, addend, &sym});
145*0b57cec5SDimitry Andric     return 1;
146*0b57cec5SDimitry Andric   }
147*0b57cec5SDimitry Andric   return 0;
148*0b57cec5SDimitry Andric }
149*0b57cec5SDimitry Andric 
150*0b57cec5SDimitry Andric // Notes about General Dynamic and Local Dynamic TLS models below. They may
151*0b57cec5SDimitry Andric // require the generation of a pair of GOT entries that have associated dynamic
152*0b57cec5SDimitry Andric // relocations. The pair of GOT entries created are of the form GOT[e0] Module
153*0b57cec5SDimitry Andric // Index (Used to find pointer to TLS block at run-time) GOT[e1] Offset of
154*0b57cec5SDimitry Andric // symbol in TLS block.
155*0b57cec5SDimitry Andric //
156*0b57cec5SDimitry Andric // Returns the number of relocations processed.
157*0b57cec5SDimitry Andric template <class ELFT>
158*0b57cec5SDimitry Andric static unsigned
159*0b57cec5SDimitry Andric handleTlsRelocation(RelType type, Symbol &sym, InputSectionBase &c,
160*0b57cec5SDimitry Andric                     typename ELFT::uint offset, int64_t addend, RelExpr expr) {
161*0b57cec5SDimitry Andric   if (!sym.isTls())
162*0b57cec5SDimitry Andric     return 0;
163*0b57cec5SDimitry Andric 
164*0b57cec5SDimitry Andric   if (config->emachine == EM_MIPS)
165*0b57cec5SDimitry Andric     return handleMipsTlsRelocation(type, sym, c, offset, addend, expr);
166*0b57cec5SDimitry Andric 
167*0b57cec5SDimitry Andric   if (oneof<R_AARCH64_TLSDESC_PAGE, R_TLSDESC, R_TLSDESC_CALL, R_TLSDESC_PC>(
168*0b57cec5SDimitry Andric           expr) &&
169*0b57cec5SDimitry Andric       config->shared) {
170*0b57cec5SDimitry Andric     if (in.got->addDynTlsEntry(sym)) {
171*0b57cec5SDimitry Andric       uint64_t off = in.got->getGlobalDynOffset(sym);
172*0b57cec5SDimitry Andric       mainPart->relaDyn->addReloc(
173*0b57cec5SDimitry Andric           {target->tlsDescRel, in.got, off, !sym.isPreemptible, &sym, 0});
174*0b57cec5SDimitry Andric     }
175*0b57cec5SDimitry Andric     if (expr != R_TLSDESC_CALL)
176*0b57cec5SDimitry Andric       c.relocations.push_back({expr, type, offset, addend, &sym});
177*0b57cec5SDimitry Andric     return 1;
178*0b57cec5SDimitry Andric   }
179*0b57cec5SDimitry Andric 
180*0b57cec5SDimitry Andric   bool canRelax = config->emachine != EM_ARM && config->emachine != EM_RISCV;
181*0b57cec5SDimitry Andric 
182*0b57cec5SDimitry Andric   // If we are producing an executable and the symbol is non-preemptable, it
183*0b57cec5SDimitry Andric   // must be defined and the code sequence can be relaxed to use Local-Exec.
184*0b57cec5SDimitry Andric   //
185*0b57cec5SDimitry Andric   // ARM and RISC-V do not support any relaxations for TLS relocations, however,
186*0b57cec5SDimitry Andric   // we can omit the DTPMOD dynamic relocations and resolve them at link time
187*0b57cec5SDimitry Andric   // because them are always 1. This may be necessary for static linking as
188*0b57cec5SDimitry Andric   // DTPMOD may not be expected at load time.
189*0b57cec5SDimitry Andric   bool isLocalInExecutable = !sym.isPreemptible && !config->shared;
190*0b57cec5SDimitry Andric 
191*0b57cec5SDimitry Andric   // Local Dynamic is for access to module local TLS variables, while still
192*0b57cec5SDimitry Andric   // being suitable for being dynamically loaded via dlopen. GOT[e0] is the
193*0b57cec5SDimitry Andric   // module index, with a special value of 0 for the current module. GOT[e1] is
194*0b57cec5SDimitry Andric   // unused. There only needs to be one module index entry.
195*0b57cec5SDimitry Andric   if (oneof<R_TLSLD_GOT, R_TLSLD_GOTPLT, R_TLSLD_PC, R_TLSLD_HINT>(
196*0b57cec5SDimitry Andric           expr)) {
197*0b57cec5SDimitry Andric     // Local-Dynamic relocs can be relaxed to Local-Exec.
198*0b57cec5SDimitry Andric     if (canRelax && !config->shared) {
199*0b57cec5SDimitry Andric       c.relocations.push_back(
200*0b57cec5SDimitry Andric           {target->adjustRelaxExpr(type, nullptr, R_RELAX_TLS_LD_TO_LE), type,
201*0b57cec5SDimitry Andric            offset, addend, &sym});
202*0b57cec5SDimitry Andric       return target->getTlsGdRelaxSkip(type);
203*0b57cec5SDimitry Andric     }
204*0b57cec5SDimitry Andric     if (expr == R_TLSLD_HINT)
205*0b57cec5SDimitry Andric       return 1;
206*0b57cec5SDimitry Andric     if (in.got->addTlsIndex()) {
207*0b57cec5SDimitry Andric       if (isLocalInExecutable)
208*0b57cec5SDimitry Andric         in.got->relocations.push_back(
209*0b57cec5SDimitry Andric             {R_ADDEND, target->symbolicRel, in.got->getTlsIndexOff(), 1, &sym});
210*0b57cec5SDimitry Andric       else
211*0b57cec5SDimitry Andric         mainPart->relaDyn->addReloc(target->tlsModuleIndexRel, in.got,
212*0b57cec5SDimitry Andric                                 in.got->getTlsIndexOff(), nullptr);
213*0b57cec5SDimitry Andric     }
214*0b57cec5SDimitry Andric     c.relocations.push_back({expr, type, offset, addend, &sym});
215*0b57cec5SDimitry Andric     return 1;
216*0b57cec5SDimitry Andric   }
217*0b57cec5SDimitry Andric 
218*0b57cec5SDimitry Andric   // Local-Dynamic relocs can be relaxed to Local-Exec.
219*0b57cec5SDimitry Andric   if (expr == R_DTPREL && !config->shared) {
220*0b57cec5SDimitry Andric     c.relocations.push_back(
221*0b57cec5SDimitry Andric         {target->adjustRelaxExpr(type, nullptr, R_RELAX_TLS_LD_TO_LE), type,
222*0b57cec5SDimitry Andric          offset, addend, &sym});
223*0b57cec5SDimitry Andric     return 1;
224*0b57cec5SDimitry Andric   }
225*0b57cec5SDimitry Andric 
226*0b57cec5SDimitry Andric   // Local-Dynamic sequence where offset of tls variable relative to dynamic
227*0b57cec5SDimitry Andric   // thread pointer is stored in the got. This cannot be relaxed to Local-Exec.
228*0b57cec5SDimitry Andric   if (expr == R_TLSLD_GOT_OFF) {
229*0b57cec5SDimitry Andric     if (!sym.isInGot()) {
230*0b57cec5SDimitry Andric       in.got->addEntry(sym);
231*0b57cec5SDimitry Andric       uint64_t off = sym.getGotOffset();
232*0b57cec5SDimitry Andric       in.got->relocations.push_back(
233*0b57cec5SDimitry Andric           {R_ABS, target->tlsOffsetRel, off, 0, &sym});
234*0b57cec5SDimitry Andric     }
235*0b57cec5SDimitry Andric     c.relocations.push_back({expr, type, offset, addend, &sym});
236*0b57cec5SDimitry Andric     return 1;
237*0b57cec5SDimitry Andric   }
238*0b57cec5SDimitry Andric 
239*0b57cec5SDimitry Andric   if (oneof<R_AARCH64_TLSDESC_PAGE, R_TLSDESC, R_TLSDESC_CALL, R_TLSDESC_PC,
240*0b57cec5SDimitry Andric             R_TLSGD_GOT, R_TLSGD_GOTPLT, R_TLSGD_PC>(expr)) {
241*0b57cec5SDimitry Andric     if (!canRelax || config->shared) {
242*0b57cec5SDimitry Andric       if (in.got->addDynTlsEntry(sym)) {
243*0b57cec5SDimitry Andric         uint64_t off = in.got->getGlobalDynOffset(sym);
244*0b57cec5SDimitry Andric 
245*0b57cec5SDimitry Andric         if (isLocalInExecutable)
246*0b57cec5SDimitry Andric           // Write one to the GOT slot.
247*0b57cec5SDimitry Andric           in.got->relocations.push_back(
248*0b57cec5SDimitry Andric               {R_ADDEND, target->symbolicRel, off, 1, &sym});
249*0b57cec5SDimitry Andric         else
250*0b57cec5SDimitry Andric           mainPart->relaDyn->addReloc(target->tlsModuleIndexRel, in.got, off, &sym);
251*0b57cec5SDimitry Andric 
252*0b57cec5SDimitry Andric         // If the symbol is preemptible we need the dynamic linker to write
253*0b57cec5SDimitry Andric         // the offset too.
254*0b57cec5SDimitry Andric         uint64_t offsetOff = off + config->wordsize;
255*0b57cec5SDimitry Andric         if (sym.isPreemptible)
256*0b57cec5SDimitry Andric           mainPart->relaDyn->addReloc(target->tlsOffsetRel, in.got, offsetOff,
257*0b57cec5SDimitry Andric                                   &sym);
258*0b57cec5SDimitry Andric         else
259*0b57cec5SDimitry Andric           in.got->relocations.push_back(
260*0b57cec5SDimitry Andric               {R_ABS, target->tlsOffsetRel, offsetOff, 0, &sym});
261*0b57cec5SDimitry Andric       }
262*0b57cec5SDimitry Andric       c.relocations.push_back({expr, type, offset, addend, &sym});
263*0b57cec5SDimitry Andric       return 1;
264*0b57cec5SDimitry Andric     }
265*0b57cec5SDimitry Andric 
266*0b57cec5SDimitry Andric     // Global-Dynamic relocs can be relaxed to Initial-Exec or Local-Exec
267*0b57cec5SDimitry Andric     // depending on the symbol being locally defined or not.
268*0b57cec5SDimitry Andric     if (sym.isPreemptible) {
269*0b57cec5SDimitry Andric       c.relocations.push_back(
270*0b57cec5SDimitry Andric           {target->adjustRelaxExpr(type, nullptr, R_RELAX_TLS_GD_TO_IE), type,
271*0b57cec5SDimitry Andric            offset, addend, &sym});
272*0b57cec5SDimitry Andric       if (!sym.isInGot()) {
273*0b57cec5SDimitry Andric         in.got->addEntry(sym);
274*0b57cec5SDimitry Andric         mainPart->relaDyn->addReloc(target->tlsGotRel, in.got, sym.getGotOffset(),
275*0b57cec5SDimitry Andric                                 &sym);
276*0b57cec5SDimitry Andric       }
277*0b57cec5SDimitry Andric     } else {
278*0b57cec5SDimitry Andric       c.relocations.push_back(
279*0b57cec5SDimitry Andric           {target->adjustRelaxExpr(type, nullptr, R_RELAX_TLS_GD_TO_LE), type,
280*0b57cec5SDimitry Andric            offset, addend, &sym});
281*0b57cec5SDimitry Andric     }
282*0b57cec5SDimitry Andric     return target->getTlsGdRelaxSkip(type);
283*0b57cec5SDimitry Andric   }
284*0b57cec5SDimitry Andric 
285*0b57cec5SDimitry Andric   // Initial-Exec relocs can be relaxed to Local-Exec if the symbol is locally
286*0b57cec5SDimitry Andric   // defined.
287*0b57cec5SDimitry Andric   if (oneof<R_GOT, R_GOTPLT, R_GOT_PC, R_AARCH64_GOT_PAGE_PC, R_GOT_OFF,
288*0b57cec5SDimitry Andric             R_TLSIE_HINT>(expr) &&
289*0b57cec5SDimitry Andric       canRelax && isLocalInExecutable) {
290*0b57cec5SDimitry Andric     c.relocations.push_back({R_RELAX_TLS_IE_TO_LE, type, offset, addend, &sym});
291*0b57cec5SDimitry Andric     return 1;
292*0b57cec5SDimitry Andric   }
293*0b57cec5SDimitry Andric 
294*0b57cec5SDimitry Andric   if (expr == R_TLSIE_HINT)
295*0b57cec5SDimitry Andric     return 1;
296*0b57cec5SDimitry Andric   return 0;
297*0b57cec5SDimitry Andric }
298*0b57cec5SDimitry Andric 
299*0b57cec5SDimitry Andric static RelType getMipsPairType(RelType type, bool isLocal) {
300*0b57cec5SDimitry Andric   switch (type) {
301*0b57cec5SDimitry Andric   case R_MIPS_HI16:
302*0b57cec5SDimitry Andric     return R_MIPS_LO16;
303*0b57cec5SDimitry Andric   case R_MIPS_GOT16:
304*0b57cec5SDimitry Andric     // In case of global symbol, the R_MIPS_GOT16 relocation does not
305*0b57cec5SDimitry Andric     // have a pair. Each global symbol has a unique entry in the GOT
306*0b57cec5SDimitry Andric     // and a corresponding instruction with help of the R_MIPS_GOT16
307*0b57cec5SDimitry Andric     // relocation loads an address of the symbol. In case of local
308*0b57cec5SDimitry Andric     // symbol, the R_MIPS_GOT16 relocation creates a GOT entry to hold
309*0b57cec5SDimitry Andric     // the high 16 bits of the symbol's value. A paired R_MIPS_LO16
310*0b57cec5SDimitry Andric     // relocations handle low 16 bits of the address. That allows
311*0b57cec5SDimitry Andric     // to allocate only one GOT entry for every 64 KBytes of local data.
312*0b57cec5SDimitry Andric     return isLocal ? R_MIPS_LO16 : R_MIPS_NONE;
313*0b57cec5SDimitry Andric   case R_MICROMIPS_GOT16:
314*0b57cec5SDimitry Andric     return isLocal ? R_MICROMIPS_LO16 : R_MIPS_NONE;
315*0b57cec5SDimitry Andric   case R_MIPS_PCHI16:
316*0b57cec5SDimitry Andric     return R_MIPS_PCLO16;
317*0b57cec5SDimitry Andric   case R_MICROMIPS_HI16:
318*0b57cec5SDimitry Andric     return R_MICROMIPS_LO16;
319*0b57cec5SDimitry Andric   default:
320*0b57cec5SDimitry Andric     return R_MIPS_NONE;
321*0b57cec5SDimitry Andric   }
322*0b57cec5SDimitry Andric }
323*0b57cec5SDimitry Andric 
324*0b57cec5SDimitry Andric // True if non-preemptable symbol always has the same value regardless of where
325*0b57cec5SDimitry Andric // the DSO is loaded.
326*0b57cec5SDimitry Andric static bool isAbsolute(const Symbol &sym) {
327*0b57cec5SDimitry Andric   if (sym.isUndefWeak())
328*0b57cec5SDimitry Andric     return true;
329*0b57cec5SDimitry Andric   if (const auto *dr = dyn_cast<Defined>(&sym))
330*0b57cec5SDimitry Andric     return dr->section == nullptr; // Absolute symbol.
331*0b57cec5SDimitry Andric   return false;
332*0b57cec5SDimitry Andric }
333*0b57cec5SDimitry Andric 
334*0b57cec5SDimitry Andric static bool isAbsoluteValue(const Symbol &sym) {
335*0b57cec5SDimitry Andric   return isAbsolute(sym) || sym.isTls();
336*0b57cec5SDimitry Andric }
337*0b57cec5SDimitry Andric 
338*0b57cec5SDimitry Andric // Returns true if Expr refers a PLT entry.
339*0b57cec5SDimitry Andric static bool needsPlt(RelExpr expr) {
340*0b57cec5SDimitry Andric   return oneof<R_PLT_PC, R_PPC32_PLTREL, R_PPC64_CALL_PLT, R_PLT>(expr);
341*0b57cec5SDimitry Andric }
342*0b57cec5SDimitry Andric 
343*0b57cec5SDimitry Andric // Returns true if Expr refers a GOT entry. Note that this function
344*0b57cec5SDimitry Andric // returns false for TLS variables even though they need GOT, because
345*0b57cec5SDimitry Andric // TLS variables uses GOT differently than the regular variables.
346*0b57cec5SDimitry Andric static bool needsGot(RelExpr expr) {
347*0b57cec5SDimitry Andric   return oneof<R_GOT, R_GOT_OFF, R_HEXAGON_GOT, R_MIPS_GOT_LOCAL_PAGE,
348*0b57cec5SDimitry Andric                R_MIPS_GOT_OFF, R_MIPS_GOT_OFF32, R_AARCH64_GOT_PAGE_PC,
349*0b57cec5SDimitry Andric                R_GOT_PC, R_GOTPLT>(expr);
350*0b57cec5SDimitry Andric }
351*0b57cec5SDimitry Andric 
352*0b57cec5SDimitry Andric // True if this expression is of the form Sym - X, where X is a position in the
353*0b57cec5SDimitry Andric // file (PC, or GOT for example).
354*0b57cec5SDimitry Andric static bool isRelExpr(RelExpr expr) {
355*0b57cec5SDimitry Andric   return oneof<R_PC, R_GOTREL, R_GOTPLTREL, R_MIPS_GOTREL, R_PPC64_CALL,
356*0b57cec5SDimitry Andric                R_PPC64_RELAX_TOC, R_AARCH64_PAGE_PC, R_RELAX_GOT_PC,
357*0b57cec5SDimitry Andric                R_RISCV_PC_INDIRECT>(expr);
358*0b57cec5SDimitry Andric }
359*0b57cec5SDimitry Andric 
360*0b57cec5SDimitry Andric // Returns true if a given relocation can be computed at link-time.
361*0b57cec5SDimitry Andric //
362*0b57cec5SDimitry Andric // For instance, we know the offset from a relocation to its target at
363*0b57cec5SDimitry Andric // link-time if the relocation is PC-relative and refers a
364*0b57cec5SDimitry Andric // non-interposable function in the same executable. This function
365*0b57cec5SDimitry Andric // will return true for such relocation.
366*0b57cec5SDimitry Andric //
367*0b57cec5SDimitry Andric // If this function returns false, that means we need to emit a
368*0b57cec5SDimitry Andric // dynamic relocation so that the relocation will be fixed at load-time.
369*0b57cec5SDimitry Andric static bool isStaticLinkTimeConstant(RelExpr e, RelType type, const Symbol &sym,
370*0b57cec5SDimitry Andric                                      InputSectionBase &s, uint64_t relOff) {
371*0b57cec5SDimitry Andric   // These expressions always compute a constant
372*0b57cec5SDimitry Andric   if (oneof<R_DTPREL, R_GOTPLT, R_GOT_OFF, R_HEXAGON_GOT, R_TLSLD_GOT_OFF,
373*0b57cec5SDimitry Andric             R_MIPS_GOT_LOCAL_PAGE, R_MIPS_GOTREL, R_MIPS_GOT_OFF,
374*0b57cec5SDimitry Andric             R_MIPS_GOT_OFF32, R_MIPS_GOT_GP_PC, R_MIPS_TLSGD,
375*0b57cec5SDimitry Andric             R_AARCH64_GOT_PAGE_PC, R_GOT_PC, R_GOTONLY_PC, R_GOTPLTONLY_PC,
376*0b57cec5SDimitry Andric             R_PLT_PC, R_TLSGD_GOT, R_TLSGD_GOTPLT, R_TLSGD_PC, R_PPC32_PLTREL,
377*0b57cec5SDimitry Andric             R_PPC64_CALL_PLT, R_PPC64_RELAX_TOC, R_RISCV_ADD, R_TLSDESC_CALL,
378*0b57cec5SDimitry Andric             R_TLSDESC_PC, R_AARCH64_TLSDESC_PAGE, R_HINT, R_TLSLD_HINT,
379*0b57cec5SDimitry Andric             R_TLSIE_HINT>(e))
380*0b57cec5SDimitry Andric     return true;
381*0b57cec5SDimitry Andric 
382*0b57cec5SDimitry Andric   // These never do, except if the entire file is position dependent or if
383*0b57cec5SDimitry Andric   // only the low bits are used.
384*0b57cec5SDimitry Andric   if (e == R_GOT || e == R_PLT || e == R_TLSDESC)
385*0b57cec5SDimitry Andric     return target->usesOnlyLowPageBits(type) || !config->isPic;
386*0b57cec5SDimitry Andric 
387*0b57cec5SDimitry Andric   if (sym.isPreemptible)
388*0b57cec5SDimitry Andric     return false;
389*0b57cec5SDimitry Andric   if (!config->isPic)
390*0b57cec5SDimitry Andric     return true;
391*0b57cec5SDimitry Andric 
392*0b57cec5SDimitry Andric   // The size of a non preemptible symbol is a constant.
393*0b57cec5SDimitry Andric   if (e == R_SIZE)
394*0b57cec5SDimitry Andric     return true;
395*0b57cec5SDimitry Andric 
396*0b57cec5SDimitry Andric   // For the target and the relocation, we want to know if they are
397*0b57cec5SDimitry Andric   // absolute or relative.
398*0b57cec5SDimitry Andric   bool absVal = isAbsoluteValue(sym);
399*0b57cec5SDimitry Andric   bool relE = isRelExpr(e);
400*0b57cec5SDimitry Andric   if (absVal && !relE)
401*0b57cec5SDimitry Andric     return true;
402*0b57cec5SDimitry Andric   if (!absVal && relE)
403*0b57cec5SDimitry Andric     return true;
404*0b57cec5SDimitry Andric   if (!absVal && !relE)
405*0b57cec5SDimitry Andric     return target->usesOnlyLowPageBits(type);
406*0b57cec5SDimitry Andric 
407*0b57cec5SDimitry Andric   // Relative relocation to an absolute value. This is normally unrepresentable,
408*0b57cec5SDimitry Andric   // but if the relocation refers to a weak undefined symbol, we allow it to
409*0b57cec5SDimitry Andric   // resolve to the image base. This is a little strange, but it allows us to
410*0b57cec5SDimitry Andric   // link function calls to such symbols. Normally such a call will be guarded
411*0b57cec5SDimitry Andric   // with a comparison, which will load a zero from the GOT.
412*0b57cec5SDimitry Andric   // Another special case is MIPS _gp_disp symbol which represents offset
413*0b57cec5SDimitry Andric   // between start of a function and '_gp' value and defined as absolute just
414*0b57cec5SDimitry Andric   // to simplify the code.
415*0b57cec5SDimitry Andric   assert(absVal && relE);
416*0b57cec5SDimitry Andric   if (sym.isUndefWeak())
417*0b57cec5SDimitry Andric     return true;
418*0b57cec5SDimitry Andric 
419*0b57cec5SDimitry Andric   // We set the final symbols values for linker script defined symbols later.
420*0b57cec5SDimitry Andric   // They always can be computed as a link time constant.
421*0b57cec5SDimitry Andric   if (sym.scriptDefined)
422*0b57cec5SDimitry Andric       return true;
423*0b57cec5SDimitry Andric 
424*0b57cec5SDimitry Andric   error("relocation " + toString(type) + " cannot refer to absolute symbol: " +
425*0b57cec5SDimitry Andric         toString(sym) + getLocation(s, sym, relOff));
426*0b57cec5SDimitry Andric   return true;
427*0b57cec5SDimitry Andric }
428*0b57cec5SDimitry Andric 
429*0b57cec5SDimitry Andric static RelExpr toPlt(RelExpr expr) {
430*0b57cec5SDimitry Andric   switch (expr) {
431*0b57cec5SDimitry Andric   case R_PPC64_CALL:
432*0b57cec5SDimitry Andric     return R_PPC64_CALL_PLT;
433*0b57cec5SDimitry Andric   case R_PC:
434*0b57cec5SDimitry Andric     return R_PLT_PC;
435*0b57cec5SDimitry Andric   case R_ABS:
436*0b57cec5SDimitry Andric     return R_PLT;
437*0b57cec5SDimitry Andric   default:
438*0b57cec5SDimitry Andric     return expr;
439*0b57cec5SDimitry Andric   }
440*0b57cec5SDimitry Andric }
441*0b57cec5SDimitry Andric 
442*0b57cec5SDimitry Andric static RelExpr fromPlt(RelExpr expr) {
443*0b57cec5SDimitry Andric   // We decided not to use a plt. Optimize a reference to the plt to a
444*0b57cec5SDimitry Andric   // reference to the symbol itself.
445*0b57cec5SDimitry Andric   switch (expr) {
446*0b57cec5SDimitry Andric   case R_PLT_PC:
447*0b57cec5SDimitry Andric   case R_PPC32_PLTREL:
448*0b57cec5SDimitry Andric     return R_PC;
449*0b57cec5SDimitry Andric   case R_PPC64_CALL_PLT:
450*0b57cec5SDimitry Andric     return R_PPC64_CALL;
451*0b57cec5SDimitry Andric   case R_PLT:
452*0b57cec5SDimitry Andric     return R_ABS;
453*0b57cec5SDimitry Andric   default:
454*0b57cec5SDimitry Andric     return expr;
455*0b57cec5SDimitry Andric   }
456*0b57cec5SDimitry Andric }
457*0b57cec5SDimitry Andric 
458*0b57cec5SDimitry Andric // Returns true if a given shared symbol is in a read-only segment in a DSO.
459*0b57cec5SDimitry Andric template <class ELFT> static bool isReadOnly(SharedSymbol &ss) {
460*0b57cec5SDimitry Andric   using Elf_Phdr = typename ELFT::Phdr;
461*0b57cec5SDimitry Andric 
462*0b57cec5SDimitry Andric   // Determine if the symbol is read-only by scanning the DSO's program headers.
463*0b57cec5SDimitry Andric   const SharedFile &file = ss.getFile();
464*0b57cec5SDimitry Andric   for (const Elf_Phdr &phdr :
465*0b57cec5SDimitry Andric        check(file.template getObj<ELFT>().program_headers()))
466*0b57cec5SDimitry Andric     if ((phdr.p_type == ELF::PT_LOAD || phdr.p_type == ELF::PT_GNU_RELRO) &&
467*0b57cec5SDimitry Andric         !(phdr.p_flags & ELF::PF_W) && ss.value >= phdr.p_vaddr &&
468*0b57cec5SDimitry Andric         ss.value < phdr.p_vaddr + phdr.p_memsz)
469*0b57cec5SDimitry Andric       return true;
470*0b57cec5SDimitry Andric   return false;
471*0b57cec5SDimitry Andric }
472*0b57cec5SDimitry Andric 
473*0b57cec5SDimitry Andric // Returns symbols at the same offset as a given symbol, including SS itself.
474*0b57cec5SDimitry Andric //
475*0b57cec5SDimitry Andric // If two or more symbols are at the same offset, and at least one of
476*0b57cec5SDimitry Andric // them are copied by a copy relocation, all of them need to be copied.
477*0b57cec5SDimitry Andric // Otherwise, they would refer to different places at runtime.
478*0b57cec5SDimitry Andric template <class ELFT>
479*0b57cec5SDimitry Andric static SmallSet<SharedSymbol *, 4> getSymbolsAt(SharedSymbol &ss) {
480*0b57cec5SDimitry Andric   using Elf_Sym = typename ELFT::Sym;
481*0b57cec5SDimitry Andric 
482*0b57cec5SDimitry Andric   SharedFile &file = ss.getFile();
483*0b57cec5SDimitry Andric 
484*0b57cec5SDimitry Andric   SmallSet<SharedSymbol *, 4> ret;
485*0b57cec5SDimitry Andric   for (const Elf_Sym &s : file.template getGlobalELFSyms<ELFT>()) {
486*0b57cec5SDimitry Andric     if (s.st_shndx == SHN_UNDEF || s.st_shndx == SHN_ABS ||
487*0b57cec5SDimitry Andric         s.getType() == STT_TLS || s.st_value != ss.value)
488*0b57cec5SDimitry Andric       continue;
489*0b57cec5SDimitry Andric     StringRef name = check(s.getName(file.getStringTable()));
490*0b57cec5SDimitry Andric     Symbol *sym = symtab->find(name);
491*0b57cec5SDimitry Andric     if (auto *alias = dyn_cast_or_null<SharedSymbol>(sym))
492*0b57cec5SDimitry Andric       ret.insert(alias);
493*0b57cec5SDimitry Andric   }
494*0b57cec5SDimitry Andric   return ret;
495*0b57cec5SDimitry Andric }
496*0b57cec5SDimitry Andric 
497*0b57cec5SDimitry Andric // When a symbol is copy relocated or we create a canonical plt entry, it is
498*0b57cec5SDimitry Andric // effectively a defined symbol. In the case of copy relocation the symbol is
499*0b57cec5SDimitry Andric // in .bss and in the case of a canonical plt entry it is in .plt. This function
500*0b57cec5SDimitry Andric // replaces the existing symbol with a Defined pointing to the appropriate
501*0b57cec5SDimitry Andric // location.
502*0b57cec5SDimitry Andric static void replaceWithDefined(Symbol &sym, SectionBase *sec, uint64_t value,
503*0b57cec5SDimitry Andric                                uint64_t size) {
504*0b57cec5SDimitry Andric   Symbol old = sym;
505*0b57cec5SDimitry Andric 
506*0b57cec5SDimitry Andric   sym.replace(Defined{sym.file, sym.getName(), sym.binding, sym.stOther,
507*0b57cec5SDimitry Andric                       sym.type, value, size, sec});
508*0b57cec5SDimitry Andric 
509*0b57cec5SDimitry Andric   sym.pltIndex = old.pltIndex;
510*0b57cec5SDimitry Andric   sym.gotIndex = old.gotIndex;
511*0b57cec5SDimitry Andric   sym.verdefIndex = old.verdefIndex;
512*0b57cec5SDimitry Andric   sym.ppc64BranchltIndex = old.ppc64BranchltIndex;
513*0b57cec5SDimitry Andric   sym.isPreemptible = true;
514*0b57cec5SDimitry Andric   sym.exportDynamic = true;
515*0b57cec5SDimitry Andric   sym.isUsedInRegularObj = true;
516*0b57cec5SDimitry Andric   sym.used = true;
517*0b57cec5SDimitry Andric }
518*0b57cec5SDimitry Andric 
519*0b57cec5SDimitry Andric // Reserve space in .bss or .bss.rel.ro for copy relocation.
520*0b57cec5SDimitry Andric //
521*0b57cec5SDimitry Andric // The copy relocation is pretty much a hack. If you use a copy relocation
522*0b57cec5SDimitry Andric // in your program, not only the symbol name but the symbol's size, RW/RO
523*0b57cec5SDimitry Andric // bit and alignment become part of the ABI. In addition to that, if the
524*0b57cec5SDimitry Andric // symbol has aliases, the aliases become part of the ABI. That's subtle,
525*0b57cec5SDimitry Andric // but if you violate that implicit ABI, that can cause very counter-
526*0b57cec5SDimitry Andric // intuitive consequences.
527*0b57cec5SDimitry Andric //
528*0b57cec5SDimitry Andric // So, what is the copy relocation? It's for linking non-position
529*0b57cec5SDimitry Andric // independent code to DSOs. In an ideal world, all references to data
530*0b57cec5SDimitry Andric // exported by DSOs should go indirectly through GOT. But if object files
531*0b57cec5SDimitry Andric // are compiled as non-PIC, all data references are direct. There is no
532*0b57cec5SDimitry Andric // way for the linker to transform the code to use GOT, as machine
533*0b57cec5SDimitry Andric // instructions are already set in stone in object files. This is where
534*0b57cec5SDimitry Andric // the copy relocation takes a role.
535*0b57cec5SDimitry Andric //
536*0b57cec5SDimitry Andric // A copy relocation instructs the dynamic linker to copy data from a DSO
537*0b57cec5SDimitry Andric // to a specified address (which is usually in .bss) at load-time. If the
538*0b57cec5SDimitry Andric // static linker (that's us) finds a direct data reference to a DSO
539*0b57cec5SDimitry Andric // symbol, it creates a copy relocation, so that the symbol can be
540*0b57cec5SDimitry Andric // resolved as if it were in .bss rather than in a DSO.
541*0b57cec5SDimitry Andric //
542*0b57cec5SDimitry Andric // As you can see in this function, we create a copy relocation for the
543*0b57cec5SDimitry Andric // dynamic linker, and the relocation contains not only symbol name but
544*0b57cec5SDimitry Andric // various other informtion about the symbol. So, such attributes become a
545*0b57cec5SDimitry Andric // part of the ABI.
546*0b57cec5SDimitry Andric //
547*0b57cec5SDimitry Andric // Note for application developers: I can give you a piece of advice if
548*0b57cec5SDimitry Andric // you are writing a shared library. You probably should export only
549*0b57cec5SDimitry Andric // functions from your library. You shouldn't export variables.
550*0b57cec5SDimitry Andric //
551*0b57cec5SDimitry Andric // As an example what can happen when you export variables without knowing
552*0b57cec5SDimitry Andric // the semantics of copy relocations, assume that you have an exported
553*0b57cec5SDimitry Andric // variable of type T. It is an ABI-breaking change to add new members at
554*0b57cec5SDimitry Andric // end of T even though doing that doesn't change the layout of the
555*0b57cec5SDimitry Andric // existing members. That's because the space for the new members are not
556*0b57cec5SDimitry Andric // reserved in .bss unless you recompile the main program. That means they
557*0b57cec5SDimitry Andric // are likely to overlap with other data that happens to be laid out next
558*0b57cec5SDimitry Andric // to the variable in .bss. This kind of issue is sometimes very hard to
559*0b57cec5SDimitry Andric // debug. What's a solution? Instead of exporting a varaible V from a DSO,
560*0b57cec5SDimitry Andric // define an accessor getV().
561*0b57cec5SDimitry Andric template <class ELFT> static void addCopyRelSymbol(SharedSymbol &ss) {
562*0b57cec5SDimitry Andric   // Copy relocation against zero-sized symbol doesn't make sense.
563*0b57cec5SDimitry Andric   uint64_t symSize = ss.getSize();
564*0b57cec5SDimitry Andric   if (symSize == 0 || ss.alignment == 0)
565*0b57cec5SDimitry Andric     fatal("cannot create a copy relocation for symbol " + toString(ss));
566*0b57cec5SDimitry Andric 
567*0b57cec5SDimitry Andric   // See if this symbol is in a read-only segment. If so, preserve the symbol's
568*0b57cec5SDimitry Andric   // memory protection by reserving space in the .bss.rel.ro section.
569*0b57cec5SDimitry Andric   bool isRO = isReadOnly<ELFT>(ss);
570*0b57cec5SDimitry Andric   BssSection *sec =
571*0b57cec5SDimitry Andric       make<BssSection>(isRO ? ".bss.rel.ro" : ".bss", symSize, ss.alignment);
572*0b57cec5SDimitry Andric   if (isRO)
573*0b57cec5SDimitry Andric     in.bssRelRo->getParent()->addSection(sec);
574*0b57cec5SDimitry Andric   else
575*0b57cec5SDimitry Andric     in.bss->getParent()->addSection(sec);
576*0b57cec5SDimitry Andric 
577*0b57cec5SDimitry Andric   // Look through the DSO's dynamic symbol table for aliases and create a
578*0b57cec5SDimitry Andric   // dynamic symbol for each one. This causes the copy relocation to correctly
579*0b57cec5SDimitry Andric   // interpose any aliases.
580*0b57cec5SDimitry Andric   for (SharedSymbol *sym : getSymbolsAt<ELFT>(ss))
581*0b57cec5SDimitry Andric     replaceWithDefined(*sym, sec, 0, sym->size);
582*0b57cec5SDimitry Andric 
583*0b57cec5SDimitry Andric   mainPart->relaDyn->addReloc(target->copyRel, sec, 0, &ss);
584*0b57cec5SDimitry Andric }
585*0b57cec5SDimitry Andric 
586*0b57cec5SDimitry Andric // MIPS has an odd notion of "paired" relocations to calculate addends.
587*0b57cec5SDimitry Andric // For example, if a relocation is of R_MIPS_HI16, there must be a
588*0b57cec5SDimitry Andric // R_MIPS_LO16 relocation after that, and an addend is calculated using
589*0b57cec5SDimitry Andric // the two relocations.
590*0b57cec5SDimitry Andric template <class ELFT, class RelTy>
591*0b57cec5SDimitry Andric static int64_t computeMipsAddend(const RelTy &rel, const RelTy *end,
592*0b57cec5SDimitry Andric                                  InputSectionBase &sec, RelExpr expr,
593*0b57cec5SDimitry Andric                                  bool isLocal) {
594*0b57cec5SDimitry Andric   if (expr == R_MIPS_GOTREL && isLocal)
595*0b57cec5SDimitry Andric     return sec.getFile<ELFT>()->mipsGp0;
596*0b57cec5SDimitry Andric 
597*0b57cec5SDimitry Andric   // The ABI says that the paired relocation is used only for REL.
598*0b57cec5SDimitry Andric   // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
599*0b57cec5SDimitry Andric   if (RelTy::IsRela)
600*0b57cec5SDimitry Andric     return 0;
601*0b57cec5SDimitry Andric 
602*0b57cec5SDimitry Andric   RelType type = rel.getType(config->isMips64EL);
603*0b57cec5SDimitry Andric   uint32_t pairTy = getMipsPairType(type, isLocal);
604*0b57cec5SDimitry Andric   if (pairTy == R_MIPS_NONE)
605*0b57cec5SDimitry Andric     return 0;
606*0b57cec5SDimitry Andric 
607*0b57cec5SDimitry Andric   const uint8_t *buf = sec.data().data();
608*0b57cec5SDimitry Andric   uint32_t symIndex = rel.getSymbol(config->isMips64EL);
609*0b57cec5SDimitry Andric 
610*0b57cec5SDimitry Andric   // To make things worse, paired relocations might not be contiguous in
611*0b57cec5SDimitry Andric   // the relocation table, so we need to do linear search. *sigh*
612*0b57cec5SDimitry Andric   for (const RelTy *ri = &rel; ri != end; ++ri)
613*0b57cec5SDimitry Andric     if (ri->getType(config->isMips64EL) == pairTy &&
614*0b57cec5SDimitry Andric         ri->getSymbol(config->isMips64EL) == symIndex)
615*0b57cec5SDimitry Andric       return target->getImplicitAddend(buf + ri->r_offset, pairTy);
616*0b57cec5SDimitry Andric 
617*0b57cec5SDimitry Andric   warn("can't find matching " + toString(pairTy) + " relocation for " +
618*0b57cec5SDimitry Andric        toString(type));
619*0b57cec5SDimitry Andric   return 0;
620*0b57cec5SDimitry Andric }
621*0b57cec5SDimitry Andric 
622*0b57cec5SDimitry Andric // Returns an addend of a given relocation. If it is RELA, an addend
623*0b57cec5SDimitry Andric // is in a relocation itself. If it is REL, we need to read it from an
624*0b57cec5SDimitry Andric // input section.
625*0b57cec5SDimitry Andric template <class ELFT, class RelTy>
626*0b57cec5SDimitry Andric static int64_t computeAddend(const RelTy &rel, const RelTy *end,
627*0b57cec5SDimitry Andric                              InputSectionBase &sec, RelExpr expr,
628*0b57cec5SDimitry Andric                              bool isLocal) {
629*0b57cec5SDimitry Andric   int64_t addend;
630*0b57cec5SDimitry Andric   RelType type = rel.getType(config->isMips64EL);
631*0b57cec5SDimitry Andric 
632*0b57cec5SDimitry Andric   if (RelTy::IsRela) {
633*0b57cec5SDimitry Andric     addend = getAddend<ELFT>(rel);
634*0b57cec5SDimitry Andric   } else {
635*0b57cec5SDimitry Andric     const uint8_t *buf = sec.data().data();
636*0b57cec5SDimitry Andric     addend = target->getImplicitAddend(buf + rel.r_offset, type);
637*0b57cec5SDimitry Andric   }
638*0b57cec5SDimitry Andric 
639*0b57cec5SDimitry Andric   if (config->emachine == EM_PPC64 && config->isPic && type == R_PPC64_TOC)
640*0b57cec5SDimitry Andric     addend += getPPC64TocBase();
641*0b57cec5SDimitry Andric   if (config->emachine == EM_MIPS)
642*0b57cec5SDimitry Andric     addend += computeMipsAddend<ELFT>(rel, end, sec, expr, isLocal);
643*0b57cec5SDimitry Andric 
644*0b57cec5SDimitry Andric   return addend;
645*0b57cec5SDimitry Andric }
646*0b57cec5SDimitry Andric 
647*0b57cec5SDimitry Andric // Custom error message if Sym is defined in a discarded section.
648*0b57cec5SDimitry Andric template <class ELFT>
649*0b57cec5SDimitry Andric static std::string maybeReportDiscarded(Undefined &sym) {
650*0b57cec5SDimitry Andric   auto *file = dyn_cast_or_null<ObjFile<ELFT>>(sym.file);
651*0b57cec5SDimitry Andric   if (!file || !sym.discardedSecIdx ||
652*0b57cec5SDimitry Andric       file->getSections()[sym.discardedSecIdx] != &InputSection::discarded)
653*0b57cec5SDimitry Andric     return "";
654*0b57cec5SDimitry Andric   ArrayRef<Elf_Shdr_Impl<ELFT>> objSections =
655*0b57cec5SDimitry Andric       CHECK(file->getObj().sections(), file);
656*0b57cec5SDimitry Andric 
657*0b57cec5SDimitry Andric   std::string msg;
658*0b57cec5SDimitry Andric   if (sym.type == ELF::STT_SECTION) {
659*0b57cec5SDimitry Andric     msg = "relocation refers to a discarded section: ";
660*0b57cec5SDimitry Andric     msg += CHECK(
661*0b57cec5SDimitry Andric         file->getObj().getSectionName(&objSections[sym.discardedSecIdx]), file);
662*0b57cec5SDimitry Andric   } else {
663*0b57cec5SDimitry Andric     msg = "relocation refers to a symbol in a discarded section: " +
664*0b57cec5SDimitry Andric           toString(sym);
665*0b57cec5SDimitry Andric   }
666*0b57cec5SDimitry Andric   msg += "\n>>> defined in " + toString(file);
667*0b57cec5SDimitry Andric 
668*0b57cec5SDimitry Andric   Elf_Shdr_Impl<ELFT> elfSec = objSections[sym.discardedSecIdx - 1];
669*0b57cec5SDimitry Andric   if (elfSec.sh_type != SHT_GROUP)
670*0b57cec5SDimitry Andric     return msg;
671*0b57cec5SDimitry Andric 
672*0b57cec5SDimitry Andric   // If the discarded section is a COMDAT.
673*0b57cec5SDimitry Andric   StringRef signature = file->getShtGroupSignature(objSections, elfSec);
674*0b57cec5SDimitry Andric   if (const InputFile *prevailing =
675*0b57cec5SDimitry Andric           symtab->comdatGroups.lookup(CachedHashStringRef(signature)))
676*0b57cec5SDimitry Andric     msg += "\n>>> section group signature: " + signature.str() +
677*0b57cec5SDimitry Andric            "\n>>> prevailing definition is in " + toString(prevailing);
678*0b57cec5SDimitry Andric   return msg;
679*0b57cec5SDimitry Andric }
680*0b57cec5SDimitry Andric 
681*0b57cec5SDimitry Andric // Undefined diagnostics are collected in a vector and emitted once all of
682*0b57cec5SDimitry Andric // them are known, so that some postprocessing on the list of undefined symbols
683*0b57cec5SDimitry Andric // can happen before lld emits diagnostics.
684*0b57cec5SDimitry Andric struct UndefinedDiag {
685*0b57cec5SDimitry Andric   Symbol *sym;
686*0b57cec5SDimitry Andric   struct Loc {
687*0b57cec5SDimitry Andric     InputSectionBase *sec;
688*0b57cec5SDimitry Andric     uint64_t offset;
689*0b57cec5SDimitry Andric   };
690*0b57cec5SDimitry Andric   std::vector<Loc> locs;
691*0b57cec5SDimitry Andric   bool isWarning;
692*0b57cec5SDimitry Andric };
693*0b57cec5SDimitry Andric 
694*0b57cec5SDimitry Andric static std::vector<UndefinedDiag> undefs;
695*0b57cec5SDimitry Andric 
696*0b57cec5SDimitry Andric template <class ELFT>
697*0b57cec5SDimitry Andric static void reportUndefinedSymbol(const UndefinedDiag &undef) {
698*0b57cec5SDimitry Andric   Symbol &sym = *undef.sym;
699*0b57cec5SDimitry Andric 
700*0b57cec5SDimitry Andric   auto visibility = [&]() -> std::string {
701*0b57cec5SDimitry Andric     switch (sym.visibility) {
702*0b57cec5SDimitry Andric     case STV_INTERNAL:
703*0b57cec5SDimitry Andric       return "internal ";
704*0b57cec5SDimitry Andric     case STV_HIDDEN:
705*0b57cec5SDimitry Andric       return "hidden ";
706*0b57cec5SDimitry Andric     case STV_PROTECTED:
707*0b57cec5SDimitry Andric       return "protected ";
708*0b57cec5SDimitry Andric     default:
709*0b57cec5SDimitry Andric       return "";
710*0b57cec5SDimitry Andric     }
711*0b57cec5SDimitry Andric   };
712*0b57cec5SDimitry Andric 
713*0b57cec5SDimitry Andric   std::string msg = maybeReportDiscarded<ELFT>(cast<Undefined>(sym));
714*0b57cec5SDimitry Andric   if (msg.empty())
715*0b57cec5SDimitry Andric     msg = "undefined " + visibility() + "symbol: " + toString(sym);
716*0b57cec5SDimitry Andric 
717*0b57cec5SDimitry Andric   const size_t maxUndefReferences = 10;
718*0b57cec5SDimitry Andric   size_t i = 0;
719*0b57cec5SDimitry Andric   for (UndefinedDiag::Loc l : undef.locs) {
720*0b57cec5SDimitry Andric     if (i >= maxUndefReferences)
721*0b57cec5SDimitry Andric       break;
722*0b57cec5SDimitry Andric     InputSectionBase &sec = *l.sec;
723*0b57cec5SDimitry Andric     uint64_t offset = l.offset;
724*0b57cec5SDimitry Andric 
725*0b57cec5SDimitry Andric     msg += "\n>>> referenced by ";
726*0b57cec5SDimitry Andric     std::string src = sec.getSrcMsg(sym, offset);
727*0b57cec5SDimitry Andric     if (!src.empty())
728*0b57cec5SDimitry Andric       msg += src + "\n>>>               ";
729*0b57cec5SDimitry Andric     msg += sec.getObjMsg(offset);
730*0b57cec5SDimitry Andric     i++;
731*0b57cec5SDimitry Andric   }
732*0b57cec5SDimitry Andric 
733*0b57cec5SDimitry Andric   if (i < undef.locs.size())
734*0b57cec5SDimitry Andric     msg += ("\n>>> referenced " + Twine(undef.locs.size() - i) + " more times")
735*0b57cec5SDimitry Andric                .str();
736*0b57cec5SDimitry Andric 
737*0b57cec5SDimitry Andric   if (sym.getName().startswith("_ZTV"))
738*0b57cec5SDimitry Andric     msg += "\nthe vtable symbol may be undefined because the class is missing "
739*0b57cec5SDimitry Andric            "its key function (see https://lld.llvm.org/missingkeyfunction)";
740*0b57cec5SDimitry Andric 
741*0b57cec5SDimitry Andric   if (undef.isWarning)
742*0b57cec5SDimitry Andric     warn(msg);
743*0b57cec5SDimitry Andric   else
744*0b57cec5SDimitry Andric     error(msg);
745*0b57cec5SDimitry Andric }
746*0b57cec5SDimitry Andric 
747*0b57cec5SDimitry Andric template <class ELFT> void elf::reportUndefinedSymbols() {
748*0b57cec5SDimitry Andric   // Find the first "undefined symbol" diagnostic for each diagnostic, and
749*0b57cec5SDimitry Andric   // collect all "referenced from" lines at the first diagnostic.
750*0b57cec5SDimitry Andric   DenseMap<Symbol *, UndefinedDiag *> firstRef;
751*0b57cec5SDimitry Andric   for (UndefinedDiag &undef : undefs) {
752*0b57cec5SDimitry Andric     assert(undef.locs.size() == 1);
753*0b57cec5SDimitry Andric     if (UndefinedDiag *canon = firstRef.lookup(undef.sym)) {
754*0b57cec5SDimitry Andric       canon->locs.push_back(undef.locs[0]);
755*0b57cec5SDimitry Andric       undef.locs.clear();
756*0b57cec5SDimitry Andric     } else
757*0b57cec5SDimitry Andric       firstRef[undef.sym] = &undef;
758*0b57cec5SDimitry Andric   }
759*0b57cec5SDimitry Andric 
760*0b57cec5SDimitry Andric   for (const UndefinedDiag &undef : undefs) {
761*0b57cec5SDimitry Andric     if (!undef.locs.empty())
762*0b57cec5SDimitry Andric       reportUndefinedSymbol<ELFT>(undef);
763*0b57cec5SDimitry Andric   }
764*0b57cec5SDimitry Andric   undefs.clear();
765*0b57cec5SDimitry Andric }
766*0b57cec5SDimitry Andric 
767*0b57cec5SDimitry Andric // Report an undefined symbol if necessary.
768*0b57cec5SDimitry Andric // Returns true if the undefined symbol will produce an error message.
769*0b57cec5SDimitry Andric template <class ELFT>
770*0b57cec5SDimitry Andric static bool maybeReportUndefined(Symbol &sym, InputSectionBase &sec,
771*0b57cec5SDimitry Andric                                  uint64_t offset) {
772*0b57cec5SDimitry Andric   if (!sym.isUndefined() || sym.isWeak())
773*0b57cec5SDimitry Andric     return false;
774*0b57cec5SDimitry Andric 
775*0b57cec5SDimitry Andric   bool canBeExternal = !sym.isLocal() && sym.computeBinding() != STB_LOCAL &&
776*0b57cec5SDimitry Andric                        sym.visibility == STV_DEFAULT;
777*0b57cec5SDimitry Andric   if (config->unresolvedSymbols == UnresolvedPolicy::Ignore && canBeExternal)
778*0b57cec5SDimitry Andric     return false;
779*0b57cec5SDimitry Andric 
780*0b57cec5SDimitry Andric   // clang (as of 2019-06-12) / gcc (as of 8.2.1) PPC64 may emit a .rela.toc
781*0b57cec5SDimitry Andric   // which references a switch table in a discarded .rodata/.text section. The
782*0b57cec5SDimitry Andric   // .toc and the .rela.toc are incorrectly not placed in the comdat. The ELF
783*0b57cec5SDimitry Andric   // spec says references from outside the group to a STB_LOCAL symbol are not
784*0b57cec5SDimitry Andric   // allowed. Work around the bug.
785*0b57cec5SDimitry Andric   if (config->emachine == EM_PPC64 &&
786*0b57cec5SDimitry Andric       cast<Undefined>(sym).discardedSecIdx != 0 && sec.name == ".toc")
787*0b57cec5SDimitry Andric     return false;
788*0b57cec5SDimitry Andric 
789*0b57cec5SDimitry Andric   bool isWarning =
790*0b57cec5SDimitry Andric       (config->unresolvedSymbols == UnresolvedPolicy::Warn && canBeExternal) ||
791*0b57cec5SDimitry Andric       config->noinhibitExec;
792*0b57cec5SDimitry Andric   undefs.push_back({&sym, {{&sec, offset}}, isWarning});
793*0b57cec5SDimitry Andric   return !isWarning;
794*0b57cec5SDimitry Andric }
795*0b57cec5SDimitry Andric 
796*0b57cec5SDimitry Andric // MIPS N32 ABI treats series of successive relocations with the same offset
797*0b57cec5SDimitry Andric // as a single relocation. The similar approach used by N64 ABI, but this ABI
798*0b57cec5SDimitry Andric // packs all relocations into the single relocation record. Here we emulate
799*0b57cec5SDimitry Andric // this for the N32 ABI. Iterate over relocation with the same offset and put
800*0b57cec5SDimitry Andric // theirs types into the single bit-set.
801*0b57cec5SDimitry Andric template <class RelTy> static RelType getMipsN32RelType(RelTy *&rel, RelTy *end) {
802*0b57cec5SDimitry Andric   RelType type = 0;
803*0b57cec5SDimitry Andric   uint64_t offset = rel->r_offset;
804*0b57cec5SDimitry Andric 
805*0b57cec5SDimitry Andric   int n = 0;
806*0b57cec5SDimitry Andric   while (rel != end && rel->r_offset == offset)
807*0b57cec5SDimitry Andric     type |= (rel++)->getType(config->isMips64EL) << (8 * n++);
808*0b57cec5SDimitry Andric   return type;
809*0b57cec5SDimitry Andric }
810*0b57cec5SDimitry Andric 
811*0b57cec5SDimitry Andric // .eh_frame sections are mergeable input sections, so their input
812*0b57cec5SDimitry Andric // offsets are not linearly mapped to output section. For each input
813*0b57cec5SDimitry Andric // offset, we need to find a section piece containing the offset and
814*0b57cec5SDimitry Andric // add the piece's base address to the input offset to compute the
815*0b57cec5SDimitry Andric // output offset. That isn't cheap.
816*0b57cec5SDimitry Andric //
817*0b57cec5SDimitry Andric // This class is to speed up the offset computation. When we process
818*0b57cec5SDimitry Andric // relocations, we access offsets in the monotonically increasing
819*0b57cec5SDimitry Andric // order. So we can optimize for that access pattern.
820*0b57cec5SDimitry Andric //
821*0b57cec5SDimitry Andric // For sections other than .eh_frame, this class doesn't do anything.
822*0b57cec5SDimitry Andric namespace {
823*0b57cec5SDimitry Andric class OffsetGetter {
824*0b57cec5SDimitry Andric public:
825*0b57cec5SDimitry Andric   explicit OffsetGetter(InputSectionBase &sec) {
826*0b57cec5SDimitry Andric     if (auto *eh = dyn_cast<EhInputSection>(&sec))
827*0b57cec5SDimitry Andric       pieces = eh->pieces;
828*0b57cec5SDimitry Andric   }
829*0b57cec5SDimitry Andric 
830*0b57cec5SDimitry Andric   // Translates offsets in input sections to offsets in output sections.
831*0b57cec5SDimitry Andric   // Given offset must increase monotonically. We assume that Piece is
832*0b57cec5SDimitry Andric   // sorted by inputOff.
833*0b57cec5SDimitry Andric   uint64_t get(uint64_t off) {
834*0b57cec5SDimitry Andric     if (pieces.empty())
835*0b57cec5SDimitry Andric       return off;
836*0b57cec5SDimitry Andric 
837*0b57cec5SDimitry Andric     while (i != pieces.size() && pieces[i].inputOff + pieces[i].size <= off)
838*0b57cec5SDimitry Andric       ++i;
839*0b57cec5SDimitry Andric     if (i == pieces.size())
840*0b57cec5SDimitry Andric       fatal(".eh_frame: relocation is not in any piece");
841*0b57cec5SDimitry Andric 
842*0b57cec5SDimitry Andric     // Pieces must be contiguous, so there must be no holes in between.
843*0b57cec5SDimitry Andric     assert(pieces[i].inputOff <= off && "Relocation not in any piece");
844*0b57cec5SDimitry Andric 
845*0b57cec5SDimitry Andric     // Offset -1 means that the piece is dead (i.e. garbage collected).
846*0b57cec5SDimitry Andric     if (pieces[i].outputOff == -1)
847*0b57cec5SDimitry Andric       return -1;
848*0b57cec5SDimitry Andric     return pieces[i].outputOff + off - pieces[i].inputOff;
849*0b57cec5SDimitry Andric   }
850*0b57cec5SDimitry Andric 
851*0b57cec5SDimitry Andric private:
852*0b57cec5SDimitry Andric   ArrayRef<EhSectionPiece> pieces;
853*0b57cec5SDimitry Andric   size_t i = 0;
854*0b57cec5SDimitry Andric };
855*0b57cec5SDimitry Andric } // namespace
856*0b57cec5SDimitry Andric 
857*0b57cec5SDimitry Andric static void addRelativeReloc(InputSectionBase *isec, uint64_t offsetInSec,
858*0b57cec5SDimitry Andric                              Symbol *sym, int64_t addend, RelExpr expr,
859*0b57cec5SDimitry Andric                              RelType type) {
860*0b57cec5SDimitry Andric   Partition &part = isec->getPartition();
861*0b57cec5SDimitry Andric 
862*0b57cec5SDimitry Andric   // Add a relative relocation. If relrDyn section is enabled, and the
863*0b57cec5SDimitry Andric   // relocation offset is guaranteed to be even, add the relocation to
864*0b57cec5SDimitry Andric   // the relrDyn section, otherwise add it to the relaDyn section.
865*0b57cec5SDimitry Andric   // relrDyn sections don't support odd offsets. Also, relrDyn sections
866*0b57cec5SDimitry Andric   // don't store the addend values, so we must write it to the relocated
867*0b57cec5SDimitry Andric   // address.
868*0b57cec5SDimitry Andric   if (part.relrDyn && isec->alignment >= 2 && offsetInSec % 2 == 0) {
869*0b57cec5SDimitry Andric     isec->relocations.push_back({expr, type, offsetInSec, addend, sym});
870*0b57cec5SDimitry Andric     part.relrDyn->relocs.push_back({isec, offsetInSec});
871*0b57cec5SDimitry Andric     return;
872*0b57cec5SDimitry Andric   }
873*0b57cec5SDimitry Andric   part.relaDyn->addReloc(target->relativeRel, isec, offsetInSec, sym, addend,
874*0b57cec5SDimitry Andric                          expr, type);
875*0b57cec5SDimitry Andric }
876*0b57cec5SDimitry Andric 
877*0b57cec5SDimitry Andric template <class ELFT, class GotPltSection>
878*0b57cec5SDimitry Andric static void addPltEntry(PltSection *plt, GotPltSection *gotPlt,
879*0b57cec5SDimitry Andric                         RelocationBaseSection *rel, RelType type, Symbol &sym) {
880*0b57cec5SDimitry Andric   plt->addEntry<ELFT>(sym);
881*0b57cec5SDimitry Andric   gotPlt->addEntry(sym);
882*0b57cec5SDimitry Andric   rel->addReloc(
883*0b57cec5SDimitry Andric       {type, gotPlt, sym.getGotPltOffset(), !sym.isPreemptible, &sym, 0});
884*0b57cec5SDimitry Andric }
885*0b57cec5SDimitry Andric 
886*0b57cec5SDimitry Andric static void addGotEntry(Symbol &sym) {
887*0b57cec5SDimitry Andric   in.got->addEntry(sym);
888*0b57cec5SDimitry Andric 
889*0b57cec5SDimitry Andric   RelExpr expr = sym.isTls() ? R_TLS : R_ABS;
890*0b57cec5SDimitry Andric   uint64_t off = sym.getGotOffset();
891*0b57cec5SDimitry Andric 
892*0b57cec5SDimitry Andric   // If a GOT slot value can be calculated at link-time, which is now,
893*0b57cec5SDimitry Andric   // we can just fill that out.
894*0b57cec5SDimitry Andric   //
895*0b57cec5SDimitry Andric   // (We don't actually write a value to a GOT slot right now, but we
896*0b57cec5SDimitry Andric   // add a static relocation to a Relocations vector so that
897*0b57cec5SDimitry Andric   // InputSection::relocate will do the work for us. We may be able
898*0b57cec5SDimitry Andric   // to just write a value now, but it is a TODO.)
899*0b57cec5SDimitry Andric   bool isLinkTimeConstant =
900*0b57cec5SDimitry Andric       !sym.isPreemptible && (!config->isPic || isAbsolute(sym));
901*0b57cec5SDimitry Andric   if (isLinkTimeConstant) {
902*0b57cec5SDimitry Andric     in.got->relocations.push_back({expr, target->symbolicRel, off, 0, &sym});
903*0b57cec5SDimitry Andric     return;
904*0b57cec5SDimitry Andric   }
905*0b57cec5SDimitry Andric 
906*0b57cec5SDimitry Andric   // Otherwise, we emit a dynamic relocation to .rel[a].dyn so that
907*0b57cec5SDimitry Andric   // the GOT slot will be fixed at load-time.
908*0b57cec5SDimitry Andric   if (!sym.isTls() && !sym.isPreemptible && config->isPic && !isAbsolute(sym)) {
909*0b57cec5SDimitry Andric     addRelativeReloc(in.got, off, &sym, 0, R_ABS, target->symbolicRel);
910*0b57cec5SDimitry Andric     return;
911*0b57cec5SDimitry Andric   }
912*0b57cec5SDimitry Andric   mainPart->relaDyn->addReloc(
913*0b57cec5SDimitry Andric       sym.isTls() ? target->tlsGotRel : target->gotRel, in.got, off, &sym, 0,
914*0b57cec5SDimitry Andric       sym.isPreemptible ? R_ADDEND : R_ABS, target->symbolicRel);
915*0b57cec5SDimitry Andric }
916*0b57cec5SDimitry Andric 
917*0b57cec5SDimitry Andric // Return true if we can define a symbol in the executable that
918*0b57cec5SDimitry Andric // contains the value/function of a symbol defined in a shared
919*0b57cec5SDimitry Andric // library.
920*0b57cec5SDimitry Andric static bool canDefineSymbolInExecutable(Symbol &sym) {
921*0b57cec5SDimitry Andric   // If the symbol has default visibility the symbol defined in the
922*0b57cec5SDimitry Andric   // executable will preempt it.
923*0b57cec5SDimitry Andric   // Note that we want the visibility of the shared symbol itself, not
924*0b57cec5SDimitry Andric   // the visibility of the symbol in the output file we are producing. That is
925*0b57cec5SDimitry Andric   // why we use Sym.stOther.
926*0b57cec5SDimitry Andric   if ((sym.stOther & 0x3) == STV_DEFAULT)
927*0b57cec5SDimitry Andric     return true;
928*0b57cec5SDimitry Andric 
929*0b57cec5SDimitry Andric   // If we are allowed to break address equality of functions, defining
930*0b57cec5SDimitry Andric   // a plt entry will allow the program to call the function in the
931*0b57cec5SDimitry Andric   // .so, but the .so and the executable will no agree on the address
932*0b57cec5SDimitry Andric   // of the function. Similar logic for objects.
933*0b57cec5SDimitry Andric   return ((sym.isFunc() && config->ignoreFunctionAddressEquality) ||
934*0b57cec5SDimitry Andric           (sym.isObject() && config->ignoreDataAddressEquality));
935*0b57cec5SDimitry Andric }
936*0b57cec5SDimitry Andric 
937*0b57cec5SDimitry Andric // The reason we have to do this early scan is as follows
938*0b57cec5SDimitry Andric // * To mmap the output file, we need to know the size
939*0b57cec5SDimitry Andric // * For that, we need to know how many dynamic relocs we will have.
940*0b57cec5SDimitry Andric // It might be possible to avoid this by outputting the file with write:
941*0b57cec5SDimitry Andric // * Write the allocated output sections, computing addresses.
942*0b57cec5SDimitry Andric // * Apply relocations, recording which ones require a dynamic reloc.
943*0b57cec5SDimitry Andric // * Write the dynamic relocations.
944*0b57cec5SDimitry Andric // * Write the rest of the file.
945*0b57cec5SDimitry Andric // This would have some drawbacks. For example, we would only know if .rela.dyn
946*0b57cec5SDimitry Andric // is needed after applying relocations. If it is, it will go after rw and rx
947*0b57cec5SDimitry Andric // sections. Given that it is ro, we will need an extra PT_LOAD. This
948*0b57cec5SDimitry Andric // complicates things for the dynamic linker and means we would have to reserve
949*0b57cec5SDimitry Andric // space for the extra PT_LOAD even if we end up not using it.
950*0b57cec5SDimitry Andric template <class ELFT, class RelTy>
951*0b57cec5SDimitry Andric static void processRelocAux(InputSectionBase &sec, RelExpr expr, RelType type,
952*0b57cec5SDimitry Andric                             uint64_t offset, Symbol &sym, const RelTy &rel,
953*0b57cec5SDimitry Andric                             int64_t addend) {
954*0b57cec5SDimitry Andric   // If the relocation is known to be a link-time constant, we know no dynamic
955*0b57cec5SDimitry Andric   // relocation will be created, pass the control to relocateAlloc() or
956*0b57cec5SDimitry Andric   // relocateNonAlloc() to resolve it.
957*0b57cec5SDimitry Andric   //
958*0b57cec5SDimitry Andric   // The behavior of an undefined weak reference is implementation defined. If
959*0b57cec5SDimitry Andric   // the relocation is to a weak undef, and we are producing an executable, let
960*0b57cec5SDimitry Andric   // relocate{,Non}Alloc() resolve it.
961*0b57cec5SDimitry Andric   if (isStaticLinkTimeConstant(expr, type, sym, sec, offset) ||
962*0b57cec5SDimitry Andric       (!config->shared && sym.isUndefWeak())) {
963*0b57cec5SDimitry Andric     sec.relocations.push_back({expr, type, offset, addend, &sym});
964*0b57cec5SDimitry Andric     return;
965*0b57cec5SDimitry Andric   }
966*0b57cec5SDimitry Andric 
967*0b57cec5SDimitry Andric   bool canWrite = (sec.flags & SHF_WRITE) || !config->zText;
968*0b57cec5SDimitry Andric   if (canWrite) {
969*0b57cec5SDimitry Andric     RelType rel = target->getDynRel(type);
970*0b57cec5SDimitry Andric     if (expr == R_GOT || (rel == target->symbolicRel && !sym.isPreemptible)) {
971*0b57cec5SDimitry Andric       addRelativeReloc(&sec, offset, &sym, addend, expr, type);
972*0b57cec5SDimitry Andric       return;
973*0b57cec5SDimitry Andric     } else if (rel != 0) {
974*0b57cec5SDimitry Andric       if (config->emachine == EM_MIPS && rel == target->symbolicRel)
975*0b57cec5SDimitry Andric         rel = target->relativeRel;
976*0b57cec5SDimitry Andric       sec.getPartition().relaDyn->addReloc(rel, &sec, offset, &sym, addend,
977*0b57cec5SDimitry Andric                                            R_ADDEND, type);
978*0b57cec5SDimitry Andric 
979*0b57cec5SDimitry Andric       // MIPS ABI turns using of GOT and dynamic relocations inside out.
980*0b57cec5SDimitry Andric       // While regular ABI uses dynamic relocations to fill up GOT entries
981*0b57cec5SDimitry Andric       // MIPS ABI requires dynamic linker to fills up GOT entries using
982*0b57cec5SDimitry Andric       // specially sorted dynamic symbol table. This affects even dynamic
983*0b57cec5SDimitry Andric       // relocations against symbols which do not require GOT entries
984*0b57cec5SDimitry Andric       // creation explicitly, i.e. do not have any GOT-relocations. So if
985*0b57cec5SDimitry Andric       // a preemptible symbol has a dynamic relocation we anyway have
986*0b57cec5SDimitry Andric       // to create a GOT entry for it.
987*0b57cec5SDimitry Andric       // If a non-preemptible symbol has a dynamic relocation against it,
988*0b57cec5SDimitry Andric       // dynamic linker takes it st_value, adds offset and writes down
989*0b57cec5SDimitry Andric       // result of the dynamic relocation. In case of preemptible symbol
990*0b57cec5SDimitry Andric       // dynamic linker performs symbol resolution, writes the symbol value
991*0b57cec5SDimitry Andric       // to the GOT entry and reads the GOT entry when it needs to perform
992*0b57cec5SDimitry Andric       // a dynamic relocation.
993*0b57cec5SDimitry Andric       // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19
994*0b57cec5SDimitry Andric       if (config->emachine == EM_MIPS)
995*0b57cec5SDimitry Andric         in.mipsGot->addEntry(*sec.file, sym, addend, expr);
996*0b57cec5SDimitry Andric       return;
997*0b57cec5SDimitry Andric     }
998*0b57cec5SDimitry Andric   }
999*0b57cec5SDimitry Andric 
1000*0b57cec5SDimitry Andric   if (!canWrite && (config->isPic && !isRelExpr(expr))) {
1001*0b57cec5SDimitry Andric     error(
1002*0b57cec5SDimitry Andric         "can't create dynamic relocation " + toString(type) + " against " +
1003*0b57cec5SDimitry Andric         (sym.getName().empty() ? "local symbol" : "symbol: " + toString(sym)) +
1004*0b57cec5SDimitry Andric         " in readonly segment; recompile object files with -fPIC "
1005*0b57cec5SDimitry Andric         "or pass '-Wl,-z,notext' to allow text relocations in the output" +
1006*0b57cec5SDimitry Andric         getLocation(sec, sym, offset));
1007*0b57cec5SDimitry Andric     return;
1008*0b57cec5SDimitry Andric   }
1009*0b57cec5SDimitry Andric 
1010*0b57cec5SDimitry Andric   // Copy relocations (for STT_OBJECT) and canonical PLT (for STT_FUNC) are only
1011*0b57cec5SDimitry Andric   // possible in an executable.
1012*0b57cec5SDimitry Andric   //
1013*0b57cec5SDimitry Andric   // Among R_ABS relocatoin types, symbolicRel has the same size as the word
1014*0b57cec5SDimitry Andric   // size. Others have fewer bits and may cause runtime overflow in -pie/-shared
1015*0b57cec5SDimitry Andric   // mode. Disallow them.
1016*0b57cec5SDimitry Andric   if (config->shared ||
1017*0b57cec5SDimitry Andric       (config->pie && expr == R_ABS && type != target->symbolicRel)) {
1018*0b57cec5SDimitry Andric     errorOrWarn(
1019*0b57cec5SDimitry Andric         "relocation " + toString(type) + " cannot be used against " +
1020*0b57cec5SDimitry Andric         (sym.getName().empty() ? "local symbol" : "symbol " + toString(sym)) +
1021*0b57cec5SDimitry Andric         "; recompile with -fPIC" + getLocation(sec, sym, offset));
1022*0b57cec5SDimitry Andric     return;
1023*0b57cec5SDimitry Andric   }
1024*0b57cec5SDimitry Andric 
1025*0b57cec5SDimitry Andric   // If the symbol is undefined we already reported any relevant errors.
1026*0b57cec5SDimitry Andric   if (sym.isUndefined())
1027*0b57cec5SDimitry Andric     return;
1028*0b57cec5SDimitry Andric 
1029*0b57cec5SDimitry Andric   if (!canDefineSymbolInExecutable(sym)) {
1030*0b57cec5SDimitry Andric     error("cannot preempt symbol: " + toString(sym) +
1031*0b57cec5SDimitry Andric           getLocation(sec, sym, offset));
1032*0b57cec5SDimitry Andric     return;
1033*0b57cec5SDimitry Andric   }
1034*0b57cec5SDimitry Andric 
1035*0b57cec5SDimitry Andric   if (sym.isObject()) {
1036*0b57cec5SDimitry Andric     // Produce a copy relocation.
1037*0b57cec5SDimitry Andric     if (auto *ss = dyn_cast<SharedSymbol>(&sym)) {
1038*0b57cec5SDimitry Andric       if (!config->zCopyreloc)
1039*0b57cec5SDimitry Andric         error("unresolvable relocation " + toString(type) +
1040*0b57cec5SDimitry Andric               " against symbol '" + toString(*ss) +
1041*0b57cec5SDimitry Andric               "'; recompile with -fPIC or remove '-z nocopyreloc'" +
1042*0b57cec5SDimitry Andric               getLocation(sec, sym, offset));
1043*0b57cec5SDimitry Andric       addCopyRelSymbol<ELFT>(*ss);
1044*0b57cec5SDimitry Andric     }
1045*0b57cec5SDimitry Andric     sec.relocations.push_back({expr, type, offset, addend, &sym});
1046*0b57cec5SDimitry Andric     return;
1047*0b57cec5SDimitry Andric   }
1048*0b57cec5SDimitry Andric 
1049*0b57cec5SDimitry Andric   if (sym.isFunc()) {
1050*0b57cec5SDimitry Andric     // This handles a non PIC program call to function in a shared library. In
1051*0b57cec5SDimitry Andric     // an ideal world, we could just report an error saying the relocation can
1052*0b57cec5SDimitry Andric     // overflow at runtime. In the real world with glibc, crt1.o has a
1053*0b57cec5SDimitry Andric     // R_X86_64_PC32 pointing to libc.so.
1054*0b57cec5SDimitry Andric     //
1055*0b57cec5SDimitry Andric     // The general idea on how to handle such cases is to create a PLT entry and
1056*0b57cec5SDimitry Andric     // use that as the function value.
1057*0b57cec5SDimitry Andric     //
1058*0b57cec5SDimitry Andric     // For the static linking part, we just return a plt expr and everything
1059*0b57cec5SDimitry Andric     // else will use the PLT entry as the address.
1060*0b57cec5SDimitry Andric     //
1061*0b57cec5SDimitry Andric     // The remaining problem is making sure pointer equality still works. We
1062*0b57cec5SDimitry Andric     // need the help of the dynamic linker for that. We let it know that we have
1063*0b57cec5SDimitry Andric     // a direct reference to a so symbol by creating an undefined symbol with a
1064*0b57cec5SDimitry Andric     // non zero st_value. Seeing that, the dynamic linker resolves the symbol to
1065*0b57cec5SDimitry Andric     // the value of the symbol we created. This is true even for got entries, so
1066*0b57cec5SDimitry Andric     // pointer equality is maintained. To avoid an infinite loop, the only entry
1067*0b57cec5SDimitry Andric     // that points to the real function is a dedicated got entry used by the
1068*0b57cec5SDimitry Andric     // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT,
1069*0b57cec5SDimitry Andric     // R_386_JMP_SLOT, etc).
1070*0b57cec5SDimitry Andric 
1071*0b57cec5SDimitry Andric     // For position independent executable on i386, the plt entry requires ebx
1072*0b57cec5SDimitry Andric     // to be set. This causes two problems:
1073*0b57cec5SDimitry Andric     // * If some code has a direct reference to a function, it was probably
1074*0b57cec5SDimitry Andric     //   compiled without -fPIE/-fPIC and doesn't maintain ebx.
1075*0b57cec5SDimitry Andric     // * If a library definition gets preempted to the executable, it will have
1076*0b57cec5SDimitry Andric     //   the wrong ebx value.
1077*0b57cec5SDimitry Andric     if (config->pie && config->emachine == EM_386)
1078*0b57cec5SDimitry Andric       errorOrWarn("symbol '" + toString(sym) +
1079*0b57cec5SDimitry Andric                   "' cannot be preempted; recompile with -fPIE" +
1080*0b57cec5SDimitry Andric                   getLocation(sec, sym, offset));
1081*0b57cec5SDimitry Andric     if (!sym.isInPlt())
1082*0b57cec5SDimitry Andric       addPltEntry<ELFT>(in.plt, in.gotPlt, in.relaPlt, target->pltRel, sym);
1083*0b57cec5SDimitry Andric     if (!sym.isDefined())
1084*0b57cec5SDimitry Andric       replaceWithDefined(
1085*0b57cec5SDimitry Andric           sym, in.plt,
1086*0b57cec5SDimitry Andric           target->pltHeaderSize + target->pltEntrySize * sym.pltIndex, 0);
1087*0b57cec5SDimitry Andric     sym.needsPltAddr = true;
1088*0b57cec5SDimitry Andric     sec.relocations.push_back({expr, type, offset, addend, &sym});
1089*0b57cec5SDimitry Andric     return;
1090*0b57cec5SDimitry Andric   }
1091*0b57cec5SDimitry Andric 
1092*0b57cec5SDimitry Andric   errorOrWarn("symbol '" + toString(sym) + "' has no type" +
1093*0b57cec5SDimitry Andric               getLocation(sec, sym, offset));
1094*0b57cec5SDimitry Andric }
1095*0b57cec5SDimitry Andric 
1096*0b57cec5SDimitry Andric struct IRelativeReloc {
1097*0b57cec5SDimitry Andric   RelType type;
1098*0b57cec5SDimitry Andric   InputSectionBase *sec;
1099*0b57cec5SDimitry Andric   uint64_t offset;
1100*0b57cec5SDimitry Andric   Symbol *sym;
1101*0b57cec5SDimitry Andric };
1102*0b57cec5SDimitry Andric 
1103*0b57cec5SDimitry Andric static std::vector<IRelativeReloc> iRelativeRelocs;
1104*0b57cec5SDimitry Andric 
1105*0b57cec5SDimitry Andric template <class ELFT, class RelTy>
1106*0b57cec5SDimitry Andric static void scanReloc(InputSectionBase &sec, OffsetGetter &getOffset, RelTy *&i,
1107*0b57cec5SDimitry Andric                       RelTy *end) {
1108*0b57cec5SDimitry Andric   const RelTy &rel = *i;
1109*0b57cec5SDimitry Andric   uint32_t symIndex = rel.getSymbol(config->isMips64EL);
1110*0b57cec5SDimitry Andric   Symbol &sym = sec.getFile<ELFT>()->getSymbol(symIndex);
1111*0b57cec5SDimitry Andric   RelType type;
1112*0b57cec5SDimitry Andric 
1113*0b57cec5SDimitry Andric   // Deal with MIPS oddity.
1114*0b57cec5SDimitry Andric   if (config->mipsN32Abi) {
1115*0b57cec5SDimitry Andric     type = getMipsN32RelType(i, end);
1116*0b57cec5SDimitry Andric   } else {
1117*0b57cec5SDimitry Andric     type = rel.getType(config->isMips64EL);
1118*0b57cec5SDimitry Andric     ++i;
1119*0b57cec5SDimitry Andric   }
1120*0b57cec5SDimitry Andric 
1121*0b57cec5SDimitry Andric   // Get an offset in an output section this relocation is applied to.
1122*0b57cec5SDimitry Andric   uint64_t offset = getOffset.get(rel.r_offset);
1123*0b57cec5SDimitry Andric   if (offset == uint64_t(-1))
1124*0b57cec5SDimitry Andric     return;
1125*0b57cec5SDimitry Andric 
1126*0b57cec5SDimitry Andric   // Error if the target symbol is undefined. Symbol index 0 may be used by
1127*0b57cec5SDimitry Andric   // marker relocations, e.g. R_*_NONE and R_ARM_V4BX. Don't error on them.
1128*0b57cec5SDimitry Andric   if (symIndex != 0 && maybeReportUndefined<ELFT>(sym, sec, rel.r_offset))
1129*0b57cec5SDimitry Andric     return;
1130*0b57cec5SDimitry Andric 
1131*0b57cec5SDimitry Andric   const uint8_t *relocatedAddr = sec.data().begin() + rel.r_offset;
1132*0b57cec5SDimitry Andric   RelExpr expr = target->getRelExpr(type, sym, relocatedAddr);
1133*0b57cec5SDimitry Andric 
1134*0b57cec5SDimitry Andric   // Ignore "hint" relocations because they are only markers for relaxation.
1135*0b57cec5SDimitry Andric   if (oneof<R_HINT, R_NONE>(expr))
1136*0b57cec5SDimitry Andric     return;
1137*0b57cec5SDimitry Andric 
1138*0b57cec5SDimitry Andric   // We can separate the small code model relocations into 2 categories:
1139*0b57cec5SDimitry Andric   // 1) Those that access the compiler generated .toc sections.
1140*0b57cec5SDimitry Andric   // 2) Those that access the linker allocated got entries.
1141*0b57cec5SDimitry Andric   // lld allocates got entries to symbols on demand. Since we don't try to sort
1142*0b57cec5SDimitry Andric   // the got entries in any way, we don't have to track which objects have
1143*0b57cec5SDimitry Andric   // got-based small code model relocs. The .toc sections get placed after the
1144*0b57cec5SDimitry Andric   // end of the linker allocated .got section and we do sort those so sections
1145*0b57cec5SDimitry Andric   // addressed with small code model relocations come first.
1146*0b57cec5SDimitry Andric   if (config->emachine == EM_PPC64 && isPPC64SmallCodeModelTocReloc(type))
1147*0b57cec5SDimitry Andric     sec.file->ppc64SmallCodeModelTocRelocs = true;
1148*0b57cec5SDimitry Andric 
1149*0b57cec5SDimitry Andric   if (sym.isGnuIFunc() && !config->zText && config->warnIfuncTextrel) {
1150*0b57cec5SDimitry Andric     warn("using ifunc symbols when text relocations are allowed may produce "
1151*0b57cec5SDimitry Andric          "a binary that will segfault, if the object file is linked with "
1152*0b57cec5SDimitry Andric          "old version of glibc (glibc 2.28 and earlier). If this applies to "
1153*0b57cec5SDimitry Andric          "you, consider recompiling the object files without -fPIC and "
1154*0b57cec5SDimitry Andric          "without -Wl,-z,notext option. Use -no-warn-ifunc-textrel to "
1155*0b57cec5SDimitry Andric          "turn off this warning." +
1156*0b57cec5SDimitry Andric          getLocation(sec, sym, offset));
1157*0b57cec5SDimitry Andric   }
1158*0b57cec5SDimitry Andric 
1159*0b57cec5SDimitry Andric   // Read an addend.
1160*0b57cec5SDimitry Andric   int64_t addend = computeAddend<ELFT>(rel, end, sec, expr, sym.isLocal());
1161*0b57cec5SDimitry Andric 
1162*0b57cec5SDimitry Andric   // Relax relocations.
1163*0b57cec5SDimitry Andric   //
1164*0b57cec5SDimitry Andric   // If we know that a PLT entry will be resolved within the same ELF module, we
1165*0b57cec5SDimitry Andric   // can skip PLT access and directly jump to the destination function. For
1166*0b57cec5SDimitry Andric   // example, if we are linking a main exectuable, all dynamic symbols that can
1167*0b57cec5SDimitry Andric   // be resolved within the executable will actually be resolved that way at
1168*0b57cec5SDimitry Andric   // runtime, because the main exectuable is always at the beginning of a search
1169*0b57cec5SDimitry Andric   // list. We can leverage that fact.
1170*0b57cec5SDimitry Andric   if (!sym.isPreemptible && (!sym.isGnuIFunc() || config->zIfuncNoplt)) {
1171*0b57cec5SDimitry Andric     if (expr == R_GOT_PC && !isAbsoluteValue(sym)) {
1172*0b57cec5SDimitry Andric       expr = target->adjustRelaxExpr(type, relocatedAddr, expr);
1173*0b57cec5SDimitry Andric     } else {
1174*0b57cec5SDimitry Andric       // Addend of R_PPC_PLTREL24 is used to choose call stub type. It should be
1175*0b57cec5SDimitry Andric       // ignored if optimized to R_PC.
1176*0b57cec5SDimitry Andric       if (config->emachine == EM_PPC && expr == R_PPC32_PLTREL)
1177*0b57cec5SDimitry Andric         addend = 0;
1178*0b57cec5SDimitry Andric       expr = fromPlt(expr);
1179*0b57cec5SDimitry Andric     }
1180*0b57cec5SDimitry Andric   }
1181*0b57cec5SDimitry Andric 
1182*0b57cec5SDimitry Andric   // If the relocation does not emit a GOT or GOTPLT entry but its computation
1183*0b57cec5SDimitry Andric   // uses their addresses, we need GOT or GOTPLT to be created.
1184*0b57cec5SDimitry Andric   //
1185*0b57cec5SDimitry Andric   // The 4 types that relative GOTPLT are all x86 and x86-64 specific.
1186*0b57cec5SDimitry Andric   if (oneof<R_GOTPLTONLY_PC, R_GOTPLTREL, R_GOTPLT, R_TLSGD_GOTPLT>(expr)) {
1187*0b57cec5SDimitry Andric     in.gotPlt->hasGotPltOffRel = true;
1188*0b57cec5SDimitry Andric   } else if (oneof<R_GOTONLY_PC, R_GOTREL, R_PPC64_TOCBASE, R_PPC64_RELAX_TOC>(
1189*0b57cec5SDimitry Andric                  expr)) {
1190*0b57cec5SDimitry Andric     in.got->hasGotOffRel = true;
1191*0b57cec5SDimitry Andric   }
1192*0b57cec5SDimitry Andric 
1193*0b57cec5SDimitry Andric   // Process some TLS relocations, including relaxing TLS relocations.
1194*0b57cec5SDimitry Andric   // Note that this function does not handle all TLS relocations.
1195*0b57cec5SDimitry Andric   if (unsigned processed =
1196*0b57cec5SDimitry Andric           handleTlsRelocation<ELFT>(type, sym, sec, offset, addend, expr)) {
1197*0b57cec5SDimitry Andric     i += (processed - 1);
1198*0b57cec5SDimitry Andric     return;
1199*0b57cec5SDimitry Andric   }
1200*0b57cec5SDimitry Andric 
1201*0b57cec5SDimitry Andric   // We were asked not to generate PLT entries for ifuncs. Instead, pass the
1202*0b57cec5SDimitry Andric   // direct relocation on through.
1203*0b57cec5SDimitry Andric   if (sym.isGnuIFunc() && config->zIfuncNoplt) {
1204*0b57cec5SDimitry Andric     sym.exportDynamic = true;
1205*0b57cec5SDimitry Andric     mainPart->relaDyn->addReloc(type, &sec, offset, &sym, addend, R_ADDEND, type);
1206*0b57cec5SDimitry Andric     return;
1207*0b57cec5SDimitry Andric   }
1208*0b57cec5SDimitry Andric 
1209*0b57cec5SDimitry Andric   // Non-preemptible ifuncs require special handling. First, handle the usual
1210*0b57cec5SDimitry Andric   // case where the symbol isn't one of these.
1211*0b57cec5SDimitry Andric   if (!sym.isGnuIFunc() || sym.isPreemptible) {
1212*0b57cec5SDimitry Andric     // If a relocation needs PLT, we create PLT and GOTPLT slots for the symbol.
1213*0b57cec5SDimitry Andric     if (needsPlt(expr) && !sym.isInPlt())
1214*0b57cec5SDimitry Andric       addPltEntry<ELFT>(in.plt, in.gotPlt, in.relaPlt, target->pltRel, sym);
1215*0b57cec5SDimitry Andric 
1216*0b57cec5SDimitry Andric     // Create a GOT slot if a relocation needs GOT.
1217*0b57cec5SDimitry Andric     if (needsGot(expr)) {
1218*0b57cec5SDimitry Andric       if (config->emachine == EM_MIPS) {
1219*0b57cec5SDimitry Andric         // MIPS ABI has special rules to process GOT entries and doesn't
1220*0b57cec5SDimitry Andric         // require relocation entries for them. A special case is TLS
1221*0b57cec5SDimitry Andric         // relocations. In that case dynamic loader applies dynamic
1222*0b57cec5SDimitry Andric         // relocations to initialize TLS GOT entries.
1223*0b57cec5SDimitry Andric         // See "Global Offset Table" in Chapter 5 in the following document
1224*0b57cec5SDimitry Andric         // for detailed description:
1225*0b57cec5SDimitry Andric         // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1226*0b57cec5SDimitry Andric         in.mipsGot->addEntry(*sec.file, sym, addend, expr);
1227*0b57cec5SDimitry Andric       } else if (!sym.isInGot()) {
1228*0b57cec5SDimitry Andric         addGotEntry(sym);
1229*0b57cec5SDimitry Andric       }
1230*0b57cec5SDimitry Andric     }
1231*0b57cec5SDimitry Andric   } else {
1232*0b57cec5SDimitry Andric     // Handle a reference to a non-preemptible ifunc. These are special in a
1233*0b57cec5SDimitry Andric     // few ways:
1234*0b57cec5SDimitry Andric     //
1235*0b57cec5SDimitry Andric     // - Unlike most non-preemptible symbols, non-preemptible ifuncs do not have
1236*0b57cec5SDimitry Andric     //   a fixed value. But assuming that all references to the ifunc are
1237*0b57cec5SDimitry Andric     //   GOT-generating or PLT-generating, the handling of an ifunc is
1238*0b57cec5SDimitry Andric     //   relatively straightforward. We create a PLT entry in Iplt, which is
1239*0b57cec5SDimitry Andric     //   usually at the end of .plt, which makes an indirect call using a
1240*0b57cec5SDimitry Andric     //   matching GOT entry in igotPlt, which is usually at the end of .got.plt.
1241*0b57cec5SDimitry Andric     //   The GOT entry is relocated using an IRELATIVE relocation in relaIplt,
1242*0b57cec5SDimitry Andric     //   which is usually at the end of .rela.plt. Unlike most relocations in
1243*0b57cec5SDimitry Andric     //   .rela.plt, which may be evaluated lazily without -z now, dynamic
1244*0b57cec5SDimitry Andric     //   loaders evaluate IRELATIVE relocs eagerly, which means that for
1245*0b57cec5SDimitry Andric     //   IRELATIVE relocs only, GOT-generating relocations can point directly to
1246*0b57cec5SDimitry Andric     //   .got.plt without requiring a separate GOT entry.
1247*0b57cec5SDimitry Andric     //
1248*0b57cec5SDimitry Andric     // - Despite the fact that an ifunc does not have a fixed value, compilers
1249*0b57cec5SDimitry Andric     //   that are not passed -fPIC will assume that they do, and will emit
1250*0b57cec5SDimitry Andric     //   direct (non-GOT-generating, non-PLT-generating) relocations to the
1251*0b57cec5SDimitry Andric     //   symbol. This means that if a direct relocation to the symbol is
1252*0b57cec5SDimitry Andric     //   seen, the linker must set a value for the symbol, and this value must
1253*0b57cec5SDimitry Andric     //   be consistent no matter what type of reference is made to the symbol.
1254*0b57cec5SDimitry Andric     //   This can be done by creating a PLT entry for the symbol in the way
1255*0b57cec5SDimitry Andric     //   described above and making it canonical, that is, making all references
1256*0b57cec5SDimitry Andric     //   point to the PLT entry instead of the resolver. In lld we also store
1257*0b57cec5SDimitry Andric     //   the address of the PLT entry in the dynamic symbol table, which means
1258*0b57cec5SDimitry Andric     //   that the symbol will also have the same value in other modules.
1259*0b57cec5SDimitry Andric     //   Because the value loaded from the GOT needs to be consistent with
1260*0b57cec5SDimitry Andric     //   the value computed using a direct relocation, a non-preemptible ifunc
1261*0b57cec5SDimitry Andric     //   may end up with two GOT entries, one in .got.plt that points to the
1262*0b57cec5SDimitry Andric     //   address returned by the resolver and is used only by the PLT entry,
1263*0b57cec5SDimitry Andric     //   and another in .got that points to the PLT entry and is used by
1264*0b57cec5SDimitry Andric     //   GOT-generating relocations.
1265*0b57cec5SDimitry Andric     //
1266*0b57cec5SDimitry Andric     // - The fact that these symbols do not have a fixed value makes them an
1267*0b57cec5SDimitry Andric     //   exception to the general rule that a statically linked executable does
1268*0b57cec5SDimitry Andric     //   not require any form of dynamic relocation. To handle these relocations
1269*0b57cec5SDimitry Andric     //   correctly, the IRELATIVE relocations are stored in an array which a
1270*0b57cec5SDimitry Andric     //   statically linked executable's startup code must enumerate using the
1271*0b57cec5SDimitry Andric     //   linker-defined symbols __rela?_iplt_{start,end}.
1272*0b57cec5SDimitry Andric     //
1273*0b57cec5SDimitry Andric     // - An absolute relocation to a non-preemptible ifunc (such as a global
1274*0b57cec5SDimitry Andric     //   variable containing a pointer to the ifunc) needs to be relocated in
1275*0b57cec5SDimitry Andric     //   the exact same way as a GOT entry, so we can avoid needing to make the
1276*0b57cec5SDimitry Andric     //   PLT entry canonical by translating such relocations into IRELATIVE
1277*0b57cec5SDimitry Andric     //   relocations in the relaIplt.
1278*0b57cec5SDimitry Andric     if (!sym.isInPlt()) {
1279*0b57cec5SDimitry Andric       // Create PLT and GOTPLT slots for the symbol.
1280*0b57cec5SDimitry Andric       sym.isInIplt = true;
1281*0b57cec5SDimitry Andric 
1282*0b57cec5SDimitry Andric       // Create a copy of the symbol to use as the target of the IRELATIVE
1283*0b57cec5SDimitry Andric       // relocation in the igotPlt. This is in case we make the PLT canonical
1284*0b57cec5SDimitry Andric       // later, which would overwrite the original symbol.
1285*0b57cec5SDimitry Andric       //
1286*0b57cec5SDimitry Andric       // FIXME: Creating a copy of the symbol here is a bit of a hack. All
1287*0b57cec5SDimitry Andric       // that's really needed to create the IRELATIVE is the section and value,
1288*0b57cec5SDimitry Andric       // so ideally we should just need to copy those.
1289*0b57cec5SDimitry Andric       auto *directSym = make<Defined>(cast<Defined>(sym));
1290*0b57cec5SDimitry Andric       addPltEntry<ELFT>(in.iplt, in.igotPlt, in.relaIplt, target->iRelativeRel,
1291*0b57cec5SDimitry Andric                         *directSym);
1292*0b57cec5SDimitry Andric       sym.pltIndex = directSym->pltIndex;
1293*0b57cec5SDimitry Andric     }
1294*0b57cec5SDimitry Andric     if (expr == R_ABS && addend == 0 && (sec.flags & SHF_WRITE)) {
1295*0b57cec5SDimitry Andric       // We might be able to represent this as an IRELATIVE. But we don't know
1296*0b57cec5SDimitry Andric       // yet whether some later relocation will make the symbol point to a
1297*0b57cec5SDimitry Andric       // canonical PLT, which would make this either a dynamic RELATIVE (PIC) or
1298*0b57cec5SDimitry Andric       // static (non-PIC) relocation. So we keep a record of the information
1299*0b57cec5SDimitry Andric       // required to process the relocation, and after scanRelocs() has been
1300*0b57cec5SDimitry Andric       // called on all relocations, the relocation is resolved by
1301*0b57cec5SDimitry Andric       // addIRelativeRelocs().
1302*0b57cec5SDimitry Andric       iRelativeRelocs.push_back({type, &sec, offset, &sym});
1303*0b57cec5SDimitry Andric       return;
1304*0b57cec5SDimitry Andric     }
1305*0b57cec5SDimitry Andric     if (needsGot(expr)) {
1306*0b57cec5SDimitry Andric       // Redirect GOT accesses to point to the Igot.
1307*0b57cec5SDimitry Andric       //
1308*0b57cec5SDimitry Andric       // This field is also used to keep track of whether we ever needed a GOT
1309*0b57cec5SDimitry Andric       // entry. If we did and we make the PLT canonical later, we'll need to
1310*0b57cec5SDimitry Andric       // create a GOT entry pointing to the PLT entry for Sym.
1311*0b57cec5SDimitry Andric       sym.gotInIgot = true;
1312*0b57cec5SDimitry Andric     } else if (!needsPlt(expr)) {
1313*0b57cec5SDimitry Andric       // Make the ifunc's PLT entry canonical by changing the value of its
1314*0b57cec5SDimitry Andric       // symbol to redirect all references to point to it.
1315*0b57cec5SDimitry Andric       unsigned entryOffset = sym.pltIndex * target->pltEntrySize;
1316*0b57cec5SDimitry Andric       if (config->zRetpolineplt)
1317*0b57cec5SDimitry Andric         entryOffset += target->pltHeaderSize;
1318*0b57cec5SDimitry Andric 
1319*0b57cec5SDimitry Andric       auto &d = cast<Defined>(sym);
1320*0b57cec5SDimitry Andric       d.section = in.iplt;
1321*0b57cec5SDimitry Andric       d.value = entryOffset;
1322*0b57cec5SDimitry Andric       d.size = 0;
1323*0b57cec5SDimitry Andric       // It's important to set the symbol type here so that dynamic loaders
1324*0b57cec5SDimitry Andric       // don't try to call the PLT as if it were an ifunc resolver.
1325*0b57cec5SDimitry Andric       d.type = STT_FUNC;
1326*0b57cec5SDimitry Andric 
1327*0b57cec5SDimitry Andric       if (sym.gotInIgot) {
1328*0b57cec5SDimitry Andric         // We previously encountered a GOT generating reference that we
1329*0b57cec5SDimitry Andric         // redirected to the Igot. Now that the PLT entry is canonical we must
1330*0b57cec5SDimitry Andric         // clear the redirection to the Igot and add a GOT entry. As we've
1331*0b57cec5SDimitry Andric         // changed the symbol type to STT_FUNC future GOT generating references
1332*0b57cec5SDimitry Andric         // will naturally use this GOT entry.
1333*0b57cec5SDimitry Andric         //
1334*0b57cec5SDimitry Andric         // We don't need to worry about creating a MIPS GOT here because ifuncs
1335*0b57cec5SDimitry Andric         // aren't a thing on MIPS.
1336*0b57cec5SDimitry Andric         sym.gotInIgot = false;
1337*0b57cec5SDimitry Andric         addGotEntry(sym);
1338*0b57cec5SDimitry Andric       }
1339*0b57cec5SDimitry Andric     }
1340*0b57cec5SDimitry Andric   }
1341*0b57cec5SDimitry Andric 
1342*0b57cec5SDimitry Andric   processRelocAux<ELFT>(sec, expr, type, offset, sym, rel, addend);
1343*0b57cec5SDimitry Andric }
1344*0b57cec5SDimitry Andric 
1345*0b57cec5SDimitry Andric template <class ELFT, class RelTy>
1346*0b57cec5SDimitry Andric static void scanRelocs(InputSectionBase &sec, ArrayRef<RelTy> rels) {
1347*0b57cec5SDimitry Andric   OffsetGetter getOffset(sec);
1348*0b57cec5SDimitry Andric 
1349*0b57cec5SDimitry Andric   // Not all relocations end up in Sec.Relocations, but a lot do.
1350*0b57cec5SDimitry Andric   sec.relocations.reserve(rels.size());
1351*0b57cec5SDimitry Andric 
1352*0b57cec5SDimitry Andric   for (auto i = rels.begin(), end = rels.end(); i != end;)
1353*0b57cec5SDimitry Andric     scanReloc<ELFT>(sec, getOffset, i, end);
1354*0b57cec5SDimitry Andric 
1355*0b57cec5SDimitry Andric   // Sort relocations by offset for more efficient searching for
1356*0b57cec5SDimitry Andric   // R_RISCV_PCREL_HI20 and R_PPC64_ADDR64.
1357*0b57cec5SDimitry Andric   if (config->emachine == EM_RISCV ||
1358*0b57cec5SDimitry Andric       (config->emachine == EM_PPC64 && sec.name == ".toc"))
1359*0b57cec5SDimitry Andric     llvm::stable_sort(sec.relocations,
1360*0b57cec5SDimitry Andric                       [](const Relocation &lhs, const Relocation &rhs) {
1361*0b57cec5SDimitry Andric                         return lhs.offset < rhs.offset;
1362*0b57cec5SDimitry Andric                       });
1363*0b57cec5SDimitry Andric }
1364*0b57cec5SDimitry Andric 
1365*0b57cec5SDimitry Andric template <class ELFT> void elf::scanRelocations(InputSectionBase &s) {
1366*0b57cec5SDimitry Andric   if (s.areRelocsRela)
1367*0b57cec5SDimitry Andric     scanRelocs<ELFT>(s, s.relas<ELFT>());
1368*0b57cec5SDimitry Andric   else
1369*0b57cec5SDimitry Andric     scanRelocs<ELFT>(s, s.rels<ELFT>());
1370*0b57cec5SDimitry Andric }
1371*0b57cec5SDimitry Andric 
1372*0b57cec5SDimitry Andric // Figure out which representation to use for any absolute relocs to
1373*0b57cec5SDimitry Andric // non-preemptible ifuncs that we visited during scanRelocs().
1374*0b57cec5SDimitry Andric void elf::addIRelativeRelocs() {
1375*0b57cec5SDimitry Andric   for (IRelativeReloc &r : iRelativeRelocs) {
1376*0b57cec5SDimitry Andric     if (r.sym->type == STT_GNU_IFUNC)
1377*0b57cec5SDimitry Andric       in.relaIplt->addReloc(
1378*0b57cec5SDimitry Andric           {target->iRelativeRel, r.sec, r.offset, true, r.sym, 0});
1379*0b57cec5SDimitry Andric     else if (config->isPic)
1380*0b57cec5SDimitry Andric       addRelativeReloc(r.sec, r.offset, r.sym, 0, R_ABS, r.type);
1381*0b57cec5SDimitry Andric     else
1382*0b57cec5SDimitry Andric       r.sec->relocations.push_back({R_ABS, r.type, r.offset, 0, r.sym});
1383*0b57cec5SDimitry Andric   }
1384*0b57cec5SDimitry Andric   iRelativeRelocs.clear();
1385*0b57cec5SDimitry Andric }
1386*0b57cec5SDimitry Andric 
1387*0b57cec5SDimitry Andric static bool mergeCmp(const InputSection *a, const InputSection *b) {
1388*0b57cec5SDimitry Andric   // std::merge requires a strict weak ordering.
1389*0b57cec5SDimitry Andric   if (a->outSecOff < b->outSecOff)
1390*0b57cec5SDimitry Andric     return true;
1391*0b57cec5SDimitry Andric 
1392*0b57cec5SDimitry Andric   if (a->outSecOff == b->outSecOff) {
1393*0b57cec5SDimitry Andric     auto *ta = dyn_cast<ThunkSection>(a);
1394*0b57cec5SDimitry Andric     auto *tb = dyn_cast<ThunkSection>(b);
1395*0b57cec5SDimitry Andric 
1396*0b57cec5SDimitry Andric     // Check if Thunk is immediately before any specific Target
1397*0b57cec5SDimitry Andric     // InputSection for example Mips LA25 Thunks.
1398*0b57cec5SDimitry Andric     if (ta && ta->getTargetInputSection() == b)
1399*0b57cec5SDimitry Andric       return true;
1400*0b57cec5SDimitry Andric 
1401*0b57cec5SDimitry Andric     // Place Thunk Sections without specific targets before
1402*0b57cec5SDimitry Andric     // non-Thunk Sections.
1403*0b57cec5SDimitry Andric     if (ta && !tb && !ta->getTargetInputSection())
1404*0b57cec5SDimitry Andric       return true;
1405*0b57cec5SDimitry Andric   }
1406*0b57cec5SDimitry Andric 
1407*0b57cec5SDimitry Andric   return false;
1408*0b57cec5SDimitry Andric }
1409*0b57cec5SDimitry Andric 
1410*0b57cec5SDimitry Andric // Call Fn on every executable InputSection accessed via the linker script
1411*0b57cec5SDimitry Andric // InputSectionDescription::Sections.
1412*0b57cec5SDimitry Andric static void forEachInputSectionDescription(
1413*0b57cec5SDimitry Andric     ArrayRef<OutputSection *> outputSections,
1414*0b57cec5SDimitry Andric     llvm::function_ref<void(OutputSection *, InputSectionDescription *)> fn) {
1415*0b57cec5SDimitry Andric   for (OutputSection *os : outputSections) {
1416*0b57cec5SDimitry Andric     if (!(os->flags & SHF_ALLOC) || !(os->flags & SHF_EXECINSTR))
1417*0b57cec5SDimitry Andric       continue;
1418*0b57cec5SDimitry Andric     for (BaseCommand *bc : os->sectionCommands)
1419*0b57cec5SDimitry Andric       if (auto *isd = dyn_cast<InputSectionDescription>(bc))
1420*0b57cec5SDimitry Andric         fn(os, isd);
1421*0b57cec5SDimitry Andric   }
1422*0b57cec5SDimitry Andric }
1423*0b57cec5SDimitry Andric 
1424*0b57cec5SDimitry Andric // Thunk Implementation
1425*0b57cec5SDimitry Andric //
1426*0b57cec5SDimitry Andric // Thunks (sometimes called stubs, veneers or branch islands) are small pieces
1427*0b57cec5SDimitry Andric // of code that the linker inserts inbetween a caller and a callee. The thunks
1428*0b57cec5SDimitry Andric // are added at link time rather than compile time as the decision on whether
1429*0b57cec5SDimitry Andric // a thunk is needed, such as the caller and callee being out of range, can only
1430*0b57cec5SDimitry Andric // be made at link time.
1431*0b57cec5SDimitry Andric //
1432*0b57cec5SDimitry Andric // It is straightforward to tell given the current state of the program when a
1433*0b57cec5SDimitry Andric // thunk is needed for a particular call. The more difficult part is that
1434*0b57cec5SDimitry Andric // the thunk needs to be placed in the program such that the caller can reach
1435*0b57cec5SDimitry Andric // the thunk and the thunk can reach the callee; furthermore, adding thunks to
1436*0b57cec5SDimitry Andric // the program alters addresses, which can mean more thunks etc.
1437*0b57cec5SDimitry Andric //
1438*0b57cec5SDimitry Andric // In lld we have a synthetic ThunkSection that can hold many Thunks.
1439*0b57cec5SDimitry Andric // The decision to have a ThunkSection act as a container means that we can
1440*0b57cec5SDimitry Andric // more easily handle the most common case of a single block of contiguous
1441*0b57cec5SDimitry Andric // Thunks by inserting just a single ThunkSection.
1442*0b57cec5SDimitry Andric //
1443*0b57cec5SDimitry Andric // The implementation of Thunks in lld is split across these areas
1444*0b57cec5SDimitry Andric // Relocations.cpp : Framework for creating and placing thunks
1445*0b57cec5SDimitry Andric // Thunks.cpp : The code generated for each supported thunk
1446*0b57cec5SDimitry Andric // Target.cpp : Target specific hooks that the framework uses to decide when
1447*0b57cec5SDimitry Andric //              a thunk is used
1448*0b57cec5SDimitry Andric // Synthetic.cpp : Implementation of ThunkSection
1449*0b57cec5SDimitry Andric // Writer.cpp : Iteratively call framework until no more Thunks added
1450*0b57cec5SDimitry Andric //
1451*0b57cec5SDimitry Andric // Thunk placement requirements:
1452*0b57cec5SDimitry Andric // Mips LA25 thunks. These must be placed immediately before the callee section
1453*0b57cec5SDimitry Andric // We can assume that the caller is in range of the Thunk. These are modelled
1454*0b57cec5SDimitry Andric // by Thunks that return the section they must precede with
1455*0b57cec5SDimitry Andric // getTargetInputSection().
1456*0b57cec5SDimitry Andric //
1457*0b57cec5SDimitry Andric // ARM interworking and range extension thunks. These thunks must be placed
1458*0b57cec5SDimitry Andric // within range of the caller. All implemented ARM thunks can always reach the
1459*0b57cec5SDimitry Andric // callee as they use an indirect jump via a register that has no range
1460*0b57cec5SDimitry Andric // restrictions.
1461*0b57cec5SDimitry Andric //
1462*0b57cec5SDimitry Andric // Thunk placement algorithm:
1463*0b57cec5SDimitry Andric // For Mips LA25 ThunkSections; the placement is explicit, it has to be before
1464*0b57cec5SDimitry Andric // getTargetInputSection().
1465*0b57cec5SDimitry Andric //
1466*0b57cec5SDimitry Andric // For thunks that must be placed within range of the caller there are many
1467*0b57cec5SDimitry Andric // possible choices given that the maximum range from the caller is usually
1468*0b57cec5SDimitry Andric // much larger than the average InputSection size. Desirable properties include:
1469*0b57cec5SDimitry Andric // - Maximize reuse of thunks by multiple callers
1470*0b57cec5SDimitry Andric // - Minimize number of ThunkSections to simplify insertion
1471*0b57cec5SDimitry Andric // - Handle impact of already added Thunks on addresses
1472*0b57cec5SDimitry Andric // - Simple to understand and implement
1473*0b57cec5SDimitry Andric //
1474*0b57cec5SDimitry Andric // In lld for the first pass, we pre-create one or more ThunkSections per
1475*0b57cec5SDimitry Andric // InputSectionDescription at Target specific intervals. A ThunkSection is
1476*0b57cec5SDimitry Andric // placed so that the estimated end of the ThunkSection is within range of the
1477*0b57cec5SDimitry Andric // start of the InputSectionDescription or the previous ThunkSection. For
1478*0b57cec5SDimitry Andric // example:
1479*0b57cec5SDimitry Andric // InputSectionDescription
1480*0b57cec5SDimitry Andric // Section 0
1481*0b57cec5SDimitry Andric // ...
1482*0b57cec5SDimitry Andric // Section N
1483*0b57cec5SDimitry Andric // ThunkSection 0
1484*0b57cec5SDimitry Andric // Section N + 1
1485*0b57cec5SDimitry Andric // ...
1486*0b57cec5SDimitry Andric // Section N + K
1487*0b57cec5SDimitry Andric // Thunk Section 1
1488*0b57cec5SDimitry Andric //
1489*0b57cec5SDimitry Andric // The intention is that we can add a Thunk to a ThunkSection that is well
1490*0b57cec5SDimitry Andric // spaced enough to service a number of callers without having to do a lot
1491*0b57cec5SDimitry Andric // of work. An important principle is that it is not an error if a Thunk cannot
1492*0b57cec5SDimitry Andric // be placed in a pre-created ThunkSection; when this happens we create a new
1493*0b57cec5SDimitry Andric // ThunkSection placed next to the caller. This allows us to handle the vast
1494*0b57cec5SDimitry Andric // majority of thunks simply, but also handle rare cases where the branch range
1495*0b57cec5SDimitry Andric // is smaller than the target specific spacing.
1496*0b57cec5SDimitry Andric //
1497*0b57cec5SDimitry Andric // The algorithm is expected to create all the thunks that are needed in a
1498*0b57cec5SDimitry Andric // single pass, with a small number of programs needing a second pass due to
1499*0b57cec5SDimitry Andric // the insertion of thunks in the first pass increasing the offset between
1500*0b57cec5SDimitry Andric // callers and callees that were only just in range.
1501*0b57cec5SDimitry Andric //
1502*0b57cec5SDimitry Andric // A consequence of allowing new ThunkSections to be created outside of the
1503*0b57cec5SDimitry Andric // pre-created ThunkSections is that in rare cases calls to Thunks that were in
1504*0b57cec5SDimitry Andric // range in pass K, are out of range in some pass > K due to the insertion of
1505*0b57cec5SDimitry Andric // more Thunks in between the caller and callee. When this happens we retarget
1506*0b57cec5SDimitry Andric // the relocation back to the original target and create another Thunk.
1507*0b57cec5SDimitry Andric 
1508*0b57cec5SDimitry Andric // Remove ThunkSections that are empty, this should only be the initial set
1509*0b57cec5SDimitry Andric // precreated on pass 0.
1510*0b57cec5SDimitry Andric 
1511*0b57cec5SDimitry Andric // Insert the Thunks for OutputSection OS into their designated place
1512*0b57cec5SDimitry Andric // in the Sections vector, and recalculate the InputSection output section
1513*0b57cec5SDimitry Andric // offsets.
1514*0b57cec5SDimitry Andric // This may invalidate any output section offsets stored outside of InputSection
1515*0b57cec5SDimitry Andric void ThunkCreator::mergeThunks(ArrayRef<OutputSection *> outputSections) {
1516*0b57cec5SDimitry Andric   forEachInputSectionDescription(
1517*0b57cec5SDimitry Andric       outputSections, [&](OutputSection *os, InputSectionDescription *isd) {
1518*0b57cec5SDimitry Andric         if (isd->thunkSections.empty())
1519*0b57cec5SDimitry Andric           return;
1520*0b57cec5SDimitry Andric 
1521*0b57cec5SDimitry Andric         // Remove any zero sized precreated Thunks.
1522*0b57cec5SDimitry Andric         llvm::erase_if(isd->thunkSections,
1523*0b57cec5SDimitry Andric                        [](const std::pair<ThunkSection *, uint32_t> &ts) {
1524*0b57cec5SDimitry Andric                          return ts.first->getSize() == 0;
1525*0b57cec5SDimitry Andric                        });
1526*0b57cec5SDimitry Andric 
1527*0b57cec5SDimitry Andric         // ISD->ThunkSections contains all created ThunkSections, including
1528*0b57cec5SDimitry Andric         // those inserted in previous passes. Extract the Thunks created this
1529*0b57cec5SDimitry Andric         // pass and order them in ascending outSecOff.
1530*0b57cec5SDimitry Andric         std::vector<ThunkSection *> newThunks;
1531*0b57cec5SDimitry Andric         for (const std::pair<ThunkSection *, uint32_t> ts : isd->thunkSections)
1532*0b57cec5SDimitry Andric           if (ts.second == pass)
1533*0b57cec5SDimitry Andric             newThunks.push_back(ts.first);
1534*0b57cec5SDimitry Andric         llvm::stable_sort(newThunks,
1535*0b57cec5SDimitry Andric                           [](const ThunkSection *a, const ThunkSection *b) {
1536*0b57cec5SDimitry Andric                             return a->outSecOff < b->outSecOff;
1537*0b57cec5SDimitry Andric                           });
1538*0b57cec5SDimitry Andric 
1539*0b57cec5SDimitry Andric         // Merge sorted vectors of Thunks and InputSections by outSecOff
1540*0b57cec5SDimitry Andric         std::vector<InputSection *> tmp;
1541*0b57cec5SDimitry Andric         tmp.reserve(isd->sections.size() + newThunks.size());
1542*0b57cec5SDimitry Andric 
1543*0b57cec5SDimitry Andric         std::merge(isd->sections.begin(), isd->sections.end(),
1544*0b57cec5SDimitry Andric                    newThunks.begin(), newThunks.end(), std::back_inserter(tmp),
1545*0b57cec5SDimitry Andric                    mergeCmp);
1546*0b57cec5SDimitry Andric 
1547*0b57cec5SDimitry Andric         isd->sections = std::move(tmp);
1548*0b57cec5SDimitry Andric       });
1549*0b57cec5SDimitry Andric }
1550*0b57cec5SDimitry Andric 
1551*0b57cec5SDimitry Andric // Find or create a ThunkSection within the InputSectionDescription (ISD) that
1552*0b57cec5SDimitry Andric // is in range of Src. An ISD maps to a range of InputSections described by a
1553*0b57cec5SDimitry Andric // linker script section pattern such as { .text .text.* }.
1554*0b57cec5SDimitry Andric ThunkSection *ThunkCreator::getISDThunkSec(OutputSection *os, InputSection *isec,
1555*0b57cec5SDimitry Andric                                            InputSectionDescription *isd,
1556*0b57cec5SDimitry Andric                                            uint32_t type, uint64_t src) {
1557*0b57cec5SDimitry Andric   for (std::pair<ThunkSection *, uint32_t> tp : isd->thunkSections) {
1558*0b57cec5SDimitry Andric     ThunkSection *ts = tp.first;
1559*0b57cec5SDimitry Andric     uint64_t tsBase = os->addr + ts->outSecOff;
1560*0b57cec5SDimitry Andric     uint64_t tsLimit = tsBase + ts->getSize();
1561*0b57cec5SDimitry Andric     if (target->inBranchRange(type, src, (src > tsLimit) ? tsBase : tsLimit))
1562*0b57cec5SDimitry Andric       return ts;
1563*0b57cec5SDimitry Andric   }
1564*0b57cec5SDimitry Andric 
1565*0b57cec5SDimitry Andric   // No suitable ThunkSection exists. This can happen when there is a branch
1566*0b57cec5SDimitry Andric   // with lower range than the ThunkSection spacing or when there are too
1567*0b57cec5SDimitry Andric   // many Thunks. Create a new ThunkSection as close to the InputSection as
1568*0b57cec5SDimitry Andric   // possible. Error if InputSection is so large we cannot place ThunkSection
1569*0b57cec5SDimitry Andric   // anywhere in Range.
1570*0b57cec5SDimitry Andric   uint64_t thunkSecOff = isec->outSecOff;
1571*0b57cec5SDimitry Andric   if (!target->inBranchRange(type, src, os->addr + thunkSecOff)) {
1572*0b57cec5SDimitry Andric     thunkSecOff = isec->outSecOff + isec->getSize();
1573*0b57cec5SDimitry Andric     if (!target->inBranchRange(type, src, os->addr + thunkSecOff))
1574*0b57cec5SDimitry Andric       fatal("InputSection too large for range extension thunk " +
1575*0b57cec5SDimitry Andric             isec->getObjMsg(src - (os->addr + isec->outSecOff)));
1576*0b57cec5SDimitry Andric   }
1577*0b57cec5SDimitry Andric   return addThunkSection(os, isd, thunkSecOff);
1578*0b57cec5SDimitry Andric }
1579*0b57cec5SDimitry Andric 
1580*0b57cec5SDimitry Andric // Add a Thunk that needs to be placed in a ThunkSection that immediately
1581*0b57cec5SDimitry Andric // precedes its Target.
1582*0b57cec5SDimitry Andric ThunkSection *ThunkCreator::getISThunkSec(InputSection *isec) {
1583*0b57cec5SDimitry Andric   ThunkSection *ts = thunkedSections.lookup(isec);
1584*0b57cec5SDimitry Andric   if (ts)
1585*0b57cec5SDimitry Andric     return ts;
1586*0b57cec5SDimitry Andric 
1587*0b57cec5SDimitry Andric   // Find InputSectionRange within Target Output Section (TOS) that the
1588*0b57cec5SDimitry Andric   // InputSection (IS) that we need to precede is in.
1589*0b57cec5SDimitry Andric   OutputSection *tos = isec->getParent();
1590*0b57cec5SDimitry Andric   for (BaseCommand *bc : tos->sectionCommands) {
1591*0b57cec5SDimitry Andric     auto *isd = dyn_cast<InputSectionDescription>(bc);
1592*0b57cec5SDimitry Andric     if (!isd || isd->sections.empty())
1593*0b57cec5SDimitry Andric       continue;
1594*0b57cec5SDimitry Andric 
1595*0b57cec5SDimitry Andric     InputSection *first = isd->sections.front();
1596*0b57cec5SDimitry Andric     InputSection *last = isd->sections.back();
1597*0b57cec5SDimitry Andric 
1598*0b57cec5SDimitry Andric     if (isec->outSecOff < first->outSecOff || last->outSecOff < isec->outSecOff)
1599*0b57cec5SDimitry Andric       continue;
1600*0b57cec5SDimitry Andric 
1601*0b57cec5SDimitry Andric     ts = addThunkSection(tos, isd, isec->outSecOff);
1602*0b57cec5SDimitry Andric     thunkedSections[isec] = ts;
1603*0b57cec5SDimitry Andric     return ts;
1604*0b57cec5SDimitry Andric   }
1605*0b57cec5SDimitry Andric 
1606*0b57cec5SDimitry Andric   return nullptr;
1607*0b57cec5SDimitry Andric }
1608*0b57cec5SDimitry Andric 
1609*0b57cec5SDimitry Andric // Create one or more ThunkSections per OS that can be used to place Thunks.
1610*0b57cec5SDimitry Andric // We attempt to place the ThunkSections using the following desirable
1611*0b57cec5SDimitry Andric // properties:
1612*0b57cec5SDimitry Andric // - Within range of the maximum number of callers
1613*0b57cec5SDimitry Andric // - Minimise the number of ThunkSections
1614*0b57cec5SDimitry Andric //
1615*0b57cec5SDimitry Andric // We follow a simple but conservative heuristic to place ThunkSections at
1616*0b57cec5SDimitry Andric // offsets that are multiples of a Target specific branch range.
1617*0b57cec5SDimitry Andric // For an InputSectionDescription that is smaller than the range, a single
1618*0b57cec5SDimitry Andric // ThunkSection at the end of the range will do.
1619*0b57cec5SDimitry Andric //
1620*0b57cec5SDimitry Andric // For an InputSectionDescription that is more than twice the size of the range,
1621*0b57cec5SDimitry Andric // we place the last ThunkSection at range bytes from the end of the
1622*0b57cec5SDimitry Andric // InputSectionDescription in order to increase the likelihood that the
1623*0b57cec5SDimitry Andric // distance from a thunk to its target will be sufficiently small to
1624*0b57cec5SDimitry Andric // allow for the creation of a short thunk.
1625*0b57cec5SDimitry Andric void ThunkCreator::createInitialThunkSections(
1626*0b57cec5SDimitry Andric     ArrayRef<OutputSection *> outputSections) {
1627*0b57cec5SDimitry Andric   uint32_t thunkSectionSpacing = target->getThunkSectionSpacing();
1628*0b57cec5SDimitry Andric 
1629*0b57cec5SDimitry Andric   forEachInputSectionDescription(
1630*0b57cec5SDimitry Andric       outputSections, [&](OutputSection *os, InputSectionDescription *isd) {
1631*0b57cec5SDimitry Andric         if (isd->sections.empty())
1632*0b57cec5SDimitry Andric           return;
1633*0b57cec5SDimitry Andric 
1634*0b57cec5SDimitry Andric         uint32_t isdBegin = isd->sections.front()->outSecOff;
1635*0b57cec5SDimitry Andric         uint32_t isdEnd =
1636*0b57cec5SDimitry Andric             isd->sections.back()->outSecOff + isd->sections.back()->getSize();
1637*0b57cec5SDimitry Andric         uint32_t lastThunkLowerBound = -1;
1638*0b57cec5SDimitry Andric         if (isdEnd - isdBegin > thunkSectionSpacing * 2)
1639*0b57cec5SDimitry Andric           lastThunkLowerBound = isdEnd - thunkSectionSpacing;
1640*0b57cec5SDimitry Andric 
1641*0b57cec5SDimitry Andric         uint32_t isecLimit;
1642*0b57cec5SDimitry Andric         uint32_t prevIsecLimit = isdBegin;
1643*0b57cec5SDimitry Andric         uint32_t thunkUpperBound = isdBegin + thunkSectionSpacing;
1644*0b57cec5SDimitry Andric 
1645*0b57cec5SDimitry Andric         for (const InputSection *isec : isd->sections) {
1646*0b57cec5SDimitry Andric           isecLimit = isec->outSecOff + isec->getSize();
1647*0b57cec5SDimitry Andric           if (isecLimit > thunkUpperBound) {
1648*0b57cec5SDimitry Andric             addThunkSection(os, isd, prevIsecLimit);
1649*0b57cec5SDimitry Andric             thunkUpperBound = prevIsecLimit + thunkSectionSpacing;
1650*0b57cec5SDimitry Andric           }
1651*0b57cec5SDimitry Andric           if (isecLimit > lastThunkLowerBound)
1652*0b57cec5SDimitry Andric             break;
1653*0b57cec5SDimitry Andric           prevIsecLimit = isecLimit;
1654*0b57cec5SDimitry Andric         }
1655*0b57cec5SDimitry Andric         addThunkSection(os, isd, isecLimit);
1656*0b57cec5SDimitry Andric       });
1657*0b57cec5SDimitry Andric }
1658*0b57cec5SDimitry Andric 
1659*0b57cec5SDimitry Andric ThunkSection *ThunkCreator::addThunkSection(OutputSection *os,
1660*0b57cec5SDimitry Andric                                             InputSectionDescription *isd,
1661*0b57cec5SDimitry Andric                                             uint64_t off) {
1662*0b57cec5SDimitry Andric   auto *ts = make<ThunkSection>(os, off);
1663*0b57cec5SDimitry Andric   ts->partition = os->partition;
1664*0b57cec5SDimitry Andric   isd->thunkSections.push_back({ts, pass});
1665*0b57cec5SDimitry Andric   return ts;
1666*0b57cec5SDimitry Andric }
1667*0b57cec5SDimitry Andric 
1668*0b57cec5SDimitry Andric static bool isThunkSectionCompatible(InputSection *source,
1669*0b57cec5SDimitry Andric                                      SectionBase *target) {
1670*0b57cec5SDimitry Andric   // We can't reuse thunks in different loadable partitions because they might
1671*0b57cec5SDimitry Andric   // not be loaded. But partition 1 (the main partition) will always be loaded.
1672*0b57cec5SDimitry Andric   if (source->partition != target->partition)
1673*0b57cec5SDimitry Andric     return target->partition == 1;
1674*0b57cec5SDimitry Andric   return true;
1675*0b57cec5SDimitry Andric }
1676*0b57cec5SDimitry Andric 
1677*0b57cec5SDimitry Andric std::pair<Thunk *, bool> ThunkCreator::getThunk(InputSection *isec,
1678*0b57cec5SDimitry Andric                                                 Relocation &rel, uint64_t src) {
1679*0b57cec5SDimitry Andric   std::vector<Thunk *> *thunkVec = nullptr;
1680*0b57cec5SDimitry Andric 
1681*0b57cec5SDimitry Andric   // We use (section, offset) pair to find the thunk position if possible so
1682*0b57cec5SDimitry Andric   // that we create only one thunk for aliased symbols or ICFed sections.
1683*0b57cec5SDimitry Andric   if (auto *d = dyn_cast<Defined>(rel.sym))
1684*0b57cec5SDimitry Andric     if (!d->isInPlt() && d->section)
1685*0b57cec5SDimitry Andric       thunkVec = &thunkedSymbolsBySection[{d->section->repl, d->value}];
1686*0b57cec5SDimitry Andric   if (!thunkVec)
1687*0b57cec5SDimitry Andric     thunkVec = &thunkedSymbols[rel.sym];
1688*0b57cec5SDimitry Andric 
1689*0b57cec5SDimitry Andric   // Check existing Thunks for Sym to see if they can be reused
1690*0b57cec5SDimitry Andric   for (Thunk *t : *thunkVec)
1691*0b57cec5SDimitry Andric     if (isThunkSectionCompatible(isec, t->getThunkTargetSym()->section) &&
1692*0b57cec5SDimitry Andric         t->isCompatibleWith(*isec, rel) &&
1693*0b57cec5SDimitry Andric         target->inBranchRange(rel.type, src, t->getThunkTargetSym()->getVA()))
1694*0b57cec5SDimitry Andric       return std::make_pair(t, false);
1695*0b57cec5SDimitry Andric 
1696*0b57cec5SDimitry Andric   // No existing compatible Thunk in range, create a new one
1697*0b57cec5SDimitry Andric   Thunk *t = addThunk(*isec, rel);
1698*0b57cec5SDimitry Andric   thunkVec->push_back(t);
1699*0b57cec5SDimitry Andric   return std::make_pair(t, true);
1700*0b57cec5SDimitry Andric }
1701*0b57cec5SDimitry Andric 
1702*0b57cec5SDimitry Andric // Return true if the relocation target is an in range Thunk.
1703*0b57cec5SDimitry Andric // Return false if the relocation is not to a Thunk. If the relocation target
1704*0b57cec5SDimitry Andric // was originally to a Thunk, but is no longer in range we revert the
1705*0b57cec5SDimitry Andric // relocation back to its original non-Thunk target.
1706*0b57cec5SDimitry Andric bool ThunkCreator::normalizeExistingThunk(Relocation &rel, uint64_t src) {
1707*0b57cec5SDimitry Andric   if (Thunk *t = thunks.lookup(rel.sym)) {
1708*0b57cec5SDimitry Andric     if (target->inBranchRange(rel.type, src, rel.sym->getVA()))
1709*0b57cec5SDimitry Andric       return true;
1710*0b57cec5SDimitry Andric     rel.sym = &t->destination;
1711*0b57cec5SDimitry Andric     if (rel.sym->isInPlt())
1712*0b57cec5SDimitry Andric       rel.expr = toPlt(rel.expr);
1713*0b57cec5SDimitry Andric   }
1714*0b57cec5SDimitry Andric   return false;
1715*0b57cec5SDimitry Andric }
1716*0b57cec5SDimitry Andric 
1717*0b57cec5SDimitry Andric // Process all relocations from the InputSections that have been assigned
1718*0b57cec5SDimitry Andric // to InputSectionDescriptions and redirect through Thunks if needed. The
1719*0b57cec5SDimitry Andric // function should be called iteratively until it returns false.
1720*0b57cec5SDimitry Andric //
1721*0b57cec5SDimitry Andric // PreConditions:
1722*0b57cec5SDimitry Andric // All InputSections that may need a Thunk are reachable from
1723*0b57cec5SDimitry Andric // OutputSectionCommands.
1724*0b57cec5SDimitry Andric //
1725*0b57cec5SDimitry Andric // All OutputSections have an address and all InputSections have an offset
1726*0b57cec5SDimitry Andric // within the OutputSection.
1727*0b57cec5SDimitry Andric //
1728*0b57cec5SDimitry Andric // The offsets between caller (relocation place) and callee
1729*0b57cec5SDimitry Andric // (relocation target) will not be modified outside of createThunks().
1730*0b57cec5SDimitry Andric //
1731*0b57cec5SDimitry Andric // PostConditions:
1732*0b57cec5SDimitry Andric // If return value is true then ThunkSections have been inserted into
1733*0b57cec5SDimitry Andric // OutputSections. All relocations that needed a Thunk based on the information
1734*0b57cec5SDimitry Andric // available to createThunks() on entry have been redirected to a Thunk. Note
1735*0b57cec5SDimitry Andric // that adding Thunks changes offsets between caller and callee so more Thunks
1736*0b57cec5SDimitry Andric // may be required.
1737*0b57cec5SDimitry Andric //
1738*0b57cec5SDimitry Andric // If return value is false then no more Thunks are needed, and createThunks has
1739*0b57cec5SDimitry Andric // made no changes. If the target requires range extension thunks, currently
1740*0b57cec5SDimitry Andric // ARM, then any future change in offset between caller and callee risks a
1741*0b57cec5SDimitry Andric // relocation out of range error.
1742*0b57cec5SDimitry Andric bool ThunkCreator::createThunks(ArrayRef<OutputSection *> outputSections) {
1743*0b57cec5SDimitry Andric   bool addressesChanged = false;
1744*0b57cec5SDimitry Andric 
1745*0b57cec5SDimitry Andric   if (pass == 0 && target->getThunkSectionSpacing())
1746*0b57cec5SDimitry Andric     createInitialThunkSections(outputSections);
1747*0b57cec5SDimitry Andric 
1748*0b57cec5SDimitry Andric   // With Thunk Size much smaller than branch range we expect to
1749*0b57cec5SDimitry Andric   // converge quickly; if we get to 10 something has gone wrong.
1750*0b57cec5SDimitry Andric   if (pass == 10)
1751*0b57cec5SDimitry Andric     fatal("thunk creation not converged");
1752*0b57cec5SDimitry Andric 
1753*0b57cec5SDimitry Andric   // Create all the Thunks and insert them into synthetic ThunkSections. The
1754*0b57cec5SDimitry Andric   // ThunkSections are later inserted back into InputSectionDescriptions.
1755*0b57cec5SDimitry Andric   // We separate the creation of ThunkSections from the insertion of the
1756*0b57cec5SDimitry Andric   // ThunkSections as ThunkSections are not always inserted into the same
1757*0b57cec5SDimitry Andric   // InputSectionDescription as the caller.
1758*0b57cec5SDimitry Andric   forEachInputSectionDescription(
1759*0b57cec5SDimitry Andric       outputSections, [&](OutputSection *os, InputSectionDescription *isd) {
1760*0b57cec5SDimitry Andric         for (InputSection *isec : isd->sections)
1761*0b57cec5SDimitry Andric           for (Relocation &rel : isec->relocations) {
1762*0b57cec5SDimitry Andric             uint64_t src = isec->getVA(rel.offset);
1763*0b57cec5SDimitry Andric 
1764*0b57cec5SDimitry Andric             // If we are a relocation to an existing Thunk, check if it is
1765*0b57cec5SDimitry Andric             // still in range. If not then Rel will be altered to point to its
1766*0b57cec5SDimitry Andric             // original target so another Thunk can be generated.
1767*0b57cec5SDimitry Andric             if (pass > 0 && normalizeExistingThunk(rel, src))
1768*0b57cec5SDimitry Andric               continue;
1769*0b57cec5SDimitry Andric 
1770*0b57cec5SDimitry Andric             if (!target->needsThunk(rel.expr, rel.type, isec->file, src,
1771*0b57cec5SDimitry Andric                                     *rel.sym))
1772*0b57cec5SDimitry Andric               continue;
1773*0b57cec5SDimitry Andric 
1774*0b57cec5SDimitry Andric             Thunk *t;
1775*0b57cec5SDimitry Andric             bool isNew;
1776*0b57cec5SDimitry Andric             std::tie(t, isNew) = getThunk(isec, rel, src);
1777*0b57cec5SDimitry Andric 
1778*0b57cec5SDimitry Andric             if (isNew) {
1779*0b57cec5SDimitry Andric               // Find or create a ThunkSection for the new Thunk
1780*0b57cec5SDimitry Andric               ThunkSection *ts;
1781*0b57cec5SDimitry Andric               if (auto *tis = t->getTargetInputSection())
1782*0b57cec5SDimitry Andric                 ts = getISThunkSec(tis);
1783*0b57cec5SDimitry Andric               else
1784*0b57cec5SDimitry Andric                 ts = getISDThunkSec(os, isec, isd, rel.type, src);
1785*0b57cec5SDimitry Andric               ts->addThunk(t);
1786*0b57cec5SDimitry Andric               thunks[t->getThunkTargetSym()] = t;
1787*0b57cec5SDimitry Andric             }
1788*0b57cec5SDimitry Andric 
1789*0b57cec5SDimitry Andric             // Redirect relocation to Thunk, we never go via the PLT to a Thunk
1790*0b57cec5SDimitry Andric             rel.sym = t->getThunkTargetSym();
1791*0b57cec5SDimitry Andric             rel.expr = fromPlt(rel.expr);
1792*0b57cec5SDimitry Andric 
1793*0b57cec5SDimitry Andric             // The addend of R_PPC_PLTREL24 should be ignored after changing to
1794*0b57cec5SDimitry Andric             // R_PC.
1795*0b57cec5SDimitry Andric             if (config->emachine == EM_PPC && rel.type == R_PPC_PLTREL24)
1796*0b57cec5SDimitry Andric               rel.addend = 0;
1797*0b57cec5SDimitry Andric           }
1798*0b57cec5SDimitry Andric 
1799*0b57cec5SDimitry Andric         for (auto &p : isd->thunkSections)
1800*0b57cec5SDimitry Andric           addressesChanged |= p.first->assignOffsets();
1801*0b57cec5SDimitry Andric       });
1802*0b57cec5SDimitry Andric 
1803*0b57cec5SDimitry Andric   for (auto &p : thunkedSections)
1804*0b57cec5SDimitry Andric     addressesChanged |= p.second->assignOffsets();
1805*0b57cec5SDimitry Andric 
1806*0b57cec5SDimitry Andric   // Merge all created synthetic ThunkSections back into OutputSection
1807*0b57cec5SDimitry Andric   mergeThunks(outputSections);
1808*0b57cec5SDimitry Andric   ++pass;
1809*0b57cec5SDimitry Andric   return addressesChanged;
1810*0b57cec5SDimitry Andric }
1811*0b57cec5SDimitry Andric 
1812*0b57cec5SDimitry Andric template void elf::scanRelocations<ELF32LE>(InputSectionBase &);
1813*0b57cec5SDimitry Andric template void elf::scanRelocations<ELF32BE>(InputSectionBase &);
1814*0b57cec5SDimitry Andric template void elf::scanRelocations<ELF64LE>(InputSectionBase &);
1815*0b57cec5SDimitry Andric template void elf::scanRelocations<ELF64BE>(InputSectionBase &);
1816*0b57cec5SDimitry Andric template void elf::reportUndefinedSymbols<ELF32LE>();
1817*0b57cec5SDimitry Andric template void elf::reportUndefinedSymbols<ELF32BE>();
1818*0b57cec5SDimitry Andric template void elf::reportUndefinedSymbols<ELF64LE>();
1819*0b57cec5SDimitry Andric template void elf::reportUndefinedSymbols<ELF64BE>();
1820