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 "OutputSections.h"
48 #include "SymbolTable.h"
49 #include "Symbols.h"
50 #include "SyntheticSections.h"
51 #include "Target.h"
52 #include "Thunks.h"
53 #include "lld/Common/Memory.h"
54 #include "lld/Common/Strings.h"
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 static std::string getLocation(InputSectionBase &S, const Symbol &Sym,
73                                uint64_t Off) {
74   std::string Msg =
75       "\n>>> defined in " + toString(Sym.File) + "\n>>> referenced by ";
76   std::string Src = S.getSrcMsg(Sym, Off);
77   if (!Src.empty())
78     Msg += Src + "\n>>>               ";
79   return Msg + S.getObjMsg(Off);
80 }
81 
82 // This function is similar to the `handleTlsRelocation`. MIPS does not
83 // support any relaxations for TLS relocations so by factoring out MIPS
84 // handling in to the separate function we can simplify the code and do not
85 // pollute other `handleTlsRelocation` by MIPS `ifs` statements.
86 // Mips has a custom MipsGotSection that handles the writing of GOT entries
87 // without dynamic relocations.
88 template <class ELFT>
89 static unsigned handleMipsTlsRelocation(RelType Type, Symbol &Sym,
90                                         InputSectionBase &C, uint64_t Offset,
91                                         int64_t Addend, RelExpr Expr) {
92   if (Expr == R_MIPS_TLSLD) {
93     if (InX::MipsGot->addTlsIndex() && Config->Pic)
94       InX::RelaDyn->addReloc(Target->TlsModuleIndexRel, InX::MipsGot,
95                              InX::MipsGot->getTlsIndexOff(), nullptr);
96     C.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
97     return 1;
98   }
99 
100   if (Expr == R_MIPS_TLSGD) {
101     if (InX::MipsGot->addDynTlsEntry(Sym) && Sym.IsPreemptible) {
102       uint64_t Off = InX::MipsGot->getGlobalDynOffset(Sym);
103       InX::RelaDyn->addReloc(Target->TlsModuleIndexRel, InX::MipsGot, Off,
104                              &Sym);
105       if (Sym.IsPreemptible)
106         InX::RelaDyn->addReloc(Target->TlsOffsetRel, InX::MipsGot,
107                                Off + Config->Wordsize, &Sym);
108     }
109     C.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
110     return 1;
111   }
112   return 0;
113 }
114 
115 // This function is similar to the `handleMipsTlsRelocation`. ARM also does not
116 // support any relaxations for TLS relocations. ARM is logically similar to Mips
117 // in how it handles TLS, but Mips uses its own custom GOT which handles some
118 // of the cases that ARM uses GOT relocations for.
119 //
120 // We look for TLS global dynamic and local dynamic relocations, these may
121 // require the generation of a pair of GOT entries that have associated
122 // dynamic relocations. When the results of the dynamic relocations can be
123 // resolved at static link time we do so. This is necessary for static linking
124 // as there will be no dynamic loader to resolve them at load-time.
125 //
126 // The pair of GOT entries created are of the form
127 // GOT[e0] Module Index (Used to find pointer to TLS block at run-time)
128 // GOT[e1] Offset of symbol in TLS block
129 template <class ELFT>
130 static unsigned handleARMTlsRelocation(RelType Type, Symbol &Sym,
131                                        InputSectionBase &C, uint64_t Offset,
132                                        int64_t Addend, RelExpr Expr) {
133   // The Dynamic TLS Module Index Relocation for a symbol defined in an
134   // executable is always 1. If the target Symbol is not preemptible then
135   // we know the offset into the TLS block at static link time.
136   bool NeedDynId = Sym.IsPreemptible || Config->Shared;
137   bool NeedDynOff = Sym.IsPreemptible;
138 
139   auto AddTlsReloc = [&](uint64_t Off, RelType Type, Symbol *Dest, bool Dyn) {
140     if (Dyn)
141       InX::RelaDyn->addReloc(Type, InX::Got, Off, Dest);
142     else
143       InX::Got->Relocations.push_back({R_ABS, Type, Off, 0, Dest});
144   };
145 
146   // Local Dynamic is for access to module local TLS variables, while still
147   // being suitable for being dynamically loaded via dlopen.
148   // GOT[e0] is the module index, with a special value of 0 for the current
149   // module. GOT[e1] is unused. There only needs to be one module index entry.
150   if (Expr == R_TLSLD_PC && InX::Got->addTlsIndex()) {
151     AddTlsReloc(InX::Got->getTlsIndexOff(), Target->TlsModuleIndexRel,
152                 NeedDynId ? nullptr : &Sym, NeedDynId);
153     C.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
154     return 1;
155   }
156 
157   // Global Dynamic is the most general purpose access model. When we know
158   // the module index and offset of symbol in TLS block we can fill these in
159   // using static GOT relocations.
160   if (Expr == R_TLSGD_PC) {
161     if (InX::Got->addDynTlsEntry(Sym)) {
162       uint64_t Off = InX::Got->getGlobalDynOffset(Sym);
163       AddTlsReloc(Off, Target->TlsModuleIndexRel, &Sym, NeedDynId);
164       AddTlsReloc(Off + Config->Wordsize, Target->TlsOffsetRel, &Sym,
165                   NeedDynOff);
166     }
167     C.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
168     return 1;
169   }
170   return 0;
171 }
172 
173 // Returns the number of relocations processed.
174 template <class ELFT>
175 static unsigned
176 handleTlsRelocation(RelType Type, Symbol &Sym, InputSectionBase &C,
177                     typename ELFT::uint Offset, int64_t Addend, RelExpr Expr) {
178   if (!(C.Flags & SHF_ALLOC))
179     return 0;
180 
181   if (!Sym.isTls())
182     return 0;
183 
184   if (Config->EMachine == EM_ARM)
185     return handleARMTlsRelocation<ELFT>(Type, Sym, C, Offset, Addend, Expr);
186   if (Config->EMachine == EM_MIPS)
187     return handleMipsTlsRelocation<ELFT>(Type, Sym, C, Offset, Addend, Expr);
188 
189   if (isRelExprOneOf<R_TLSDESC, R_TLSDESC_PAGE, R_TLSDESC_CALL>(Expr) &&
190       Config->Shared) {
191     if (InX::Got->addDynTlsEntry(Sym)) {
192       uint64_t Off = InX::Got->getGlobalDynOffset(Sym);
193       InX::RelaDyn->addReloc(
194           {Target->TlsDescRel, InX::Got, Off, !Sym.IsPreemptible, &Sym, 0});
195     }
196     if (Expr != R_TLSDESC_CALL)
197       C.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
198     return 1;
199   }
200 
201   if (isRelExprOneOf<R_TLSLD_PC, R_TLSLD>(Expr)) {
202     // Local-Dynamic relocs can be relaxed to Local-Exec.
203     if (!Config->Shared) {
204       C.Relocations.push_back(
205           {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Sym});
206       return 2;
207     }
208     if (InX::Got->addTlsIndex())
209       InX::RelaDyn->addReloc(Target->TlsModuleIndexRel, InX::Got,
210                              InX::Got->getTlsIndexOff(), nullptr);
211     C.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
212     return 1;
213   }
214 
215   // Local-Dynamic relocs can be relaxed to Local-Exec.
216   if (isRelExprOneOf<R_ABS, R_TLSLD, R_TLSLD_PC>(Expr) && !Config->Shared) {
217     C.Relocations.push_back({R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Sym});
218     return 1;
219   }
220 
221   if (isRelExprOneOf<R_TLSDESC, R_TLSDESC_PAGE, R_TLSDESC_CALL, R_TLSGD,
222                      R_TLSGD_GOT, R_TLSGD_PC>(Expr)) {
223     if (Config->Shared) {
224       if (InX::Got->addDynTlsEntry(Sym)) {
225         uint64_t Off = InX::Got->getGlobalDynOffset(Sym);
226         InX::RelaDyn->addReloc(Target->TlsModuleIndexRel, InX::Got, Off, &Sym);
227 
228         // If the symbol is preemptible we need the dynamic linker to write
229         // the offset too.
230         uint64_t OffsetOff = Off + Config->Wordsize;
231         if (Sym.IsPreemptible)
232           InX::RelaDyn->addReloc(Target->TlsOffsetRel, InX::Got, OffsetOff,
233                                  &Sym);
234         else
235           InX::Got->Relocations.push_back(
236               {R_ABS, Target->TlsOffsetRel, OffsetOff, 0, &Sym});
237       }
238       C.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
239       return 1;
240     }
241 
242     // Global-Dynamic relocs can be relaxed to Initial-Exec or Local-Exec
243     // depending on the symbol being locally defined or not.
244     if (Sym.IsPreemptible) {
245       C.Relocations.push_back(
246           {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_IE), Type,
247            Offset, Addend, &Sym});
248       if (!Sym.isInGot()) {
249         InX::Got->addEntry(Sym);
250         InX::RelaDyn->addReloc(Target->TlsGotRel, InX::Got, Sym.getGotOffset(),
251                                &Sym);
252       }
253     } else {
254       C.Relocations.push_back(
255           {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_LE), Type,
256            Offset, Addend, &Sym});
257     }
258     return Target->TlsGdRelaxSkip;
259   }
260 
261   // Initial-Exec relocs can be relaxed to Local-Exec if the symbol is locally
262   // defined.
263   if (isRelExprOneOf<R_GOT, R_GOT_FROM_END, R_GOT_PC, R_GOT_PAGE_PC>(Expr) &&
264       !Config->Shared && !Sym.IsPreemptible) {
265     C.Relocations.push_back({R_RELAX_TLS_IE_TO_LE, Type, Offset, Addend, &Sym});
266     return 1;
267   }
268 
269   if (Expr == R_TLSDESC_CALL)
270     return 1;
271   return 0;
272 }
273 
274 static RelType getMipsPairType(RelType Type, bool IsLocal) {
275   switch (Type) {
276   case R_MIPS_HI16:
277     return R_MIPS_LO16;
278   case R_MIPS_GOT16:
279     // In case of global symbol, the R_MIPS_GOT16 relocation does not
280     // have a pair. Each global symbol has a unique entry in the GOT
281     // and a corresponding instruction with help of the R_MIPS_GOT16
282     // relocation loads an address of the symbol. In case of local
283     // symbol, the R_MIPS_GOT16 relocation creates a GOT entry to hold
284     // the high 16 bits of the symbol's value. A paired R_MIPS_LO16
285     // relocations handle low 16 bits of the address. That allows
286     // to allocate only one GOT entry for every 64 KBytes of local data.
287     return IsLocal ? R_MIPS_LO16 : R_MIPS_NONE;
288   case R_MICROMIPS_GOT16:
289     return IsLocal ? R_MICROMIPS_LO16 : R_MIPS_NONE;
290   case R_MIPS_PCHI16:
291     return R_MIPS_PCLO16;
292   case R_MICROMIPS_HI16:
293     return R_MICROMIPS_LO16;
294   default:
295     return R_MIPS_NONE;
296   }
297 }
298 
299 // True if non-preemptable symbol always has the same value regardless of where
300 // the DSO is loaded.
301 static bool isAbsolute(const Symbol &Sym) {
302   if (Sym.isUndefWeak())
303     return true;
304   if (const auto *DR = dyn_cast<Defined>(&Sym))
305     return DR->Section == nullptr; // Absolute symbol.
306   return false;
307 }
308 
309 static bool isAbsoluteValue(const Symbol &Sym) {
310   return isAbsolute(Sym) || Sym.isTls();
311 }
312 
313 // Returns true if Expr refers a PLT entry.
314 static bool needsPlt(RelExpr Expr) {
315   return isRelExprOneOf<R_PLT_PC, R_PPC_CALL_PLT, R_PLT, R_PLT_PAGE_PC>(Expr);
316 }
317 
318 // Returns true if Expr refers a GOT entry. Note that this function
319 // returns false for TLS variables even though they need GOT, because
320 // TLS variables uses GOT differently than the regular variables.
321 static bool needsGot(RelExpr Expr) {
322   return isRelExprOneOf<R_GOT, R_GOT_OFF, R_MIPS_GOT_LOCAL_PAGE, R_MIPS_GOT_OFF,
323                         R_MIPS_GOT_OFF32, R_GOT_PAGE_PC, R_GOT_PC,
324                         R_GOT_FROM_END>(Expr);
325 }
326 
327 // True if this expression is of the form Sym - X, where X is a position in the
328 // file (PC, or GOT for example).
329 static bool isRelExpr(RelExpr Expr) {
330   return isRelExprOneOf<R_PC, R_GOTREL, R_GOTREL_FROM_END, R_MIPS_GOTREL,
331                         R_PPC_CALL, R_PPC_CALL_PLT, R_PAGE_PC,
332                         R_RELAX_GOT_PC>(Expr);
333 }
334 
335 // Returns true if a given relocation can be computed at link-time.
336 //
337 // For instance, we know the offset from a relocation to its target at
338 // link-time if the relocation is PC-relative and refers a
339 // non-interposable function in the same executable. This function
340 // will return true for such relocation.
341 //
342 // If this function returns false, that means we need to emit a
343 // dynamic relocation so that the relocation will be fixed at load-time.
344 static bool isStaticLinkTimeConstant(RelExpr E, RelType Type, const Symbol &Sym,
345                                      InputSectionBase &S, uint64_t RelOff) {
346   // These expressions always compute a constant
347   if (isRelExprOneOf<R_GOT_FROM_END, R_GOT_OFF, R_MIPS_GOT_LOCAL_PAGE,
348                      R_MIPS_GOTREL, R_MIPS_GOT_OFF, R_MIPS_GOT_OFF32,
349                      R_MIPS_GOT_GP_PC, R_MIPS_TLSGD, R_GOT_PAGE_PC, R_GOT_PC,
350                      R_GOTONLY_PC, R_GOTONLY_PC_FROM_END, R_PLT_PC, R_TLSGD_GOT,
351                      R_TLSGD_PC, R_TLSGD, R_PPC_CALL_PLT, R_TLSDESC_CALL,
352                      R_TLSDESC_PAGE, R_HINT>(E))
353     return true;
354 
355   // These never do, except if the entire file is position dependent or if
356   // only the low bits are used.
357   if (E == R_GOT || E == R_PLT || E == R_TLSDESC)
358     return Target->usesOnlyLowPageBits(Type) || !Config->Pic;
359 
360   if (Sym.IsPreemptible)
361     return false;
362   if (!Config->Pic)
363     return true;
364 
365   // The size of a non preemptible symbol is a constant.
366   if (E == R_SIZE)
367     return true;
368 
369   // For the target and the relocation, we want to know if they are
370   // absolute or relative.
371   bool AbsVal = isAbsoluteValue(Sym);
372   bool RelE = isRelExpr(E);
373   if (AbsVal && !RelE)
374     return true;
375   if (!AbsVal && RelE)
376     return true;
377   if (!AbsVal && !RelE)
378     return Target->usesOnlyLowPageBits(Type);
379 
380   // Relative relocation to an absolute value. This is normally unrepresentable,
381   // but if the relocation refers to a weak undefined symbol, we allow it to
382   // resolve to the image base. This is a little strange, but it allows us to
383   // link function calls to such symbols. Normally such a call will be guarded
384   // with a comparison, which will load a zero from the GOT.
385   // Another special case is MIPS _gp_disp symbol which represents offset
386   // between start of a function and '_gp' value and defined as absolute just
387   // to simplify the code.
388   assert(AbsVal && RelE);
389   if (Sym.isUndefWeak())
390     return true;
391 
392   error("relocation " + toString(Type) + " cannot refer to absolute symbol: " +
393         toString(Sym) + getLocation(S, Sym, RelOff));
394   return true;
395 }
396 
397 static RelExpr toPlt(RelExpr Expr) {
398   switch (Expr) {
399   case R_PPC_CALL:
400     return R_PPC_CALL_PLT;
401   case R_PC:
402     return R_PLT_PC;
403   case R_PAGE_PC:
404     return R_PLT_PAGE_PC;
405   case R_ABS:
406     return R_PLT;
407   default:
408     return Expr;
409   }
410 }
411 
412 static RelExpr fromPlt(RelExpr Expr) {
413   // We decided not to use a plt. Optimize a reference to the plt to a
414   // reference to the symbol itself.
415   switch (Expr) {
416   case R_PLT_PC:
417     return R_PC;
418   case R_PPC_CALL_PLT:
419     return R_PPC_CALL;
420   case R_PLT:
421     return R_ABS;
422   default:
423     return Expr;
424   }
425 }
426 
427 // Returns true if a given shared symbol is in a read-only segment in a DSO.
428 template <class ELFT> static bool isReadOnly(SharedSymbol &SS) {
429   typedef typename ELFT::Phdr Elf_Phdr;
430 
431   // Determine if the symbol is read-only by scanning the DSO's program headers.
432   const SharedFile<ELFT> &File = SS.getFile<ELFT>();
433   for (const Elf_Phdr &Phdr : check(File.getObj().program_headers()))
434     if ((Phdr.p_type == ELF::PT_LOAD || Phdr.p_type == ELF::PT_GNU_RELRO) &&
435         !(Phdr.p_flags & ELF::PF_W) && SS.Value >= Phdr.p_vaddr &&
436         SS.Value < Phdr.p_vaddr + Phdr.p_memsz)
437       return true;
438   return false;
439 }
440 
441 // Returns symbols at the same offset as a given symbol, including SS itself.
442 //
443 // If two or more symbols are at the same offset, and at least one of
444 // them are copied by a copy relocation, all of them need to be copied.
445 // Otherwise, they would refer different places at runtime.
446 template <class ELFT>
447 static std::vector<SharedSymbol *> getSymbolsAt(SharedSymbol &SS) {
448   typedef typename ELFT::Sym Elf_Sym;
449 
450   SharedFile<ELFT> &File = SS.getFile<ELFT>();
451 
452   std::vector<SharedSymbol *> Ret;
453   for (const Elf_Sym &S : File.getGlobalELFSyms()) {
454     if (S.st_shndx == SHN_UNDEF || S.st_shndx == SHN_ABS ||
455         S.st_value != SS.Value)
456       continue;
457     StringRef Name = check(S.getName(File.getStringTable()));
458     Symbol *Sym = Symtab->find(Name);
459     if (auto *Alias = dyn_cast_or_null<SharedSymbol>(Sym))
460       Ret.push_back(Alias);
461   }
462   return Ret;
463 }
464 
465 // When a symbol is copy relocated or we create a canonical plt entry, it is
466 // effectively a defined symbol. In the case of copy relocation the symbol is
467 // in .bss and in the case of a canonical plt entry it is in .plt. This function
468 // replaces the existing symbol with a Defined pointing to the appropriate
469 // location.
470 static void replaceWithDefined(Symbol &Sym, SectionBase *Sec, uint64_t Value,
471                                uint64_t Size) {
472   Symbol Old = Sym;
473   replaceSymbol<Defined>(&Sym, Sym.File, Sym.getName(), Sym.Binding,
474                          Sym.StOther, Sym.Type, Value, Size, Sec);
475   Sym.PltIndex = Old.PltIndex;
476   Sym.GotIndex = Old.GotIndex;
477   Sym.VerdefIndex = Old.VerdefIndex;
478   Sym.IsInGlobalMipsGot = Old.IsInGlobalMipsGot;
479   Sym.IsPreemptible = true;
480   Sym.ExportDynamic = true;
481   Sym.IsUsedInRegularObj = true;
482   Sym.Used = true;
483 }
484 
485 // Reserve space in .bss or .bss.rel.ro for copy relocation.
486 //
487 // The copy relocation is pretty much a hack. If you use a copy relocation
488 // in your program, not only the symbol name but the symbol's size, RW/RO
489 // bit and alignment become part of the ABI. In addition to that, if the
490 // symbol has aliases, the aliases become part of the ABI. That's subtle,
491 // but if you violate that implicit ABI, that can cause very counter-
492 // intuitive consequences.
493 //
494 // So, what is the copy relocation? It's for linking non-position
495 // independent code to DSOs. In an ideal world, all references to data
496 // exported by DSOs should go indirectly through GOT. But if object files
497 // are compiled as non-PIC, all data references are direct. There is no
498 // way for the linker to transform the code to use GOT, as machine
499 // instructions are already set in stone in object files. This is where
500 // the copy relocation takes a role.
501 //
502 // A copy relocation instructs the dynamic linker to copy data from a DSO
503 // to a specified address (which is usually in .bss) at load-time. If the
504 // static linker (that's us) finds a direct data reference to a DSO
505 // symbol, it creates a copy relocation, so that the symbol can be
506 // resolved as if it were in .bss rather than in a DSO.
507 //
508 // As you can see in this function, we create a copy relocation for the
509 // dynamic linker, and the relocation contains not only symbol name but
510 // various other informtion about the symbol. So, such attributes become a
511 // part of the ABI.
512 //
513 // Note for application developers: I can give you a piece of advice if
514 // you are writing a shared library. You probably should export only
515 // functions from your library. You shouldn't export variables.
516 //
517 // As an example what can happen when you export variables without knowing
518 // the semantics of copy relocations, assume that you have an exported
519 // variable of type T. It is an ABI-breaking change to add new members at
520 // end of T even though doing that doesn't change the layout of the
521 // existing members. That's because the space for the new members are not
522 // reserved in .bss unless you recompile the main program. That means they
523 // are likely to overlap with other data that happens to be laid out next
524 // to the variable in .bss. This kind of issue is sometimes very hard to
525 // debug. What's a solution? Instead of exporting a varaible V from a DSO,
526 // define an accessor getV().
527 template <class ELFT> static void addCopyRelSymbol(SharedSymbol &SS) {
528   // Copy relocation against zero-sized symbol doesn't make sense.
529   uint64_t SymSize = SS.getSize();
530   if (SymSize == 0)
531     fatal("cannot create a copy relocation for symbol " + toString(SS));
532 
533   // See if this symbol is in a read-only segment. If so, preserve the symbol's
534   // memory protection by reserving space in the .bss.rel.ro section.
535   bool IsReadOnly = isReadOnly<ELFT>(SS);
536   BssSection *Sec = make<BssSection>(IsReadOnly ? ".bss.rel.ro" : ".bss",
537                                      SymSize, SS.Alignment);
538   if (IsReadOnly)
539     InX::BssRelRo->getParent()->addSection(Sec);
540   else
541     InX::Bss->getParent()->addSection(Sec);
542 
543   // Look through the DSO's dynamic symbol table for aliases and create a
544   // dynamic symbol for each one. This causes the copy relocation to correctly
545   // interpose any aliases.
546   for (SharedSymbol *Sym : getSymbolsAt<ELFT>(SS))
547     replaceWithDefined(*Sym, Sec, 0, Sym->Size);
548 
549   InX::RelaDyn->addReloc(Target->CopyRel, Sec, 0, &SS);
550 }
551 
552 // MIPS has an odd notion of "paired" relocations to calculate addends.
553 // For example, if a relocation is of R_MIPS_HI16, there must be a
554 // R_MIPS_LO16 relocation after that, and an addend is calculated using
555 // the two relocations.
556 template <class ELFT, class RelTy>
557 static int64_t computeMipsAddend(const RelTy &Rel, const RelTy *End,
558                                  InputSectionBase &Sec, RelExpr Expr,
559                                  bool IsLocal) {
560   if (Expr == R_MIPS_GOTREL && IsLocal)
561     return Sec.getFile<ELFT>()->MipsGp0;
562 
563   // The ABI says that the paired relocation is used only for REL.
564   // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
565   if (RelTy::IsRela)
566     return 0;
567 
568   RelType Type = Rel.getType(Config->IsMips64EL);
569   uint32_t PairTy = getMipsPairType(Type, IsLocal);
570   if (PairTy == R_MIPS_NONE)
571     return 0;
572 
573   const uint8_t *Buf = Sec.Data.data();
574   uint32_t SymIndex = Rel.getSymbol(Config->IsMips64EL);
575 
576   // To make things worse, paired relocations might not be contiguous in
577   // the relocation table, so we need to do linear search. *sigh*
578   for (const RelTy *RI = &Rel; RI != End; ++RI)
579     if (RI->getType(Config->IsMips64EL) == PairTy &&
580         RI->getSymbol(Config->IsMips64EL) == SymIndex)
581       return Target->getImplicitAddend(Buf + RI->r_offset, PairTy);
582 
583   warn("can't find matching " + toString(PairTy) + " relocation for " +
584        toString(Type));
585   return 0;
586 }
587 
588 // Returns an addend of a given relocation. If it is RELA, an addend
589 // is in a relocation itself. If it is REL, we need to read it from an
590 // input section.
591 template <class ELFT, class RelTy>
592 static int64_t computeAddend(const RelTy &Rel, const RelTy *End,
593                              InputSectionBase &Sec, RelExpr Expr,
594                              bool IsLocal) {
595   int64_t Addend;
596   RelType Type = Rel.getType(Config->IsMips64EL);
597 
598   if (RelTy::IsRela) {
599     Addend = getAddend<ELFT>(Rel);
600   } else {
601     const uint8_t *Buf = Sec.Data.data();
602     Addend = Target->getImplicitAddend(Buf + Rel.r_offset, Type);
603   }
604 
605   if (Config->EMachine == EM_PPC64 && Config->Pic && Type == R_PPC64_TOC)
606     Addend += getPPC64TocBase();
607   if (Config->EMachine == EM_MIPS)
608     Addend += computeMipsAddend<ELFT>(Rel, End, Sec, Expr, IsLocal);
609 
610   return Addend;
611 }
612 
613 // Report an undefined symbol if necessary.
614 // Returns true if this function printed out an error message.
615 static bool maybeReportUndefined(Symbol &Sym, InputSectionBase &Sec,
616                                  uint64_t Offset) {
617   if (Config->UnresolvedSymbols == UnresolvedPolicy::IgnoreAll)
618     return false;
619 
620   if (Sym.isLocal() || !Sym.isUndefined() || Sym.isWeak())
621     return false;
622 
623   bool CanBeExternal =
624       Sym.computeBinding() != STB_LOCAL && Sym.Visibility == STV_DEFAULT;
625   if (Config->UnresolvedSymbols == UnresolvedPolicy::Ignore && CanBeExternal)
626     return false;
627 
628   std::string Msg =
629       "undefined symbol: " + toString(Sym) + "\n>>> referenced by ";
630 
631   std::string Src = Sec.getSrcMsg(Sym, Offset);
632   if (!Src.empty())
633     Msg += Src + "\n>>>               ";
634   Msg += Sec.getObjMsg(Offset);
635 
636   if ((Config->UnresolvedSymbols == UnresolvedPolicy::Warn && CanBeExternal) ||
637       Config->NoinhibitExec) {
638     warn(Msg);
639     return false;
640   }
641 
642   error(Msg);
643   return true;
644 }
645 
646 // MIPS N32 ABI treats series of successive relocations with the same offset
647 // as a single relocation. The similar approach used by N64 ABI, but this ABI
648 // packs all relocations into the single relocation record. Here we emulate
649 // this for the N32 ABI. Iterate over relocation with the same offset and put
650 // theirs types into the single bit-set.
651 template <class RelTy> static RelType getMipsN32RelType(RelTy *&Rel, RelTy *End) {
652   RelType Type = 0;
653   uint64_t Offset = Rel->r_offset;
654 
655   int N = 0;
656   while (Rel != End && Rel->r_offset == Offset)
657     Type |= (Rel++)->getType(Config->IsMips64EL) << (8 * N++);
658   return Type;
659 }
660 
661 // .eh_frame sections are mergeable input sections, so their input
662 // offsets are not linearly mapped to output section. For each input
663 // offset, we need to find a section piece containing the offset and
664 // add the piece's base address to the input offset to compute the
665 // output offset. That isn't cheap.
666 //
667 // This class is to speed up the offset computation. When we process
668 // relocations, we access offsets in the monotonically increasing
669 // order. So we can optimize for that access pattern.
670 //
671 // For sections other than .eh_frame, this class doesn't do anything.
672 namespace {
673 class OffsetGetter {
674 public:
675   explicit OffsetGetter(InputSectionBase &Sec) {
676     if (auto *Eh = dyn_cast<EhInputSection>(&Sec))
677       Pieces = Eh->Pieces;
678   }
679 
680   // Translates offsets in input sections to offsets in output sections.
681   // Given offset must increase monotonically. We assume that Piece is
682   // sorted by InputOff.
683   uint64_t get(uint64_t Off) {
684     if (Pieces.empty())
685       return Off;
686 
687     while (I != Pieces.size() && Pieces[I].InputOff + Pieces[I].Size <= Off)
688       ++I;
689     if (I == Pieces.size())
690       return Off;
691 
692     // Pieces must be contiguous, so there must be no holes in between.
693     assert(Pieces[I].InputOff <= Off && "Relocation not in any piece");
694 
695     // Offset -1 means that the piece is dead (i.e. garbage collected).
696     if (Pieces[I].OutputOff == -1)
697       return -1;
698     return Pieces[I].OutputOff + Off - Pieces[I].InputOff;
699   }
700 
701 private:
702   ArrayRef<EhSectionPiece> Pieces;
703   size_t I = 0;
704 };
705 } // namespace
706 
707 template <class ELFT, class GotPltSection>
708 static void addPltEntry(PltSection *Plt, GotPltSection *GotPlt,
709                         RelocationBaseSection *Rel, RelType Type, Symbol &Sym) {
710   Plt->addEntry<ELFT>(Sym);
711   GotPlt->addEntry(Sym);
712   Rel->addReloc(
713       {Type, GotPlt, Sym.getGotPltOffset(), !Sym.IsPreemptible, &Sym, 0});
714 }
715 
716 template <class ELFT> static void addGotEntry(Symbol &Sym) {
717   InX::Got->addEntry(Sym);
718 
719   RelExpr Expr = Sym.isTls() ? R_TLS : R_ABS;
720   uint64_t Off = Sym.getGotOffset();
721 
722   // If a GOT slot value can be calculated at link-time, which is now,
723   // we can just fill that out.
724   //
725   // (We don't actually write a value to a GOT slot right now, but we
726   // add a static relocation to a Relocations vector so that
727   // InputSection::relocate will do the work for us. We may be able
728   // to just write a value now, but it is a TODO.)
729   bool IsLinkTimeConstant =
730       !Sym.IsPreemptible && (!Config->Pic || isAbsolute(Sym));
731   if (IsLinkTimeConstant) {
732     InX::Got->Relocations.push_back({Expr, Target->GotRel, Off, 0, &Sym});
733     return;
734   }
735 
736   // Otherwise, we emit a dynamic relocation to .rel[a].dyn so that
737   // the GOT slot will be fixed at load-time.
738   RelType Type;
739   if (Sym.isTls())
740     Type = Target->TlsGotRel;
741   else if (!Sym.IsPreemptible && Config->Pic && !isAbsolute(Sym))
742     Type = Target->RelativeRel;
743   else
744     Type = Target->GotRel;
745   InX::RelaDyn->addReloc(Type, InX::Got, Off, &Sym, 0,
746                          Sym.IsPreemptible ? R_ADDEND : R_ABS, Target->GotRel);
747 }
748 
749 // Return true if we can define a symbol in the executable that
750 // contains the value/function of a symbol defined in a shared
751 // library.
752 static bool canDefineSymbolInExecutable(Symbol &Sym) {
753   // If the symbol has default visibility the symbol defined in the
754   // executable will preempt it.
755   // Note that we want the visibility of the shared symbol itself, not
756   // the visibility of the symbol in the output file we are producing. That is
757   // why we use Sym.StOther.
758   if ((Sym.StOther & 0x3) == STV_DEFAULT)
759     return true;
760 
761   // If we are allowed to break address equality of functions, defining
762   // a plt entry will allow the program to call the function in the
763   // .so, but the .so and the executable will no agree on the address
764   // of the function. Similar logic for objects.
765   return ((Sym.isFunc() && Config->IgnoreFunctionAddressEquality) ||
766           (Sym.isObject() && Config->IgnoreDataAddressEquality));
767 }
768 
769 // The reason we have to do this early scan is as follows
770 // * To mmap the output file, we need to know the size
771 // * For that, we need to know how many dynamic relocs we will have.
772 // It might be possible to avoid this by outputting the file with write:
773 // * Write the allocated output sections, computing addresses.
774 // * Apply relocations, recording which ones require a dynamic reloc.
775 // * Write the dynamic relocations.
776 // * Write the rest of the file.
777 // This would have some drawbacks. For example, we would only know if .rela.dyn
778 // is needed after applying relocations. If it is, it will go after rw and rx
779 // sections. Given that it is ro, we will need an extra PT_LOAD. This
780 // complicates things for the dynamic linker and means we would have to reserve
781 // space for the extra PT_LOAD even if we end up not using it.
782 template <class ELFT, class RelTy>
783 static void processRelocAux(InputSectionBase &Sec, RelExpr Expr, RelType Type,
784                             uint64_t Offset, Symbol &Sym, const RelTy &Rel,
785                             int64_t Addend) {
786   if (isStaticLinkTimeConstant(Expr, Type, Sym, Sec, Offset)) {
787     Sec.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
788     return;
789   }
790   bool CanWrite = (Sec.Flags & SHF_WRITE) || !Config->ZText;
791   if (CanWrite) {
792     // R_GOT refers to a position in the got, even if the symbol is preemptible.
793     bool IsPreemptibleValue = Sym.IsPreemptible && Expr != R_GOT;
794 
795     if (!IsPreemptibleValue) {
796       InX::RelaDyn->addReloc(Target->RelativeRel, &Sec, Offset, &Sym, Addend,
797                              Expr, Type);
798       return;
799     } else if (RelType Rel = Target->getDynRel(Type)) {
800       InX::RelaDyn->addReloc(Rel, &Sec, Offset, &Sym, Addend, R_ADDEND, Type);
801 
802       // MIPS ABI turns using of GOT and dynamic relocations inside out.
803       // While regular ABI uses dynamic relocations to fill up GOT entries
804       // MIPS ABI requires dynamic linker to fills up GOT entries using
805       // specially sorted dynamic symbol table. This affects even dynamic
806       // relocations against symbols which do not require GOT entries
807       // creation explicitly, i.e. do not have any GOT-relocations. So if
808       // a preemptible symbol has a dynamic relocation we anyway have
809       // to create a GOT entry for it.
810       // If a non-preemptible symbol has a dynamic relocation against it,
811       // dynamic linker takes it st_value, adds offset and writes down
812       // result of the dynamic relocation. In case of preemptible symbol
813       // dynamic linker performs symbol resolution, writes the symbol value
814       // to the GOT entry and reads the GOT entry when it needs to perform
815       // a dynamic relocation.
816       // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19
817       if (Config->EMachine == EM_MIPS)
818         InX::MipsGot->addEntry(Sym, Addend, Expr);
819       return;
820     }
821   }
822 
823   // If the relocation is to a weak undef, and we are producing
824   // executable, give up on it and produce a non preemptible 0.
825   if (!Config->Shared && Sym.isUndefWeak()) {
826     Sec.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
827     return;
828   }
829 
830   if (!CanWrite && (Config->Pic && !isRelExpr(Expr))) {
831     error(
832         "can't create dynamic relocation " + toString(Type) + " against " +
833         (Sym.getName().empty() ? "local symbol" : "symbol: " + toString(Sym)) +
834         " in readonly segment; recompile object files with -fPIC "
835         "or pass '-Wl,-z,notext' to allow text relocations in the output" +
836         getLocation(Sec, Sym, Offset));
837     return;
838   }
839 
840   // Copy relocations are only possible if we are creating an executable.
841   if (Config->Shared) {
842     errorOrWarn("relocation " + toString(Type) +
843                 " cannot be used against symbol " + toString(Sym) +
844                 "; recompile with -fPIC" + getLocation(Sec, Sym, Offset));
845     return;
846   }
847 
848   // If the symbol is undefined we already reported any relevant errors.
849   if (Sym.isUndefined())
850     return;
851 
852   if (!canDefineSymbolInExecutable(Sym)) {
853     error("cannot preempt symbol: " + toString(Sym) +
854           getLocation(Sec, Sym, Offset));
855     return;
856   }
857 
858   if (Sym.isObject()) {
859     // Produce a copy relocation.
860     if (auto *SS = dyn_cast<SharedSymbol>(&Sym)) {
861       if (!Config->ZCopyreloc)
862         error("unresolvable relocation " + toString(Type) +
863               " against symbol '" + toString(*SS) +
864               "'; recompile with -fPIC or remove '-z nocopyreloc'" +
865               getLocation(Sec, Sym, Offset));
866       addCopyRelSymbol<ELFT>(*SS);
867     }
868     Sec.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
869     return;
870   }
871 
872   if (Sym.isFunc()) {
873     // This handles a non PIC program call to function in a shared library. In
874     // an ideal world, we could just report an error saying the relocation can
875     // overflow at runtime. In the real world with glibc, crt1.o has a
876     // R_X86_64_PC32 pointing to libc.so.
877     //
878     // The general idea on how to handle such cases is to create a PLT entry and
879     // use that as the function value.
880     //
881     // For the static linking part, we just return a plt expr and everything
882     // else will use the PLT entry as the address.
883     //
884     // The remaining problem is making sure pointer equality still works. We
885     // need the help of the dynamic linker for that. We let it know that we have
886     // a direct reference to a so symbol by creating an undefined symbol with a
887     // non zero st_value. Seeing that, the dynamic linker resolves the symbol to
888     // the value of the symbol we created. This is true even for got entries, so
889     // pointer equality is maintained. To avoid an infinite loop, the only entry
890     // that points to the real function is a dedicated got entry used by the
891     // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT,
892     // R_386_JMP_SLOT, etc).
893 
894     // For position independent executable on i386, the plt entry requires ebx
895     // to be set. This causes two problems:
896     // * If some code has a direct reference to a function, it was probably
897     //   compiled without -fPIE/-fPIC and doesn't maintain ebx.
898     // * If a library definition gets preempted to the executable, it will have
899     //   the wrong ebx value.
900     if (Config->Pie && Config->EMachine == EM_386)
901       errorOrWarn("symbol '" + toString(Sym) +
902                   "' cannot be preempted; recompile with -fPIE" +
903                   getLocation(Sec, Sym, Offset));
904     if (!Sym.isInPlt())
905       addPltEntry<ELFT>(InX::Plt, InX::GotPlt, InX::RelaPlt, Target->PltRel,
906                         Sym);
907     if (!Sym.isDefined())
908       replaceWithDefined(Sym, InX::Plt, Sym.getPltOffset(), 0);
909     Sym.NeedsPltAddr = true;
910     Sec.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
911     return;
912   }
913 
914   errorOrWarn("symbol '" + toString(Sym) + "' has no type" +
915               getLocation(Sec, Sym, Offset));
916 }
917 
918 template <class ELFT, class RelTy>
919 static void scanReloc(InputSectionBase &Sec, OffsetGetter &GetOffset, RelTy *&I,
920                       RelTy *End) {
921   const RelTy &Rel = *I;
922   Symbol &Sym = Sec.getFile<ELFT>()->getRelocTargetSym(Rel);
923   RelType Type;
924 
925   // Deal with MIPS oddity.
926   if (Config->MipsN32Abi) {
927     Type = getMipsN32RelType(I, End);
928   } else {
929     Type = Rel.getType(Config->IsMips64EL);
930     ++I;
931   }
932 
933   // Get an offset in an output section this relocation is applied to.
934   uint64_t Offset = GetOffset.get(Rel.r_offset);
935   if (Offset == uint64_t(-1))
936     return;
937 
938   // Skip if the target symbol is an erroneous undefined symbol.
939   if (maybeReportUndefined(Sym, Sec, Rel.r_offset))
940     return;
941 
942   const uint8_t *RelocatedAddr = Sec.Data.begin() + Rel.r_offset;
943   RelExpr Expr = Target->getRelExpr(Type, Sym, RelocatedAddr);
944 
945   // Ignore "hint" relocations because they are only markers for relaxation.
946   if (isRelExprOneOf<R_HINT, R_NONE>(Expr))
947     return;
948 
949   // Strenghten or relax relocations.
950   //
951   // GNU ifunc symbols must be accessed via PLT because their addresses
952   // are determined by runtime.
953   //
954   // On the other hand, if we know that a PLT entry will be resolved within
955   // the same ELF module, we can skip PLT access and directly jump to the
956   // destination function. For example, if we are linking a main exectuable,
957   // all dynamic symbols that can be resolved within the executable will
958   // actually be resolved that way at runtime, because the main exectuable
959   // is always at the beginning of a search list. We can leverage that fact.
960   if (Sym.isGnuIFunc())
961     Expr = toPlt(Expr);
962   else if (!Sym.IsPreemptible && Expr == R_GOT_PC && !isAbsoluteValue(Sym))
963     Expr = Target->adjustRelaxExpr(Type, RelocatedAddr, Expr);
964   else if (!Sym.IsPreemptible)
965     Expr = fromPlt(Expr);
966 
967   // This relocation does not require got entry, but it is relative to got and
968   // needs it to be created. Here we request for that.
969   if (isRelExprOneOf<R_GOTONLY_PC, R_GOTONLY_PC_FROM_END, R_GOTREL,
970                      R_GOTREL_FROM_END, R_PPC_TOC>(Expr))
971     InX::Got->HasGotOffRel = true;
972 
973   // Read an addend.
974   int64_t Addend = computeAddend<ELFT>(Rel, End, Sec, Expr, Sym.isLocal());
975 
976   // Process some TLS relocations, including relaxing TLS relocations.
977   // Note that this function does not handle all TLS relocations.
978   if (unsigned Processed =
979           handleTlsRelocation<ELFT>(Type, Sym, Sec, Offset, Addend, Expr)) {
980     I += (Processed - 1);
981     return;
982   }
983 
984   // If a relocation needs PLT, we create PLT and GOTPLT slots for the symbol.
985   if (needsPlt(Expr) && !Sym.isInPlt()) {
986     if (Sym.isGnuIFunc() && !Sym.IsPreemptible)
987       addPltEntry<ELFT>(InX::Iplt, InX::IgotPlt, InX::RelaIplt,
988                         Target->IRelativeRel, Sym);
989     else
990       addPltEntry<ELFT>(InX::Plt, InX::GotPlt, InX::RelaPlt, Target->PltRel,
991                         Sym);
992   }
993 
994   // Create a GOT slot if a relocation needs GOT.
995   if (needsGot(Expr)) {
996     if (Config->EMachine == EM_MIPS) {
997       // MIPS ABI has special rules to process GOT entries and doesn't
998       // require relocation entries for them. A special case is TLS
999       // relocations. In that case dynamic loader applies dynamic
1000       // relocations to initialize TLS GOT entries.
1001       // See "Global Offset Table" in Chapter 5 in the following document
1002       // for detailed description:
1003       // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1004       InX::MipsGot->addEntry(Sym, Addend, Expr);
1005       if (Sym.isTls() && Sym.IsPreemptible)
1006         InX::RelaDyn->addReloc(Target->TlsGotRel, InX::MipsGot,
1007                                Sym.getGotOffset(), &Sym);
1008     } else if (!Sym.isInGot()) {
1009       addGotEntry<ELFT>(Sym);
1010     }
1011   }
1012 
1013   processRelocAux<ELFT>(Sec, Expr, Type, Offset, Sym, Rel, Addend);
1014 }
1015 
1016 template <class ELFT, class RelTy>
1017 static void scanRelocs(InputSectionBase &Sec, ArrayRef<RelTy> Rels) {
1018   OffsetGetter GetOffset(Sec);
1019 
1020   // Not all relocations end up in Sec.Relocations, but a lot do.
1021   Sec.Relocations.reserve(Rels.size());
1022 
1023   for (auto I = Rels.begin(), End = Rels.end(); I != End;)
1024     scanReloc<ELFT>(Sec, GetOffset, I, End);
1025 }
1026 
1027 template <class ELFT> void elf::scanRelocations(InputSectionBase &S) {
1028   if (S.AreRelocsRela)
1029     scanRelocs<ELFT>(S, S.relas<ELFT>());
1030   else
1031     scanRelocs<ELFT>(S, S.rels<ELFT>());
1032 }
1033 
1034 // Thunk Implementation
1035 //
1036 // Thunks (sometimes called stubs, veneers or branch islands) are small pieces
1037 // of code that the linker inserts inbetween a caller and a callee. The thunks
1038 // are added at link time rather than compile time as the decision on whether
1039 // a thunk is needed, such as the caller and callee being out of range, can only
1040 // be made at link time.
1041 //
1042 // It is straightforward to tell given the current state of the program when a
1043 // thunk is needed for a particular call. The more difficult part is that
1044 // the thunk needs to be placed in the program such that the caller can reach
1045 // the thunk and the thunk can reach the callee; furthermore, adding thunks to
1046 // the program alters addresses, which can mean more thunks etc.
1047 //
1048 // In lld we have a synthetic ThunkSection that can hold many Thunks.
1049 // The decision to have a ThunkSection act as a container means that we can
1050 // more easily handle the most common case of a single block of contiguous
1051 // Thunks by inserting just a single ThunkSection.
1052 //
1053 // The implementation of Thunks in lld is split across these areas
1054 // Relocations.cpp : Framework for creating and placing thunks
1055 // Thunks.cpp : The code generated for each supported thunk
1056 // Target.cpp : Target specific hooks that the framework uses to decide when
1057 //              a thunk is used
1058 // Synthetic.cpp : Implementation of ThunkSection
1059 // Writer.cpp : Iteratively call framework until no more Thunks added
1060 //
1061 // Thunk placement requirements:
1062 // Mips LA25 thunks. These must be placed immediately before the callee section
1063 // We can assume that the caller is in range of the Thunk. These are modelled
1064 // by Thunks that return the section they must precede with
1065 // getTargetInputSection().
1066 //
1067 // ARM interworking and range extension thunks. These thunks must be placed
1068 // within range of the caller. All implemented ARM thunks can always reach the
1069 // callee as they use an indirect jump via a register that has no range
1070 // restrictions.
1071 //
1072 // Thunk placement algorithm:
1073 // For Mips LA25 ThunkSections; the placement is explicit, it has to be before
1074 // getTargetInputSection().
1075 //
1076 // For thunks that must be placed within range of the caller there are many
1077 // possible choices given that the maximum range from the caller is usually
1078 // much larger than the average InputSection size. Desirable properties include:
1079 // - Maximize reuse of thunks by multiple callers
1080 // - Minimize number of ThunkSections to simplify insertion
1081 // - Handle impact of already added Thunks on addresses
1082 // - Simple to understand and implement
1083 //
1084 // In lld for the first pass, we pre-create one or more ThunkSections per
1085 // InputSectionDescription at Target specific intervals. A ThunkSection is
1086 // placed so that the estimated end of the ThunkSection is within range of the
1087 // start of the InputSectionDescription or the previous ThunkSection. For
1088 // example:
1089 // InputSectionDescription
1090 // Section 0
1091 // ...
1092 // Section N
1093 // ThunkSection 0
1094 // Section N + 1
1095 // ...
1096 // Section N + K
1097 // Thunk Section 1
1098 //
1099 // The intention is that we can add a Thunk to a ThunkSection that is well
1100 // spaced enough to service a number of callers without having to do a lot
1101 // of work. An important principle is that it is not an error if a Thunk cannot
1102 // be placed in a pre-created ThunkSection; when this happens we create a new
1103 // ThunkSection placed next to the caller. This allows us to handle the vast
1104 // majority of thunks simply, but also handle rare cases where the branch range
1105 // is smaller than the target specific spacing.
1106 //
1107 // The algorithm is expected to create all the thunks that are needed in a
1108 // single pass, with a small number of programs needing a second pass due to
1109 // the insertion of thunks in the first pass increasing the offset between
1110 // callers and callees that were only just in range.
1111 //
1112 // A consequence of allowing new ThunkSections to be created outside of the
1113 // pre-created ThunkSections is that in rare cases calls to Thunks that were in
1114 // range in pass K, are out of range in some pass > K due to the insertion of
1115 // more Thunks in between the caller and callee. When this happens we retarget
1116 // the relocation back to the original target and create another Thunk.
1117 
1118 // Remove ThunkSections that are empty, this should only be the initial set
1119 // precreated on pass 0.
1120 
1121 // Insert the Thunks for OutputSection OS into their designated place
1122 // in the Sections vector, and recalculate the InputSection output section
1123 // offsets.
1124 // This may invalidate any output section offsets stored outside of InputSection
1125 void ThunkCreator::mergeThunks(ArrayRef<OutputSection *> OutputSections) {
1126   forEachInputSectionDescription(
1127       OutputSections, [&](OutputSection *OS, InputSectionDescription *ISD) {
1128         if (ISD->ThunkSections.empty())
1129           return;
1130 
1131         // Remove any zero sized precreated Thunks.
1132         llvm::erase_if(ISD->ThunkSections,
1133                        [](const std::pair<ThunkSection *, uint32_t> &TS) {
1134                          return TS.first->getSize() == 0;
1135                        });
1136         // ISD->ThunkSections contains all created ThunkSections, including
1137         // those inserted in previous passes. Extract the Thunks created this
1138         // pass and order them in ascending OutSecOff.
1139         std::vector<ThunkSection *> NewThunks;
1140         for (const std::pair<ThunkSection *, uint32_t> TS : ISD->ThunkSections)
1141           if (TS.second == Pass)
1142             NewThunks.push_back(TS.first);
1143         std::stable_sort(NewThunks.begin(), NewThunks.end(),
1144                          [](const ThunkSection *A, const ThunkSection *B) {
1145                            return A->OutSecOff < B->OutSecOff;
1146                          });
1147 
1148         // Merge sorted vectors of Thunks and InputSections by OutSecOff
1149         std::vector<InputSection *> Tmp;
1150         Tmp.reserve(ISD->Sections.size() + NewThunks.size());
1151         auto MergeCmp = [](const InputSection *A, const InputSection *B) {
1152           // std::merge requires a strict weak ordering.
1153           if (A->OutSecOff < B->OutSecOff)
1154             return true;
1155           if (A->OutSecOff == B->OutSecOff) {
1156             auto *TA = dyn_cast<ThunkSection>(A);
1157             auto *TB = dyn_cast<ThunkSection>(B);
1158             // Check if Thunk is immediately before any specific Target
1159             // InputSection for example Mips LA25 Thunks.
1160             if (TA && TA->getTargetInputSection() == B)
1161               return true;
1162             if (TA && !TB && !TA->getTargetInputSection())
1163               // Place Thunk Sections without specific targets before
1164               // non-Thunk Sections.
1165               return true;
1166           }
1167           return false;
1168         };
1169         std::merge(ISD->Sections.begin(), ISD->Sections.end(),
1170                    NewThunks.begin(), NewThunks.end(), std::back_inserter(Tmp),
1171                    MergeCmp);
1172         ISD->Sections = std::move(Tmp);
1173       });
1174 }
1175 
1176 // Find or create a ThunkSection within the InputSectionDescription (ISD) that
1177 // is in range of Src. An ISD maps to a range of InputSections described by a
1178 // linker script section pattern such as { .text .text.* }.
1179 ThunkSection *ThunkCreator::getISDThunkSec(OutputSection *OS, InputSection *IS,
1180                                            InputSectionDescription *ISD,
1181                                            uint32_t Type, uint64_t Src) {
1182   for (std::pair<ThunkSection *, uint32_t> TP : ISD->ThunkSections) {
1183     ThunkSection *TS = TP.first;
1184     uint64_t TSBase = OS->Addr + TS->OutSecOff;
1185     uint64_t TSLimit = TSBase + TS->getSize();
1186     if (Target->inBranchRange(Type, Src, (Src > TSLimit) ? TSBase : TSLimit))
1187       return TS;
1188   }
1189 
1190   // No suitable ThunkSection exists. This can happen when there is a branch
1191   // with lower range than the ThunkSection spacing or when there are too
1192   // many Thunks. Create a new ThunkSection as close to the InputSection as
1193   // possible. Error if InputSection is so large we cannot place ThunkSection
1194   // anywhere in Range.
1195   uint64_t ThunkSecOff = IS->OutSecOff;
1196   if (!Target->inBranchRange(Type, Src, OS->Addr + ThunkSecOff)) {
1197     ThunkSecOff = IS->OutSecOff + IS->getSize();
1198     if (!Target->inBranchRange(Type, Src, OS->Addr + ThunkSecOff))
1199       fatal("InputSection too large for range extension thunk " +
1200             IS->getObjMsg(Src - (OS->Addr + IS->OutSecOff)));
1201   }
1202   return addThunkSection(OS, ISD, ThunkSecOff);
1203 }
1204 
1205 // Add a Thunk that needs to be placed in a ThunkSection that immediately
1206 // precedes its Target.
1207 ThunkSection *ThunkCreator::getISThunkSec(InputSection *IS) {
1208   ThunkSection *TS = ThunkedSections.lookup(IS);
1209   if (TS)
1210     return TS;
1211 
1212   // Find InputSectionRange within Target Output Section (TOS) that the
1213   // InputSection (IS) that we need to precede is in.
1214   OutputSection *TOS = IS->getParent();
1215   for (BaseCommand *BC : TOS->SectionCommands)
1216     if (auto *ISD = dyn_cast<InputSectionDescription>(BC)) {
1217       if (ISD->Sections.empty())
1218         continue;
1219       InputSection *first = ISD->Sections.front();
1220       InputSection *last = ISD->Sections.back();
1221       if (IS->OutSecOff >= first->OutSecOff &&
1222           IS->OutSecOff <= last->OutSecOff) {
1223         TS = addThunkSection(TOS, ISD, IS->OutSecOff);
1224         ThunkedSections[IS] = TS;
1225         break;
1226       }
1227     }
1228   return TS;
1229 }
1230 
1231 // Create one or more ThunkSections per OS that can be used to place Thunks.
1232 // We attempt to place the ThunkSections using the following desirable
1233 // properties:
1234 // - Within range of the maximum number of callers
1235 // - Minimise the number of ThunkSections
1236 //
1237 // We follow a simple but conservative heuristic to place ThunkSections at
1238 // offsets that are multiples of a Target specific branch range.
1239 // For an InputSectionDescription that is smaller than the range, a single
1240 // ThunkSection at the end of the range will do.
1241 //
1242 // For an InputSectionDescription that is more than twice the size of the range,
1243 // we place the last ThunkSection at range bytes from the end of the
1244 // InputSectionDescription in order to increase the likelihood that the
1245 // distance from a thunk to its target will be sufficiently small to
1246 // allow for the creation of a short thunk.
1247 void ThunkCreator::createInitialThunkSections(
1248     ArrayRef<OutputSection *> OutputSections) {
1249   forEachInputSectionDescription(
1250       OutputSections, [&](OutputSection *OS, InputSectionDescription *ISD) {
1251         if (ISD->Sections.empty())
1252           return;
1253         uint32_t ISDBegin = ISD->Sections.front()->OutSecOff;
1254         uint32_t ISDEnd =
1255             ISD->Sections.back()->OutSecOff + ISD->Sections.back()->getSize();
1256         uint32_t LastThunkLowerBound = -1;
1257         if (ISDEnd - ISDBegin > Target->ThunkSectionSpacing * 2)
1258           LastThunkLowerBound = ISDEnd - Target->ThunkSectionSpacing;
1259 
1260         uint32_t ISLimit;
1261         uint32_t PrevISLimit = ISDBegin;
1262         uint32_t ThunkUpperBound = ISDBegin + Target->ThunkSectionSpacing;
1263 
1264         for (const InputSection *IS : ISD->Sections) {
1265           ISLimit = IS->OutSecOff + IS->getSize();
1266           if (ISLimit > ThunkUpperBound) {
1267             addThunkSection(OS, ISD, PrevISLimit);
1268             ThunkUpperBound = PrevISLimit + Target->ThunkSectionSpacing;
1269           }
1270           if (ISLimit > LastThunkLowerBound)
1271             break;
1272           PrevISLimit = ISLimit;
1273         }
1274         addThunkSection(OS, ISD, ISLimit);
1275       });
1276 }
1277 
1278 ThunkSection *ThunkCreator::addThunkSection(OutputSection *OS,
1279                                             InputSectionDescription *ISD,
1280                                             uint64_t Off) {
1281   auto *TS = make<ThunkSection>(OS, Off);
1282   ISD->ThunkSections.push_back(std::make_pair(TS, Pass));
1283   return TS;
1284 }
1285 
1286 std::pair<Thunk *, bool> ThunkCreator::getThunk(Symbol &Sym, RelType Type,
1287                                                 uint64_t Src) {
1288   std::vector<Thunk *> *ThunkVec = nullptr;
1289   // We use (section, offset) pair to find the thunk position if possible so
1290   // that we create only one thunk for aliased symbols or ICFed sections.
1291   if (auto *D = dyn_cast<Defined>(&Sym))
1292     if (!D->isInPlt() && D->Section)
1293       ThunkVec = &ThunkedSymbolsBySection[{D->Section->Repl, D->Value}];
1294   if (!ThunkVec)
1295     ThunkVec = &ThunkedSymbols[&Sym];
1296   // Check existing Thunks for Sym to see if they can be reused
1297   for (Thunk *ET : *ThunkVec)
1298     if (ET->isCompatibleWith(Type) &&
1299         Target->inBranchRange(Type, Src, ET->getThunkTargetSym()->getVA()))
1300       return std::make_pair(ET, false);
1301   // No existing compatible Thunk in range, create a new one
1302   Thunk *T = addThunk(Type, Sym);
1303   ThunkVec->push_back(T);
1304   return std::make_pair(T, true);
1305 }
1306 
1307 // Call Fn on every executable InputSection accessed via the linker script
1308 // InputSectionDescription::Sections.
1309 void ThunkCreator::forEachInputSectionDescription(
1310     ArrayRef<OutputSection *> OutputSections,
1311     std::function<void(OutputSection *, InputSectionDescription *)> Fn) {
1312   for (OutputSection *OS : OutputSections) {
1313     if (!(OS->Flags & SHF_ALLOC) || !(OS->Flags & SHF_EXECINSTR))
1314       continue;
1315     for (BaseCommand *BC : OS->SectionCommands)
1316       if (auto *ISD = dyn_cast<InputSectionDescription>(BC))
1317         Fn(OS, ISD);
1318   }
1319 }
1320 
1321 // Return true if the relocation target is an in range Thunk.
1322 // Return false if the relocation is not to a Thunk. If the relocation target
1323 // was originally to a Thunk, but is no longer in range we revert the
1324 // relocation back to its original non-Thunk target.
1325 bool ThunkCreator::normalizeExistingThunk(Relocation &Rel, uint64_t Src) {
1326   if (Thunk *ET = Thunks.lookup(Rel.Sym)) {
1327     if (Target->inBranchRange(Rel.Type, Src, Rel.Sym->getVA()))
1328       return true;
1329     Rel.Sym = &ET->Destination;
1330     if (Rel.Sym->isInPlt())
1331       Rel.Expr = toPlt(Rel.Expr);
1332   }
1333   return false;
1334 }
1335 
1336 // Process all relocations from the InputSections that have been assigned
1337 // to InputSectionDescriptions and redirect through Thunks if needed. The
1338 // function should be called iteratively until it returns false.
1339 //
1340 // PreConditions:
1341 // All InputSections that may need a Thunk are reachable from
1342 // OutputSectionCommands.
1343 //
1344 // All OutputSections have an address and all InputSections have an offset
1345 // within the OutputSection.
1346 //
1347 // The offsets between caller (relocation place) and callee
1348 // (relocation target) will not be modified outside of createThunks().
1349 //
1350 // PostConditions:
1351 // If return value is true then ThunkSections have been inserted into
1352 // OutputSections. All relocations that needed a Thunk based on the information
1353 // available to createThunks() on entry have been redirected to a Thunk. Note
1354 // that adding Thunks changes offsets between caller and callee so more Thunks
1355 // may be required.
1356 //
1357 // If return value is false then no more Thunks are needed, and createThunks has
1358 // made no changes. If the target requires range extension thunks, currently
1359 // ARM, then any future change in offset between caller and callee risks a
1360 // relocation out of range error.
1361 bool ThunkCreator::createThunks(ArrayRef<OutputSection *> OutputSections) {
1362   bool AddressesChanged = false;
1363   if (Pass == 0 && Target->ThunkSectionSpacing)
1364     createInitialThunkSections(OutputSections);
1365   else if (Pass == 10)
1366     // With Thunk Size much smaller than branch range we expect to
1367     // converge quickly; if we get to 10 something has gone wrong.
1368     fatal("thunk creation not converged");
1369 
1370   // Create all the Thunks and insert them into synthetic ThunkSections. The
1371   // ThunkSections are later inserted back into InputSectionDescriptions.
1372   // We separate the creation of ThunkSections from the insertion of the
1373   // ThunkSections as ThunkSections are not always inserted into the same
1374   // InputSectionDescription as the caller.
1375   forEachInputSectionDescription(
1376       OutputSections, [&](OutputSection *OS, InputSectionDescription *ISD) {
1377         for (InputSection *IS : ISD->Sections)
1378           for (Relocation &Rel : IS->Relocations) {
1379             uint64_t Src = IS->getVA(Rel.Offset);
1380 
1381             // If we are a relocation to an existing Thunk, check if it is
1382             // still in range. If not then Rel will be altered to point to its
1383             // original target so another Thunk can be generated.
1384             if (Pass > 0 && normalizeExistingThunk(Rel, Src))
1385               continue;
1386 
1387             if (!Target->needsThunk(Rel.Expr, Rel.Type, IS->File, Src,
1388                                     *Rel.Sym))
1389               continue;
1390             Thunk *T;
1391             bool IsNew;
1392             std::tie(T, IsNew) = getThunk(*Rel.Sym, Rel.Type, Src);
1393             if (IsNew) {
1394               // Find or create a ThunkSection for the new Thunk
1395               ThunkSection *TS;
1396               if (auto *TIS = T->getTargetInputSection())
1397                 TS = getISThunkSec(TIS);
1398               else
1399                 TS = getISDThunkSec(OS, IS, ISD, Rel.Type, Src);
1400               TS->addThunk(T);
1401               Thunks[T->getThunkTargetSym()] = T;
1402             }
1403             // Redirect relocation to Thunk, we never go via the PLT to a Thunk
1404             Rel.Sym = T->getThunkTargetSym();
1405             Rel.Expr = fromPlt(Rel.Expr);
1406           }
1407         for (auto &P : ISD->ThunkSections)
1408           AddressesChanged |= P.first->assignOffsets();
1409       });
1410   for (auto &P : ThunkedSections)
1411     AddressesChanged |= P.second->assignOffsets();
1412 
1413   // Merge all created synthetic ThunkSections back into OutputSection
1414   mergeThunks(OutputSections);
1415   ++Pass;
1416   return AddressesChanged;
1417 }
1418 
1419 template void elf::scanRelocations<ELF32LE>(InputSectionBase &);
1420 template void elf::scanRelocations<ELF32BE>(InputSectionBase &);
1421 template void elf::scanRelocations<ELF64LE>(InputSectionBase &);
1422 template void elf::scanRelocations<ELF64BE>(InputSectionBase &);
1423