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