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