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