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