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