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