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