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