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