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