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