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