1 //===- Relocations.cpp ----------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains platform-independent functions to process relocations.
11 // I'll describe the overview of this file here.
12 //
13 // Simple relocations are easy to handle for the linker. For example,
14 // for R_X86_64_PC64 relocs, the linker just has to fix up locations
15 // with the relative offsets to the target symbols. It would just be
16 // reading records from relocation sections and applying them to output.
17 //
18 // But not all relocations are that easy to handle. For example, for
19 // R_386_GOTOFF relocs, the linker has to create new GOT entries for
20 // symbols if they don't exist, and fix up locations with GOT entry
21 // offsets from the beginning of GOT section. So there is more than
22 // fixing addresses in relocation processing.
23 //
24 // ELF defines a large number of complex relocations.
25 //
26 // The functions in this file analyze relocations and do whatever needs
27 // to be done. It includes, but not limited to, the following.
28 //
29 //  - create GOT/PLT entries
30 //  - create new relocations in .dynsym to let the dynamic linker resolve
31 //    them at runtime (since ELF supports dynamic linking, not all
32 //    relocations can be resolved at link-time)
33 //  - create COPY relocs and reserve space in .bss
34 //  - replace expensive relocs (in terms of runtime cost) with cheap ones
35 //  - error out infeasible combinations such as PIC and non-relative relocs
36 //
37 // Note that the functions in this file don't actually apply relocations
38 // because it doesn't know about the output file nor the output file buffer.
39 // It instead stores Relocation objects to InputSection's Relocations
40 // vector to let it apply later in InputSection::writeTo.
41 //
42 //===----------------------------------------------------------------------===//
43 
44 #include "Relocations.h"
45 #include "Config.h"
46 #include "LinkerScript.h"
47 #include "Memory.h"
48 #include "OutputSections.h"
49 #include "Strings.h"
50 #include "SymbolTable.h"
51 #include "SyntheticSections.h"
52 #include "Target.h"
53 #include "Thunks.h"
54 
55 #include "llvm/Support/Endian.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include <algorithm>
58 
59 using namespace llvm;
60 using namespace llvm::ELF;
61 using namespace llvm::object;
62 using namespace llvm::support::endian;
63 
64 using namespace lld;
65 using namespace lld::elf;
66 
67 // Construct a message in the following format.
68 //
69 // >>> defined in /home/alice/src/foo.o
70 // >>> referenced by bar.c:12 (/home/alice/src/bar.c:12)
71 // >>>               /home/alice/src/bar.o:(.text+0x1)
72 template <class ELFT>
73 static std::string getLocation(InputSectionBase &S, const SymbolBody &Sym,
74                                uint64_t Off) {
75   std::string Msg =
76       "\n>>> defined in " + toString(Sym.getFile()) + "\n>>> referenced by ";
77   std::string Src = S.getSrcMsg<ELFT>(Off);
78   if (!Src.empty())
79     Msg += Src + "\n>>>               ";
80   return Msg + S.getObjMsg<ELFT>(Off);
81 }
82 
83 // This is a MIPS-specific rule.
84 //
85 // In case of MIPS GP-relative relocations always resolve to a definition
86 // in a regular input file, ignoring the one-definition rule. So we,
87 // for example, should not attempt to create a dynamic relocation even
88 // if the target symbol is preemptible. There are two two MIPS GP-relative
89 // relocations R_MIPS_GPREL16 and R_MIPS_GPREL32. But only R_MIPS_GPREL16
90 // can be against a preemptible symbol.
91 //
92 // To get MIPS relocation type we apply 0xff mask. In case of O32 ABI all
93 // relocation types occupy eight bit. In case of N64 ABI we extract first
94 // relocation from 3-in-1 packet because only the first relocation can
95 // be against a real symbol.
96 static bool isMipsGprel(RelType Type) {
97   if (Config->EMachine != EM_MIPS)
98     return false;
99   Type &= 0xff;
100   return Type == R_MIPS_GPREL16 || Type == R_MICROMIPS_GPREL16 ||
101          Type == R_MICROMIPS_GPREL7_S2;
102 }
103 
104 // This function is similar to the `handleTlsRelocation`. MIPS does not
105 // support any relaxations for TLS relocations so by factoring out MIPS
106 // handling in to the separate function we can simplify the code and do not
107 // pollute other `handleTlsRelocation` by MIPS `ifs` statements.
108 // Mips has a custom MipsGotSection that handles the writing of GOT entries
109 // without dynamic relocations.
110 template <class ELFT>
111 static unsigned handleMipsTlsRelocation(RelType Type, SymbolBody &Body,
112                                         InputSectionBase &C, uint64_t Offset,
113                                         int64_t Addend, RelExpr Expr) {
114   if (Expr == R_MIPS_TLSLD) {
115     if (InX::MipsGot->addTlsIndex() && Config->Pic)
116       In<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, InX::MipsGot,
117                                    InX::MipsGot->getTlsIndexOff(), false,
118                                    nullptr, 0});
119     C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
120     return 1;
121   }
122 
123   if (Expr == R_MIPS_TLSGD) {
124     if (InX::MipsGot->addDynTlsEntry(Body) && Body.IsPreemptible) {
125       uint64_t Off = InX::MipsGot->getGlobalDynOffset(Body);
126       In<ELFT>::RelaDyn->addReloc(
127           {Target->TlsModuleIndexRel, InX::MipsGot, Off, false, &Body, 0});
128       if (Body.IsPreemptible)
129         In<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, InX::MipsGot,
130                                      Off + Config->Wordsize, false, &Body, 0});
131     }
132     C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
133     return 1;
134   }
135   return 0;
136 }
137 
138 // This function is similar to the `handleMipsTlsRelocation`. ARM also does not
139 // support any relaxations for TLS relocations. ARM is logically similar to Mips
140 // in how it handles TLS, but Mips uses its own custom GOT which handles some
141 // of the cases that ARM uses GOT relocations for.
142 //
143 // We look for TLS global dynamic and local dynamic relocations, these may
144 // require the generation of a pair of GOT entries that have associated
145 // dynamic relocations. When the results of the dynamic relocations can be
146 // resolved at static link time we do so. This is necessary for static linking
147 // as there will be no dynamic loader to resolve them at load-time.
148 //
149 // The pair of GOT entries created are of the form
150 // GOT[e0] Module Index (Used to find pointer to TLS block at run-time)
151 // GOT[e1] Offset of symbol in TLS block
152 template <class ELFT>
153 static unsigned handleARMTlsRelocation(RelType Type, SymbolBody &Body,
154                                        InputSectionBase &C, uint64_t Offset,
155                                        int64_t Addend, RelExpr Expr) {
156   // The Dynamic TLS Module Index Relocation for a symbol defined in an
157   // executable is always 1. If the target Symbol is not preemptible then
158   // we know the offset into the TLS block at static link time.
159   bool NeedDynId = Body.IsPreemptible || Config->Shared;
160   bool NeedDynOff = Body.IsPreemptible;
161 
162   auto AddTlsReloc = [&](uint64_t Off, RelType Type, SymbolBody *Dest,
163                          bool Dyn) {
164     if (Dyn)
165       In<ELFT>::RelaDyn->addReloc({Type, InX::Got, Off, false, Dest, 0});
166     else
167       InX::Got->Relocations.push_back({R_ABS, Type, Off, 0, Dest});
168   };
169 
170   // Local Dynamic is for access to module local TLS variables, while still
171   // being suitable for being dynamically loaded via dlopen.
172   // GOT[e0] is the module index, with a special value of 0 for the current
173   // module. GOT[e1] is unused. There only needs to be one module index entry.
174   if (Expr == R_TLSLD_PC && InX::Got->addTlsIndex()) {
175     AddTlsReloc(InX::Got->getTlsIndexOff(), Target->TlsModuleIndexRel,
176                 NeedDynId ? nullptr : &Body, NeedDynId);
177     C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
178     return 1;
179   }
180 
181   // Global Dynamic is the most general purpose access model. When we know
182   // the module index and offset of symbol in TLS block we can fill these in
183   // using static GOT relocations.
184   if (Expr == R_TLSGD_PC) {
185     if (InX::Got->addDynTlsEntry(Body)) {
186       uint64_t Off = InX::Got->getGlobalDynOffset(Body);
187       AddTlsReloc(Off, Target->TlsModuleIndexRel, &Body, NeedDynId);
188       AddTlsReloc(Off + Config->Wordsize, Target->TlsOffsetRel, &Body,
189                   NeedDynOff);
190     }
191     C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
192     return 1;
193   }
194   return 0;
195 }
196 
197 // Returns the number of relocations processed.
198 template <class ELFT>
199 static unsigned
200 handleTlsRelocation(RelType Type, SymbolBody &Body, InputSectionBase &C,
201                     typename ELFT::uint Offset, int64_t Addend, RelExpr Expr) {
202   if (!(C.Flags & SHF_ALLOC))
203     return 0;
204 
205   if (!Body.isTls())
206     return 0;
207 
208   if (Config->EMachine == EM_ARM)
209     return handleARMTlsRelocation<ELFT>(Type, Body, C, Offset, Addend, Expr);
210   if (Config->EMachine == EM_MIPS)
211     return handleMipsTlsRelocation<ELFT>(Type, Body, C, Offset, Addend, Expr);
212 
213   if (isRelExprOneOf<R_TLSDESC, R_TLSDESC_PAGE, R_TLSDESC_CALL>(Expr) &&
214       Config->Shared) {
215     if (InX::Got->addDynTlsEntry(Body)) {
216       uint64_t Off = InX::Got->getGlobalDynOffset(Body);
217       In<ELFT>::RelaDyn->addReloc(
218           {Target->TlsDescRel, InX::Got, Off, !Body.IsPreemptible, &Body, 0});
219     }
220     if (Expr != R_TLSDESC_CALL)
221       C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
222     return 1;
223   }
224 
225   if (isRelExprOneOf<R_TLSLD_PC, R_TLSLD>(Expr)) {
226     // Local-Dynamic relocs can be relaxed to Local-Exec.
227     if (!Config->Shared) {
228       C.Relocations.push_back(
229           {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Body});
230       return 2;
231     }
232     if (InX::Got->addTlsIndex())
233       In<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, InX::Got,
234                                    InX::Got->getTlsIndexOff(), false, nullptr,
235                                    0});
236     C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
237     return 1;
238   }
239 
240   // Local-Dynamic relocs can be relaxed to Local-Exec.
241   if (isRelExprOneOf<R_ABS, R_TLSLD, R_TLSLD_PC>(Expr) && !Config->Shared) {
242     C.Relocations.push_back(
243         {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Body});
244     return 1;
245   }
246 
247   if (isRelExprOneOf<R_TLSDESC, R_TLSDESC_PAGE, R_TLSDESC_CALL, R_TLSGD,
248                      R_TLSGD_PC>(Expr)) {
249     if (Config->Shared) {
250       if (InX::Got->addDynTlsEntry(Body)) {
251         uint64_t Off = InX::Got->getGlobalDynOffset(Body);
252         In<ELFT>::RelaDyn->addReloc(
253             {Target->TlsModuleIndexRel, InX::Got, Off, false, &Body, 0});
254 
255         // If the symbol is preemptible we need the dynamic linker to write
256         // the offset too.
257         uint64_t OffsetOff = Off + Config->Wordsize;
258         if (Body.IsPreemptible)
259           In<ELFT>::RelaDyn->addReloc(
260               {Target->TlsOffsetRel, InX::Got, OffsetOff, false, &Body, 0});
261         else
262           InX::Got->Relocations.push_back(
263               {R_ABS, Target->TlsOffsetRel, OffsetOff, 0, &Body});
264       }
265       C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
266       return 1;
267     }
268 
269     // Global-Dynamic relocs can be relaxed to Initial-Exec or Local-Exec
270     // depending on the symbol being locally defined or not.
271     if (Body.IsPreemptible) {
272       C.Relocations.push_back(
273           {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_IE), Type,
274            Offset, Addend, &Body});
275       if (!Body.isInGot()) {
276         InX::Got->addEntry(Body);
277         In<ELFT>::RelaDyn->addReloc({Target->TlsGotRel, InX::Got,
278                                      Body.getGotOffset(), false, &Body, 0});
279       }
280     } else {
281       C.Relocations.push_back(
282           {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_LE), Type,
283            Offset, Addend, &Body});
284     }
285     return Target->TlsGdRelaxSkip;
286   }
287 
288   // Initial-Exec relocs can be relaxed to Local-Exec if the symbol is locally
289   // defined.
290   if (isRelExprOneOf<R_GOT, R_GOT_FROM_END, R_GOT_PC, R_GOT_PAGE_PC>(Expr) &&
291       !Config->Shared && !Body.IsPreemptible) {
292     C.Relocations.push_back(
293         {R_RELAX_TLS_IE_TO_LE, Type, Offset, Addend, &Body});
294     return 1;
295   }
296 
297   if (Expr == R_TLSDESC_CALL)
298     return 1;
299   return 0;
300 }
301 
302 static RelType getMipsPairType(RelType Type, bool IsLocal) {
303   switch (Type) {
304   case R_MIPS_HI16:
305     return R_MIPS_LO16;
306   case R_MIPS_GOT16:
307     // I don't know why these relocations had to be defined like this,
308     // but they are handled differently when they refer to local symbols.
309     return IsLocal ? R_MIPS_LO16 : R_MIPS_NONE;
310   case R_MICROMIPS_GOT16:
311     return IsLocal ? R_MICROMIPS_LO16 : R_MIPS_NONE;
312   case R_MIPS_PCHI16:
313     return R_MIPS_PCLO16;
314   case R_MICROMIPS_HI16:
315     return R_MICROMIPS_LO16;
316   default:
317     return R_MIPS_NONE;
318   }
319 }
320 
321 // True if non-preemptable symbol always has the same value regardless of where
322 // the DSO is loaded.
323 static bool isAbsolute(const SymbolBody &Body) {
324   if (Body.isUndefWeak())
325     return true;
326   if (const auto *DR = dyn_cast<DefinedRegular>(&Body))
327     return DR->Section == nullptr; // Absolute symbol.
328   return false;
329 }
330 
331 static bool isAbsoluteValue(const SymbolBody &Body) {
332   return isAbsolute(Body) || Body.isTls();
333 }
334 
335 // Returns true if Expr refers a PLT entry.
336 static bool needsPlt(RelExpr Expr) {
337   return isRelExprOneOf<R_PLT_PC, R_PPC_PLT_OPD, R_PLT, R_PLT_PAGE_PC>(Expr);
338 }
339 
340 // Returns true if Expr refers a GOT entry. Note that this function
341 // returns false for TLS variables even though they need GOT, because
342 // TLS variables uses GOT differently than the regular variables.
343 static bool needsGot(RelExpr Expr) {
344   return isRelExprOneOf<R_GOT, R_GOT_OFF, R_MIPS_GOT_LOCAL_PAGE, R_MIPS_GOT_OFF,
345                         R_MIPS_GOT_OFF32, R_GOT_PAGE_PC, R_GOT_PC,
346                         R_GOT_FROM_END>(Expr);
347 }
348 
349 // True if this expression is of the form Sym - X, where X is a position in the
350 // file (PC, or GOT for example).
351 static bool isRelExpr(RelExpr Expr) {
352   return isRelExprOneOf<R_PC, R_GOTREL, R_GOTREL_FROM_END, R_MIPS_GOTREL,
353                         R_PAGE_PC, R_RELAX_GOT_PC>(Expr);
354 }
355 
356 // Returns true if a given relocation can be computed at link-time.
357 //
358 // For instance, we know the offset from a relocation to its target at
359 // link-time if the relocation is PC-relative and refers a
360 // non-interposable function in the same executable. This function
361 // will return true for such relocation.
362 //
363 // If this function returns false, that means we need to emit a
364 // dynamic relocation so that the relocation will be fixed at load-time.
365 template <class ELFT>
366 static bool isStaticLinkTimeConstant(RelExpr E, RelType Type,
367                                      const SymbolBody &Body,
368                                      InputSectionBase &S, uint64_t RelOff) {
369   // These expressions always compute a constant
370   if (isRelExprOneOf<R_SIZE, R_GOT_FROM_END, R_GOT_OFF, R_MIPS_GOT_LOCAL_PAGE,
371                      R_MIPS_GOT_OFF, R_MIPS_GOT_OFF32, R_MIPS_GOT_GP_PC,
372                      R_MIPS_TLSGD, R_GOT_PAGE_PC, R_GOT_PC, R_GOTONLY_PC,
373                      R_GOTONLY_PC_FROM_END, R_PLT_PC, R_TLSGD_PC, R_TLSGD,
374                      R_PPC_PLT_OPD, R_TLSDESC_CALL, R_TLSDESC_PAGE, R_HINT>(E))
375     return true;
376 
377   // These never do, except if the entire file is position dependent or if
378   // only the low bits are used.
379   if (E == R_GOT || E == R_PLT || E == R_TLSDESC)
380     return Target->usesOnlyLowPageBits(Type) || !Config->Pic;
381 
382   if (Body.IsPreemptible)
383     return false;
384   if (!Config->Pic)
385     return true;
386 
387   // For the target and the relocation, we want to know if they are
388   // absolute or relative.
389   bool AbsVal = isAbsoluteValue(Body);
390   bool RelE = isRelExpr(E);
391   if (AbsVal && !RelE)
392     return true;
393   if (!AbsVal && RelE)
394     return true;
395   if (!AbsVal && !RelE)
396     return Target->usesOnlyLowPageBits(Type);
397 
398   // Relative relocation to an absolute value. This is normally unrepresentable,
399   // but if the relocation refers to a weak undefined symbol, we allow it to
400   // resolve to the image base. This is a little strange, but it allows us to
401   // link function calls to such symbols. Normally such a call will be guarded
402   // with a comparison, which will load a zero from the GOT.
403   // Another special case is MIPS _gp_disp symbol which represents offset
404   // between start of a function and '_gp' value and defined as absolute just
405   // to simplify the code.
406   assert(AbsVal && RelE);
407   if (Body.isUndefWeak())
408     return true;
409 
410   error("relocation " + toString(Type) + " cannot refer to absolute symbol: " +
411         toString(Body) + getLocation<ELFT>(S, Body, RelOff));
412   return true;
413 }
414 
415 static RelExpr toPlt(RelExpr Expr) {
416   if (Expr == R_PPC_OPD)
417     return R_PPC_PLT_OPD;
418   if (Expr == R_PC)
419     return R_PLT_PC;
420   if (Expr == R_PAGE_PC)
421     return R_PLT_PAGE_PC;
422   if (Expr == R_ABS)
423     return R_PLT;
424   return Expr;
425 }
426 
427 static RelExpr fromPlt(RelExpr Expr) {
428   // We decided not to use a plt. Optimize a reference to the plt to a
429   // reference to the symbol itself.
430   if (Expr == R_PLT_PC)
431     return R_PC;
432   if (Expr == R_PPC_PLT_OPD)
433     return R_PPC_OPD;
434   if (Expr == R_PLT)
435     return R_ABS;
436   return Expr;
437 }
438 
439 // Returns true if a given shared symbol is in a read-only segment in a DSO.
440 template <class ELFT> static bool isReadOnly(SharedSymbol *SS) {
441   typedef typename ELFT::Phdr Elf_Phdr;
442   uint64_t Value = SS->getValue<ELFT>();
443 
444   // Determine if the symbol is read-only by scanning the DSO's program headers.
445   const SharedFile<ELFT> *File = SS->getFile<ELFT>();
446   for (const Elf_Phdr &Phdr : check(File->getObj().program_headers()))
447     if ((Phdr.p_type == ELF::PT_LOAD || Phdr.p_type == ELF::PT_GNU_RELRO) &&
448         !(Phdr.p_flags & ELF::PF_W) && Value >= Phdr.p_vaddr &&
449         Value < Phdr.p_vaddr + Phdr.p_memsz)
450       return true;
451   return false;
452 }
453 
454 // Returns symbols at the same offset as a given symbol, including SS itself.
455 //
456 // If two or more symbols are at the same offset, and at least one of
457 // them are copied by a copy relocation, all of them need to be copied.
458 // Otherwise, they would refer different places at runtime.
459 template <class ELFT>
460 static std::vector<SharedSymbol *> getSymbolsAt(SharedSymbol *SS) {
461   typedef typename ELFT::Sym Elf_Sym;
462 
463   SharedFile<ELFT> *File = SS->getFile<ELFT>();
464   uint64_t Shndx = SS->getShndx<ELFT>();
465   uint64_t Value = SS->getValue<ELFT>();
466 
467   std::vector<SharedSymbol *> Ret;
468   for (const Elf_Sym &S : File->getGlobalELFSyms()) {
469     if (S.st_shndx != Shndx || S.st_value != Value)
470       continue;
471     StringRef Name = check(S.getName(File->getStringTable()));
472     SymbolBody *Sym = Symtab->find(Name);
473     if (auto *Alias = dyn_cast_or_null<SharedSymbol>(Sym))
474       Ret.push_back(Alias);
475   }
476   return Ret;
477 }
478 
479 // Reserve space in .bss or .bss.rel.ro for copy relocation.
480 //
481 // The copy relocation is pretty much a hack. If you use a copy relocation
482 // in your program, not only the symbol name but the symbol's size, RW/RO
483 // bit and alignment become part of the ABI. In addition to that, if the
484 // symbol has aliases, the aliases become part of the ABI. That's subtle,
485 // but if you violate that implicit ABI, that can cause very counter-
486 // intuitive consequences.
487 //
488 // So, what is the copy relocation? It's for linking non-position
489 // independent code to DSOs. In an ideal world, all references to data
490 // exported by DSOs should go indirectly through GOT. But if object files
491 // are compiled as non-PIC, all data references are direct. There is no
492 // way for the linker to transform the code to use GOT, as machine
493 // instructions are already set in stone in object files. This is where
494 // the copy relocation takes a role.
495 //
496 // A copy relocation instructs the dynamic linker to copy data from a DSO
497 // to a specified address (which is usually in .bss) at load-time. If the
498 // static linker (that's us) finds a direct data reference to a DSO
499 // symbol, it creates a copy relocation, so that the symbol can be
500 // resolved as if it were in .bss rather than in a DSO.
501 //
502 // As you can see in this function, we create a copy relocation for the
503 // dynamic linker, and the relocation contains not only symbol name but
504 // various other informtion about the symbol. So, such attributes become a
505 // part of the ABI.
506 //
507 // Note for application developers: I can give you a piece of advice if
508 // you are writing a shared library. You probably should export only
509 // functions from your library. You shouldn't export variables.
510 //
511 // As an example what can happen when you export variables without knowing
512 // the semantics of copy relocations, assume that you have an exported
513 // variable of type T. It is an ABI-breaking change to add new members at
514 // end of T even though doing that doesn't change the layout of the
515 // existing members. That's because the space for the new members are not
516 // reserved in .bss unless you recompile the main program. That means they
517 // are likely to overlap with other data that happens to be laid out next
518 // to the variable in .bss. This kind of issue is sometimes very hard to
519 // debug. What's a solution? Instead of exporting a varaible V from a DSO,
520 // define an accessor getV().
521 template <class ELFT> static void addCopyRelSymbol(SharedSymbol *SS) {
522   // Copy relocation against zero-sized symbol doesn't make sense.
523   uint64_t SymSize = SS->template getSize<ELFT>();
524   if (SymSize == 0)
525     fatal("cannot create a copy relocation for symbol " + toString(*SS));
526 
527   // See if this symbol is in a read-only segment. If so, preserve the symbol's
528   // memory protection by reserving space in the .bss.rel.ro section.
529   bool IsReadOnly = isReadOnly<ELFT>(SS);
530   BssSection *Sec = make<BssSection>(IsReadOnly ? ".bss.rel.ro" : ".bss",
531                                      SymSize, SS->getAlignment<ELFT>());
532   if (IsReadOnly)
533     InX::BssRelRo->getParent()->addSection(Sec);
534   else
535     InX::Bss->getParent()->addSection(Sec);
536 
537   // Look through the DSO's dynamic symbol table for aliases and create a
538   // dynamic symbol for each one. This causes the copy relocation to correctly
539   // interpose any aliases.
540   for (SharedSymbol *Sym : getSymbolsAt<ELFT>(SS)) {
541     Sym->CopyRelSec = Sec;
542     Sym->IsPreemptible = false;
543     Sym->symbol()->IsUsedInRegularObj = true;
544   }
545 
546   In<ELFT>::RelaDyn->addReloc({Target->CopyRel, Sec, 0, false, SS, 0});
547 }
548 
549 static void errorOrWarn(const Twine &Msg) {
550   if (!Config->NoinhibitExec)
551     error(Msg);
552   else
553     warn(Msg);
554 }
555 
556 template <class ELFT>
557 static RelExpr adjustExpr(SymbolBody &Body, RelExpr Expr, RelType Type,
558                           InputSectionBase &S, uint64_t RelOff) {
559   // We can create any dynamic relocation if a section is simply writable.
560   if (S.Flags & SHF_WRITE)
561     return Expr;
562 
563   // Or, if we are allowed to create dynamic relocations against
564   // read-only sections (i.e. unless "-z notext" is given),
565   // we can create a dynamic relocation as we want, too.
566   if (!Config->ZText)
567     return Expr;
568 
569   // If a relocation can be applied at link-time, we don't need to
570   // create a dynamic relocation in the first place.
571   if (isStaticLinkTimeConstant<ELFT>(Expr, Type, Body, S, RelOff))
572     return Expr;
573 
574   // If we got here we know that this relocation would require the dynamic
575   // linker to write a value to read only memory.
576 
577   // If the relocation is to a weak undef, give up on it and produce a
578   // non preemptible 0.
579   if (Body.isUndefWeak()) {
580     Body.IsPreemptible = false;
581     return Expr;
582   }
583 
584   // We can hack around it if we are producing an executable and
585   // the refered symbol can be preemepted to refer to the executable.
586   if (Config->Shared || (Config->Pic && !isRelExpr(Expr))) {
587     error("can't create dynamic relocation " + toString(Type) + " against " +
588           (Body.getName().empty() ? "local symbol"
589                                   : "symbol: " + toString(Body)) +
590           " in readonly segment; recompile object files with -fPIC" +
591           getLocation<ELFT>(S, Body, RelOff));
592     return Expr;
593   }
594 
595   if (Body.getVisibility() != STV_DEFAULT) {
596     error("cannot preempt symbol: " + toString(Body) +
597           getLocation<ELFT>(S, Body, RelOff));
598     return Expr;
599   }
600 
601   if (Body.isObject()) {
602     // Produce a copy relocation.
603     auto *B = cast<SharedSymbol>(&Body);
604     if (!B->CopyRelSec) {
605       if (Config->ZNocopyreloc)
606         error("unresolvable relocation " + toString(Type) +
607               " against symbol '" + toString(*B) +
608               "'; recompile with -fPIC or remove '-z nocopyreloc'" +
609               getLocation<ELFT>(S, Body, RelOff));
610 
611       addCopyRelSymbol<ELFT>(B);
612     }
613     return Expr;
614   }
615 
616   if (Body.isFunc()) {
617     // This handles a non PIC program call to function in a shared library. In
618     // an ideal world, we could just report an error saying the relocation can
619     // overflow at runtime. In the real world with glibc, crt1.o has a
620     // R_X86_64_PC32 pointing to libc.so.
621     //
622     // The general idea on how to handle such cases is to create a PLT entry and
623     // use that as the function value.
624     //
625     // For the static linking part, we just return a plt expr and everything
626     // else will use the the PLT entry as the address.
627     //
628     // The remaining problem is making sure pointer equality still works. We
629     // need the help of the dynamic linker for that. We let it know that we have
630     // a direct reference to a so symbol by creating an undefined symbol with a
631     // non zero st_value. Seeing that, the dynamic linker resolves the symbol to
632     // the value of the symbol we created. This is true even for got entries, so
633     // pointer equality is maintained. To avoid an infinite loop, the only entry
634     // that points to the real function is a dedicated got entry used by the
635     // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT,
636     // R_386_JMP_SLOT, etc).
637     Body.NeedsPltAddr = true;
638     Body.IsPreemptible = false;
639     return toPlt(Expr);
640   }
641 
642   errorOrWarn("symbol '" + toString(Body) + "' defined in " +
643               toString(Body.getFile()) + " has no type");
644   return Expr;
645 }
646 
647 // MIPS has an odd notion of "paired" relocations to calculate addends.
648 // For example, if a relocation is of R_MIPS_HI16, there must be a
649 // R_MIPS_LO16 relocation after that, and an addend is calculated using
650 // the two relocations.
651 template <class ELFT, class RelTy>
652 static int64_t computeMipsAddend(const RelTy &Rel, const RelTy *End,
653                                  InputSectionBase &Sec, RelExpr Expr,
654                                  bool IsLocal) {
655   if (Expr == R_MIPS_GOTREL && IsLocal)
656     return Sec.getFile<ELFT>()->MipsGp0;
657 
658   // The ABI says that the paired relocation is used only for REL.
659   // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
660   if (RelTy::IsRela)
661     return 0;
662 
663   RelType Type = Rel.getType(Config->IsMips64EL);
664   uint32_t PairTy = getMipsPairType(Type, IsLocal);
665   if (PairTy == R_MIPS_NONE)
666     return 0;
667 
668   const uint8_t *Buf = Sec.Data.data();
669   uint32_t SymIndex = Rel.getSymbol(Config->IsMips64EL);
670 
671   // To make things worse, paired relocations might not be contiguous in
672   // the relocation table, so we need to do linear search. *sigh*
673   for (const RelTy *RI = &Rel; RI != End; ++RI)
674     if (RI->getType(Config->IsMips64EL) == PairTy &&
675         RI->getSymbol(Config->IsMips64EL) == SymIndex)
676       return Target->getImplicitAddend(Buf + RI->r_offset, PairTy);
677 
678   warn("can't find matching " + toString(PairTy) + " relocation for " +
679        toString(Type));
680   return 0;
681 }
682 
683 // Returns an addend of a given relocation. If it is RELA, an addend
684 // is in a relocation itself. If it is REL, we need to read it from an
685 // input section.
686 template <class ELFT, class RelTy>
687 static int64_t computeAddend(const RelTy &Rel, const RelTy *End,
688                              InputSectionBase &Sec, RelExpr Expr,
689                              bool IsLocal) {
690   int64_t Addend;
691   RelType Type = Rel.getType(Config->IsMips64EL);
692 
693   if (RelTy::IsRela) {
694     Addend = getAddend<ELFT>(Rel);
695   } else {
696     const uint8_t *Buf = Sec.Data.data();
697     Addend = Target->getImplicitAddend(Buf + Rel.r_offset, Type);
698   }
699 
700   if (Config->EMachine == EM_PPC64 && Config->Pic && Type == R_PPC64_TOC)
701     Addend += getPPC64TocBase();
702   if (Config->EMachine == EM_MIPS)
703     Addend += computeMipsAddend<ELFT>(Rel, End, Sec, Expr, IsLocal);
704 
705   return Addend;
706 }
707 
708 // Report an undefined symbol if necessary.
709 // Returns true if this function printed out an error message.
710 template <class ELFT>
711 static bool maybeReportUndefined(SymbolBody &Sym, InputSectionBase &Sec,
712                                  uint64_t Offset) {
713   if (Config->UnresolvedSymbols == UnresolvedPolicy::IgnoreAll)
714     return false;
715 
716   if (Sym.isLocal() || !Sym.isUndefined() || Sym.symbol()->isWeak())
717     return false;
718 
719   bool CanBeExternal = Sym.symbol()->computeBinding() != STB_LOCAL &&
720                        Sym.getVisibility() == STV_DEFAULT;
721   if (Config->UnresolvedSymbols == UnresolvedPolicy::Ignore && CanBeExternal)
722     return false;
723 
724   std::string Msg =
725       "undefined symbol: " + toString(Sym) + "\n>>> referenced by ";
726 
727   std::string Src = Sec.getSrcMsg<ELFT>(Offset);
728   if (!Src.empty())
729     Msg += Src + "\n>>>               ";
730   Msg += Sec.getObjMsg<ELFT>(Offset);
731 
732   if ((Config->UnresolvedSymbols == UnresolvedPolicy::Warn && CanBeExternal) ||
733       Config->NoinhibitExec) {
734     warn(Msg);
735     return false;
736   }
737 
738   error(Msg);
739   return true;
740 }
741 
742 // MIPS N32 ABI treats series of successive relocations with the same offset
743 // as a single relocation. The similar approach used by N64 ABI, but this ABI
744 // packs all relocations into the single relocation record. Here we emulate
745 // this for the N32 ABI. Iterate over relocation with the same offset and put
746 // theirs types into the single bit-set.
747 template <class RelTy> static RelType getMipsN32RelType(RelTy *&Rel, RelTy *End) {
748   RelType Type = Rel->getType(Config->IsMips64EL);
749   uint64_t Offset = Rel->r_offset;
750 
751   int N = 0;
752   while (Rel + 1 != End && (Rel + 1)->r_offset == Offset)
753     Type |= (++Rel)->getType(Config->IsMips64EL) << (8 * ++N);
754   return Type;
755 }
756 
757 // .eh_frame sections are mergeable input sections, so their input
758 // offsets are not linearly mapped to output section. For each input
759 // offset, we need to find a section piece containing the offset and
760 // add the piece's base address to the input offset to compute the
761 // output offset. That isn't cheap.
762 //
763 // This class is to speed up the offset computation. When we process
764 // relocations, we access offsets in the monotonically increasing
765 // order. So we can optimize for that access pattern.
766 //
767 // For sections other than .eh_frame, this class doesn't do anything.
768 namespace {
769 class OffsetGetter {
770 public:
771   explicit OffsetGetter(InputSectionBase &Sec) {
772     if (auto *Eh = dyn_cast<EhInputSection>(&Sec))
773       Pieces = Eh->Pieces;
774   }
775 
776   // Translates offsets in input sections to offsets in output sections.
777   // Given offset must increase monotonically. We assume that Piece is
778   // sorted by InputOff.
779   uint64_t get(uint64_t Off) {
780     if (Pieces.empty())
781       return Off;
782 
783     while (I != Pieces.size() && Pieces[I].InputOff + Pieces[I].Size <= Off)
784       ++I;
785     if (I == Pieces.size())
786       return Off;
787 
788     // Pieces must be contiguous, so there must be no holes in between.
789     assert(Pieces[I].InputOff <= Off && "Relocation not in any piece");
790 
791     // Offset -1 means that the piece is dead (i.e. garbage collected).
792     if (Pieces[I].OutputOff == -1)
793       return -1;
794     return Pieces[I].OutputOff + Off - Pieces[I].InputOff;
795   }
796 
797 private:
798   ArrayRef<EhSectionPiece> Pieces;
799   size_t I = 0;
800 };
801 } // namespace
802 
803 template <class ELFT, class GotPltSection>
804 static void addPltEntry(PltSection *Plt, GotPltSection *GotPlt,
805                         RelocationSection<ELFT> *Rel, RelType Type,
806                         SymbolBody &Sym, bool UseSymVA) {
807   Plt->addEntry<ELFT>(Sym);
808   GotPlt->addEntry(Sym);
809   Rel->addReloc({Type, GotPlt, Sym.getGotPltOffset(), UseSymVA, &Sym, 0});
810 }
811 
812 template <class ELFT>
813 static void addGotEntry(SymbolBody &Sym, bool Preemptible) {
814   InX::Got->addEntry(Sym);
815 
816   RelExpr Expr = Sym.isTls() ? R_TLS : R_ABS;
817   uint64_t Off = Sym.getGotOffset();
818 
819   // If a GOT slot value can be calculated at link-time, which is now,
820   // we can just fill that out.
821   //
822   // (We don't actually write a value to a GOT slot right now, but we
823   // add a static relocation to a Relocations vector so that
824   // InputSection::relocate will do the work for us. We may be able
825   // to just write a value now, but it is a TODO.)
826   bool IsLinkTimeConstant = !Preemptible && (!Config->Pic || isAbsolute(Sym));
827   if (IsLinkTimeConstant) {
828     InX::Got->Relocations.push_back({Expr, Target->GotRel, Off, 0, &Sym});
829     return;
830   }
831 
832   // Otherwise, we emit a dynamic relocation to .rel[a].dyn so that
833   // the GOT slot will be fixed at load-time.
834   RelType Type;
835   if (Sym.isTls())
836     Type = Target->TlsGotRel;
837   else if (!Preemptible && Config->Pic && !isAbsolute(Sym))
838     Type = Target->RelativeRel;
839   else
840     Type = Target->GotRel;
841   In<ELFT>::RelaDyn->addReloc({Type, InX::Got, Off, !Preemptible, &Sym, 0});
842 
843   // REL type relocations don't have addend fields unlike RELAs, and
844   // their addends are stored to the section to which they are applied.
845   // So, store addends if we need to.
846   //
847   // This is ugly -- the difference between REL and RELA should be
848   // handled in a better way. It's a TODO.
849   if (!Config->IsRela)
850     InX::Got->Relocations.push_back({R_ABS, Target->GotRel, Off, 0, &Sym});
851 }
852 
853 // The reason we have to do this early scan is as follows
854 // * To mmap the output file, we need to know the size
855 // * For that, we need to know how many dynamic relocs we will have.
856 // It might be possible to avoid this by outputting the file with write:
857 // * Write the allocated output sections, computing addresses.
858 // * Apply relocations, recording which ones require a dynamic reloc.
859 // * Write the dynamic relocations.
860 // * Write the rest of the file.
861 // This would have some drawbacks. For example, we would only know if .rela.dyn
862 // is needed after applying relocations. If it is, it will go after rw and rx
863 // sections. Given that it is ro, we will need an extra PT_LOAD. This
864 // complicates things for the dynamic linker and means we would have to reserve
865 // space for the extra PT_LOAD even if we end up not using it.
866 template <class ELFT, class RelTy>
867 static void scanRelocs(InputSectionBase &Sec, ArrayRef<RelTy> Rels) {
868   OffsetGetter GetOffset(Sec);
869 
870   for (auto I = Rels.begin(), End = Rels.end(); I != End; ++I) {
871     const RelTy &Rel = *I;
872     SymbolBody &Body = Sec.getFile<ELFT>()->getRelocTargetSym(Rel);
873     RelType Type = Rel.getType(Config->IsMips64EL);
874 
875     // Deal with MIPS oddity.
876     if (Config->MipsN32Abi)
877       Type = getMipsN32RelType(I, End);
878 
879     // Get an offset in an output section this relocation is applied to.
880     uint64_t Offset = GetOffset.get(Rel.r_offset);
881     if (Offset == uint64_t(-1))
882       continue;
883 
884     // Skip if the target symbol is an erroneous undefined symbol.
885     if (maybeReportUndefined<ELFT>(Body, Sec, Rel.r_offset))
886       continue;
887 
888     RelExpr Expr =
889         Target->getRelExpr(Type, Body, Sec.Data.begin() + Rel.r_offset);
890 
891     // Ignore "hint" relocations because they are only markers for relaxation.
892     if (isRelExprOneOf<R_HINT, R_NONE>(Expr))
893       continue;
894 
895     // Handle yet another MIPS-ness.
896     if (isMipsGprel(Type)) {
897       int64_t Addend = computeAddend<ELFT>(Rel, End, Sec, Expr, Body.isLocal());
898       Sec.Relocations.push_back({R_MIPS_GOTREL, Type, Offset, Addend, &Body});
899       continue;
900     }
901 
902     bool Preemptible = Body.IsPreemptible;
903 
904     // Strenghten or relax a PLT access.
905     //
906     // GNU ifunc symbols must be accessed via PLT because their addresses
907     // are determined by runtime.
908     //
909     // On the other hand, if we know that a PLT entry will be resolved within
910     // the same ELF module, we can skip PLT access and directly jump to the
911     // destination function. For example, if we are linking a main exectuable,
912     // all dynamic symbols that can be resolved within the executable will
913     // actually be resolved that way at runtime, because the main exectuable
914     // is always at the beginning of a search list. We can leverage that fact.
915     if (Body.isGnuIFunc())
916       Expr = toPlt(Expr);
917     else if (!Preemptible && Expr == R_GOT_PC && !isAbsoluteValue(Body))
918       Expr =
919           Target->adjustRelaxExpr(Type, Sec.Data.data() + Rel.r_offset, Expr);
920     else if (!Preemptible)
921       Expr = fromPlt(Expr);
922 
923     Expr = adjustExpr<ELFT>(Body, Expr, Type, Sec, Rel.r_offset);
924     if (ErrorCount)
925       continue;
926 
927     // This relocation does not require got entry, but it is relative to got and
928     // needs it to be created. Here we request for that.
929     if (isRelExprOneOf<R_GOTONLY_PC, R_GOTONLY_PC_FROM_END, R_GOTREL,
930                        R_GOTREL_FROM_END, R_PPC_TOC>(Expr))
931       InX::Got->HasGotOffRel = true;
932 
933     // Read an addend.
934     int64_t Addend = computeAddend<ELFT>(Rel, End, Sec, Expr, Body.isLocal());
935 
936     // Process some TLS relocations, including relaxing TLS relocations.
937     // Note that this function does not handle all TLS relocations.
938     if (unsigned Processed =
939             handleTlsRelocation<ELFT>(Type, Body, Sec, Offset, Addend, Expr)) {
940       I += (Processed - 1);
941       continue;
942     }
943 
944     // If a relocation needs PLT, we create PLT and GOTPLT slots for the symbol.
945     if (needsPlt(Expr) && !Body.isInPlt()) {
946       if (Body.isGnuIFunc() && !Preemptible)
947         addPltEntry(InX::Iplt, InX::IgotPlt, In<ELFT>::RelaIplt,
948                     Target->IRelativeRel, Body, true);
949       else
950         addPltEntry(InX::Plt, InX::GotPlt, In<ELFT>::RelaPlt, Target->PltRel,
951                     Body, !Preemptible);
952     }
953 
954     // Create a GOT slot if a relocation needs GOT.
955     if (needsGot(Expr)) {
956       if (Config->EMachine == EM_MIPS) {
957         // MIPS ABI has special rules to process GOT entries and doesn't
958         // require relocation entries for them. A special case is TLS
959         // relocations. In that case dynamic loader applies dynamic
960         // relocations to initialize TLS GOT entries.
961         // See "Global Offset Table" in Chapter 5 in the following document
962         // for detailed description:
963         // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
964         InX::MipsGot->addEntry(Body, Addend, Expr);
965         if (Body.isTls() && Body.IsPreemptible)
966           In<ELFT>::RelaDyn->addReloc({Target->TlsGotRel, InX::MipsGot,
967                                        Body.getGotOffset(), false, &Body, 0});
968       } else if (!Body.isInGot()) {
969         addGotEntry<ELFT>(Body, Preemptible);
970       }
971     }
972 
973     if (!needsPlt(Expr) && !needsGot(Expr) && Body.IsPreemptible) {
974       // We don't know anything about the finaly symbol. Just ask the dynamic
975       // linker to handle the relocation for us.
976       if (!Target->isPicRel(Type))
977         errorOrWarn(
978             "relocation " + toString(Type) +
979             " cannot be used against shared object; recompile with -fPIC" +
980             getLocation<ELFT>(Sec, Body, Offset));
981 
982       In<ELFT>::RelaDyn->addReloc(
983           {Target->getDynRel(Type), &Sec, Offset, false, &Body, Addend});
984 
985       // MIPS ABI turns using of GOT and dynamic relocations inside out.
986       // While regular ABI uses dynamic relocations to fill up GOT entries
987       // MIPS ABI requires dynamic linker to fills up GOT entries using
988       // specially sorted dynamic symbol table. This affects even dynamic
989       // relocations against symbols which do not require GOT entries
990       // creation explicitly, i.e. do not have any GOT-relocations. So if
991       // a preemptible symbol has a dynamic relocation we anyway have
992       // to create a GOT entry for it.
993       // If a non-preemptible symbol has a dynamic relocation against it,
994       // dynamic linker takes it st_value, adds offset and writes down
995       // result of the dynamic relocation. In case of preemptible symbol
996       // dynamic linker performs symbol resolution, writes the symbol value
997       // to the GOT entry and reads the GOT entry when it needs to perform
998       // a dynamic relocation.
999       // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19
1000       if (Config->EMachine == EM_MIPS)
1001         InX::MipsGot->addEntry(Body, Addend, Expr);
1002       continue;
1003     }
1004 
1005     // If the relocation points to something in the file, we can process it.
1006     bool IsConstant =
1007         isStaticLinkTimeConstant<ELFT>(Expr, Type, Body, Sec, Rel.r_offset);
1008 
1009     // The size is not going to change, so we fold it in here.
1010     if (Expr == R_SIZE)
1011       Addend += Body.getSize<ELFT>();
1012 
1013     // If the produced value is a constant, we just remember to write it
1014     // when outputting this section. We also have to do it if the format
1015     // uses Elf_Rel, since in that case the written value is the addend.
1016     if (IsConstant) {
1017       Sec.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
1018       continue;
1019     }
1020 
1021     // If the output being produced is position independent, the final value
1022     // is still not known. In that case we still need some help from the
1023     // dynamic linker. We can however do better than just copying the incoming
1024     // relocation. We can process some of it and and just ask the dynamic
1025     // linker to add the load address.
1026     if (Config->IsRela) {
1027       In<ELFT>::RelaDyn->addReloc(
1028           {Target->RelativeRel, &Sec, Offset, true, &Body, Addend});
1029     } else {
1030       // In REL, addends are stored to the target section.
1031       In<ELFT>::RelaDyn->addReloc(
1032           {Target->RelativeRel, &Sec, Offset, true, &Body, 0});
1033       Sec.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
1034     }
1035   }
1036 }
1037 
1038 template <class ELFT> void elf::scanRelocations(InputSectionBase &S) {
1039   if (S.AreRelocsRela)
1040     scanRelocs<ELFT>(S, S.relas<ELFT>());
1041   else
1042     scanRelocs<ELFT>(S, S.rels<ELFT>());
1043 }
1044 
1045 // Insert the Thunks for OutputSection OS into their designated place
1046 // in the Sections vector, and recalculate the InputSection output section
1047 // offsets.
1048 // This may invalidate any output section offsets stored outside of InputSection
1049 void ThunkCreator::mergeThunks() {
1050   for (auto &KV : ThunkSections) {
1051     std::vector<InputSection *> *ISR = KV.first;
1052     std::vector<ThunkSection *> &Thunks = KV.second;
1053 
1054     // Order Thunks in ascending OutSecOff
1055     auto ThunkCmp = [](const ThunkSection *A, const ThunkSection *B) {
1056       return A->OutSecOff < B->OutSecOff;
1057     };
1058     std::stable_sort(Thunks.begin(), Thunks.end(), ThunkCmp);
1059 
1060     // Merge sorted vectors of Thunks and InputSections by OutSecOff
1061     std::vector<InputSection *> Tmp;
1062     Tmp.reserve(ISR->size() + Thunks.size());
1063     auto MergeCmp = [](const InputSection *A, const InputSection *B) {
1064       // std::merge requires a strict weak ordering.
1065       if (A->OutSecOff < B->OutSecOff)
1066         return true;
1067       if (A->OutSecOff == B->OutSecOff)
1068         // Check if Thunk is immediately before any specific Target InputSection
1069         // for example Mips LA25 Thunks.
1070         if (auto *TA = dyn_cast<ThunkSection>(A))
1071           if (TA && TA->getTargetInputSection() == B)
1072             return true;
1073       return false;
1074     };
1075     std::merge(ISR->begin(), ISR->end(), Thunks.begin(), Thunks.end(),
1076                std::back_inserter(Tmp), MergeCmp);
1077     *ISR = std::move(Tmp);
1078   }
1079 }
1080 
1081 static uint32_t findEndOfFirstNonExec(OutputSection &Cmd) {
1082   for (BaseCommand *Base : Cmd.SectionCommands)
1083     if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
1084       for (auto *IS : ISD->Sections)
1085         if ((IS->Flags & SHF_EXECINSTR) == 0)
1086           return IS->OutSecOff + IS->getSize();
1087   return 0;
1088 }
1089 
1090 ThunkSection *ThunkCreator::getOSThunkSec(OutputSection *OS,
1091                                           std::vector<InputSection *> *ISR) {
1092   if (CurTS == nullptr) {
1093     uint32_t Off = findEndOfFirstNonExec(*OS);
1094     CurTS = addThunkSection(OS, ISR, Off);
1095   }
1096   return CurTS;
1097 }
1098 
1099 // Add a Thunk that needs to be placed in a ThunkSection that immediately
1100 // precedes its Target.
1101 ThunkSection *ThunkCreator::getISThunkSec(InputSection *IS) {
1102   ThunkSection *TS = ThunkedSections.lookup(IS);
1103   if (TS)
1104     return TS;
1105 
1106   // Find InputSectionRange within Target Output Section (TOS) that the
1107   // InputSection (IS) that we need to precede is in.
1108   OutputSection *TOS = IS->getParent();
1109   std::vector<InputSection *> *Range = nullptr;
1110   for (BaseCommand *BC : TOS->SectionCommands)
1111     if (auto *ISD = dyn_cast<InputSectionDescription>(BC)) {
1112       InputSection *first = ISD->Sections.front();
1113       InputSection *last = ISD->Sections.back();
1114       if (IS->OutSecOff >= first->OutSecOff &&
1115           IS->OutSecOff <= last->OutSecOff) {
1116         Range = &ISD->Sections;
1117         break;
1118       }
1119     }
1120   TS = addThunkSection(TOS, Range, IS->OutSecOff);
1121   ThunkedSections[IS] = TS;
1122   return TS;
1123 }
1124 
1125 ThunkSection *ThunkCreator::addThunkSection(OutputSection *OS,
1126                                             std::vector<InputSection *> *ISR,
1127                                             uint64_t Off) {
1128   auto *TS = make<ThunkSection>(OS, Off);
1129   ThunkSections[ISR].push_back(TS);
1130   return TS;
1131 }
1132 
1133 std::pair<Thunk *, bool> ThunkCreator::getThunk(SymbolBody &Body,
1134                                                 RelType Type) {
1135   auto Res = ThunkedSymbols.insert({&Body, std::vector<Thunk *>()});
1136   if (!Res.second) {
1137     // Check existing Thunks for Body to see if they can be reused
1138     for (Thunk *ET : Res.first->second)
1139       if (ET->isCompatibleWith(Type))
1140         return std::make_pair(ET, false);
1141   }
1142   // No existing compatible Thunk in range, create a new one
1143   Thunk *T = addThunk(Type, Body);
1144   Res.first->second.push_back(T);
1145   return std::make_pair(T, true);
1146 }
1147 
1148 // Call Fn on every executable InputSection accessed via the linker script
1149 // InputSectionDescription::Sections.
1150 void ThunkCreator::forEachExecInputSection(
1151     ArrayRef<OutputSection *> OutputSections,
1152     std::function<void(OutputSection *, std::vector<InputSection *> *,
1153                        InputSection *)>
1154         Fn) {
1155   for (OutputSection *OS : OutputSections) {
1156     if (!(OS->Flags & SHF_ALLOC) || !(OS->Flags & SHF_EXECINSTR))
1157       continue;
1158     for (BaseCommand *BC : OS->SectionCommands)
1159       if (auto *ISD = dyn_cast<InputSectionDescription>(BC)) {
1160         CurTS = nullptr;
1161         for (InputSection *IS : ISD->Sections)
1162           Fn(OS, &ISD->Sections, IS);
1163       }
1164   }
1165 }
1166 
1167 // Process all relocations from the InputSections that have been assigned
1168 // to OutputSections and redirect through Thunks if needed.
1169 //
1170 // createThunks must be called after scanRelocs has created the Relocations for
1171 // each InputSection. It must be called before the static symbol table is
1172 // finalized. If any Thunks are added to an OutputSection the output section
1173 // offsets of the InputSections will change.
1174 //
1175 // FIXME: All Thunks are assumed to be in range of the relocation. Range
1176 // extension Thunks are not yet supported.
1177 bool ThunkCreator::createThunks(ArrayRef<OutputSection *> OutputSections) {
1178   if (Pass > 0)
1179     ThunkSections.clear();
1180 
1181   // Create all the Thunks and insert them into synthetic ThunkSections. The
1182   // ThunkSections are later inserted back into the OutputSection.
1183 
1184   // We separate the creation of ThunkSections from the insertion of the
1185   // ThunkSections back into the OutputSection as ThunkSections are not always
1186   // inserted into the same OutputSection as the caller.
1187   forEachExecInputSection(OutputSections, [&](OutputSection *OS,
1188                                               std::vector<InputSection *> *ISR,
1189                                               InputSection *IS) {
1190     for (Relocation &Rel : IS->Relocations) {
1191       SymbolBody &Body = *Rel.Sym;
1192       if (Thunks.find(&Body) != Thunks.end() ||
1193           !Target->needsThunk(Rel.Expr, Rel.Type, IS->File, Body))
1194         continue;
1195       Thunk *T;
1196       bool IsNew;
1197       std::tie(T, IsNew) = getThunk(Body, Rel.Type);
1198       if (IsNew) {
1199         // Find or create a ThunkSection for the new Thunk
1200         ThunkSection *TS;
1201         if (auto *TIS = T->getTargetInputSection())
1202           TS = getISThunkSec(TIS);
1203         else
1204           TS = getOSThunkSec(OS, ISR);
1205         TS->addThunk(T);
1206         Thunks[T->ThunkSym] = T;
1207       }
1208       // Redirect relocation to Thunk, we never go via the PLT to a Thunk
1209       Rel.Sym = T->ThunkSym;
1210       Rel.Expr = fromPlt(Rel.Expr);
1211     }
1212   });
1213   // Merge all created synthetic ThunkSections back into OutputSection
1214   mergeThunks();
1215   ++Pass;
1216   return !ThunkSections.empty();
1217 }
1218 
1219 template void elf::scanRelocations<ELF32LE>(InputSectionBase &);
1220 template void elf::scanRelocations<ELF32BE>(InputSectionBase &);
1221 template void elf::scanRelocations<ELF64LE>(InputSectionBase &);
1222 template void elf::scanRelocations<ELF64BE>(InputSectionBase &);
1223