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