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_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_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   // We set the final symbols values for linker script defined symbols later.
425   // They always can be computed as a link time constant.
426   if (Sym.ScriptDefined)
427     return true;
428 
429   // For the target and the relocation, we want to know if they are
430   // absolute or relative.
431   bool AbsVal = isAbsoluteValue(Sym);
432   bool RelE = isRelExpr(E);
433   if (AbsVal && !RelE)
434     return true;
435   if (!AbsVal && RelE)
436     return true;
437   if (!AbsVal && !RelE)
438     return Target->usesOnlyLowPageBits(Type);
439 
440   // Relative relocation to an absolute value. This is normally unrepresentable,
441   // but if the relocation refers to a weak undefined symbol, we allow it to
442   // resolve to the image base. This is a little strange, but it allows us to
443   // link function calls to such symbols. Normally such a call will be guarded
444   // with a comparison, which will load a zero from the GOT.
445   // Another special case is MIPS _gp_disp symbol which represents offset
446   // between start of a function and '_gp' value and defined as absolute just
447   // to simplify the code.
448   assert(AbsVal && RelE);
449   if (Sym.isUndefWeak())
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   replaceSymbol<Defined>(&Sym, Sym.File, Sym.getName(), Sym.Binding,
533                          Sym.StOther, Sym.Type, Value, Size, Sec);
534   Sym.PltIndex = Old.PltIndex;
535   Sym.GotIndex = Old.GotIndex;
536   Sym.VerdefIndex = Old.VerdefIndex;
537   Sym.PPC64BranchltIndex = Old.PPC64BranchltIndex;
538   Sym.IsPreemptible = true;
539   Sym.ExportDynamic = true;
540   Sym.IsUsedInRegularObj = true;
541   Sym.Used = true;
542 }
543 
544 // Reserve space in .bss or .bss.rel.ro for copy relocation.
545 //
546 // The copy relocation is pretty much a hack. If you use a copy relocation
547 // in your program, not only the symbol name but the symbol's size, RW/RO
548 // bit and alignment become part of the ABI. In addition to that, if the
549 // symbol has aliases, the aliases become part of the ABI. That's subtle,
550 // but if you violate that implicit ABI, that can cause very counter-
551 // intuitive consequences.
552 //
553 // So, what is the copy relocation? It's for linking non-position
554 // independent code to DSOs. In an ideal world, all references to data
555 // exported by DSOs should go indirectly through GOT. But if object files
556 // are compiled as non-PIC, all data references are direct. There is no
557 // way for the linker to transform the code to use GOT, as machine
558 // instructions are already set in stone in object files. This is where
559 // the copy relocation takes a role.
560 //
561 // A copy relocation instructs the dynamic linker to copy data from a DSO
562 // to a specified address (which is usually in .bss) at load-time. If the
563 // static linker (that's us) finds a direct data reference to a DSO
564 // symbol, it creates a copy relocation, so that the symbol can be
565 // resolved as if it were in .bss rather than in a DSO.
566 //
567 // As you can see in this function, we create a copy relocation for the
568 // dynamic linker, and the relocation contains not only symbol name but
569 // various other informtion about the symbol. So, such attributes become a
570 // part of the ABI.
571 //
572 // Note for application developers: I can give you a piece of advice if
573 // you are writing a shared library. You probably should export only
574 // functions from your library. You shouldn't export variables.
575 //
576 // As an example what can happen when you export variables without knowing
577 // the semantics of copy relocations, assume that you have an exported
578 // variable of type T. It is an ABI-breaking change to add new members at
579 // end of T even though doing that doesn't change the layout of the
580 // existing members. That's because the space for the new members are not
581 // reserved in .bss unless you recompile the main program. That means they
582 // are likely to overlap with other data that happens to be laid out next
583 // to the variable in .bss. This kind of issue is sometimes very hard to
584 // debug. What's a solution? Instead of exporting a varaible V from a DSO,
585 // define an accessor getV().
586 template <class ELFT> static void addCopyRelSymbol(SharedSymbol &SS) {
587   // Copy relocation against zero-sized symbol doesn't make sense.
588   uint64_t SymSize = SS.getSize();
589   if (SymSize == 0 || SS.Alignment == 0)
590     fatal("cannot create a copy relocation for symbol " + toString(SS));
591 
592   // See if this symbol is in a read-only segment. If so, preserve the symbol's
593   // memory protection by reserving space in the .bss.rel.ro section.
594   bool IsReadOnly = isReadOnly<ELFT>(SS);
595   BssSection *Sec = make<BssSection>(IsReadOnly ? ".bss.rel.ro" : ".bss",
596                                      SymSize, SS.Alignment);
597   if (IsReadOnly)
598     In.BssRelRo->getParent()->addSection(Sec);
599   else
600     In.Bss->getParent()->addSection(Sec);
601 
602   // Look through the DSO's dynamic symbol table for aliases and create a
603   // dynamic symbol for each one. This causes the copy relocation to correctly
604   // interpose any aliases.
605   for (SharedSymbol *Sym : getSymbolsAt<ELFT>(SS))
606     replaceWithDefined(*Sym, Sec, 0, Sym->Size);
607 
608   In.RelaDyn->addReloc(Target->CopyRel, Sec, 0, &SS);
609 }
610 
611 // MIPS has an odd notion of "paired" relocations to calculate addends.
612 // For example, if a relocation is of R_MIPS_HI16, there must be a
613 // R_MIPS_LO16 relocation after that, and an addend is calculated using
614 // the two relocations.
615 template <class ELFT, class RelTy>
616 static int64_t computeMipsAddend(const RelTy &Rel, const RelTy *End,
617                                  InputSectionBase &Sec, RelExpr Expr,
618                                  bool IsLocal) {
619   if (Expr == R_MIPS_GOTREL && IsLocal)
620     return Sec.getFile<ELFT>()->MipsGp0;
621 
622   // The ABI says that the paired relocation is used only for REL.
623   // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
624   if (RelTy::IsRela)
625     return 0;
626 
627   RelType Type = Rel.getType(Config->IsMips64EL);
628   uint32_t PairTy = getMipsPairType(Type, IsLocal);
629   if (PairTy == R_MIPS_NONE)
630     return 0;
631 
632   const uint8_t *Buf = Sec.data().data();
633   uint32_t SymIndex = Rel.getSymbol(Config->IsMips64EL);
634 
635   // To make things worse, paired relocations might not be contiguous in
636   // the relocation table, so we need to do linear search. *sigh*
637   for (const RelTy *RI = &Rel; RI != End; ++RI)
638     if (RI->getType(Config->IsMips64EL) == PairTy &&
639         RI->getSymbol(Config->IsMips64EL) == SymIndex)
640       return Target->getImplicitAddend(Buf + RI->r_offset, PairTy);
641 
642   warn("can't find matching " + toString(PairTy) + " relocation for " +
643        toString(Type));
644   return 0;
645 }
646 
647 // Returns an addend of a given relocation. If it is RELA, an addend
648 // is in a relocation itself. If it is REL, we need to read it from an
649 // input section.
650 template <class ELFT, class RelTy>
651 static int64_t computeAddend(const RelTy &Rel, const RelTy *End,
652                              InputSectionBase &Sec, RelExpr Expr,
653                              bool IsLocal) {
654   int64_t Addend;
655   RelType Type = Rel.getType(Config->IsMips64EL);
656 
657   if (RelTy::IsRela) {
658     Addend = getAddend<ELFT>(Rel);
659   } else {
660     const uint8_t *Buf = Sec.data().data();
661     Addend = Target->getImplicitAddend(Buf + Rel.r_offset, Type);
662   }
663 
664   if (Config->EMachine == EM_PPC64 && Config->Pic && Type == R_PPC64_TOC)
665     Addend += getPPC64TocBase();
666   if (Config->EMachine == EM_MIPS)
667     Addend += computeMipsAddend<ELFT>(Rel, End, Sec, Expr, IsLocal);
668 
669   return Addend;
670 }
671 
672 // Report an undefined symbol if necessary.
673 // Returns true if this function printed out an error message.
674 static bool maybeReportUndefined(Symbol &Sym, InputSectionBase &Sec,
675                                  uint64_t Offset) {
676   if (Sym.isLocal() || !Sym.isUndefined() || Sym.isWeak())
677     return false;
678 
679   bool CanBeExternal =
680       Sym.computeBinding() != STB_LOCAL && Sym.Visibility == STV_DEFAULT;
681   if (Config->UnresolvedSymbols == UnresolvedPolicy::Ignore && CanBeExternal)
682     return false;
683 
684   std::string Msg = "undefined ";
685   if (Sym.Visibility == STV_INTERNAL)
686     Msg += "internal ";
687   else if (Sym.Visibility == STV_HIDDEN)
688     Msg += "hidden ";
689   else if (Sym.Visibility == STV_PROTECTED)
690     Msg += "protected ";
691   Msg += "symbol: " + toString(Sym) + "\n>>> referenced by ";
692 
693   std::string Src = Sec.getSrcMsg(Sym, Offset);
694   if (!Src.empty())
695     Msg += Src + "\n>>>               ";
696   Msg += Sec.getObjMsg(Offset);
697 
698   if (Sym.getName().startswith("_ZTV"))
699     Msg += "\nthe vtable symbol may be undefined because the class is missing "
700            "its key function (see https://lld.llvm.org/missingkeyfunction)";
701 
702   if ((Config->UnresolvedSymbols == UnresolvedPolicy::Warn && CanBeExternal) ||
703       Config->NoinhibitExec) {
704     warn(Msg);
705     return false;
706   }
707 
708   error(Msg);
709   return true;
710 }
711 
712 // MIPS N32 ABI treats series of successive relocations with the same offset
713 // as a single relocation. The similar approach used by N64 ABI, but this ABI
714 // packs all relocations into the single relocation record. Here we emulate
715 // this for the N32 ABI. Iterate over relocation with the same offset and put
716 // theirs types into the single bit-set.
717 template <class RelTy> static RelType getMipsN32RelType(RelTy *&Rel, RelTy *End) {
718   RelType Type = 0;
719   uint64_t Offset = Rel->r_offset;
720 
721   int N = 0;
722   while (Rel != End && Rel->r_offset == Offset)
723     Type |= (Rel++)->getType(Config->IsMips64EL) << (8 * N++);
724   return Type;
725 }
726 
727 // .eh_frame sections are mergeable input sections, so their input
728 // offsets are not linearly mapped to output section. For each input
729 // offset, we need to find a section piece containing the offset and
730 // add the piece's base address to the input offset to compute the
731 // output offset. That isn't cheap.
732 //
733 // This class is to speed up the offset computation. When we process
734 // relocations, we access offsets in the monotonically increasing
735 // order. So we can optimize for that access pattern.
736 //
737 // For sections other than .eh_frame, this class doesn't do anything.
738 namespace {
739 class OffsetGetter {
740 public:
741   explicit OffsetGetter(InputSectionBase &Sec) {
742     if (auto *Eh = dyn_cast<EhInputSection>(&Sec))
743       Pieces = Eh->Pieces;
744   }
745 
746   // Translates offsets in input sections to offsets in output sections.
747   // Given offset must increase monotonically. We assume that Piece is
748   // sorted by InputOff.
749   uint64_t get(uint64_t Off) {
750     if (Pieces.empty())
751       return Off;
752 
753     while (I != Pieces.size() && Pieces[I].InputOff + Pieces[I].Size <= Off)
754       ++I;
755     if (I == Pieces.size())
756       fatal(".eh_frame: relocation is not in any piece");
757 
758     // Pieces must be contiguous, so there must be no holes in between.
759     assert(Pieces[I].InputOff <= Off && "Relocation not in any piece");
760 
761     // Offset -1 means that the piece is dead (i.e. garbage collected).
762     if (Pieces[I].OutputOff == -1)
763       return -1;
764     return Pieces[I].OutputOff + Off - Pieces[I].InputOff;
765   }
766 
767 private:
768   ArrayRef<EhSectionPiece> Pieces;
769   size_t I = 0;
770 };
771 } // namespace
772 
773 static void addRelativeReloc(InputSectionBase *IS, uint64_t OffsetInSec,
774                              Symbol *Sym, int64_t Addend, RelExpr Expr,
775                              RelType Type) {
776   // Add a relative relocation. If RelrDyn section is enabled, and the
777   // relocation offset is guaranteed to be even, add the relocation to
778   // the RelrDyn section, otherwise add it to the RelaDyn section.
779   // RelrDyn sections don't support odd offsets. Also, RelrDyn sections
780   // don't store the addend values, so we must write it to the relocated
781   // address.
782   if (In.RelrDyn && IS->Alignment >= 2 && OffsetInSec % 2 == 0) {
783     IS->Relocations.push_back({Expr, Type, OffsetInSec, Addend, Sym});
784     In.RelrDyn->Relocs.push_back({IS, OffsetInSec});
785     return;
786   }
787   In.RelaDyn->addReloc(Target->RelativeRel, IS, OffsetInSec, Sym, Addend, Expr,
788                        Type);
789 }
790 
791 template <class ELFT, class GotPltSection>
792 static void addPltEntry(PltSection *Plt, GotPltSection *GotPlt,
793                         RelocationBaseSection *Rel, RelType Type, Symbol &Sym) {
794   Plt->addEntry<ELFT>(Sym);
795   GotPlt->addEntry(Sym);
796   Rel->addReloc(
797       {Type, GotPlt, Sym.getGotPltOffset(), !Sym.IsPreemptible, &Sym, 0});
798 }
799 
800 static void addGotEntry(Symbol &Sym) {
801   In.Got->addEntry(Sym);
802 
803   RelExpr Expr = Sym.isTls() ? R_TLS : R_ABS;
804   uint64_t Off = Sym.getGotOffset();
805 
806   // If a GOT slot value can be calculated at link-time, which is now,
807   // we can just fill that out.
808   //
809   // (We don't actually write a value to a GOT slot right now, but we
810   // add a static relocation to a Relocations vector so that
811   // InputSection::relocate will do the work for us. We may be able
812   // to just write a value now, but it is a TODO.)
813   bool IsLinkTimeConstant =
814       !Sym.IsPreemptible && (!Config->Pic || isAbsolute(Sym));
815   if (IsLinkTimeConstant) {
816     In.Got->Relocations.push_back({Expr, Target->GotRel, Off, 0, &Sym});
817     return;
818   }
819 
820   // Otherwise, we emit a dynamic relocation to .rel[a].dyn so that
821   // the GOT slot will be fixed at load-time.
822   if (!Sym.isTls() && !Sym.IsPreemptible && Config->Pic && !isAbsolute(Sym)) {
823     addRelativeReloc(In.Got, Off, &Sym, 0, R_ABS, Target->GotRel);
824     return;
825   }
826   In.RelaDyn->addReloc(Sym.isTls() ? Target->TlsGotRel : Target->GotRel, In.Got,
827                        Off, &Sym, 0, Sym.IsPreemptible ? R_ADDEND : R_ABS,
828                        Target->GotRel);
829 }
830 
831 // Return true if we can define a symbol in the executable that
832 // contains the value/function of a symbol defined in a shared
833 // library.
834 static bool canDefineSymbolInExecutable(Symbol &Sym) {
835   // If the symbol has default visibility the symbol defined in the
836   // executable will preempt it.
837   // Note that we want the visibility of the shared symbol itself, not
838   // the visibility of the symbol in the output file we are producing. That is
839   // why we use Sym.StOther.
840   if ((Sym.StOther & 0x3) == STV_DEFAULT)
841     return true;
842 
843   // If we are allowed to break address equality of functions, defining
844   // a plt entry will allow the program to call the function in the
845   // .so, but the .so and the executable will no agree on the address
846   // of the function. Similar logic for objects.
847   return ((Sym.isFunc() && Config->IgnoreFunctionAddressEquality) ||
848           (Sym.isObject() && Config->IgnoreDataAddressEquality));
849 }
850 
851 // The reason we have to do this early scan is as follows
852 // * To mmap the output file, we need to know the size
853 // * For that, we need to know how many dynamic relocs we will have.
854 // It might be possible to avoid this by outputting the file with write:
855 // * Write the allocated output sections, computing addresses.
856 // * Apply relocations, recording which ones require a dynamic reloc.
857 // * Write the dynamic relocations.
858 // * Write the rest of the file.
859 // This would have some drawbacks. For example, we would only know if .rela.dyn
860 // is needed after applying relocations. If it is, it will go after rw and rx
861 // sections. Given that it is ro, we will need an extra PT_LOAD. This
862 // complicates things for the dynamic linker and means we would have to reserve
863 // space for the extra PT_LOAD even if we end up not using it.
864 template <class ELFT, class RelTy>
865 static void processRelocAux(InputSectionBase &Sec, RelExpr Expr, RelType Type,
866                             uint64_t Offset, Symbol &Sym, const RelTy &Rel,
867                             int64_t Addend) {
868   if (isStaticLinkTimeConstant(Expr, Type, Sym, Sec, Offset)) {
869     Sec.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
870     return;
871   }
872   bool CanWrite = (Sec.Flags & SHF_WRITE) || !Config->ZText;
873   if (CanWrite) {
874     // R_GOT refers to a position in the got, even if the symbol is preemptible.
875     bool IsPreemptibleValue = Sym.IsPreemptible && Expr != R_GOT;
876 
877     if (!IsPreemptibleValue) {
878       addRelativeReloc(&Sec, Offset, &Sym, Addend, Expr, Type);
879       return;
880     } else if (RelType Rel = Target->getDynRel(Type)) {
881       In.RelaDyn->addReloc(Rel, &Sec, Offset, &Sym, Addend, R_ADDEND, Type);
882 
883       // MIPS ABI turns using of GOT and dynamic relocations inside out.
884       // While regular ABI uses dynamic relocations to fill up GOT entries
885       // MIPS ABI requires dynamic linker to fills up GOT entries using
886       // specially sorted dynamic symbol table. This affects even dynamic
887       // relocations against symbols which do not require GOT entries
888       // creation explicitly, i.e. do not have any GOT-relocations. So if
889       // a preemptible symbol has a dynamic relocation we anyway have
890       // to create a GOT entry for it.
891       // If a non-preemptible symbol has a dynamic relocation against it,
892       // dynamic linker takes it st_value, adds offset and writes down
893       // result of the dynamic relocation. In case of preemptible symbol
894       // dynamic linker performs symbol resolution, writes the symbol value
895       // to the GOT entry and reads the GOT entry when it needs to perform
896       // a dynamic relocation.
897       // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19
898       if (Config->EMachine == EM_MIPS)
899         In.MipsGot->addEntry(*Sec.File, Sym, Addend, Expr);
900       return;
901     }
902   }
903 
904   // If the relocation is to a weak undef, and we are producing
905   // executable, give up on it and produce a non preemptible 0.
906   if (!Config->Shared && Sym.isUndefWeak()) {
907     Sec.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
908     return;
909   }
910 
911   if (!CanWrite && (Config->Pic && !isRelExpr(Expr))) {
912     error(
913         "can't create dynamic relocation " + toString(Type) + " against " +
914         (Sym.getName().empty() ? "local symbol" : "symbol: " + toString(Sym)) +
915         " in readonly segment; recompile object files with -fPIC "
916         "or pass '-Wl,-z,notext' to allow text relocations in the output" +
917         getLocation(Sec, Sym, Offset));
918     return;
919   }
920 
921   // Copy relocations are only possible if we are creating an executable.
922   if (Config->Shared) {
923     errorOrWarn("relocation " + toString(Type) +
924                 " cannot be used against symbol " + toString(Sym) +
925                 "; recompile with -fPIC" + getLocation(Sec, Sym, Offset));
926     return;
927   }
928 
929   // If the symbol is undefined we already reported any relevant errors.
930   if (Sym.isUndefined())
931     return;
932 
933   if (!canDefineSymbolInExecutable(Sym)) {
934     error("cannot preempt symbol: " + toString(Sym) +
935           getLocation(Sec, Sym, Offset));
936     return;
937   }
938 
939   if (Sym.isObject()) {
940     // Produce a copy relocation.
941     if (auto *SS = dyn_cast<SharedSymbol>(&Sym)) {
942       if (!Config->ZCopyreloc)
943         error("unresolvable relocation " + toString(Type) +
944               " against symbol '" + toString(*SS) +
945               "'; recompile with -fPIC or remove '-z nocopyreloc'" +
946               getLocation(Sec, Sym, Offset));
947       addCopyRelSymbol<ELFT>(*SS);
948     }
949     Sec.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
950     return;
951   }
952 
953   if (Sym.isFunc()) {
954     // This handles a non PIC program call to function in a shared library. In
955     // an ideal world, we could just report an error saying the relocation can
956     // overflow at runtime. In the real world with glibc, crt1.o has a
957     // R_X86_64_PC32 pointing to libc.so.
958     //
959     // The general idea on how to handle such cases is to create a PLT entry and
960     // use that as the function value.
961     //
962     // For the static linking part, we just return a plt expr and everything
963     // else will use the PLT entry as the address.
964     //
965     // The remaining problem is making sure pointer equality still works. We
966     // need the help of the dynamic linker for that. We let it know that we have
967     // a direct reference to a so symbol by creating an undefined symbol with a
968     // non zero st_value. Seeing that, the dynamic linker resolves the symbol to
969     // the value of the symbol we created. This is true even for got entries, so
970     // pointer equality is maintained. To avoid an infinite loop, the only entry
971     // that points to the real function is a dedicated got entry used by the
972     // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT,
973     // R_386_JMP_SLOT, etc).
974 
975     // For position independent executable on i386, the plt entry requires ebx
976     // to be set. This causes two problems:
977     // * If some code has a direct reference to a function, it was probably
978     //   compiled without -fPIE/-fPIC and doesn't maintain ebx.
979     // * If a library definition gets preempted to the executable, it will have
980     //   the wrong ebx value.
981     if (Config->Pie && Config->EMachine == EM_386)
982       errorOrWarn("symbol '" + toString(Sym) +
983                   "' cannot be preempted; recompile with -fPIE" +
984                   getLocation(Sec, Sym, Offset));
985     if (!Sym.isInPlt())
986       addPltEntry<ELFT>(In.Plt, In.GotPlt, In.RelaPlt, Target->PltRel, Sym);
987     if (!Sym.isDefined())
988       replaceWithDefined(
989           Sym, In.Plt,
990           Target->PltHeaderSize + Target->PltEntrySize * Sym.PltIndex, 0);
991     Sym.NeedsPltAddr = true;
992     Sec.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
993     return;
994   }
995 
996   errorOrWarn("symbol '" + toString(Sym) + "' has no type" +
997               getLocation(Sec, Sym, Offset));
998 }
999 
1000 struct IRelativeReloc {
1001   RelType Type;
1002   InputSectionBase *Sec;
1003   uint64_t Offset;
1004   Symbol *Sym;
1005 };
1006 
1007 static std::vector<IRelativeReloc> IRelativeRelocs;
1008 
1009 template <class ELFT, class RelTy>
1010 static void scanReloc(InputSectionBase &Sec, OffsetGetter &GetOffset, RelTy *&I,
1011                       RelTy *End) {
1012   const RelTy &Rel = *I;
1013   Symbol &Sym = Sec.getFile<ELFT>()->getRelocTargetSym(Rel);
1014   RelType Type;
1015 
1016   // Deal with MIPS oddity.
1017   if (Config->MipsN32Abi) {
1018     Type = getMipsN32RelType(I, End);
1019   } else {
1020     Type = Rel.getType(Config->IsMips64EL);
1021     ++I;
1022   }
1023 
1024   // Get an offset in an output section this relocation is applied to.
1025   uint64_t Offset = GetOffset.get(Rel.r_offset);
1026   if (Offset == uint64_t(-1))
1027     return;
1028 
1029   // Skip if the target symbol is an erroneous undefined symbol.
1030   if (maybeReportUndefined(Sym, Sec, Rel.r_offset))
1031     return;
1032 
1033   const uint8_t *RelocatedAddr = Sec.data().begin() + Rel.r_offset;
1034   RelExpr Expr = Target->getRelExpr(Type, Sym, RelocatedAddr);
1035 
1036   // Ignore "hint" relocations because they are only markers for relaxation.
1037   if (oneof<R_HINT, R_NONE>(Expr))
1038     return;
1039 
1040   // We can separate the small code model relocations into 2 categories:
1041   // 1) Those that access the compiler generated .toc sections.
1042   // 2) Those that access the linker allocated got entries.
1043   // lld allocates got entries to symbols on demand. Since we don't try to sort
1044   // the got entries in any way, we don't have to track which objects have
1045   // got-based small code model relocs. The .toc sections get placed after the
1046   // end of the linker allocated .got section and we do sort those so sections
1047   // addressed with small code model relocations come first.
1048   if (Config->EMachine == EM_PPC64 && isPPC64SmallCodeModelTocReloc(Type))
1049     Sec.File->PPC64SmallCodeModelTocRelocs = true;
1050 
1051   if (Sym.isGnuIFunc() && !Config->ZText && Config->WarnIfuncTextrel) {
1052     warn("using ifunc symbols when text relocations are allowed may produce "
1053          "a binary that will segfault, if the object file is linked with "
1054          "old version of glibc (glibc 2.28 and earlier). If this applies to "
1055          "you, consider recompiling the object files without -fPIC and "
1056          "without -Wl,-z,notext option. Use -no-warn-ifunc-textrel to "
1057          "turn off this warning." +
1058          getLocation(Sec, Sym, Offset));
1059   }
1060 
1061   // Relax relocations.
1062   //
1063   // If we know that a PLT entry will be resolved within the same ELF module, we
1064   // can skip PLT access and directly jump to the destination function. For
1065   // example, if we are linking a main exectuable, all dynamic symbols that can
1066   // be resolved within the executable will actually be resolved that way at
1067   // runtime, because the main exectuable is always at the beginning of a search
1068   // list. We can leverage that fact.
1069   if (!Sym.IsPreemptible && !Sym.isGnuIFunc()) {
1070     if (Expr == R_GOT_PC && !isAbsoluteValue(Sym))
1071       Expr = Target->adjustRelaxExpr(Type, RelocatedAddr, Expr);
1072     else
1073       Expr = fromPlt(Expr);
1074   }
1075 
1076   // If the relocation does not emit a GOT or GOTPLT entry but its computation
1077   // uses their addresses, we need GOT or GOTPLT to be created.
1078   //
1079   // The 4 types that relative GOTPLT are all x86 and x86-64 specific.
1080   if (oneof<R_GOTPLTONLY_PC, R_GOTPLTREL, R_GOTPLT, R_TLSGD_GOTPLT>(Expr)) {
1081     In.GotPlt->HasGotPltOffRel = true;
1082   } else if (oneof<R_GOTONLY_PC, R_GOTREL, R_PPC_TOC>(Expr)) {
1083     In.Got->HasGotOffRel = true;
1084   }
1085 
1086   // Read an addend.
1087   int64_t Addend = computeAddend<ELFT>(Rel, End, Sec, Expr, Sym.isLocal());
1088 
1089   // Process some TLS relocations, including relaxing TLS relocations.
1090   // Note that this function does not handle all TLS relocations.
1091   if (unsigned Processed =
1092           handleTlsRelocation<ELFT>(Type, Sym, Sec, Offset, Addend, Expr)) {
1093     I += (Processed - 1);
1094     return;
1095   }
1096 
1097   // Non-preemptible ifuncs require special handling. First, handle the usual
1098   // case where the symbol isn't one of these.
1099   if (!Sym.isGnuIFunc() || Sym.IsPreemptible) {
1100     // If a relocation needs PLT, we create PLT and GOTPLT slots for the symbol.
1101     if (needsPlt(Expr) && !Sym.isInPlt())
1102       addPltEntry<ELFT>(In.Plt, In.GotPlt, In.RelaPlt, Target->PltRel, Sym);
1103 
1104     // Create a GOT slot if a relocation needs GOT.
1105     if (needsGot(Expr)) {
1106       if (Config->EMachine == EM_MIPS) {
1107         // MIPS ABI has special rules to process GOT entries and doesn't
1108         // require relocation entries for them. A special case is TLS
1109         // relocations. In that case dynamic loader applies dynamic
1110         // relocations to initialize TLS GOT entries.
1111         // See "Global Offset Table" in Chapter 5 in the following document
1112         // for detailed description:
1113         // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1114         In.MipsGot->addEntry(*Sec.File, Sym, Addend, Expr);
1115       } else if (!Sym.isInGot()) {
1116         addGotEntry(Sym);
1117       }
1118     }
1119   } else {
1120     // Handle a reference to a non-preemptible ifunc. These are special in a
1121     // few ways:
1122     //
1123     // - Unlike most non-preemptible symbols, non-preemptible ifuncs do not have
1124     //   a fixed value. But assuming that all references to the ifunc are
1125     //   GOT-generating or PLT-generating, the handling of an ifunc is
1126     //   relatively straightforward. We create a PLT entry in Iplt, which is
1127     //   usually at the end of .plt, which makes an indirect call using a
1128     //   matching GOT entry in IgotPlt, which is usually at the end of .got.plt.
1129     //   The GOT entry is relocated using an IRELATIVE relocation in RelaIplt,
1130     //   which is usually at the end of .rela.plt. Unlike most relocations in
1131     //   .rela.plt, which may be evaluated lazily without -z now, dynamic
1132     //   loaders evaluate IRELATIVE relocs eagerly, which means that for
1133     //   IRELATIVE relocs only, GOT-generating relocations can point directly to
1134     //   .got.plt without requiring a separate GOT entry.
1135     //
1136     // - Despite the fact that an ifunc does not have a fixed value, compilers
1137     //   that are not passed -fPIC will assume that they do, and will emit
1138     //   direct (non-GOT-generating, non-PLT-generating) relocations to the
1139     //   symbol. This means that if a direct relocation to the symbol is
1140     //   seen, the linker must set a value for the symbol, and this value must
1141     //   be consistent no matter what type of reference is made to the symbol.
1142     //   This can be done by creating a PLT entry for the symbol in the way
1143     //   described above and making it canonical, that is, making all references
1144     //   point to the PLT entry instead of the resolver. In lld we also store
1145     //   the address of the PLT entry in the dynamic symbol table, which means
1146     //   that the symbol will also have the same value in other modules.
1147     //   Because the value loaded from the GOT needs to be consistent with
1148     //   the value computed using a direct relocation, a non-preemptible ifunc
1149     //   may end up with two GOT entries, one in .got.plt that points to the
1150     //   address returned by the resolver and is used only by the PLT entry,
1151     //   and another in .got that points to the PLT entry and is used by
1152     //   GOT-generating relocations.
1153     //
1154     // - The fact that these symbols do not have a fixed value makes them an
1155     //   exception to the general rule that a statically linked executable does
1156     //   not require any form of dynamic relocation. To handle these relocations
1157     //   correctly, the IRELATIVE relocations are stored in an array which a
1158     //   statically linked executable's startup code must enumerate using the
1159     //   linker-defined symbols __rela?_iplt_{start,end}.
1160     //
1161     // - An absolute relocation to a non-preemptible ifunc (such as a global
1162     //   variable containing a pointer to the ifunc) needs to be relocated in
1163     //   the exact same way as a GOT entry, so we can avoid needing to make the
1164     //   PLT entry canonical by translating such relocations into IRELATIVE
1165     //   relocations in the RelaIplt.
1166     if (!Sym.isInPlt()) {
1167       // Create PLT and GOTPLT slots for the symbol.
1168       Sym.IsInIplt = true;
1169 
1170       // Create a copy of the symbol to use as the target of the IRELATIVE
1171       // relocation in the IgotPlt. This is in case we make the PLT canonical
1172       // later, which would overwrite the original symbol.
1173       //
1174       // FIXME: Creating a copy of the symbol here is a bit of a hack. All
1175       // that's really needed to create the IRELATIVE is the section and value,
1176       // so ideally we should just need to copy those.
1177       auto *DirectSym = make<Defined>(cast<Defined>(Sym));
1178       addPltEntry<ELFT>(In.Iplt, In.IgotPlt, In.RelaIplt, Target->IRelativeRel,
1179                         *DirectSym);
1180       Sym.PltIndex = DirectSym->PltIndex;
1181     }
1182     if (Expr == R_ABS && Addend == 0 && (Sec.Flags & SHF_WRITE)) {
1183       // We might be able to represent this as an IRELATIVE. But we don't know
1184       // yet whether some later relocation will make the symbol point to a
1185       // canonical PLT, which would make this either a dynamic RELATIVE (PIC) or
1186       // static (non-PIC) relocation. So we keep a record of the information
1187       // required to process the relocation, and after scanRelocs() has been
1188       // called on all relocations, the relocation is resolved by
1189       // addIRelativeRelocs().
1190       IRelativeRelocs.push_back({Type, &Sec, Offset, &Sym});
1191       return;
1192     }
1193     if (needsGot(Expr)) {
1194       // Redirect GOT accesses to point to the Igot.
1195       //
1196       // This field is also used to keep track of whether we ever needed a GOT
1197       // entry. If we did and we make the PLT canonical later, we'll need to
1198       // create a GOT entry pointing to the PLT entry for Sym.
1199       Sym.GotInIgot = true;
1200     } else if (!needsPlt(Expr)) {
1201       // Make the ifunc's PLT entry canonical by changing the value of its
1202       // symbol to redirect all references to point to it.
1203       unsigned EntryOffset = Sym.PltIndex * Target->PltEntrySize;
1204       if (Config->ZRetpolineplt)
1205         EntryOffset += Target->PltHeaderSize;
1206 
1207       auto &D = cast<Defined>(Sym);
1208       D.Section = In.Iplt;
1209       D.Value = EntryOffset;
1210       D.Size = 0;
1211       // It's important to set the symbol type here so that dynamic loaders
1212       // don't try to call the PLT as if it were an ifunc resolver.
1213       D.Type = STT_FUNC;
1214 
1215       if (Sym.GotInIgot) {
1216         // We previously encountered a GOT generating reference that we
1217         // redirected to the Igot. Now that the PLT entry is canonical we must
1218         // clear the redirection to the Igot and add a GOT entry. As we've
1219         // changed the symbol type to STT_FUNC future GOT generating references
1220         // will naturally use this GOT entry.
1221         //
1222         // We don't need to worry about creating a MIPS GOT here because ifuncs
1223         // aren't a thing on MIPS.
1224         Sym.GotInIgot = false;
1225         addGotEntry(Sym);
1226       }
1227     }
1228   }
1229 
1230   processRelocAux<ELFT>(Sec, Expr, Type, Offset, Sym, Rel, Addend);
1231 }
1232 
1233 template <class ELFT, class RelTy>
1234 static void scanRelocs(InputSectionBase &Sec, ArrayRef<RelTy> Rels) {
1235   OffsetGetter GetOffset(Sec);
1236 
1237   // Not all relocations end up in Sec.Relocations, but a lot do.
1238   Sec.Relocations.reserve(Rels.size());
1239 
1240   for (auto I = Rels.begin(), End = Rels.end(); I != End;)
1241     scanReloc<ELFT>(Sec, GetOffset, I, End);
1242 
1243   // Sort relocations by offset to binary search for R_RISCV_PCREL_HI20
1244   if (Config->EMachine == EM_RISCV)
1245     llvm::stable_sort(Sec.Relocations,
1246                       [](const Relocation &LHS, const Relocation &RHS) {
1247                         return LHS.Offset < RHS.Offset;
1248                       });
1249 }
1250 
1251 template <class ELFT> void elf::scanRelocations(InputSectionBase &S) {
1252   if (S.AreRelocsRela)
1253     scanRelocs<ELFT>(S, S.relas<ELFT>());
1254   else
1255     scanRelocs<ELFT>(S, S.rels<ELFT>());
1256 }
1257 
1258 // Figure out which representation to use for any absolute relocs to
1259 // non-preemptible ifuncs that we visited during scanRelocs().
1260 void elf::addIRelativeRelocs() {
1261   for (IRelativeReloc &R : IRelativeRelocs) {
1262     if (R.Sym->Type == STT_GNU_IFUNC)
1263       In.RelaIplt->addReloc(
1264           {Target->IRelativeRel, R.Sec, R.Offset, true, R.Sym, 0});
1265     else if (Config->Pic)
1266       addRelativeReloc(R.Sec, R.Offset, R.Sym, 0, R_ABS, R.Type);
1267     else
1268       R.Sec->Relocations.push_back({R_ABS, R.Type, R.Offset, 0, R.Sym});
1269   }
1270   IRelativeRelocs.clear();
1271 }
1272 
1273 static bool mergeCmp(const InputSection *A, const InputSection *B) {
1274   // std::merge requires a strict weak ordering.
1275   if (A->OutSecOff < B->OutSecOff)
1276     return true;
1277 
1278   if (A->OutSecOff == B->OutSecOff) {
1279     auto *TA = dyn_cast<ThunkSection>(A);
1280     auto *TB = dyn_cast<ThunkSection>(B);
1281 
1282     // Check if Thunk is immediately before any specific Target
1283     // InputSection for example Mips LA25 Thunks.
1284     if (TA && TA->getTargetInputSection() == B)
1285       return true;
1286 
1287     // Place Thunk Sections without specific targets before
1288     // non-Thunk Sections.
1289     if (TA && !TB && !TA->getTargetInputSection())
1290       return true;
1291   }
1292 
1293   return false;
1294 }
1295 
1296 // Call Fn on every executable InputSection accessed via the linker script
1297 // InputSectionDescription::Sections.
1298 static void forEachInputSectionDescription(
1299     ArrayRef<OutputSection *> OutputSections,
1300     llvm::function_ref<void(OutputSection *, InputSectionDescription *)> Fn) {
1301   for (OutputSection *OS : OutputSections) {
1302     if (!(OS->Flags & SHF_ALLOC) || !(OS->Flags & SHF_EXECINSTR))
1303       continue;
1304     for (BaseCommand *BC : OS->SectionCommands)
1305       if (auto *ISD = dyn_cast<InputSectionDescription>(BC))
1306         Fn(OS, ISD);
1307   }
1308 }
1309 
1310 // Thunk Implementation
1311 //
1312 // Thunks (sometimes called stubs, veneers or branch islands) are small pieces
1313 // of code that the linker inserts inbetween a caller and a callee. The thunks
1314 // are added at link time rather than compile time as the decision on whether
1315 // a thunk is needed, such as the caller and callee being out of range, can only
1316 // be made at link time.
1317 //
1318 // It is straightforward to tell given the current state of the program when a
1319 // thunk is needed for a particular call. The more difficult part is that
1320 // the thunk needs to be placed in the program such that the caller can reach
1321 // the thunk and the thunk can reach the callee; furthermore, adding thunks to
1322 // the program alters addresses, which can mean more thunks etc.
1323 //
1324 // In lld we have a synthetic ThunkSection that can hold many Thunks.
1325 // The decision to have a ThunkSection act as a container means that we can
1326 // more easily handle the most common case of a single block of contiguous
1327 // Thunks by inserting just a single ThunkSection.
1328 //
1329 // The implementation of Thunks in lld is split across these areas
1330 // Relocations.cpp : Framework for creating and placing thunks
1331 // Thunks.cpp : The code generated for each supported thunk
1332 // Target.cpp : Target specific hooks that the framework uses to decide when
1333 //              a thunk is used
1334 // Synthetic.cpp : Implementation of ThunkSection
1335 // Writer.cpp : Iteratively call framework until no more Thunks added
1336 //
1337 // Thunk placement requirements:
1338 // Mips LA25 thunks. These must be placed immediately before the callee section
1339 // We can assume that the caller is in range of the Thunk. These are modelled
1340 // by Thunks that return the section they must precede with
1341 // getTargetInputSection().
1342 //
1343 // ARM interworking and range extension thunks. These thunks must be placed
1344 // within range of the caller. All implemented ARM thunks can always reach the
1345 // callee as they use an indirect jump via a register that has no range
1346 // restrictions.
1347 //
1348 // Thunk placement algorithm:
1349 // For Mips LA25 ThunkSections; the placement is explicit, it has to be before
1350 // getTargetInputSection().
1351 //
1352 // For thunks that must be placed within range of the caller there are many
1353 // possible choices given that the maximum range from the caller is usually
1354 // much larger than the average InputSection size. Desirable properties include:
1355 // - Maximize reuse of thunks by multiple callers
1356 // - Minimize number of ThunkSections to simplify insertion
1357 // - Handle impact of already added Thunks on addresses
1358 // - Simple to understand and implement
1359 //
1360 // In lld for the first pass, we pre-create one or more ThunkSections per
1361 // InputSectionDescription at Target specific intervals. A ThunkSection is
1362 // placed so that the estimated end of the ThunkSection is within range of the
1363 // start of the InputSectionDescription or the previous ThunkSection. For
1364 // example:
1365 // InputSectionDescription
1366 // Section 0
1367 // ...
1368 // Section N
1369 // ThunkSection 0
1370 // Section N + 1
1371 // ...
1372 // Section N + K
1373 // Thunk Section 1
1374 //
1375 // The intention is that we can add a Thunk to a ThunkSection that is well
1376 // spaced enough to service a number of callers without having to do a lot
1377 // of work. An important principle is that it is not an error if a Thunk cannot
1378 // be placed in a pre-created ThunkSection; when this happens we create a new
1379 // ThunkSection placed next to the caller. This allows us to handle the vast
1380 // majority of thunks simply, but also handle rare cases where the branch range
1381 // is smaller than the target specific spacing.
1382 //
1383 // The algorithm is expected to create all the thunks that are needed in a
1384 // single pass, with a small number of programs needing a second pass due to
1385 // the insertion of thunks in the first pass increasing the offset between
1386 // callers and callees that were only just in range.
1387 //
1388 // A consequence of allowing new ThunkSections to be created outside of the
1389 // pre-created ThunkSections is that in rare cases calls to Thunks that were in
1390 // range in pass K, are out of range in some pass > K due to the insertion of
1391 // more Thunks in between the caller and callee. When this happens we retarget
1392 // the relocation back to the original target and create another Thunk.
1393 
1394 // Remove ThunkSections that are empty, this should only be the initial set
1395 // precreated on pass 0.
1396 
1397 // Insert the Thunks for OutputSection OS into their designated place
1398 // in the Sections vector, and recalculate the InputSection output section
1399 // offsets.
1400 // This may invalidate any output section offsets stored outside of InputSection
1401 void ThunkCreator::mergeThunks(ArrayRef<OutputSection *> OutputSections) {
1402   forEachInputSectionDescription(
1403       OutputSections, [&](OutputSection *OS, InputSectionDescription *ISD) {
1404         if (ISD->ThunkSections.empty())
1405           return;
1406 
1407         // Remove any zero sized precreated Thunks.
1408         llvm::erase_if(ISD->ThunkSections,
1409                        [](const std::pair<ThunkSection *, uint32_t> &TS) {
1410                          return TS.first->getSize() == 0;
1411                        });
1412 
1413         // ISD->ThunkSections contains all created ThunkSections, including
1414         // those inserted in previous passes. Extract the Thunks created this
1415         // pass and order them in ascending OutSecOff.
1416         std::vector<ThunkSection *> NewThunks;
1417         for (const std::pair<ThunkSection *, uint32_t> TS : ISD->ThunkSections)
1418           if (TS.second == Pass)
1419             NewThunks.push_back(TS.first);
1420         llvm::stable_sort(NewThunks,
1421                           [](const ThunkSection *A, const ThunkSection *B) {
1422                             return A->OutSecOff < B->OutSecOff;
1423                           });
1424 
1425         // Merge sorted vectors of Thunks and InputSections by OutSecOff
1426         std::vector<InputSection *> Tmp;
1427         Tmp.reserve(ISD->Sections.size() + NewThunks.size());
1428 
1429         std::merge(ISD->Sections.begin(), ISD->Sections.end(),
1430                    NewThunks.begin(), NewThunks.end(), std::back_inserter(Tmp),
1431                    mergeCmp);
1432 
1433         ISD->Sections = std::move(Tmp);
1434       });
1435 }
1436 
1437 // Find or create a ThunkSection within the InputSectionDescription (ISD) that
1438 // is in range of Src. An ISD maps to a range of InputSections described by a
1439 // linker script section pattern such as { .text .text.* }.
1440 ThunkSection *ThunkCreator::getISDThunkSec(OutputSection *OS, InputSection *IS,
1441                                            InputSectionDescription *ISD,
1442                                            uint32_t Type, uint64_t Src) {
1443   for (std::pair<ThunkSection *, uint32_t> TP : ISD->ThunkSections) {
1444     ThunkSection *TS = TP.first;
1445     uint64_t TSBase = OS->Addr + TS->OutSecOff;
1446     uint64_t TSLimit = TSBase + TS->getSize();
1447     if (Target->inBranchRange(Type, Src, (Src > TSLimit) ? TSBase : TSLimit))
1448       return TS;
1449   }
1450 
1451   // No suitable ThunkSection exists. This can happen when there is a branch
1452   // with lower range than the ThunkSection spacing or when there are too
1453   // many Thunks. Create a new ThunkSection as close to the InputSection as
1454   // possible. Error if InputSection is so large we cannot place ThunkSection
1455   // anywhere in Range.
1456   uint64_t ThunkSecOff = IS->OutSecOff;
1457   if (!Target->inBranchRange(Type, Src, OS->Addr + ThunkSecOff)) {
1458     ThunkSecOff = IS->OutSecOff + IS->getSize();
1459     if (!Target->inBranchRange(Type, Src, OS->Addr + ThunkSecOff))
1460       fatal("InputSection too large for range extension thunk " +
1461             IS->getObjMsg(Src - (OS->Addr + IS->OutSecOff)));
1462   }
1463   return addThunkSection(OS, ISD, ThunkSecOff);
1464 }
1465 
1466 // Add a Thunk that needs to be placed in a ThunkSection that immediately
1467 // precedes its Target.
1468 ThunkSection *ThunkCreator::getISThunkSec(InputSection *IS) {
1469   ThunkSection *TS = ThunkedSections.lookup(IS);
1470   if (TS)
1471     return TS;
1472 
1473   // Find InputSectionRange within Target Output Section (TOS) that the
1474   // InputSection (IS) that we need to precede is in.
1475   OutputSection *TOS = IS->getParent();
1476   for (BaseCommand *BC : TOS->SectionCommands) {
1477     auto *ISD = dyn_cast<InputSectionDescription>(BC);
1478     if (!ISD || ISD->Sections.empty())
1479       continue;
1480 
1481     InputSection *First = ISD->Sections.front();
1482     InputSection *Last = ISD->Sections.back();
1483 
1484     if (IS->OutSecOff < First->OutSecOff || Last->OutSecOff < IS->OutSecOff)
1485       continue;
1486 
1487     TS = addThunkSection(TOS, ISD, IS->OutSecOff);
1488     ThunkedSections[IS] = TS;
1489     return TS;
1490   }
1491 
1492   return nullptr;
1493 }
1494 
1495 // Create one or more ThunkSections per OS that can be used to place Thunks.
1496 // We attempt to place the ThunkSections using the following desirable
1497 // properties:
1498 // - Within range of the maximum number of callers
1499 // - Minimise the number of ThunkSections
1500 //
1501 // We follow a simple but conservative heuristic to place ThunkSections at
1502 // offsets that are multiples of a Target specific branch range.
1503 // For an InputSectionDescription that is smaller than the range, a single
1504 // ThunkSection at the end of the range will do.
1505 //
1506 // For an InputSectionDescription that is more than twice the size of the range,
1507 // we place the last ThunkSection at range bytes from the end of the
1508 // InputSectionDescription in order to increase the likelihood that the
1509 // distance from a thunk to its target will be sufficiently small to
1510 // allow for the creation of a short thunk.
1511 void ThunkCreator::createInitialThunkSections(
1512     ArrayRef<OutputSection *> OutputSections) {
1513   uint32_t ThunkSectionSpacing = Target->getThunkSectionSpacing();
1514 
1515   forEachInputSectionDescription(
1516       OutputSections, [&](OutputSection *OS, InputSectionDescription *ISD) {
1517         if (ISD->Sections.empty())
1518           return;
1519 
1520         uint32_t ISDBegin = ISD->Sections.front()->OutSecOff;
1521         uint32_t ISDEnd =
1522             ISD->Sections.back()->OutSecOff + ISD->Sections.back()->getSize();
1523         uint32_t LastThunkLowerBound = -1;
1524         if (ISDEnd - ISDBegin > ThunkSectionSpacing * 2)
1525           LastThunkLowerBound = ISDEnd - ThunkSectionSpacing;
1526 
1527         uint32_t ISLimit;
1528         uint32_t PrevISLimit = ISDBegin;
1529         uint32_t ThunkUpperBound = ISDBegin + ThunkSectionSpacing;
1530 
1531         for (const InputSection *IS : ISD->Sections) {
1532           ISLimit = IS->OutSecOff + IS->getSize();
1533           if (ISLimit > ThunkUpperBound) {
1534             addThunkSection(OS, ISD, PrevISLimit);
1535             ThunkUpperBound = PrevISLimit + ThunkSectionSpacing;
1536           }
1537           if (ISLimit > LastThunkLowerBound)
1538             break;
1539           PrevISLimit = ISLimit;
1540         }
1541         addThunkSection(OS, ISD, ISLimit);
1542       });
1543 }
1544 
1545 ThunkSection *ThunkCreator::addThunkSection(OutputSection *OS,
1546                                             InputSectionDescription *ISD,
1547                                             uint64_t Off) {
1548   auto *TS = make<ThunkSection>(OS, Off);
1549   ISD->ThunkSections.push_back({TS, Pass});
1550   return TS;
1551 }
1552 
1553 std::pair<Thunk *, bool> ThunkCreator::getThunk(Symbol &Sym, RelType Type,
1554                                                 uint64_t Src) {
1555   std::vector<Thunk *> *ThunkVec = nullptr;
1556 
1557   // We use (section, offset) pair to find the thunk position if possible so
1558   // that we create only one thunk for aliased symbols or ICFed sections.
1559   if (auto *D = dyn_cast<Defined>(&Sym))
1560     if (!D->isInPlt() && D->Section)
1561       ThunkVec = &ThunkedSymbolsBySection[{D->Section->Repl, D->Value}];
1562   if (!ThunkVec)
1563     ThunkVec = &ThunkedSymbols[&Sym];
1564 
1565   // Check existing Thunks for Sym to see if they can be reused
1566   for (Thunk *T : *ThunkVec)
1567     if (T->isCompatibleWith(Type) &&
1568         Target->inBranchRange(Type, Src, T->getThunkTargetSym()->getVA()))
1569       return std::make_pair(T, false);
1570 
1571   // No existing compatible Thunk in range, create a new one
1572   Thunk *T = addThunk(Type, Sym);
1573   ThunkVec->push_back(T);
1574   return std::make_pair(T, true);
1575 }
1576 
1577 // Return true if the relocation target is an in range Thunk.
1578 // Return false if the relocation is not to a Thunk. If the relocation target
1579 // was originally to a Thunk, but is no longer in range we revert the
1580 // relocation back to its original non-Thunk target.
1581 bool ThunkCreator::normalizeExistingThunk(Relocation &Rel, uint64_t Src) {
1582   if (Thunk *T = Thunks.lookup(Rel.Sym)) {
1583     if (Target->inBranchRange(Rel.Type, Src, Rel.Sym->getVA()))
1584       return true;
1585     Rel.Sym = &T->Destination;
1586     if (Rel.Sym->isInPlt())
1587       Rel.Expr = toPlt(Rel.Expr);
1588   }
1589   return false;
1590 }
1591 
1592 // Process all relocations from the InputSections that have been assigned
1593 // to InputSectionDescriptions and redirect through Thunks if needed. The
1594 // function should be called iteratively until it returns false.
1595 //
1596 // PreConditions:
1597 // All InputSections that may need a Thunk are reachable from
1598 // OutputSectionCommands.
1599 //
1600 // All OutputSections have an address and all InputSections have an offset
1601 // within the OutputSection.
1602 //
1603 // The offsets between caller (relocation place) and callee
1604 // (relocation target) will not be modified outside of createThunks().
1605 //
1606 // PostConditions:
1607 // If return value is true then ThunkSections have been inserted into
1608 // OutputSections. All relocations that needed a Thunk based on the information
1609 // available to createThunks() on entry have been redirected to a Thunk. Note
1610 // that adding Thunks changes offsets between caller and callee so more Thunks
1611 // may be required.
1612 //
1613 // If return value is false then no more Thunks are needed, and createThunks has
1614 // made no changes. If the target requires range extension thunks, currently
1615 // ARM, then any future change in offset between caller and callee risks a
1616 // relocation out of range error.
1617 bool ThunkCreator::createThunks(ArrayRef<OutputSection *> OutputSections) {
1618   bool AddressesChanged = false;
1619 
1620   if (Pass == 0 && Target->getThunkSectionSpacing())
1621     createInitialThunkSections(OutputSections);
1622 
1623   // With Thunk Size much smaller than branch range we expect to
1624   // converge quickly; if we get to 10 something has gone wrong.
1625   if (Pass == 10)
1626     fatal("thunk creation not converged");
1627 
1628   // Create all the Thunks and insert them into synthetic ThunkSections. The
1629   // ThunkSections are later inserted back into InputSectionDescriptions.
1630   // We separate the creation of ThunkSections from the insertion of the
1631   // ThunkSections as ThunkSections are not always inserted into the same
1632   // InputSectionDescription as the caller.
1633   forEachInputSectionDescription(
1634       OutputSections, [&](OutputSection *OS, InputSectionDescription *ISD) {
1635         for (InputSection *IS : ISD->Sections)
1636           for (Relocation &Rel : IS->Relocations) {
1637             uint64_t Src = IS->getVA(Rel.Offset);
1638 
1639             // If we are a relocation to an existing Thunk, check if it is
1640             // still in range. If not then Rel will be altered to point to its
1641             // original target so another Thunk can be generated.
1642             if (Pass > 0 && normalizeExistingThunk(Rel, Src))
1643               continue;
1644 
1645             if (!Target->needsThunk(Rel.Expr, Rel.Type, IS->File, Src,
1646                                     *Rel.Sym))
1647               continue;
1648 
1649             Thunk *T;
1650             bool IsNew;
1651             std::tie(T, IsNew) = getThunk(*Rel.Sym, Rel.Type, Src);
1652 
1653             if (IsNew) {
1654               // Find or create a ThunkSection for the new Thunk
1655               ThunkSection *TS;
1656               if (auto *TIS = T->getTargetInputSection())
1657                 TS = getISThunkSec(TIS);
1658               else
1659                 TS = getISDThunkSec(OS, IS, ISD, Rel.Type, Src);
1660               TS->addThunk(T);
1661               Thunks[T->getThunkTargetSym()] = T;
1662             }
1663 
1664             // Redirect relocation to Thunk, we never go via the PLT to a Thunk
1665             Rel.Sym = T->getThunkTargetSym();
1666             Rel.Expr = fromPlt(Rel.Expr);
1667           }
1668 
1669         for (auto &P : ISD->ThunkSections)
1670           AddressesChanged |= P.first->assignOffsets();
1671       });
1672 
1673   for (auto &P : ThunkedSections)
1674     AddressesChanged |= P.second->assignOffsets();
1675 
1676   // Merge all created synthetic ThunkSections back into OutputSection
1677   mergeThunks(OutputSections);
1678   ++Pass;
1679   return AddressesChanged;
1680 }
1681 
1682 template void elf::scanRelocations<ELF32LE>(InputSectionBase &);
1683 template void elf::scanRelocations<ELF32BE>(InputSectionBase &);
1684 template void elf::scanRelocations<ELF64LE>(InputSectionBase &);
1685 template void elf::scanRelocations<ELF64BE>(InputSectionBase &);
1686