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/Support/Endian.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include <algorithm>
59 
60 using namespace llvm;
61 using namespace llvm::ELF;
62 using namespace llvm::object;
63 using namespace llvm::support::endian;
64 
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 // Construct a message in the following format.
77 //
78 // >>> defined in /home/alice/src/foo.o
79 // >>> referenced by bar.c:12 (/home/alice/src/bar.c:12)
80 // >>>               /home/alice/src/bar.o:(.text+0x1)
81 static std::string getLocation(InputSectionBase &S, const Symbol &Sym,
82                                uint64_t Off) {
83   std::string Msg = "\n>>> defined in ";
84   if (Sym.File)
85     Msg += toString(Sym.File);
86   else if (Optional<std::string> Loc = getLinkerScriptLocation(Sym))
87     Msg += *Loc;
88 
89   Msg += "\n>>> referenced by ";
90   std::string Src = S.getSrcMsg(Sym, Off);
91   if (!Src.empty())
92     Msg += Src + "\n>>>               ";
93   return Msg + S.getObjMsg(Off);
94 }
95 
96 namespace {
97 // Build a bitmask with one bit set for each RelExpr.
98 //
99 // Constexpr function arguments can't be used in static asserts, so we
100 // use template arguments to build the mask.
101 // But function template partial specializations don't exist (needed
102 // for base case of the recursion), so we need a dummy struct.
103 template <RelExpr... Exprs> struct RelExprMaskBuilder {
104   static inline uint64_t build() { return 0; }
105 };
106 
107 // Specialization for recursive case.
108 template <RelExpr Head, RelExpr... Tail>
109 struct RelExprMaskBuilder<Head, Tail...> {
110   static inline uint64_t build() {
111     static_assert(0 <= Head && Head < 64,
112                   "RelExpr is too large for 64-bit mask!");
113     return (uint64_t(1) << Head) | RelExprMaskBuilder<Tail...>::build();
114   }
115 };
116 } // namespace
117 
118 // Return true if `Expr` is one of `Exprs`.
119 // There are fewer than 64 RelExpr's, so we can represent any set of
120 // RelExpr's as a constant bit mask and test for membership with a
121 // couple cheap bitwise operations.
122 template <RelExpr... Exprs> bool oneof(RelExpr Expr) {
123   assert(0 <= Expr && (int)Expr < 64 &&
124          "RelExpr is too large for 64-bit mask!");
125   return (uint64_t(1) << Expr) & RelExprMaskBuilder<Exprs...>::build();
126 }
127 
128 // This function is similar to the `handleTlsRelocation`. MIPS does not
129 // support any relaxations for TLS relocations so by factoring out MIPS
130 // handling in to the separate function we can simplify the code and do not
131 // pollute other `handleTlsRelocation` by MIPS `ifs` statements.
132 // Mips has a custom MipsGotSection that handles the writing of GOT entries
133 // without dynamic relocations.
134 static unsigned handleMipsTlsRelocation(RelType Type, Symbol &Sym,
135                                         InputSectionBase &C, uint64_t Offset,
136                                         int64_t Addend, RelExpr Expr) {
137   if (Expr == R_MIPS_TLSLD) {
138     In.MipsGot->addTlsIndex(*C.File);
139     C.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
140     return 1;
141   }
142   if (Expr == R_MIPS_TLSGD) {
143     In.MipsGot->addDynTlsEntry(*C.File, Sym);
144     C.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
145     return 1;
146   }
147   return 0;
148 }
149 
150 // This function is similar to the `handleMipsTlsRelocation`. ARM also does not
151 // support any relaxations for TLS relocations. ARM is logically similar to Mips
152 // in how it handles TLS, but Mips uses its own custom GOT which handles some
153 // of the cases that ARM uses GOT relocations for.
154 //
155 // We look for TLS global dynamic and local dynamic relocations, these may
156 // require the generation of a pair of GOT entries that have associated
157 // dynamic relocations. When the results of the dynamic relocations can be
158 // resolved at static link time we do so. This is necessary for static linking
159 // as there will be no dynamic loader to resolve them at load-time.
160 //
161 // The pair of GOT entries created are of the form
162 // GOT[e0] Module Index (Used to find pointer to TLS block at run-time)
163 // GOT[e1] Offset of symbol in TLS block
164 static unsigned handleARMTlsRelocation(RelType Type, Symbol &Sym,
165                                        InputSectionBase &C, uint64_t Offset,
166                                        int64_t Addend, RelExpr Expr) {
167   // The Dynamic TLS Module Index Relocation for a symbol defined in an
168   // executable is always 1. If the target Symbol is not preemptible then
169   // we know the offset into the TLS block at static link time.
170   bool NeedDynId = Sym.IsPreemptible || Config->Shared;
171   bool NeedDynOff = Sym.IsPreemptible;
172 
173   auto AddTlsReloc = [&](uint64_t Off, RelType Type, Symbol *Dest, bool Dyn) {
174     if (Dyn)
175       In.RelaDyn->addReloc(Type, In.Got, Off, Dest);
176     else
177       In.Got->Relocations.push_back({R_ABS, Type, Off, 0, Dest});
178   };
179 
180   // Local Dynamic is for access to module local TLS variables, while still
181   // being suitable for being dynamically loaded via dlopen.
182   // GOT[e0] is the module index, with a special value of 0 for the current
183   // module. GOT[e1] is unused. There only needs to be one module index entry.
184   if (Expr == R_TLSLD_PC && In.Got->addTlsIndex()) {
185     AddTlsReloc(In.Got->getTlsIndexOff(), Target->TlsModuleIndexRel,
186                 NeedDynId ? nullptr : &Sym, NeedDynId);
187     C.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
188     return 1;
189   }
190 
191   // Global Dynamic is the most general purpose access model. When we know
192   // the module index and offset of symbol in TLS block we can fill these in
193   // using static GOT relocations.
194   if (Expr == R_TLSGD_PC) {
195     if (In.Got->addDynTlsEntry(Sym)) {
196       uint64_t Off = In.Got->getGlobalDynOffset(Sym);
197       AddTlsReloc(Off, Target->TlsModuleIndexRel, &Sym, NeedDynId);
198       AddTlsReloc(Off + Config->Wordsize, Target->TlsOffsetRel, &Sym,
199                   NeedDynOff);
200     }
201     C.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
202     return 1;
203   }
204   return 0;
205 }
206 
207 // Returns the number of relocations processed.
208 template <class ELFT>
209 static unsigned
210 handleTlsRelocation(RelType Type, Symbol &Sym, InputSectionBase &C,
211                     typename ELFT::uint Offset, int64_t Addend, RelExpr Expr) {
212   if (!Sym.isTls())
213     return 0;
214 
215   if (Config->EMachine == EM_ARM)
216     return handleARMTlsRelocation(Type, Sym, C, Offset, Addend, Expr);
217   if (Config->EMachine == EM_MIPS)
218     return handleMipsTlsRelocation(Type, Sym, C, Offset, Addend, Expr);
219 
220   if (oneof<R_TLSDESC, R_AARCH64_TLSDESC_PAGE, R_TLSDESC_CALL>(Expr) &&
221       Config->Shared) {
222     if (In.Got->addDynTlsEntry(Sym)) {
223       uint64_t Off = In.Got->getGlobalDynOffset(Sym);
224       In.RelaDyn->addReloc(
225           {Target->TlsDescRel, In.Got, Off, !Sym.IsPreemptible, &Sym, 0});
226     }
227     if (Expr != R_TLSDESC_CALL)
228       C.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
229     return 1;
230   }
231 
232   if (oneof<R_TLSLD_GOT, R_TLSLD_GOTPLT, R_TLSLD_PC, R_TLSLD_HINT>(
233           Expr)) {
234     // Local-Dynamic relocs can be relaxed to Local-Exec.
235     if (!Config->Shared) {
236       C.Relocations.push_back(
237           {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_LD_TO_LE), Type,
238            Offset, Addend, &Sym});
239       return Target->getTlsGdRelaxSkip(Type);
240     }
241     if (Expr == R_TLSLD_HINT)
242       return 1;
243     if (In.Got->addTlsIndex())
244       In.RelaDyn->addReloc(Target->TlsModuleIndexRel, In.Got,
245                            In.Got->getTlsIndexOff(), nullptr);
246     C.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
247     return 1;
248   }
249 
250   // Local-Dynamic relocs can be relaxed to Local-Exec.
251   if (Expr == R_DTPREL && !Config->Shared) {
252     C.Relocations.push_back(
253         {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_LD_TO_LE), Type,
254          Offset, Addend, &Sym});
255     return 1;
256   }
257 
258   // Local-Dynamic sequence where offset of tls variable relative to dynamic
259   // thread pointer is stored in the got.
260   if (Expr == R_TLSLD_GOT_OFF) {
261     // Local-Dynamic relocs can be relaxed to local-exec
262     if (!Config->Shared) {
263       C.Relocations.push_back({R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Sym});
264       return 1;
265     }
266     if (!Sym.isInGot()) {
267       In.Got->addEntry(Sym);
268       uint64_t Off = Sym.getGotOffset();
269       In.Got->Relocations.push_back(
270           {R_ABS, Target->TlsOffsetRel, Off, 0, &Sym});
271     }
272     C.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
273     return 1;
274   }
275 
276   if (oneof<R_TLSDESC, R_AARCH64_TLSDESC_PAGE, R_TLSDESC_CALL, R_TLSGD_GOT,
277             R_TLSGD_GOTPLT, R_TLSGD_PC>(Expr)) {
278     if (Config->Shared) {
279       if (In.Got->addDynTlsEntry(Sym)) {
280         uint64_t Off = In.Got->getGlobalDynOffset(Sym);
281         In.RelaDyn->addReloc(Target->TlsModuleIndexRel, In.Got, Off, &Sym);
282 
283         // If the symbol is preemptible we need the dynamic linker to write
284         // the offset too.
285         uint64_t OffsetOff = Off + Config->Wordsize;
286         if (Sym.IsPreemptible)
287           In.RelaDyn->addReloc(Target->TlsOffsetRel, In.Got, OffsetOff, &Sym);
288         else
289           In.Got->Relocations.push_back(
290               {R_ABS, Target->TlsOffsetRel, OffsetOff, 0, &Sym});
291       }
292       C.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
293       return 1;
294     }
295 
296     // Global-Dynamic relocs can be relaxed to Initial-Exec or Local-Exec
297     // depending on the symbol being locally defined or not.
298     if (Sym.IsPreemptible) {
299       C.Relocations.push_back(
300           {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_IE), Type,
301            Offset, Addend, &Sym});
302       if (!Sym.isInGot()) {
303         In.Got->addEntry(Sym);
304         In.RelaDyn->addReloc(Target->TlsGotRel, In.Got, Sym.getGotOffset(),
305                              &Sym);
306       }
307     } else {
308       C.Relocations.push_back(
309           {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_LE), Type,
310            Offset, Addend, &Sym});
311     }
312     return Target->getTlsGdRelaxSkip(Type);
313   }
314 
315   // Initial-Exec relocs can be relaxed to Local-Exec if the symbol is locally
316   // defined.
317   if (oneof<R_GOT, R_GOTPLT, R_GOT_PC, R_AARCH64_GOT_PAGE_PC, R_GOT_OFF,
318             R_TLSIE_HINT>(Expr) &&
319       !Config->Shared && !Sym.IsPreemptible) {
320     C.Relocations.push_back({R_RELAX_TLS_IE_TO_LE, Type, Offset, Addend, &Sym});
321     return 1;
322   }
323 
324   if (Expr == R_TLSIE_HINT)
325     return 1;
326   return 0;
327 }
328 
329 static RelType getMipsPairType(RelType Type, bool IsLocal) {
330   switch (Type) {
331   case R_MIPS_HI16:
332     return R_MIPS_LO16;
333   case R_MIPS_GOT16:
334     // In case of global symbol, the R_MIPS_GOT16 relocation does not
335     // have a pair. Each global symbol has a unique entry in the GOT
336     // and a corresponding instruction with help of the R_MIPS_GOT16
337     // relocation loads an address of the symbol. In case of local
338     // symbol, the R_MIPS_GOT16 relocation creates a GOT entry to hold
339     // the high 16 bits of the symbol's value. A paired R_MIPS_LO16
340     // relocations handle low 16 bits of the address. That allows
341     // to allocate only one GOT entry for every 64 KBytes of local data.
342     return IsLocal ? R_MIPS_LO16 : R_MIPS_NONE;
343   case R_MICROMIPS_GOT16:
344     return IsLocal ? R_MICROMIPS_LO16 : R_MIPS_NONE;
345   case R_MIPS_PCHI16:
346     return R_MIPS_PCLO16;
347   case R_MICROMIPS_HI16:
348     return R_MICROMIPS_LO16;
349   default:
350     return R_MIPS_NONE;
351   }
352 }
353 
354 // True if non-preemptable symbol always has the same value regardless of where
355 // the DSO is loaded.
356 static bool isAbsolute(const Symbol &Sym) {
357   if (Sym.isUndefWeak())
358     return true;
359   if (const auto *DR = dyn_cast<Defined>(&Sym))
360     return DR->Section == nullptr; // Absolute symbol.
361   return false;
362 }
363 
364 static bool isAbsoluteValue(const Symbol &Sym) {
365   return isAbsolute(Sym) || Sym.isTls();
366 }
367 
368 // Returns true if Expr refers a PLT entry.
369 static bool needsPlt(RelExpr Expr) {
370   return oneof<R_PLT_PC, R_PPC_CALL_PLT, R_PLT>(Expr);
371 }
372 
373 // Returns true if Expr refers a GOT entry. Note that this function
374 // returns false for TLS variables even though they need GOT, because
375 // TLS variables uses GOT differently than the regular variables.
376 static bool needsGot(RelExpr Expr) {
377   return oneof<R_GOT, R_GOT_OFF, R_HEXAGON_GOT, R_MIPS_GOT_LOCAL_PAGE,
378                R_MIPS_GOT_OFF, R_MIPS_GOT_OFF32, R_AARCH64_GOT_PAGE_PC,
379                R_GOT_PC, R_GOTPLT>(Expr);
380 }
381 
382 // True if this expression is of the form Sym - X, where X is a position in the
383 // file (PC, or GOT for example).
384 static bool isRelExpr(RelExpr Expr) {
385   return oneof<R_PC, R_GOTREL, R_GOTPLTREL, R_MIPS_GOTREL, R_PPC_CALL,
386                R_PPC64_RELAX_TOC, R_PPC_CALL_PLT, R_AARCH64_PAGE_PC, R_RELAX_GOT_PC>(Expr);
387 }
388 
389 // Returns true if a given relocation can be computed at link-time.
390 //
391 // For instance, we know the offset from a relocation to its target at
392 // link-time if the relocation is PC-relative and refers a
393 // non-interposable function in the same executable. This function
394 // will return true for such relocation.
395 //
396 // If this function returns false, that means we need to emit a
397 // dynamic relocation so that the relocation will be fixed at load-time.
398 static bool isStaticLinkTimeConstant(RelExpr E, RelType Type, const Symbol &Sym,
399                                      InputSectionBase &S, uint64_t RelOff) {
400   // These expressions always compute a constant
401   if (oneof<R_DTPREL, R_GOTPLT, R_GOT_OFF, R_HEXAGON_GOT, R_TLSLD_GOT_OFF,
402             R_MIPS_GOT_LOCAL_PAGE, R_MIPS_GOTREL, R_MIPS_GOT_OFF,
403             R_MIPS_GOT_OFF32, R_MIPS_GOT_GP_PC, R_MIPS_TLSGD,
404             R_AARCH64_GOT_PAGE_PC, R_GOT_PC, R_GOTONLY_PC, R_GOTPLTONLY_PC,
405             R_PLT_PC, R_TLSGD_GOT, R_TLSGD_GOTPLT, R_TLSGD_PC, R_PPC_CALL_PLT,
406             R_PPC64_RELAX_TOC, R_TLSDESC_CALL, R_AARCH64_TLSDESC_PAGE, R_HINT, R_TLSLD_HINT,
407             R_TLSIE_HINT>(E))
408     return true;
409 
410   // These never do, except if the entire file is position dependent or if
411   // only the low bits are used.
412   if (E == R_GOT || E == R_PLT || E == R_TLSDESC)
413     return Target->usesOnlyLowPageBits(Type) || !Config->Pic;
414 
415   if (Sym.IsPreemptible)
416     return false;
417   if (!Config->Pic)
418     return true;
419 
420   // The size of a non preemptible symbol is a constant.
421   if (E == R_SIZE)
422     return true;
423 
424   // For the target and the relocation, we want to know if they are
425   // absolute or relative.
426   bool AbsVal = isAbsoluteValue(Sym);
427   bool RelE = isRelExpr(E);
428   if (AbsVal && !RelE)
429     return true;
430   if (!AbsVal && RelE)
431     return true;
432   if (!AbsVal && !RelE)
433     return Target->usesOnlyLowPageBits(Type);
434 
435   // Relative relocation to an absolute value. This is normally unrepresentable,
436   // but if the relocation refers to a weak undefined symbol, we allow it to
437   // resolve to the image base. This is a little strange, but it allows us to
438   // link function calls to such symbols. Normally such a call will be guarded
439   // with a comparison, which will load a zero from the GOT.
440   // Another special case is MIPS _gp_disp symbol which represents offset
441   // between start of a function and '_gp' value and defined as absolute just
442   // to simplify the code.
443   assert(AbsVal && RelE);
444   if (Sym.isUndefWeak())
445     return true;
446 
447   // We set the final symbols values for linker script defined symbols later.
448   // They always can be computed as a link time constant.
449   if (Sym.ScriptDefined)
450       return true;
451 
452   error("relocation " + toString(Type) + " cannot refer to absolute symbol: " +
453         toString(Sym) + getLocation(S, Sym, RelOff));
454   return true;
455 }
456 
457 static RelExpr toPlt(RelExpr Expr) {
458   switch (Expr) {
459   case R_PPC_CALL:
460     return R_PPC_CALL_PLT;
461   case R_PC:
462     return R_PLT_PC;
463   case R_ABS:
464     return R_PLT;
465   default:
466     return Expr;
467   }
468 }
469 
470 static RelExpr fromPlt(RelExpr Expr) {
471   // We decided not to use a plt. Optimize a reference to the plt to a
472   // reference to the symbol itself.
473   switch (Expr) {
474   case R_PLT_PC:
475     return R_PC;
476   case R_PPC_CALL_PLT:
477     return R_PPC_CALL;
478   case R_PLT:
479     return R_ABS;
480   default:
481     return Expr;
482   }
483 }
484 
485 // Returns true if a given shared symbol is in a read-only segment in a DSO.
486 template <class ELFT> static bool isReadOnly(SharedSymbol &SS) {
487   using Elf_Phdr = typename ELFT::Phdr;
488 
489   // Determine if the symbol is read-only by scanning the DSO's program headers.
490   const SharedFile &File = SS.getFile();
491   for (const Elf_Phdr &Phdr :
492        check(File.template getObj<ELFT>().program_headers()))
493     if ((Phdr.p_type == ELF::PT_LOAD || Phdr.p_type == ELF::PT_GNU_RELRO) &&
494         !(Phdr.p_flags & ELF::PF_W) && SS.Value >= Phdr.p_vaddr &&
495         SS.Value < Phdr.p_vaddr + Phdr.p_memsz)
496       return true;
497   return false;
498 }
499 
500 // Returns symbols at the same offset as a given symbol, including SS itself.
501 //
502 // If two or more symbols are at the same offset, and at least one of
503 // them are copied by a copy relocation, all of them need to be copied.
504 // Otherwise, they would refer to different places at runtime.
505 template <class ELFT>
506 static SmallSet<SharedSymbol *, 4> getSymbolsAt(SharedSymbol &SS) {
507   using Elf_Sym = typename ELFT::Sym;
508 
509   SharedFile &File = SS.getFile();
510 
511   SmallSet<SharedSymbol *, 4> Ret;
512   for (const Elf_Sym &S : File.template getGlobalELFSyms<ELFT>()) {
513     if (S.st_shndx == SHN_UNDEF || S.st_shndx == SHN_ABS ||
514         S.getType() == STT_TLS || S.st_value != SS.Value)
515       continue;
516     StringRef Name = check(S.getName(File.getStringTable()));
517     Symbol *Sym = Symtab->find(Name);
518     if (auto *Alias = dyn_cast_or_null<SharedSymbol>(Sym))
519       Ret.insert(Alias);
520   }
521   return Ret;
522 }
523 
524 // When a symbol is copy relocated or we create a canonical plt entry, it is
525 // effectively a defined symbol. In the case of copy relocation the symbol is
526 // in .bss and in the case of a canonical plt entry it is in .plt. This function
527 // replaces the existing symbol with a Defined pointing to the appropriate
528 // location.
529 static void replaceWithDefined(Symbol &Sym, SectionBase *Sec, uint64_t Value,
530                                uint64_t Size) {
531   Symbol Old = Sym;
532 
533   Sym.replace(Defined{Sym.File, Sym.getName(), Sym.Binding, Sym.StOther,
534                       Sym.Type, Value, Size, Sec});
535 
536   Sym.PltIndex = Old.PltIndex;
537   Sym.GotIndex = Old.GotIndex;
538   Sym.VerdefIndex = Old.VerdefIndex;
539   Sym.PPC64BranchltIndex = Old.PPC64BranchltIndex;
540   Sym.IsPreemptible = true;
541   Sym.ExportDynamic = true;
542   Sym.IsUsedInRegularObj = true;
543   Sym.Used = true;
544 }
545 
546 // Reserve space in .bss or .bss.rel.ro for copy relocation.
547 //
548 // The copy relocation is pretty much a hack. If you use a copy relocation
549 // in your program, not only the symbol name but the symbol's size, RW/RO
550 // bit and alignment become part of the ABI. In addition to that, if the
551 // symbol has aliases, the aliases become part of the ABI. That's subtle,
552 // but if you violate that implicit ABI, that can cause very counter-
553 // intuitive consequences.
554 //
555 // So, what is the copy relocation? It's for linking non-position
556 // independent code to DSOs. In an ideal world, all references to data
557 // exported by DSOs should go indirectly through GOT. But if object files
558 // are compiled as non-PIC, all data references are direct. There is no
559 // way for the linker to transform the code to use GOT, as machine
560 // instructions are already set in stone in object files. This is where
561 // the copy relocation takes a role.
562 //
563 // A copy relocation instructs the dynamic linker to copy data from a DSO
564 // to a specified address (which is usually in .bss) at load-time. If the
565 // static linker (that's us) finds a direct data reference to a DSO
566 // symbol, it creates a copy relocation, so that the symbol can be
567 // resolved as if it were in .bss rather than in a DSO.
568 //
569 // As you can see in this function, we create a copy relocation for the
570 // dynamic linker, and the relocation contains not only symbol name but
571 // various other informtion about the symbol. So, such attributes become a
572 // part of the ABI.
573 //
574 // Note for application developers: I can give you a piece of advice if
575 // you are writing a shared library. You probably should export only
576 // functions from your library. You shouldn't export variables.
577 //
578 // As an example what can happen when you export variables without knowing
579 // the semantics of copy relocations, assume that you have an exported
580 // variable of type T. It is an ABI-breaking change to add new members at
581 // end of T even though doing that doesn't change the layout of the
582 // existing members. That's because the space for the new members are not
583 // reserved in .bss unless you recompile the main program. That means they
584 // are likely to overlap with other data that happens to be laid out next
585 // to the variable in .bss. This kind of issue is sometimes very hard to
586 // debug. What's a solution? Instead of exporting a varaible V from a DSO,
587 // define an accessor getV().
588 template <class ELFT> static void addCopyRelSymbol(SharedSymbol &SS) {
589   // Copy relocation against zero-sized symbol doesn't make sense.
590   uint64_t SymSize = SS.getSize();
591   if (SymSize == 0 || SS.Alignment == 0)
592     fatal("cannot create a copy relocation for symbol " + toString(SS));
593 
594   // See if this symbol is in a read-only segment. If so, preserve the symbol's
595   // memory protection by reserving space in the .bss.rel.ro section.
596   bool IsReadOnly = isReadOnly<ELFT>(SS);
597   BssSection *Sec = make<BssSection>(IsReadOnly ? ".bss.rel.ro" : ".bss",
598                                      SymSize, SS.Alignment);
599   if (IsReadOnly)
600     In.BssRelRo->getParent()->addSection(Sec);
601   else
602     In.Bss->getParent()->addSection(Sec);
603 
604   // Look through the DSO's dynamic symbol table for aliases and create a
605   // dynamic symbol for each one. This causes the copy relocation to correctly
606   // interpose any aliases.
607   for (SharedSymbol *Sym : getSymbolsAt<ELFT>(SS))
608     replaceWithDefined(*Sym, Sec, 0, Sym->Size);
609 
610   In.RelaDyn->addReloc(Target->CopyRel, Sec, 0, &SS);
611 }
612 
613 // MIPS has an odd notion of "paired" relocations to calculate addends.
614 // For example, if a relocation is of R_MIPS_HI16, there must be a
615 // R_MIPS_LO16 relocation after that, and an addend is calculated using
616 // the two relocations.
617 template <class ELFT, class RelTy>
618 static int64_t computeMipsAddend(const RelTy &Rel, const RelTy *End,
619                                  InputSectionBase &Sec, RelExpr Expr,
620                                  bool IsLocal) {
621   if (Expr == R_MIPS_GOTREL && IsLocal)
622     return Sec.getFile<ELFT>()->MipsGp0;
623 
624   // The ABI says that the paired relocation is used only for REL.
625   // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
626   if (RelTy::IsRela)
627     return 0;
628 
629   RelType Type = Rel.getType(Config->IsMips64EL);
630   uint32_t PairTy = getMipsPairType(Type, IsLocal);
631   if (PairTy == R_MIPS_NONE)
632     return 0;
633 
634   const uint8_t *Buf = Sec.data().data();
635   uint32_t SymIndex = Rel.getSymbol(Config->IsMips64EL);
636 
637   // To make things worse, paired relocations might not be contiguous in
638   // the relocation table, so we need to do linear search. *sigh*
639   for (const RelTy *RI = &Rel; RI != End; ++RI)
640     if (RI->getType(Config->IsMips64EL) == PairTy &&
641         RI->getSymbol(Config->IsMips64EL) == SymIndex)
642       return Target->getImplicitAddend(Buf + RI->r_offset, PairTy);
643 
644   warn("can't find matching " + toString(PairTy) + " relocation for " +
645        toString(Type));
646   return 0;
647 }
648 
649 // Returns an addend of a given relocation. If it is RELA, an addend
650 // is in a relocation itself. If it is REL, we need to read it from an
651 // input section.
652 template <class ELFT, class RelTy>
653 static int64_t computeAddend(const RelTy &Rel, const RelTy *End,
654                              InputSectionBase &Sec, RelExpr Expr,
655                              bool IsLocal) {
656   int64_t Addend;
657   RelType Type = Rel.getType(Config->IsMips64EL);
658 
659   if (RelTy::IsRela) {
660     Addend = getAddend<ELFT>(Rel);
661   } else {
662     const uint8_t *Buf = Sec.data().data();
663     Addend = Target->getImplicitAddend(Buf + Rel.r_offset, Type);
664   }
665 
666   if (Config->EMachine == EM_PPC64 && Config->Pic && Type == R_PPC64_TOC)
667     Addend += getPPC64TocBase();
668   if (Config->EMachine == EM_MIPS)
669     Addend += computeMipsAddend<ELFT>(Rel, End, Sec, Expr, IsLocal);
670 
671   return Addend;
672 }
673 
674 // Custom error message if Sym is defined in a discarded section.
675 template <class ELFT>
676 static std::string maybeReportDiscarded(Undefined &Sym, InputSectionBase &Sec,
677                                         uint64_t Offset) {
678   auto *File = dyn_cast_or_null<ObjFile<ELFT>>(Sym.File);
679   if (!File || !Sym.DiscardedSecIdx ||
680       File->getSections()[Sym.DiscardedSecIdx] != &InputSection::Discarded)
681     return "";
682   ArrayRef<Elf_Shdr_Impl<ELFT>> ObjSections =
683       CHECK(File->getObj().sections(), File);
684   std::string Msg =
685       "relocation refers to a symbol in a discarded section: " + toString(Sym) +
686       "\n>>> defined in " + toString(File);
687 
688   Elf_Shdr_Impl<ELFT> ELFSec = ObjSections[Sym.DiscardedSecIdx - 1];
689   if (ELFSec.sh_type != SHT_GROUP)
690     return Msg;
691 
692   // If the discarded section is a COMDAT.
693   StringRef Signature = File->getShtGroupSignature(ObjSections, ELFSec);
694   if (const InputFile *Prevailing =
695           Symtab->ComdatGroups.lookup(CachedHashStringRef(Signature)))
696     Msg += "\n>>> section group signature: " + Signature.str() +
697            "\n>>> prevailing definition is in " + toString(Prevailing);
698   return Msg;
699 }
700 
701 // Report an undefined symbol if necessary.
702 // Returns true if this function printed out an error message.
703 template <class ELFT>
704 static bool maybeReportUndefined(Symbol &Sym, InputSectionBase &Sec,
705                                  uint64_t Offset) {
706   if (!Sym.isUndefined() || Sym.isWeak())
707     return false;
708 
709   bool CanBeExternal = !Sym.isLocal() && Sym.computeBinding() != STB_LOCAL &&
710                        Sym.Visibility == STV_DEFAULT;
711   if (Config->UnresolvedSymbols == UnresolvedPolicy::Ignore && CanBeExternal)
712     return false;
713 
714   auto Visibility = [&]() -> std::string {
715     switch (Sym.Visibility) {
716     case STV_INTERNAL:
717       return "internal ";
718     case STV_HIDDEN:
719       return "hidden ";
720     case STV_PROTECTED:
721       return "protected ";
722     default:
723       return "";
724     }
725   };
726 
727   std::string Msg =
728       maybeReportDiscarded<ELFT>(cast<Undefined>(Sym), Sec, Offset);
729   if (Msg.empty())
730     Msg = "undefined " + Visibility() + "symbol: " + toString(Sym);
731 
732   Msg += "\n>>> referenced by ";
733   std::string Src = Sec.getSrcMsg(Sym, Offset);
734   if (!Src.empty())
735     Msg += Src + "\n>>>               ";
736   Msg += Sec.getObjMsg(Offset);
737 
738   if (Sym.getName().startswith("_ZTV"))
739     Msg += "\nthe vtable symbol may be undefined because the class is missing "
740            "its key function (see https://lld.llvm.org/missingkeyfunction)";
741 
742   if ((Config->UnresolvedSymbols == UnresolvedPolicy::Warn && CanBeExternal) ||
743       Config->NoinhibitExec) {
744     warn(Msg);
745     return false;
746   }
747 
748   error(Msg);
749   return true;
750 }
751 
752 // MIPS N32 ABI treats series of successive relocations with the same offset
753 // as a single relocation. The similar approach used by N64 ABI, but this ABI
754 // packs all relocations into the single relocation record. Here we emulate
755 // this for the N32 ABI. Iterate over relocation with the same offset and put
756 // theirs types into the single bit-set.
757 template <class RelTy> static RelType getMipsN32RelType(RelTy *&Rel, RelTy *End) {
758   RelType Type = 0;
759   uint64_t Offset = Rel->r_offset;
760 
761   int N = 0;
762   while (Rel != End && Rel->r_offset == Offset)
763     Type |= (Rel++)->getType(Config->IsMips64EL) << (8 * N++);
764   return Type;
765 }
766 
767 // .eh_frame sections are mergeable input sections, so their input
768 // offsets are not linearly mapped to output section. For each input
769 // offset, we need to find a section piece containing the offset and
770 // add the piece's base address to the input offset to compute the
771 // output offset. That isn't cheap.
772 //
773 // This class is to speed up the offset computation. When we process
774 // relocations, we access offsets in the monotonically increasing
775 // order. So we can optimize for that access pattern.
776 //
777 // For sections other than .eh_frame, this class doesn't do anything.
778 namespace {
779 class OffsetGetter {
780 public:
781   explicit OffsetGetter(InputSectionBase &Sec) {
782     if (auto *Eh = dyn_cast<EhInputSection>(&Sec))
783       Pieces = Eh->Pieces;
784   }
785 
786   // Translates offsets in input sections to offsets in output sections.
787   // Given offset must increase monotonically. We assume that Piece is
788   // sorted by InputOff.
789   uint64_t get(uint64_t Off) {
790     if (Pieces.empty())
791       return Off;
792 
793     while (I != Pieces.size() && Pieces[I].InputOff + Pieces[I].Size <= Off)
794       ++I;
795     if (I == Pieces.size())
796       fatal(".eh_frame: relocation is not in any piece");
797 
798     // Pieces must be contiguous, so there must be no holes in between.
799     assert(Pieces[I].InputOff <= Off && "Relocation not in any piece");
800 
801     // Offset -1 means that the piece is dead (i.e. garbage collected).
802     if (Pieces[I].OutputOff == -1)
803       return -1;
804     return Pieces[I].OutputOff + Off - Pieces[I].InputOff;
805   }
806 
807 private:
808   ArrayRef<EhSectionPiece> Pieces;
809   size_t I = 0;
810 };
811 } // namespace
812 
813 static void addRelativeReloc(InputSectionBase *IS, uint64_t OffsetInSec,
814                              Symbol *Sym, int64_t Addend, RelExpr Expr,
815                              RelType Type) {
816   // Add a relative relocation. If RelrDyn section is enabled, and the
817   // relocation offset is guaranteed to be even, add the relocation to
818   // the RelrDyn section, otherwise add it to the RelaDyn section.
819   // RelrDyn sections don't support odd offsets. Also, RelrDyn sections
820   // don't store the addend values, so we must write it to the relocated
821   // address.
822   if (In.RelrDyn && IS->Alignment >= 2 && OffsetInSec % 2 == 0) {
823     IS->Relocations.push_back({Expr, Type, OffsetInSec, Addend, Sym});
824     In.RelrDyn->Relocs.push_back({IS, OffsetInSec});
825     return;
826   }
827   In.RelaDyn->addReloc(Target->RelativeRel, IS, OffsetInSec, Sym, Addend, Expr,
828                        Type);
829 }
830 
831 template <class ELFT, class GotPltSection>
832 static void addPltEntry(PltSection *Plt, GotPltSection *GotPlt,
833                         RelocationBaseSection *Rel, RelType Type, Symbol &Sym) {
834   Plt->addEntry<ELFT>(Sym);
835   GotPlt->addEntry(Sym);
836   Rel->addReloc(
837       {Type, GotPlt, Sym.getGotPltOffset(), !Sym.IsPreemptible, &Sym, 0});
838 }
839 
840 static void addGotEntry(Symbol &Sym) {
841   In.Got->addEntry(Sym);
842 
843   RelExpr Expr = Sym.isTls() ? R_TLS : R_ABS;
844   uint64_t Off = Sym.getGotOffset();
845 
846   // If a GOT slot value can be calculated at link-time, which is now,
847   // we can just fill that out.
848   //
849   // (We don't actually write a value to a GOT slot right now, but we
850   // add a static relocation to a Relocations vector so that
851   // InputSection::relocate will do the work for us. We may be able
852   // to just write a value now, but it is a TODO.)
853   bool IsLinkTimeConstant =
854       !Sym.IsPreemptible && (!Config->Pic || isAbsolute(Sym));
855   if (IsLinkTimeConstant) {
856     In.Got->Relocations.push_back({Expr, Target->GotRel, Off, 0, &Sym});
857     return;
858   }
859 
860   // Otherwise, we emit a dynamic relocation to .rel[a].dyn so that
861   // the GOT slot will be fixed at load-time.
862   if (!Sym.isTls() && !Sym.IsPreemptible && Config->Pic && !isAbsolute(Sym)) {
863     addRelativeReloc(In.Got, Off, &Sym, 0, R_ABS, Target->GotRel);
864     return;
865   }
866   In.RelaDyn->addReloc(Sym.isTls() ? Target->TlsGotRel : Target->GotRel, In.Got,
867                        Off, &Sym, 0, Sym.IsPreemptible ? R_ADDEND : R_ABS,
868                        Target->GotRel);
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 // The reason we have to do this early scan is as follows
892 // * To mmap the output file, we need to know the size
893 // * For that, we need to know how many dynamic relocs we will have.
894 // It might be possible to avoid this by outputting the file with write:
895 // * Write the allocated output sections, computing addresses.
896 // * Apply relocations, recording which ones require a dynamic reloc.
897 // * Write the dynamic relocations.
898 // * Write the rest of the file.
899 // This would have some drawbacks. For example, we would only know if .rela.dyn
900 // is needed after applying relocations. If it is, it will go after rw and rx
901 // sections. Given that it is ro, we will need an extra PT_LOAD. This
902 // complicates things for the dynamic linker and means we would have to reserve
903 // space for the extra PT_LOAD even if we end up not using it.
904 template <class ELFT, class RelTy>
905 static void processRelocAux(InputSectionBase &Sec, RelExpr Expr, RelType Type,
906                             uint64_t Offset, Symbol &Sym, const RelTy &Rel,
907                             int64_t Addend) {
908   if (isStaticLinkTimeConstant(Expr, Type, Sym, Sec, Offset)) {
909     Sec.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
910     return;
911   }
912   bool CanWrite = (Sec.Flags & SHF_WRITE) || !Config->ZText;
913   if (CanWrite) {
914     // R_GOT refers to a position in the got, even if the symbol is preemptible.
915     bool IsPreemptibleValue = Sym.IsPreemptible && Expr != R_GOT;
916 
917     if (!IsPreemptibleValue) {
918       addRelativeReloc(&Sec, Offset, &Sym, Addend, Expr, Type);
919       return;
920     } else if (RelType Rel = Target->getDynRel(Type)) {
921       In.RelaDyn->addReloc(Rel, &Sec, Offset, &Sym, Addend, R_ADDEND, Type);
922 
923       // MIPS ABI turns using of GOT and dynamic relocations inside out.
924       // While regular ABI uses dynamic relocations to fill up GOT entries
925       // MIPS ABI requires dynamic linker to fills up GOT entries using
926       // specially sorted dynamic symbol table. This affects even dynamic
927       // relocations against symbols which do not require GOT entries
928       // creation explicitly, i.e. do not have any GOT-relocations. So if
929       // a preemptible symbol has a dynamic relocation we anyway have
930       // to create a GOT entry for it.
931       // If a non-preemptible symbol has a dynamic relocation against it,
932       // dynamic linker takes it st_value, adds offset and writes down
933       // result of the dynamic relocation. In case of preemptible symbol
934       // dynamic linker performs symbol resolution, writes the symbol value
935       // to the GOT entry and reads the GOT entry when it needs to perform
936       // a dynamic relocation.
937       // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19
938       if (Config->EMachine == EM_MIPS)
939         In.MipsGot->addEntry(*Sec.File, Sym, Addend, Expr);
940       return;
941     }
942   }
943 
944   // If the relocation is to a weak undef, and we are producing
945   // executable, give up on it and produce a non preemptible 0.
946   if (!Config->Shared && Sym.isUndefWeak()) {
947     Sec.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
948     return;
949   }
950 
951   if (!CanWrite && (Config->Pic && !isRelExpr(Expr))) {
952     error(
953         "can't create dynamic relocation " + toString(Type) + " against " +
954         (Sym.getName().empty() ? "local symbol" : "symbol: " + toString(Sym)) +
955         " in readonly segment; recompile object files with -fPIC "
956         "or pass '-Wl,-z,notext' to allow text relocations in the output" +
957         getLocation(Sec, Sym, Offset));
958     return;
959   }
960 
961   // Copy relocations are only possible if we are creating an executable.
962   if (Config->Shared) {
963     errorOrWarn("relocation " + toString(Type) +
964                 " cannot be used against symbol " + toString(Sym) +
965                 "; recompile with -fPIC" + getLocation(Sec, Sym, Offset));
966     return;
967   }
968 
969   // If the symbol is undefined we already reported any relevant errors.
970   if (Sym.isUndefined())
971     return;
972 
973   if (!canDefineSymbolInExecutable(Sym)) {
974     error("cannot preempt symbol: " + toString(Sym) +
975           getLocation(Sec, Sym, Offset));
976     return;
977   }
978 
979   if (Sym.isObject()) {
980     // Produce a copy relocation.
981     if (auto *SS = dyn_cast<SharedSymbol>(&Sym)) {
982       if (!Config->ZCopyreloc)
983         error("unresolvable relocation " + toString(Type) +
984               " against symbol '" + toString(*SS) +
985               "'; recompile with -fPIC or remove '-z nocopyreloc'" +
986               getLocation(Sec, Sym, Offset));
987       addCopyRelSymbol<ELFT>(*SS);
988     }
989     Sec.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
990     return;
991   }
992 
993   if (Sym.isFunc()) {
994     // This handles a non PIC program call to function in a shared library. In
995     // an ideal world, we could just report an error saying the relocation can
996     // overflow at runtime. In the real world with glibc, crt1.o has a
997     // R_X86_64_PC32 pointing to libc.so.
998     //
999     // The general idea on how to handle such cases is to create a PLT entry and
1000     // use that as the function value.
1001     //
1002     // For the static linking part, we just return a plt expr and everything
1003     // else will use the PLT entry as the address.
1004     //
1005     // The remaining problem is making sure pointer equality still works. We
1006     // need the help of the dynamic linker for that. We let it know that we have
1007     // a direct reference to a so symbol by creating an undefined symbol with a
1008     // non zero st_value. Seeing that, the dynamic linker resolves the symbol to
1009     // the value of the symbol we created. This is true even for got entries, so
1010     // pointer equality is maintained. To avoid an infinite loop, the only entry
1011     // that points to the real function is a dedicated got entry used by the
1012     // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT,
1013     // R_386_JMP_SLOT, etc).
1014 
1015     // For position independent executable on i386, the plt entry requires ebx
1016     // to be set. This causes two problems:
1017     // * If some code has a direct reference to a function, it was probably
1018     //   compiled without -fPIE/-fPIC and doesn't maintain ebx.
1019     // * If a library definition gets preempted to the executable, it will have
1020     //   the wrong ebx value.
1021     if (Config->Pie && Config->EMachine == EM_386)
1022       errorOrWarn("symbol '" + toString(Sym) +
1023                   "' cannot be preempted; recompile with -fPIE" +
1024                   getLocation(Sec, Sym, Offset));
1025     if (!Sym.isInPlt())
1026       addPltEntry<ELFT>(In.Plt, In.GotPlt, In.RelaPlt, Target->PltRel, Sym);
1027     if (!Sym.isDefined())
1028       replaceWithDefined(
1029           Sym, In.Plt,
1030           Target->PltHeaderSize + Target->PltEntrySize * Sym.PltIndex, 0);
1031     Sym.NeedsPltAddr = true;
1032     Sec.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
1033     return;
1034   }
1035 
1036   errorOrWarn("symbol '" + toString(Sym) + "' has no type" +
1037               getLocation(Sec, Sym, Offset));
1038 }
1039 
1040 struct IRelativeReloc {
1041   RelType Type;
1042   InputSectionBase *Sec;
1043   uint64_t Offset;
1044   Symbol *Sym;
1045 };
1046 
1047 static std::vector<IRelativeReloc> IRelativeRelocs;
1048 
1049 template <class ELFT, class RelTy>
1050 static void scanReloc(InputSectionBase &Sec, OffsetGetter &GetOffset, RelTy *&I,
1051                       RelTy *End) {
1052   const RelTy &Rel = *I;
1053   uint32_t SymIndex = Rel.getSymbol(Config->IsMips64EL);
1054   Symbol &Sym = Sec.getFile<ELFT>()->getSymbol(SymIndex);
1055   RelType Type;
1056 
1057   // Deal with MIPS oddity.
1058   if (Config->MipsN32Abi) {
1059     Type = getMipsN32RelType(I, End);
1060   } else {
1061     Type = Rel.getType(Config->IsMips64EL);
1062     ++I;
1063   }
1064 
1065   // Get an offset in an output section this relocation is applied to.
1066   uint64_t Offset = GetOffset.get(Rel.r_offset);
1067   if (Offset == uint64_t(-1))
1068     return;
1069 
1070   // Error if the target symbol is undefined. Symbol index 0 may be used by
1071   // marker relocations, e.g. R_*_NONE and R_ARM_V4BX. Don't error on them.
1072   if (SymIndex != 0 && maybeReportUndefined<ELFT>(Sym, Sec, Rel.r_offset))
1073     return;
1074 
1075   const uint8_t *RelocatedAddr = Sec.data().begin() + Rel.r_offset;
1076   RelExpr Expr = Target->getRelExpr(Type, Sym, RelocatedAddr);
1077 
1078   // Ignore "hint" relocations because they are only markers for relaxation.
1079   if (oneof<R_HINT, R_NONE>(Expr))
1080     return;
1081 
1082   // We can separate the small code model relocations into 2 categories:
1083   // 1) Those that access the compiler generated .toc sections.
1084   // 2) Those that access the linker allocated got entries.
1085   // lld allocates got entries to symbols on demand. Since we don't try to sort
1086   // the got entries in any way, we don't have to track which objects have
1087   // got-based small code model relocs. The .toc sections get placed after the
1088   // end of the linker allocated .got section and we do sort those so sections
1089   // addressed with small code model relocations come first.
1090   if (Config->EMachine == EM_PPC64 && isPPC64SmallCodeModelTocReloc(Type))
1091     Sec.File->PPC64SmallCodeModelTocRelocs = true;
1092 
1093   if (Sym.isGnuIFunc() && !Config->ZText && Config->WarnIfuncTextrel) {
1094     warn("using ifunc symbols when text relocations are allowed may produce "
1095          "a binary that will segfault, if the object file is linked with "
1096          "old version of glibc (glibc 2.28 and earlier). If this applies to "
1097          "you, consider recompiling the object files without -fPIC and "
1098          "without -Wl,-z,notext option. Use -no-warn-ifunc-textrel to "
1099          "turn off this warning." +
1100          getLocation(Sec, Sym, Offset));
1101   }
1102 
1103   // Relax relocations.
1104   //
1105   // If we know that a PLT entry will be resolved within the same ELF module, we
1106   // can skip PLT access and directly jump to the destination function. For
1107   // example, if we are linking a main exectuable, all dynamic symbols that can
1108   // be resolved within the executable will actually be resolved that way at
1109   // runtime, because the main exectuable is always at the beginning of a search
1110   // list. We can leverage that fact.
1111   if (!Sym.IsPreemptible && (!Sym.isGnuIFunc() || Config->ZIfuncNoplt)) {
1112     if (Expr == R_GOT_PC && !isAbsoluteValue(Sym))
1113       Expr = Target->adjustRelaxExpr(Type, RelocatedAddr, Expr);
1114     else
1115       Expr = fromPlt(Expr);
1116   }
1117 
1118   // If the relocation does not emit a GOT or GOTPLT entry but its computation
1119   // uses their addresses, we need GOT or GOTPLT to be created.
1120   //
1121   // The 4 types that relative GOTPLT are all x86 and x86-64 specific.
1122   if (oneof<R_GOTPLTONLY_PC, R_GOTPLTREL, R_GOTPLT, R_TLSGD_GOTPLT>(Expr)) {
1123     In.GotPlt->HasGotPltOffRel = true;
1124   } else if (oneof<R_GOTONLY_PC, R_GOTREL, R_PPC_TOC, R_PPC64_RELAX_TOC>(Expr)) {
1125     In.Got->HasGotOffRel = true;
1126   }
1127 
1128   // Read an addend.
1129   int64_t Addend = computeAddend<ELFT>(Rel, End, Sec, Expr, Sym.isLocal());
1130 
1131   // Process some TLS relocations, including relaxing TLS relocations.
1132   // Note that this function does not handle all TLS relocations.
1133   if (unsigned Processed =
1134           handleTlsRelocation<ELFT>(Type, Sym, Sec, Offset, Addend, Expr)) {
1135     I += (Processed - 1);
1136     return;
1137   }
1138 
1139   // We were asked not to generate PLT entries for ifuncs. Instead, pass the
1140   // direct relocation on through.
1141   if (Sym.isGnuIFunc() && Config->ZIfuncNoplt) {
1142     Sym.ExportDynamic = true;
1143     In.RelaDyn->addReloc(Type, &Sec, Offset, &Sym, Addend, R_ADDEND, Type);
1144     return;
1145   }
1146 
1147   // Non-preemptible ifuncs require special handling. First, handle the usual
1148   // case where the symbol isn't one of these.
1149   if (!Sym.isGnuIFunc() || Sym.IsPreemptible) {
1150     // If a relocation needs PLT, we create PLT and GOTPLT slots for the symbol.
1151     if (needsPlt(Expr) && !Sym.isInPlt())
1152       addPltEntry<ELFT>(In.Plt, In.GotPlt, In.RelaPlt, Target->PltRel, Sym);
1153 
1154     // Create a GOT slot if a relocation needs GOT.
1155     if (needsGot(Expr)) {
1156       if (Config->EMachine == EM_MIPS) {
1157         // MIPS ABI has special rules to process GOT entries and doesn't
1158         // require relocation entries for them. A special case is TLS
1159         // relocations. In that case dynamic loader applies dynamic
1160         // relocations to initialize TLS GOT entries.
1161         // See "Global Offset Table" in Chapter 5 in the following document
1162         // for detailed description:
1163         // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1164         In.MipsGot->addEntry(*Sec.File, Sym, Addend, Expr);
1165       } else if (!Sym.isInGot()) {
1166         addGotEntry(Sym);
1167       }
1168     }
1169   } else {
1170     // Handle a reference to a non-preemptible ifunc. These are special in a
1171     // few ways:
1172     //
1173     // - Unlike most non-preemptible symbols, non-preemptible ifuncs do not have
1174     //   a fixed value. But assuming that all references to the ifunc are
1175     //   GOT-generating or PLT-generating, the handling of an ifunc is
1176     //   relatively straightforward. We create a PLT entry in Iplt, which is
1177     //   usually at the end of .plt, which makes an indirect call using a
1178     //   matching GOT entry in IgotPlt, which is usually at the end of .got.plt.
1179     //   The GOT entry is relocated using an IRELATIVE relocation in RelaIplt,
1180     //   which is usually at the end of .rela.plt. Unlike most relocations in
1181     //   .rela.plt, which may be evaluated lazily without -z now, dynamic
1182     //   loaders evaluate IRELATIVE relocs eagerly, which means that for
1183     //   IRELATIVE relocs only, GOT-generating relocations can point directly to
1184     //   .got.plt without requiring a separate GOT entry.
1185     //
1186     // - Despite the fact that an ifunc does not have a fixed value, compilers
1187     //   that are not passed -fPIC will assume that they do, and will emit
1188     //   direct (non-GOT-generating, non-PLT-generating) relocations to the
1189     //   symbol. This means that if a direct relocation to the symbol is
1190     //   seen, the linker must set a value for the symbol, and this value must
1191     //   be consistent no matter what type of reference is made to the symbol.
1192     //   This can be done by creating a PLT entry for the symbol in the way
1193     //   described above and making it canonical, that is, making all references
1194     //   point to the PLT entry instead of the resolver. In lld we also store
1195     //   the address of the PLT entry in the dynamic symbol table, which means
1196     //   that the symbol will also have the same value in other modules.
1197     //   Because the value loaded from the GOT needs to be consistent with
1198     //   the value computed using a direct relocation, a non-preemptible ifunc
1199     //   may end up with two GOT entries, one in .got.plt that points to the
1200     //   address returned by the resolver and is used only by the PLT entry,
1201     //   and another in .got that points to the PLT entry and is used by
1202     //   GOT-generating relocations.
1203     //
1204     // - The fact that these symbols do not have a fixed value makes them an
1205     //   exception to the general rule that a statically linked executable does
1206     //   not require any form of dynamic relocation. To handle these relocations
1207     //   correctly, the IRELATIVE relocations are stored in an array which a
1208     //   statically linked executable's startup code must enumerate using the
1209     //   linker-defined symbols __rela?_iplt_{start,end}.
1210     //
1211     // - An absolute relocation to a non-preemptible ifunc (such as a global
1212     //   variable containing a pointer to the ifunc) needs to be relocated in
1213     //   the exact same way as a GOT entry, so we can avoid needing to make the
1214     //   PLT entry canonical by translating such relocations into IRELATIVE
1215     //   relocations in the RelaIplt.
1216     if (!Sym.isInPlt()) {
1217       // Create PLT and GOTPLT slots for the symbol.
1218       Sym.IsInIplt = true;
1219 
1220       // Create a copy of the symbol to use as the target of the IRELATIVE
1221       // relocation in the IgotPlt. This is in case we make the PLT canonical
1222       // later, which would overwrite the original symbol.
1223       //
1224       // FIXME: Creating a copy of the symbol here is a bit of a hack. All
1225       // that's really needed to create the IRELATIVE is the section and value,
1226       // so ideally we should just need to copy those.
1227       auto *DirectSym = make<Defined>(cast<Defined>(Sym));
1228       addPltEntry<ELFT>(In.Iplt, In.IgotPlt, In.RelaIplt, Target->IRelativeRel,
1229                         *DirectSym);
1230       Sym.PltIndex = DirectSym->PltIndex;
1231     }
1232     if (Expr == R_ABS && Addend == 0 && (Sec.Flags & SHF_WRITE)) {
1233       // We might be able to represent this as an IRELATIVE. But we don't know
1234       // yet whether some later relocation will make the symbol point to a
1235       // canonical PLT, which would make this either a dynamic RELATIVE (PIC) or
1236       // static (non-PIC) relocation. So we keep a record of the information
1237       // required to process the relocation, and after scanRelocs() has been
1238       // called on all relocations, the relocation is resolved by
1239       // addIRelativeRelocs().
1240       IRelativeRelocs.push_back({Type, &Sec, Offset, &Sym});
1241       return;
1242     }
1243     if (needsGot(Expr)) {
1244       // Redirect GOT accesses to point to the Igot.
1245       //
1246       // This field is also used to keep track of whether we ever needed a GOT
1247       // entry. If we did and we make the PLT canonical later, we'll need to
1248       // create a GOT entry pointing to the PLT entry for Sym.
1249       Sym.GotInIgot = true;
1250     } else if (!needsPlt(Expr)) {
1251       // Make the ifunc's PLT entry canonical by changing the value of its
1252       // symbol to redirect all references to point to it.
1253       unsigned EntryOffset = Sym.PltIndex * Target->PltEntrySize;
1254       if (Config->ZRetpolineplt)
1255         EntryOffset += Target->PltHeaderSize;
1256 
1257       auto &D = cast<Defined>(Sym);
1258       D.Section = In.Iplt;
1259       D.Value = EntryOffset;
1260       D.Size = 0;
1261       // It's important to set the symbol type here so that dynamic loaders
1262       // don't try to call the PLT as if it were an ifunc resolver.
1263       D.Type = STT_FUNC;
1264 
1265       if (Sym.GotInIgot) {
1266         // We previously encountered a GOT generating reference that we
1267         // redirected to the Igot. Now that the PLT entry is canonical we must
1268         // clear the redirection to the Igot and add a GOT entry. As we've
1269         // changed the symbol type to STT_FUNC future GOT generating references
1270         // will naturally use this GOT entry.
1271         //
1272         // We don't need to worry about creating a MIPS GOT here because ifuncs
1273         // aren't a thing on MIPS.
1274         Sym.GotInIgot = false;
1275         addGotEntry(Sym);
1276       }
1277     }
1278   }
1279 
1280   processRelocAux<ELFT>(Sec, Expr, Type, Offset, Sym, Rel, Addend);
1281 }
1282 
1283 template <class ELFT, class RelTy>
1284 static void scanRelocs(InputSectionBase &Sec, ArrayRef<RelTy> Rels) {
1285   OffsetGetter GetOffset(Sec);
1286 
1287   // Not all relocations end up in Sec.Relocations, but a lot do.
1288   Sec.Relocations.reserve(Rels.size());
1289 
1290   for (auto I = Rels.begin(), End = Rels.end(); I != End;)
1291     scanReloc<ELFT>(Sec, GetOffset, I, End);
1292 
1293   // Sort relocations by offset for more efficient searching for
1294   // R_RISCV_PCREL_HI20 and R_PPC64_ADDR64.
1295   if (Config->EMachine == EM_RISCV ||
1296       (Config->EMachine == EM_PPC64 && Sec.Name == ".toc"))
1297     llvm::stable_sort(Sec.Relocations,
1298                       [](const Relocation &LHS, const Relocation &RHS) {
1299                         return LHS.Offset < RHS.Offset;
1300                       });
1301 }
1302 
1303 template <class ELFT> void elf::scanRelocations(InputSectionBase &S) {
1304   if (S.AreRelocsRela)
1305     scanRelocs<ELFT>(S, S.relas<ELFT>());
1306   else
1307     scanRelocs<ELFT>(S, S.rels<ELFT>());
1308 }
1309 
1310 // Figure out which representation to use for any absolute relocs to
1311 // non-preemptible ifuncs that we visited during scanRelocs().
1312 void elf::addIRelativeRelocs() {
1313   for (IRelativeReloc &R : IRelativeRelocs) {
1314     if (R.Sym->Type == STT_GNU_IFUNC)
1315       In.RelaIplt->addReloc(
1316           {Target->IRelativeRel, R.Sec, R.Offset, true, R.Sym, 0});
1317     else if (Config->Pic)
1318       addRelativeReloc(R.Sec, R.Offset, R.Sym, 0, R_ABS, R.Type);
1319     else
1320       R.Sec->Relocations.push_back({R_ABS, R.Type, R.Offset, 0, R.Sym});
1321   }
1322   IRelativeRelocs.clear();
1323 }
1324 
1325 static bool mergeCmp(const InputSection *A, const InputSection *B) {
1326   // std::merge requires a strict weak ordering.
1327   if (A->OutSecOff < B->OutSecOff)
1328     return true;
1329 
1330   if (A->OutSecOff == B->OutSecOff) {
1331     auto *TA = dyn_cast<ThunkSection>(A);
1332     auto *TB = dyn_cast<ThunkSection>(B);
1333 
1334     // Check if Thunk is immediately before any specific Target
1335     // InputSection for example Mips LA25 Thunks.
1336     if (TA && TA->getTargetInputSection() == B)
1337       return true;
1338 
1339     // Place Thunk Sections without specific targets before
1340     // non-Thunk Sections.
1341     if (TA && !TB && !TA->getTargetInputSection())
1342       return true;
1343   }
1344 
1345   return false;
1346 }
1347 
1348 // Call Fn on every executable InputSection accessed via the linker script
1349 // InputSectionDescription::Sections.
1350 static void forEachInputSectionDescription(
1351     ArrayRef<OutputSection *> OutputSections,
1352     llvm::function_ref<void(OutputSection *, InputSectionDescription *)> Fn) {
1353   for (OutputSection *OS : OutputSections) {
1354     if (!(OS->Flags & SHF_ALLOC) || !(OS->Flags & SHF_EXECINSTR))
1355       continue;
1356     for (BaseCommand *BC : OS->SectionCommands)
1357       if (auto *ISD = dyn_cast<InputSectionDescription>(BC))
1358         Fn(OS, ISD);
1359   }
1360 }
1361 
1362 // Thunk Implementation
1363 //
1364 // Thunks (sometimes called stubs, veneers or branch islands) are small pieces
1365 // of code that the linker inserts inbetween a caller and a callee. The thunks
1366 // are added at link time rather than compile time as the decision on whether
1367 // a thunk is needed, such as the caller and callee being out of range, can only
1368 // be made at link time.
1369 //
1370 // It is straightforward to tell given the current state of the program when a
1371 // thunk is needed for a particular call. The more difficult part is that
1372 // the thunk needs to be placed in the program such that the caller can reach
1373 // the thunk and the thunk can reach the callee; furthermore, adding thunks to
1374 // the program alters addresses, which can mean more thunks etc.
1375 //
1376 // In lld we have a synthetic ThunkSection that can hold many Thunks.
1377 // The decision to have a ThunkSection act as a container means that we can
1378 // more easily handle the most common case of a single block of contiguous
1379 // Thunks by inserting just a single ThunkSection.
1380 //
1381 // The implementation of Thunks in lld is split across these areas
1382 // Relocations.cpp : Framework for creating and placing thunks
1383 // Thunks.cpp : The code generated for each supported thunk
1384 // Target.cpp : Target specific hooks that the framework uses to decide when
1385 //              a thunk is used
1386 // Synthetic.cpp : Implementation of ThunkSection
1387 // Writer.cpp : Iteratively call framework until no more Thunks added
1388 //
1389 // Thunk placement requirements:
1390 // Mips LA25 thunks. These must be placed immediately before the callee section
1391 // We can assume that the caller is in range of the Thunk. These are modelled
1392 // by Thunks that return the section they must precede with
1393 // getTargetInputSection().
1394 //
1395 // ARM interworking and range extension thunks. These thunks must be placed
1396 // within range of the caller. All implemented ARM thunks can always reach the
1397 // callee as they use an indirect jump via a register that has no range
1398 // restrictions.
1399 //
1400 // Thunk placement algorithm:
1401 // For Mips LA25 ThunkSections; the placement is explicit, it has to be before
1402 // getTargetInputSection().
1403 //
1404 // For thunks that must be placed within range of the caller there are many
1405 // possible choices given that the maximum range from the caller is usually
1406 // much larger than the average InputSection size. Desirable properties include:
1407 // - Maximize reuse of thunks by multiple callers
1408 // - Minimize number of ThunkSections to simplify insertion
1409 // - Handle impact of already added Thunks on addresses
1410 // - Simple to understand and implement
1411 //
1412 // In lld for the first pass, we pre-create one or more ThunkSections per
1413 // InputSectionDescription at Target specific intervals. A ThunkSection is
1414 // placed so that the estimated end of the ThunkSection is within range of the
1415 // start of the InputSectionDescription or the previous ThunkSection. For
1416 // example:
1417 // InputSectionDescription
1418 // Section 0
1419 // ...
1420 // Section N
1421 // ThunkSection 0
1422 // Section N + 1
1423 // ...
1424 // Section N + K
1425 // Thunk Section 1
1426 //
1427 // The intention is that we can add a Thunk to a ThunkSection that is well
1428 // spaced enough to service a number of callers without having to do a lot
1429 // of work. An important principle is that it is not an error if a Thunk cannot
1430 // be placed in a pre-created ThunkSection; when this happens we create a new
1431 // ThunkSection placed next to the caller. This allows us to handle the vast
1432 // majority of thunks simply, but also handle rare cases where the branch range
1433 // is smaller than the target specific spacing.
1434 //
1435 // The algorithm is expected to create all the thunks that are needed in a
1436 // single pass, with a small number of programs needing a second pass due to
1437 // the insertion of thunks in the first pass increasing the offset between
1438 // callers and callees that were only just in range.
1439 //
1440 // A consequence of allowing new ThunkSections to be created outside of the
1441 // pre-created ThunkSections is that in rare cases calls to Thunks that were in
1442 // range in pass K, are out of range in some pass > K due to the insertion of
1443 // more Thunks in between the caller and callee. When this happens we retarget
1444 // the relocation back to the original target and create another Thunk.
1445 
1446 // Remove ThunkSections that are empty, this should only be the initial set
1447 // precreated on pass 0.
1448 
1449 // Insert the Thunks for OutputSection OS into their designated place
1450 // in the Sections vector, and recalculate the InputSection output section
1451 // offsets.
1452 // This may invalidate any output section offsets stored outside of InputSection
1453 void ThunkCreator::mergeThunks(ArrayRef<OutputSection *> OutputSections) {
1454   forEachInputSectionDescription(
1455       OutputSections, [&](OutputSection *OS, InputSectionDescription *ISD) {
1456         if (ISD->ThunkSections.empty())
1457           return;
1458 
1459         // Remove any zero sized precreated Thunks.
1460         llvm::erase_if(ISD->ThunkSections,
1461                        [](const std::pair<ThunkSection *, uint32_t> &TS) {
1462                          return TS.first->getSize() == 0;
1463                        });
1464 
1465         // ISD->ThunkSections contains all created ThunkSections, including
1466         // those inserted in previous passes. Extract the Thunks created this
1467         // pass and order them in ascending OutSecOff.
1468         std::vector<ThunkSection *> NewThunks;
1469         for (const std::pair<ThunkSection *, uint32_t> TS : ISD->ThunkSections)
1470           if (TS.second == Pass)
1471             NewThunks.push_back(TS.first);
1472         llvm::stable_sort(NewThunks,
1473                           [](const ThunkSection *A, const ThunkSection *B) {
1474                             return A->OutSecOff < B->OutSecOff;
1475                           });
1476 
1477         // Merge sorted vectors of Thunks and InputSections by OutSecOff
1478         std::vector<InputSection *> Tmp;
1479         Tmp.reserve(ISD->Sections.size() + NewThunks.size());
1480 
1481         std::merge(ISD->Sections.begin(), ISD->Sections.end(),
1482                    NewThunks.begin(), NewThunks.end(), std::back_inserter(Tmp),
1483                    mergeCmp);
1484 
1485         ISD->Sections = std::move(Tmp);
1486       });
1487 }
1488 
1489 // Find or create a ThunkSection within the InputSectionDescription (ISD) that
1490 // is in range of Src. An ISD maps to a range of InputSections described by a
1491 // linker script section pattern such as { .text .text.* }.
1492 ThunkSection *ThunkCreator::getISDThunkSec(OutputSection *OS, InputSection *IS,
1493                                            InputSectionDescription *ISD,
1494                                            uint32_t Type, uint64_t Src) {
1495   for (std::pair<ThunkSection *, uint32_t> TP : ISD->ThunkSections) {
1496     ThunkSection *TS = TP.first;
1497     uint64_t TSBase = OS->Addr + TS->OutSecOff;
1498     uint64_t TSLimit = TSBase + TS->getSize();
1499     if (Target->inBranchRange(Type, Src, (Src > TSLimit) ? TSBase : TSLimit))
1500       return TS;
1501   }
1502 
1503   // No suitable ThunkSection exists. This can happen when there is a branch
1504   // with lower range than the ThunkSection spacing or when there are too
1505   // many Thunks. Create a new ThunkSection as close to the InputSection as
1506   // possible. Error if InputSection is so large we cannot place ThunkSection
1507   // anywhere in Range.
1508   uint64_t ThunkSecOff = IS->OutSecOff;
1509   if (!Target->inBranchRange(Type, Src, OS->Addr + ThunkSecOff)) {
1510     ThunkSecOff = IS->OutSecOff + IS->getSize();
1511     if (!Target->inBranchRange(Type, Src, OS->Addr + ThunkSecOff))
1512       fatal("InputSection too large for range extension thunk " +
1513             IS->getObjMsg(Src - (OS->Addr + IS->OutSecOff)));
1514   }
1515   return addThunkSection(OS, ISD, ThunkSecOff);
1516 }
1517 
1518 // Add a Thunk that needs to be placed in a ThunkSection that immediately
1519 // precedes its Target.
1520 ThunkSection *ThunkCreator::getISThunkSec(InputSection *IS) {
1521   ThunkSection *TS = ThunkedSections.lookup(IS);
1522   if (TS)
1523     return TS;
1524 
1525   // Find InputSectionRange within Target Output Section (TOS) that the
1526   // InputSection (IS) that we need to precede is in.
1527   OutputSection *TOS = IS->getParent();
1528   for (BaseCommand *BC : TOS->SectionCommands) {
1529     auto *ISD = dyn_cast<InputSectionDescription>(BC);
1530     if (!ISD || ISD->Sections.empty())
1531       continue;
1532 
1533     InputSection *First = ISD->Sections.front();
1534     InputSection *Last = ISD->Sections.back();
1535 
1536     if (IS->OutSecOff < First->OutSecOff || Last->OutSecOff < IS->OutSecOff)
1537       continue;
1538 
1539     TS = addThunkSection(TOS, ISD, IS->OutSecOff);
1540     ThunkedSections[IS] = TS;
1541     return TS;
1542   }
1543 
1544   return nullptr;
1545 }
1546 
1547 // Create one or more ThunkSections per OS that can be used to place Thunks.
1548 // We attempt to place the ThunkSections using the following desirable
1549 // properties:
1550 // - Within range of the maximum number of callers
1551 // - Minimise the number of ThunkSections
1552 //
1553 // We follow a simple but conservative heuristic to place ThunkSections at
1554 // offsets that are multiples of a Target specific branch range.
1555 // For an InputSectionDescription that is smaller than the range, a single
1556 // ThunkSection at the end of the range will do.
1557 //
1558 // For an InputSectionDescription that is more than twice the size of the range,
1559 // we place the last ThunkSection at range bytes from the end of the
1560 // InputSectionDescription in order to increase the likelihood that the
1561 // distance from a thunk to its target will be sufficiently small to
1562 // allow for the creation of a short thunk.
1563 void ThunkCreator::createInitialThunkSections(
1564     ArrayRef<OutputSection *> OutputSections) {
1565   uint32_t ThunkSectionSpacing = Target->getThunkSectionSpacing();
1566 
1567   forEachInputSectionDescription(
1568       OutputSections, [&](OutputSection *OS, InputSectionDescription *ISD) {
1569         if (ISD->Sections.empty())
1570           return;
1571 
1572         uint32_t ISDBegin = ISD->Sections.front()->OutSecOff;
1573         uint32_t ISDEnd =
1574             ISD->Sections.back()->OutSecOff + ISD->Sections.back()->getSize();
1575         uint32_t LastThunkLowerBound = -1;
1576         if (ISDEnd - ISDBegin > ThunkSectionSpacing * 2)
1577           LastThunkLowerBound = ISDEnd - ThunkSectionSpacing;
1578 
1579         uint32_t ISLimit;
1580         uint32_t PrevISLimit = ISDBegin;
1581         uint32_t ThunkUpperBound = ISDBegin + ThunkSectionSpacing;
1582 
1583         for (const InputSection *IS : ISD->Sections) {
1584           ISLimit = IS->OutSecOff + IS->getSize();
1585           if (ISLimit > ThunkUpperBound) {
1586             addThunkSection(OS, ISD, PrevISLimit);
1587             ThunkUpperBound = PrevISLimit + ThunkSectionSpacing;
1588           }
1589           if (ISLimit > LastThunkLowerBound)
1590             break;
1591           PrevISLimit = ISLimit;
1592         }
1593         addThunkSection(OS, ISD, ISLimit);
1594       });
1595 }
1596 
1597 ThunkSection *ThunkCreator::addThunkSection(OutputSection *OS,
1598                                             InputSectionDescription *ISD,
1599                                             uint64_t Off) {
1600   auto *TS = make<ThunkSection>(OS, Off);
1601   ISD->ThunkSections.push_back({TS, Pass});
1602   return TS;
1603 }
1604 
1605 std::pair<Thunk *, bool> ThunkCreator::getThunk(Symbol &Sym, RelType Type,
1606                                                 uint64_t Src) {
1607   std::vector<Thunk *> *ThunkVec = nullptr;
1608 
1609   // We use (section, offset) pair to find the thunk position if possible so
1610   // that we create only one thunk for aliased symbols or ICFed sections.
1611   if (auto *D = dyn_cast<Defined>(&Sym))
1612     if (!D->isInPlt() && D->Section)
1613       ThunkVec = &ThunkedSymbolsBySection[{D->Section->Repl, D->Value}];
1614   if (!ThunkVec)
1615     ThunkVec = &ThunkedSymbols[&Sym];
1616 
1617   // Check existing Thunks for Sym to see if they can be reused
1618   for (Thunk *T : *ThunkVec)
1619     if (T->isCompatibleWith(Type) &&
1620         Target->inBranchRange(Type, Src, T->getThunkTargetSym()->getVA()))
1621       return std::make_pair(T, false);
1622 
1623   // No existing compatible Thunk in range, create a new one
1624   Thunk *T = addThunk(Type, Sym);
1625   ThunkVec->push_back(T);
1626   return std::make_pair(T, true);
1627 }
1628 
1629 // Return true if the relocation target is an in range Thunk.
1630 // Return false if the relocation is not to a Thunk. If the relocation target
1631 // was originally to a Thunk, but is no longer in range we revert the
1632 // relocation back to its original non-Thunk target.
1633 bool ThunkCreator::normalizeExistingThunk(Relocation &Rel, uint64_t Src) {
1634   if (Thunk *T = Thunks.lookup(Rel.Sym)) {
1635     if (Target->inBranchRange(Rel.Type, Src, Rel.Sym->getVA()))
1636       return true;
1637     Rel.Sym = &T->Destination;
1638     if (Rel.Sym->isInPlt())
1639       Rel.Expr = toPlt(Rel.Expr);
1640   }
1641   return false;
1642 }
1643 
1644 // Process all relocations from the InputSections that have been assigned
1645 // to InputSectionDescriptions and redirect through Thunks if needed. The
1646 // function should be called iteratively until it returns false.
1647 //
1648 // PreConditions:
1649 // All InputSections that may need a Thunk are reachable from
1650 // OutputSectionCommands.
1651 //
1652 // All OutputSections have an address and all InputSections have an offset
1653 // within the OutputSection.
1654 //
1655 // The offsets between caller (relocation place) and callee
1656 // (relocation target) will not be modified outside of createThunks().
1657 //
1658 // PostConditions:
1659 // If return value is true then ThunkSections have been inserted into
1660 // OutputSections. All relocations that needed a Thunk based on the information
1661 // available to createThunks() on entry have been redirected to a Thunk. Note
1662 // that adding Thunks changes offsets between caller and callee so more Thunks
1663 // may be required.
1664 //
1665 // If return value is false then no more Thunks are needed, and createThunks has
1666 // made no changes. If the target requires range extension thunks, currently
1667 // ARM, then any future change in offset between caller and callee risks a
1668 // relocation out of range error.
1669 bool ThunkCreator::createThunks(ArrayRef<OutputSection *> OutputSections) {
1670   bool AddressesChanged = false;
1671 
1672   if (Pass == 0 && Target->getThunkSectionSpacing())
1673     createInitialThunkSections(OutputSections);
1674 
1675   // With Thunk Size much smaller than branch range we expect to
1676   // converge quickly; if we get to 10 something has gone wrong.
1677   if (Pass == 10)
1678     fatal("thunk creation not converged");
1679 
1680   // Create all the Thunks and insert them into synthetic ThunkSections. The
1681   // ThunkSections are later inserted back into InputSectionDescriptions.
1682   // We separate the creation of ThunkSections from the insertion of the
1683   // ThunkSections as ThunkSections are not always inserted into the same
1684   // InputSectionDescription as the caller.
1685   forEachInputSectionDescription(
1686       OutputSections, [&](OutputSection *OS, InputSectionDescription *ISD) {
1687         for (InputSection *IS : ISD->Sections)
1688           for (Relocation &Rel : IS->Relocations) {
1689             uint64_t Src = IS->getVA(Rel.Offset);
1690 
1691             // If we are a relocation to an existing Thunk, check if it is
1692             // still in range. If not then Rel will be altered to point to its
1693             // original target so another Thunk can be generated.
1694             if (Pass > 0 && normalizeExistingThunk(Rel, Src))
1695               continue;
1696 
1697             if (!Target->needsThunk(Rel.Expr, Rel.Type, IS->File, Src,
1698                                     *Rel.Sym))
1699               continue;
1700 
1701             Thunk *T;
1702             bool IsNew;
1703             std::tie(T, IsNew) = getThunk(*Rel.Sym, Rel.Type, Src);
1704 
1705             if (IsNew) {
1706               // Find or create a ThunkSection for the new Thunk
1707               ThunkSection *TS;
1708               if (auto *TIS = T->getTargetInputSection())
1709                 TS = getISThunkSec(TIS);
1710               else
1711                 TS = getISDThunkSec(OS, IS, ISD, Rel.Type, Src);
1712               TS->addThunk(T);
1713               Thunks[T->getThunkTargetSym()] = T;
1714             }
1715 
1716             // Redirect relocation to Thunk, we never go via the PLT to a Thunk
1717             Rel.Sym = T->getThunkTargetSym();
1718             Rel.Expr = fromPlt(Rel.Expr);
1719           }
1720 
1721         for (auto &P : ISD->ThunkSections)
1722           AddressesChanged |= P.first->assignOffsets();
1723       });
1724 
1725   for (auto &P : ThunkedSections)
1726     AddressesChanged |= P.second->assignOffsets();
1727 
1728   // Merge all created synthetic ThunkSections back into OutputSection
1729   mergeThunks(OutputSections);
1730   ++Pass;
1731   return AddressesChanged;
1732 }
1733 
1734 template void elf::scanRelocations<ELF32LE>(InputSectionBase &);
1735 template void elf::scanRelocations<ELF32BE>(InputSectionBase &);
1736 template void elf::scanRelocations<ELF64LE>(InputSectionBase &);
1737 template void elf::scanRelocations<ELF64BE>(InputSectionBase &);
1738