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