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