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