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