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