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