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