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 (Sym.getName().startswith("_ZTV"))
667     Msg += "\nthe vtable symbol may be undefined because the class is missing "
668            "its key function (see https://lld.llvm.org/missingkeyfunction)";
669 
670   if ((Config->UnresolvedSymbols == UnresolvedPolicy::Warn && CanBeExternal) ||
671       Config->NoinhibitExec) {
672     warn(Msg);
673     return false;
674   }
675 
676   error(Msg);
677   return true;
678 }
679 
680 // MIPS N32 ABI treats series of successive relocations with the same offset
681 // as a single relocation. The similar approach used by N64 ABI, but this ABI
682 // packs all relocations into the single relocation record. Here we emulate
683 // this for the N32 ABI. Iterate over relocation with the same offset and put
684 // theirs types into the single bit-set.
685 template <class RelTy> static RelType getMipsN32RelType(RelTy *&Rel, RelTy *End) {
686   RelType Type = 0;
687   uint64_t Offset = Rel->r_offset;
688 
689   int N = 0;
690   while (Rel != End && Rel->r_offset == Offset)
691     Type |= (Rel++)->getType(Config->IsMips64EL) << (8 * N++);
692   return Type;
693 }
694 
695 // .eh_frame sections are mergeable input sections, so their input
696 // offsets are not linearly mapped to output section. For each input
697 // offset, we need to find a section piece containing the offset and
698 // add the piece's base address to the input offset to compute the
699 // output offset. That isn't cheap.
700 //
701 // This class is to speed up the offset computation. When we process
702 // relocations, we access offsets in the monotonically increasing
703 // order. So we can optimize for that access pattern.
704 //
705 // For sections other than .eh_frame, this class doesn't do anything.
706 namespace {
707 class OffsetGetter {
708 public:
709   explicit OffsetGetter(InputSectionBase &Sec) {
710     if (auto *Eh = dyn_cast<EhInputSection>(&Sec))
711       Pieces = Eh->Pieces;
712   }
713 
714   // Translates offsets in input sections to offsets in output sections.
715   // Given offset must increase monotonically. We assume that Piece is
716   // sorted by InputOff.
717   uint64_t get(uint64_t Off) {
718     if (Pieces.empty())
719       return Off;
720 
721     while (I != Pieces.size() && Pieces[I].InputOff + Pieces[I].Size <= Off)
722       ++I;
723     if (I == Pieces.size())
724       fatal(".eh_frame: relocation is not in any piece");
725 
726     // Pieces must be contiguous, so there must be no holes in between.
727     assert(Pieces[I].InputOff <= Off && "Relocation not in any piece");
728 
729     // Offset -1 means that the piece is dead (i.e. garbage collected).
730     if (Pieces[I].OutputOff == -1)
731       return -1;
732     return Pieces[I].OutputOff + Off - Pieces[I].InputOff;
733   }
734 
735 private:
736   ArrayRef<EhSectionPiece> Pieces;
737   size_t I = 0;
738 };
739 } // namespace
740 
741 static void addRelativeReloc(InputSectionBase *IS, uint64_t OffsetInSec,
742                              Symbol *Sym, int64_t Addend, RelExpr Expr,
743                              RelType Type) {
744   // Add a relative relocation. If RelrDyn section is enabled, and the
745   // relocation offset is guaranteed to be even, add the relocation to
746   // the RelrDyn section, otherwise add it to the RelaDyn section.
747   // RelrDyn sections don't support odd offsets. Also, RelrDyn sections
748   // don't store the addend values, so we must write it to the relocated
749   // address.
750   if (In.RelrDyn && IS->Alignment >= 2 && OffsetInSec % 2 == 0) {
751     IS->Relocations.push_back({Expr, Type, OffsetInSec, Addend, Sym});
752     In.RelrDyn->Relocs.push_back({IS, OffsetInSec});
753     return;
754   }
755   In.RelaDyn->addReloc(Target->RelativeRel, IS, OffsetInSec, Sym, Addend, Expr,
756                        Type);
757 }
758 
759 template <class ELFT, class GotPltSection>
760 static void addPltEntry(PltSection *Plt, GotPltSection *GotPlt,
761                         RelocationBaseSection *Rel, RelType Type, Symbol &Sym) {
762   Plt->addEntry<ELFT>(Sym);
763   GotPlt->addEntry(Sym);
764   Rel->addReloc(
765       {Type, GotPlt, Sym.getGotPltOffset(), !Sym.IsPreemptible, &Sym, 0});
766 }
767 
768 template <class ELFT> static void addGotEntry(Symbol &Sym) {
769   In.Got->addEntry(Sym);
770 
771   RelExpr Expr;
772   if (Sym.isTls())
773     Expr = R_TLS;
774   else if (Sym.isGnuIFunc())
775     Expr = R_PLT;
776   else
777     Expr = R_ABS;
778 
779   uint64_t Off = Sym.getGotOffset();
780 
781   // If a GOT slot value can be calculated at link-time, which is now,
782   // we can just fill that out.
783   //
784   // (We don't actually write a value to a GOT slot right now, but we
785   // add a static relocation to a Relocations vector so that
786   // InputSection::relocate will do the work for us. We may be able
787   // to just write a value now, but it is a TODO.)
788   bool IsLinkTimeConstant =
789       !Sym.IsPreemptible && (!Config->Pic || isAbsolute(Sym));
790   if (IsLinkTimeConstant) {
791     In.Got->Relocations.push_back({Expr, Target->GotRel, Off, 0, &Sym});
792     return;
793   }
794 
795   // Otherwise, we emit a dynamic relocation to .rel[a].dyn so that
796   // the GOT slot will be fixed at load-time.
797   if (!Sym.isTls() && !Sym.IsPreemptible && Config->Pic && !isAbsolute(Sym)) {
798     addRelativeReloc(In.Got, Off, &Sym, 0, R_ABS, Target->GotRel);
799     return;
800   }
801   In.RelaDyn->addReloc(Sym.isTls() ? Target->TlsGotRel : Target->GotRel, In.Got,
802                        Off, &Sym, 0, Sym.IsPreemptible ? R_ADDEND : R_ABS,
803                        Target->GotRel);
804 }
805 
806 // Return true if we can define a symbol in the executable that
807 // contains the value/function of a symbol defined in a shared
808 // library.
809 static bool canDefineSymbolInExecutable(Symbol &Sym) {
810   // If the symbol has default visibility the symbol defined in the
811   // executable will preempt it.
812   // Note that we want the visibility of the shared symbol itself, not
813   // the visibility of the symbol in the output file we are producing. That is
814   // why we use Sym.StOther.
815   if ((Sym.StOther & 0x3) == STV_DEFAULT)
816     return true;
817 
818   // If we are allowed to break address equality of functions, defining
819   // a plt entry will allow the program to call the function in the
820   // .so, but the .so and the executable will no agree on the address
821   // of the function. Similar logic for objects.
822   return ((Sym.isFunc() && Config->IgnoreFunctionAddressEquality) ||
823           (Sym.isObject() && Config->IgnoreDataAddressEquality));
824 }
825 
826 // The reason we have to do this early scan is as follows
827 // * To mmap the output file, we need to know the size
828 // * For that, we need to know how many dynamic relocs we will have.
829 // It might be possible to avoid this by outputting the file with write:
830 // * Write the allocated output sections, computing addresses.
831 // * Apply relocations, recording which ones require a dynamic reloc.
832 // * Write the dynamic relocations.
833 // * Write the rest of the file.
834 // This would have some drawbacks. For example, we would only know if .rela.dyn
835 // is needed after applying relocations. If it is, it will go after rw and rx
836 // sections. Given that it is ro, we will need an extra PT_LOAD. This
837 // complicates things for the dynamic linker and means we would have to reserve
838 // space for the extra PT_LOAD even if we end up not using it.
839 template <class ELFT, class RelTy>
840 static void processRelocAux(InputSectionBase &Sec, RelExpr Expr, RelType Type,
841                             uint64_t Offset, Symbol &Sym, const RelTy &Rel,
842                             int64_t Addend) {
843   if (isStaticLinkTimeConstant(Expr, Type, Sym, Sec, Offset)) {
844     Sec.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
845     return;
846   }
847   bool CanWrite = (Sec.Flags & SHF_WRITE) || !Config->ZText;
848   if (CanWrite) {
849     // R_GOT refers to a position in the got, even if the symbol is preemptible.
850     bool IsPreemptibleValue = Sym.IsPreemptible && Expr != R_GOT;
851 
852     if (!IsPreemptibleValue) {
853       addRelativeReloc(&Sec, Offset, &Sym, Addend, Expr, Type);
854       return;
855     } else if (RelType Rel = Target->getDynRel(Type)) {
856       In.RelaDyn->addReloc(Rel, &Sec, Offset, &Sym, Addend, R_ADDEND, Type);
857 
858       // MIPS ABI turns using of GOT and dynamic relocations inside out.
859       // While regular ABI uses dynamic relocations to fill up GOT entries
860       // MIPS ABI requires dynamic linker to fills up GOT entries using
861       // specially sorted dynamic symbol table. This affects even dynamic
862       // relocations against symbols which do not require GOT entries
863       // creation explicitly, i.e. do not have any GOT-relocations. So if
864       // a preemptible symbol has a dynamic relocation we anyway have
865       // to create a GOT entry for it.
866       // If a non-preemptible symbol has a dynamic relocation against it,
867       // dynamic linker takes it st_value, adds offset and writes down
868       // result of the dynamic relocation. In case of preemptible symbol
869       // dynamic linker performs symbol resolution, writes the symbol value
870       // to the GOT entry and reads the GOT entry when it needs to perform
871       // a dynamic relocation.
872       // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19
873       if (Config->EMachine == EM_MIPS)
874         In.MipsGot->addEntry(*Sec.File, Sym, Addend, Expr);
875       return;
876     }
877   }
878 
879   // If the relocation is to a weak undef, and we are producing
880   // executable, give up on it and produce a non preemptible 0.
881   if (!Config->Shared && Sym.isUndefWeak()) {
882     Sec.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
883     return;
884   }
885 
886   if (!CanWrite && (Config->Pic && !isRelExpr(Expr))) {
887     error(
888         "can't create dynamic relocation " + toString(Type) + " against " +
889         (Sym.getName().empty() ? "local symbol" : "symbol: " + toString(Sym)) +
890         " in readonly segment; recompile object files with -fPIC "
891         "or pass '-Wl,-z,notext' to allow text relocations in the output" +
892         getLocation(Sec, Sym, Offset));
893     return;
894   }
895 
896   // Copy relocations are only possible if we are creating an executable.
897   if (Config->Shared) {
898     errorOrWarn("relocation " + toString(Type) +
899                 " cannot be used against symbol " + toString(Sym) +
900                 "; recompile with -fPIC" + getLocation(Sec, Sym, Offset));
901     return;
902   }
903 
904   // If the symbol is undefined we already reported any relevant errors.
905   if (Sym.isUndefined())
906     return;
907 
908   if (!canDefineSymbolInExecutable(Sym)) {
909     error("cannot preempt symbol: " + toString(Sym) +
910           getLocation(Sec, Sym, Offset));
911     return;
912   }
913 
914   if (Sym.isObject()) {
915     // Produce a copy relocation.
916     if (auto *SS = dyn_cast<SharedSymbol>(&Sym)) {
917       if (!Config->ZCopyreloc)
918         error("unresolvable relocation " + toString(Type) +
919               " against symbol '" + toString(*SS) +
920               "'; recompile with -fPIC or remove '-z nocopyreloc'" +
921               getLocation(Sec, Sym, Offset));
922       addCopyRelSymbol<ELFT>(*SS);
923     }
924     Sec.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
925     return;
926   }
927 
928   if (Sym.isFunc()) {
929     // This handles a non PIC program call to function in a shared library. In
930     // an ideal world, we could just report an error saying the relocation can
931     // overflow at runtime. In the real world with glibc, crt1.o has a
932     // R_X86_64_PC32 pointing to libc.so.
933     //
934     // The general idea on how to handle such cases is to create a PLT entry and
935     // use that as the function value.
936     //
937     // For the static linking part, we just return a plt expr and everything
938     // else will use the PLT entry as the address.
939     //
940     // The remaining problem is making sure pointer equality still works. We
941     // need the help of the dynamic linker for that. We let it know that we have
942     // a direct reference to a so symbol by creating an undefined symbol with a
943     // non zero st_value. Seeing that, the dynamic linker resolves the symbol to
944     // the value of the symbol we created. This is true even for got entries, so
945     // pointer equality is maintained. To avoid an infinite loop, the only entry
946     // that points to the real function is a dedicated got entry used by the
947     // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT,
948     // R_386_JMP_SLOT, etc).
949 
950     // For position independent executable on i386, the plt entry requires ebx
951     // to be set. This causes two problems:
952     // * If some code has a direct reference to a function, it was probably
953     //   compiled without -fPIE/-fPIC and doesn't maintain ebx.
954     // * If a library definition gets preempted to the executable, it will have
955     //   the wrong ebx value.
956     if (Config->Pie && Config->EMachine == EM_386)
957       errorOrWarn("symbol '" + toString(Sym) +
958                   "' cannot be preempted; recompile with -fPIE" +
959                   getLocation(Sec, Sym, Offset));
960     if (!Sym.isInPlt())
961       addPltEntry<ELFT>(In.Plt, In.GotPlt, In.RelaPlt, Target->PltRel, Sym);
962     if (!Sym.isDefined())
963       replaceWithDefined(Sym, In.Plt, getPltEntryOffset(Sym.PltIndex), 0);
964     Sym.NeedsPltAddr = true;
965     Sec.Relocations.push_back({Expr, Type, Offset, Addend, &Sym});
966     return;
967   }
968 
969   errorOrWarn("symbol '" + toString(Sym) + "' has no type" +
970               getLocation(Sec, Sym, Offset));
971 }
972 
973 template <class ELFT, class RelTy>
974 static void scanReloc(InputSectionBase &Sec, OffsetGetter &GetOffset, RelTy *&I,
975                       RelTy *End) {
976   const RelTy &Rel = *I;
977   Symbol &Sym = Sec.getFile<ELFT>()->getRelocTargetSym(Rel);
978   RelType Type;
979 
980   // Deal with MIPS oddity.
981   if (Config->MipsN32Abi) {
982     Type = getMipsN32RelType(I, End);
983   } else {
984     Type = Rel.getType(Config->IsMips64EL);
985     ++I;
986   }
987 
988   // Get an offset in an output section this relocation is applied to.
989   uint64_t Offset = GetOffset.get(Rel.r_offset);
990   if (Offset == uint64_t(-1))
991     return;
992 
993   // Skip if the target symbol is an erroneous undefined symbol.
994   if (maybeReportUndefined(Sym, Sec, Rel.r_offset))
995     return;
996 
997   const uint8_t *RelocatedAddr = Sec.data().begin() + Rel.r_offset;
998   RelExpr Expr = Target->getRelExpr(Type, Sym, RelocatedAddr);
999 
1000   // Ignore "hint" relocations because they are only markers for relaxation.
1001   if (isRelExprOneOf<R_HINT, R_NONE>(Expr))
1002     return;
1003 
1004   // Strenghten or relax relocations.
1005   //
1006   // GNU ifunc symbols must be accessed via PLT because their addresses
1007   // are determined by runtime.
1008   //
1009   // On the other hand, if we know that a PLT entry will be resolved within
1010   // the same ELF module, we can skip PLT access and directly jump to the
1011   // destination function. For example, if we are linking a main exectuable,
1012   // all dynamic symbols that can be resolved within the executable will
1013   // actually be resolved that way at runtime, because the main exectuable
1014   // is always at the beginning of a search list. We can leverage that fact.
1015   if (Sym.isGnuIFunc()) {
1016     if (!Config->ZText && Config->WarnIfuncTextrel) {
1017       warn("using ifunc symbols when text relocations are allowed may produce "
1018            "a binary that will segfault, if the object file is linked with "
1019            "old version of glibc (glibc 2.28 and earlier). If this applies to "
1020            "you, consider recompiling the object files without -fPIC and "
1021            "without -Wl,-z,notext option. Use -no-warn-ifunc-textrel to "
1022            "turn off this warning." +
1023            getLocation(Sec, Sym, Offset));
1024     }
1025     Expr = toPlt(Expr);
1026   } else if (!Sym.IsPreemptible && Expr == R_GOT_PC && !isAbsoluteValue(Sym)) {
1027     Expr = Target->adjustRelaxExpr(Type, RelocatedAddr, Expr);
1028   } else if (!Sym.IsPreemptible) {
1029     Expr = fromPlt(Expr);
1030   }
1031 
1032   // This relocation does not require got entry, but it is relative to got and
1033   // needs it to be created. Here we request for that.
1034   if (isRelExprOneOf<R_GOTONLY_PC, R_GOTONLY_PC_FROM_END, R_GOTREL,
1035                      R_GOTREL_FROM_END, R_PPC_TOC>(Expr))
1036     In.Got->HasGotOffRel = true;
1037 
1038   // Read an addend.
1039   int64_t Addend = computeAddend<ELFT>(Rel, End, Sec, Expr, Sym.isLocal());
1040 
1041   // Process some TLS relocations, including relaxing TLS relocations.
1042   // Note that this function does not handle all TLS relocations.
1043   if (unsigned Processed =
1044           handleTlsRelocation<ELFT>(Type, Sym, Sec, Offset, Addend, Expr)) {
1045     I += (Processed - 1);
1046     return;
1047   }
1048 
1049   // If a relocation needs PLT, we create PLT and GOTPLT slots for the symbol.
1050   if (needsPlt(Expr) && !Sym.isInPlt()) {
1051     if (Sym.isGnuIFunc() && !Sym.IsPreemptible)
1052       addPltEntry<ELFT>(In.Iplt, In.IgotPlt, In.RelaIplt, Target->IRelativeRel,
1053                         Sym);
1054     else
1055       addPltEntry<ELFT>(In.Plt, In.GotPlt, In.RelaPlt, Target->PltRel, Sym);
1056   }
1057 
1058   // Create a GOT slot if a relocation needs GOT.
1059   if (needsGot(Expr)) {
1060     if (Config->EMachine == EM_MIPS) {
1061       // MIPS ABI has special rules to process GOT entries and doesn't
1062       // require relocation entries for them. A special case is TLS
1063       // relocations. In that case dynamic loader applies dynamic
1064       // relocations to initialize TLS GOT entries.
1065       // See "Global Offset Table" in Chapter 5 in the following document
1066       // for detailed description:
1067       // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1068       In.MipsGot->addEntry(*Sec.File, Sym, Addend, Expr);
1069     } else if (!Sym.isInGot()) {
1070       addGotEntry<ELFT>(Sym);
1071     }
1072   }
1073 
1074   processRelocAux<ELFT>(Sec, Expr, Type, Offset, Sym, Rel, Addend);
1075 }
1076 
1077 template <class ELFT, class RelTy>
1078 static void scanRelocs(InputSectionBase &Sec, ArrayRef<RelTy> Rels) {
1079   OffsetGetter GetOffset(Sec);
1080 
1081   // Not all relocations end up in Sec.Relocations, but a lot do.
1082   Sec.Relocations.reserve(Rels.size());
1083 
1084   for (auto I = Rels.begin(), End = Rels.end(); I != End;)
1085     scanReloc<ELFT>(Sec, GetOffset, I, End);
1086 
1087   // Sort relocations by offset to binary search for R_RISCV_PCREL_HI20
1088   if (Config->EMachine == EM_RISCV)
1089     std::stable_sort(Sec.Relocations.begin(), Sec.Relocations.end(),
1090                      RelocationOffsetComparator{});
1091 }
1092 
1093 template <class ELFT> void elf::scanRelocations(InputSectionBase &S) {
1094   if (S.AreRelocsRela)
1095     scanRelocs<ELFT>(S, S.relas<ELFT>());
1096   else
1097     scanRelocs<ELFT>(S, S.rels<ELFT>());
1098 }
1099 
1100 static bool mergeCmp(const InputSection *A, const InputSection *B) {
1101   // std::merge requires a strict weak ordering.
1102   if (A->OutSecOff < B->OutSecOff)
1103     return true;
1104 
1105   if (A->OutSecOff == B->OutSecOff) {
1106     auto *TA = dyn_cast<ThunkSection>(A);
1107     auto *TB = dyn_cast<ThunkSection>(B);
1108 
1109     // Check if Thunk is immediately before any specific Target
1110     // InputSection for example Mips LA25 Thunks.
1111     if (TA && TA->getTargetInputSection() == B)
1112       return true;
1113 
1114     // Place Thunk Sections without specific targets before
1115     // non-Thunk Sections.
1116     if (TA && !TB && !TA->getTargetInputSection())
1117       return true;
1118   }
1119 
1120   return false;
1121 }
1122 
1123 // Call Fn on every executable InputSection accessed via the linker script
1124 // InputSectionDescription::Sections.
1125 static void forEachInputSectionDescription(
1126     ArrayRef<OutputSection *> OutputSections,
1127     llvm::function_ref<void(OutputSection *, InputSectionDescription *)> Fn) {
1128   for (OutputSection *OS : OutputSections) {
1129     if (!(OS->Flags & SHF_ALLOC) || !(OS->Flags & SHF_EXECINSTR))
1130       continue;
1131     for (BaseCommand *BC : OS->SectionCommands)
1132       if (auto *ISD = dyn_cast<InputSectionDescription>(BC))
1133         Fn(OS, ISD);
1134   }
1135 }
1136 
1137 // Thunk Implementation
1138 //
1139 // Thunks (sometimes called stubs, veneers or branch islands) are small pieces
1140 // of code that the linker inserts inbetween a caller and a callee. The thunks
1141 // are added at link time rather than compile time as the decision on whether
1142 // a thunk is needed, such as the caller and callee being out of range, can only
1143 // be made at link time.
1144 //
1145 // It is straightforward to tell given the current state of the program when a
1146 // thunk is needed for a particular call. The more difficult part is that
1147 // the thunk needs to be placed in the program such that the caller can reach
1148 // the thunk and the thunk can reach the callee; furthermore, adding thunks to
1149 // the program alters addresses, which can mean more thunks etc.
1150 //
1151 // In lld we have a synthetic ThunkSection that can hold many Thunks.
1152 // The decision to have a ThunkSection act as a container means that we can
1153 // more easily handle the most common case of a single block of contiguous
1154 // Thunks by inserting just a single ThunkSection.
1155 //
1156 // The implementation of Thunks in lld is split across these areas
1157 // Relocations.cpp : Framework for creating and placing thunks
1158 // Thunks.cpp : The code generated for each supported thunk
1159 // Target.cpp : Target specific hooks that the framework uses to decide when
1160 //              a thunk is used
1161 // Synthetic.cpp : Implementation of ThunkSection
1162 // Writer.cpp : Iteratively call framework until no more Thunks added
1163 //
1164 // Thunk placement requirements:
1165 // Mips LA25 thunks. These must be placed immediately before the callee section
1166 // We can assume that the caller is in range of the Thunk. These are modelled
1167 // by Thunks that return the section they must precede with
1168 // getTargetInputSection().
1169 //
1170 // ARM interworking and range extension thunks. These thunks must be placed
1171 // within range of the caller. All implemented ARM thunks can always reach the
1172 // callee as they use an indirect jump via a register that has no range
1173 // restrictions.
1174 //
1175 // Thunk placement algorithm:
1176 // For Mips LA25 ThunkSections; the placement is explicit, it has to be before
1177 // getTargetInputSection().
1178 //
1179 // For thunks that must be placed within range of the caller there are many
1180 // possible choices given that the maximum range from the caller is usually
1181 // much larger than the average InputSection size. Desirable properties include:
1182 // - Maximize reuse of thunks by multiple callers
1183 // - Minimize number of ThunkSections to simplify insertion
1184 // - Handle impact of already added Thunks on addresses
1185 // - Simple to understand and implement
1186 //
1187 // In lld for the first pass, we pre-create one or more ThunkSections per
1188 // InputSectionDescription at Target specific intervals. A ThunkSection is
1189 // placed so that the estimated end of the ThunkSection is within range of the
1190 // start of the InputSectionDescription or the previous ThunkSection. For
1191 // example:
1192 // InputSectionDescription
1193 // Section 0
1194 // ...
1195 // Section N
1196 // ThunkSection 0
1197 // Section N + 1
1198 // ...
1199 // Section N + K
1200 // Thunk Section 1
1201 //
1202 // The intention is that we can add a Thunk to a ThunkSection that is well
1203 // spaced enough to service a number of callers without having to do a lot
1204 // of work. An important principle is that it is not an error if a Thunk cannot
1205 // be placed in a pre-created ThunkSection; when this happens we create a new
1206 // ThunkSection placed next to the caller. This allows us to handle the vast
1207 // majority of thunks simply, but also handle rare cases where the branch range
1208 // is smaller than the target specific spacing.
1209 //
1210 // The algorithm is expected to create all the thunks that are needed in a
1211 // single pass, with a small number of programs needing a second pass due to
1212 // the insertion of thunks in the first pass increasing the offset between
1213 // callers and callees that were only just in range.
1214 //
1215 // A consequence of allowing new ThunkSections to be created outside of the
1216 // pre-created ThunkSections is that in rare cases calls to Thunks that were in
1217 // range in pass K, are out of range in some pass > K due to the insertion of
1218 // more Thunks in between the caller and callee. When this happens we retarget
1219 // the relocation back to the original target and create another Thunk.
1220 
1221 // Remove ThunkSections that are empty, this should only be the initial set
1222 // precreated on pass 0.
1223 
1224 // Insert the Thunks for OutputSection OS into their designated place
1225 // in the Sections vector, and recalculate the InputSection output section
1226 // offsets.
1227 // This may invalidate any output section offsets stored outside of InputSection
1228 void ThunkCreator::mergeThunks(ArrayRef<OutputSection *> OutputSections) {
1229   forEachInputSectionDescription(
1230       OutputSections, [&](OutputSection *OS, InputSectionDescription *ISD) {
1231         if (ISD->ThunkSections.empty())
1232           return;
1233 
1234         // Remove any zero sized precreated Thunks.
1235         llvm::erase_if(ISD->ThunkSections,
1236                        [](const std::pair<ThunkSection *, uint32_t> &TS) {
1237                          return TS.first->getSize() == 0;
1238                        });
1239 
1240         // ISD->ThunkSections contains all created ThunkSections, including
1241         // those inserted in previous passes. Extract the Thunks created this
1242         // pass and order them in ascending OutSecOff.
1243         std::vector<ThunkSection *> NewThunks;
1244         for (const std::pair<ThunkSection *, uint32_t> TS : ISD->ThunkSections)
1245           if (TS.second == Pass)
1246             NewThunks.push_back(TS.first);
1247         std::stable_sort(NewThunks.begin(), NewThunks.end(),
1248                          [](const ThunkSection *A, const ThunkSection *B) {
1249                            return A->OutSecOff < B->OutSecOff;
1250                          });
1251 
1252         // Merge sorted vectors of Thunks and InputSections by OutSecOff
1253         std::vector<InputSection *> Tmp;
1254         Tmp.reserve(ISD->Sections.size() + NewThunks.size());
1255 
1256         std::merge(ISD->Sections.begin(), ISD->Sections.end(),
1257                    NewThunks.begin(), NewThunks.end(), std::back_inserter(Tmp),
1258                    mergeCmp);
1259 
1260         ISD->Sections = std::move(Tmp);
1261       });
1262 }
1263 
1264 // Find or create a ThunkSection within the InputSectionDescription (ISD) that
1265 // is in range of Src. An ISD maps to a range of InputSections described by a
1266 // linker script section pattern such as { .text .text.* }.
1267 ThunkSection *ThunkCreator::getISDThunkSec(OutputSection *OS, InputSection *IS,
1268                                            InputSectionDescription *ISD,
1269                                            uint32_t Type, uint64_t Src) {
1270   for (std::pair<ThunkSection *, uint32_t> TP : ISD->ThunkSections) {
1271     ThunkSection *TS = TP.first;
1272     uint64_t TSBase = OS->Addr + TS->OutSecOff;
1273     uint64_t TSLimit = TSBase + TS->getSize();
1274     if (Target->inBranchRange(Type, Src, (Src > TSLimit) ? TSBase : TSLimit))
1275       return TS;
1276   }
1277 
1278   // No suitable ThunkSection exists. This can happen when there is a branch
1279   // with lower range than the ThunkSection spacing or when there are too
1280   // many Thunks. Create a new ThunkSection as close to the InputSection as
1281   // possible. Error if InputSection is so large we cannot place ThunkSection
1282   // anywhere in Range.
1283   uint64_t ThunkSecOff = IS->OutSecOff;
1284   if (!Target->inBranchRange(Type, Src, OS->Addr + ThunkSecOff)) {
1285     ThunkSecOff = IS->OutSecOff + IS->getSize();
1286     if (!Target->inBranchRange(Type, Src, OS->Addr + ThunkSecOff))
1287       fatal("InputSection too large for range extension thunk " +
1288             IS->getObjMsg(Src - (OS->Addr + IS->OutSecOff)));
1289   }
1290   return addThunkSection(OS, ISD, ThunkSecOff);
1291 }
1292 
1293 // Add a Thunk that needs to be placed in a ThunkSection that immediately
1294 // precedes its Target.
1295 ThunkSection *ThunkCreator::getISThunkSec(InputSection *IS) {
1296   ThunkSection *TS = ThunkedSections.lookup(IS);
1297   if (TS)
1298     return TS;
1299 
1300   // Find InputSectionRange within Target Output Section (TOS) that the
1301   // InputSection (IS) that we need to precede is in.
1302   OutputSection *TOS = IS->getParent();
1303   for (BaseCommand *BC : TOS->SectionCommands) {
1304     auto *ISD = dyn_cast<InputSectionDescription>(BC);
1305     if (!ISD || ISD->Sections.empty())
1306       continue;
1307 
1308     InputSection *First = ISD->Sections.front();
1309     InputSection *Last = ISD->Sections.back();
1310 
1311     if (IS->OutSecOff < First->OutSecOff || Last->OutSecOff < IS->OutSecOff)
1312       continue;
1313 
1314     TS = addThunkSection(TOS, ISD, IS->OutSecOff);
1315     ThunkedSections[IS] = TS;
1316     return TS;
1317   }
1318 
1319   return nullptr;
1320 }
1321 
1322 // Create one or more ThunkSections per OS that can be used to place Thunks.
1323 // We attempt to place the ThunkSections using the following desirable
1324 // properties:
1325 // - Within range of the maximum number of callers
1326 // - Minimise the number of ThunkSections
1327 //
1328 // We follow a simple but conservative heuristic to place ThunkSections at
1329 // offsets that are multiples of a Target specific branch range.
1330 // For an InputSectionDescription that is smaller than the range, a single
1331 // ThunkSection at the end of the range will do.
1332 //
1333 // For an InputSectionDescription that is more than twice the size of the range,
1334 // we place the last ThunkSection at range bytes from the end of the
1335 // InputSectionDescription in order to increase the likelihood that the
1336 // distance from a thunk to its target will be sufficiently small to
1337 // allow for the creation of a short thunk.
1338 void ThunkCreator::createInitialThunkSections(
1339     ArrayRef<OutputSection *> OutputSections) {
1340   uint32_t ThunkSectionSpacing = Target->getThunkSectionSpacing();
1341 
1342   forEachInputSectionDescription(
1343       OutputSections, [&](OutputSection *OS, InputSectionDescription *ISD) {
1344         if (ISD->Sections.empty())
1345           return;
1346 
1347         uint32_t ISDBegin = ISD->Sections.front()->OutSecOff;
1348         uint32_t ISDEnd =
1349             ISD->Sections.back()->OutSecOff + ISD->Sections.back()->getSize();
1350         uint32_t LastThunkLowerBound = -1;
1351         if (ISDEnd - ISDBegin > ThunkSectionSpacing * 2)
1352           LastThunkLowerBound = ISDEnd - ThunkSectionSpacing;
1353 
1354         uint32_t ISLimit;
1355         uint32_t PrevISLimit = ISDBegin;
1356         uint32_t ThunkUpperBound = ISDBegin + ThunkSectionSpacing;
1357 
1358         for (const InputSection *IS : ISD->Sections) {
1359           ISLimit = IS->OutSecOff + IS->getSize();
1360           if (ISLimit > ThunkUpperBound) {
1361             addThunkSection(OS, ISD, PrevISLimit);
1362             ThunkUpperBound = PrevISLimit + ThunkSectionSpacing;
1363           }
1364           if (ISLimit > LastThunkLowerBound)
1365             break;
1366           PrevISLimit = ISLimit;
1367         }
1368         addThunkSection(OS, ISD, ISLimit);
1369       });
1370 }
1371 
1372 ThunkSection *ThunkCreator::addThunkSection(OutputSection *OS,
1373                                             InputSectionDescription *ISD,
1374                                             uint64_t Off) {
1375   auto *TS = make<ThunkSection>(OS, Off);
1376   ISD->ThunkSections.push_back({TS, Pass});
1377   return TS;
1378 }
1379 
1380 std::pair<Thunk *, bool> ThunkCreator::getThunk(Symbol &Sym, RelType Type,
1381                                                 uint64_t Src) {
1382   std::vector<Thunk *> *ThunkVec = nullptr;
1383 
1384   // We use (section, offset) pair to find the thunk position if possible so
1385   // that we create only one thunk for aliased symbols or ICFed sections.
1386   if (auto *D = dyn_cast<Defined>(&Sym))
1387     if (!D->isInPlt() && D->Section)
1388       ThunkVec = &ThunkedSymbolsBySection[{D->Section->Repl, D->Value}];
1389   if (!ThunkVec)
1390     ThunkVec = &ThunkedSymbols[&Sym];
1391 
1392   // Check existing Thunks for Sym to see if they can be reused
1393   for (Thunk *T : *ThunkVec)
1394     if (T->isCompatibleWith(Type) &&
1395         Target->inBranchRange(Type, Src, T->getThunkTargetSym()->getVA()))
1396       return std::make_pair(T, false);
1397 
1398   // No existing compatible Thunk in range, create a new one
1399   Thunk *T = addThunk(Type, Sym);
1400   ThunkVec->push_back(T);
1401   return std::make_pair(T, true);
1402 }
1403 
1404 // Return true if the relocation target is an in range Thunk.
1405 // Return false if the relocation is not to a Thunk. If the relocation target
1406 // was originally to a Thunk, but is no longer in range we revert the
1407 // relocation back to its original non-Thunk target.
1408 bool ThunkCreator::normalizeExistingThunk(Relocation &Rel, uint64_t Src) {
1409   if (Thunk *T = Thunks.lookup(Rel.Sym)) {
1410     if (Target->inBranchRange(Rel.Type, Src, Rel.Sym->getVA()))
1411       return true;
1412     Rel.Sym = &T->Destination;
1413     if (Rel.Sym->isInPlt())
1414       Rel.Expr = toPlt(Rel.Expr);
1415   }
1416   return false;
1417 }
1418 
1419 // Process all relocations from the InputSections that have been assigned
1420 // to InputSectionDescriptions and redirect through Thunks if needed. The
1421 // function should be called iteratively until it returns false.
1422 //
1423 // PreConditions:
1424 // All InputSections that may need a Thunk are reachable from
1425 // OutputSectionCommands.
1426 //
1427 // All OutputSections have an address and all InputSections have an offset
1428 // within the OutputSection.
1429 //
1430 // The offsets between caller (relocation place) and callee
1431 // (relocation target) will not be modified outside of createThunks().
1432 //
1433 // PostConditions:
1434 // If return value is true then ThunkSections have been inserted into
1435 // OutputSections. All relocations that needed a Thunk based on the information
1436 // available to createThunks() on entry have been redirected to a Thunk. Note
1437 // that adding Thunks changes offsets between caller and callee so more Thunks
1438 // may be required.
1439 //
1440 // If return value is false then no more Thunks are needed, and createThunks has
1441 // made no changes. If the target requires range extension thunks, currently
1442 // ARM, then any future change in offset between caller and callee risks a
1443 // relocation out of range error.
1444 bool ThunkCreator::createThunks(ArrayRef<OutputSection *> OutputSections) {
1445   bool AddressesChanged = false;
1446 
1447   if (Pass == 0 && Target->getThunkSectionSpacing())
1448     createInitialThunkSections(OutputSections);
1449 
1450   // With Thunk Size much smaller than branch range we expect to
1451   // converge quickly; if we get to 10 something has gone wrong.
1452   if (Pass == 10)
1453     fatal("thunk creation not converged");
1454 
1455   // Create all the Thunks and insert them into synthetic ThunkSections. The
1456   // ThunkSections are later inserted back into InputSectionDescriptions.
1457   // We separate the creation of ThunkSections from the insertion of the
1458   // ThunkSections as ThunkSections are not always inserted into the same
1459   // InputSectionDescription as the caller.
1460   forEachInputSectionDescription(
1461       OutputSections, [&](OutputSection *OS, InputSectionDescription *ISD) {
1462         for (InputSection *IS : ISD->Sections)
1463           for (Relocation &Rel : IS->Relocations) {
1464             uint64_t Src = IS->getVA(Rel.Offset);
1465 
1466             // If we are a relocation to an existing Thunk, check if it is
1467             // still in range. If not then Rel will be altered to point to its
1468             // original target so another Thunk can be generated.
1469             if (Pass > 0 && normalizeExistingThunk(Rel, Src))
1470               continue;
1471 
1472             if (!Target->needsThunk(Rel.Expr, Rel.Type, IS->File, Src,
1473                                     *Rel.Sym))
1474               continue;
1475 
1476             Thunk *T;
1477             bool IsNew;
1478             std::tie(T, IsNew) = getThunk(*Rel.Sym, Rel.Type, Src);
1479 
1480             if (IsNew) {
1481               // Find or create a ThunkSection for the new Thunk
1482               ThunkSection *TS;
1483               if (auto *TIS = T->getTargetInputSection())
1484                 TS = getISThunkSec(TIS);
1485               else
1486                 TS = getISDThunkSec(OS, IS, ISD, Rel.Type, Src);
1487               TS->addThunk(T);
1488               Thunks[T->getThunkTargetSym()] = T;
1489             }
1490 
1491             // Redirect relocation to Thunk, we never go via the PLT to a Thunk
1492             Rel.Sym = T->getThunkTargetSym();
1493             Rel.Expr = fromPlt(Rel.Expr);
1494           }
1495 
1496         for (auto &P : ISD->ThunkSections)
1497           AddressesChanged |= P.first->assignOffsets();
1498       });
1499 
1500   for (auto &P : ThunkedSections)
1501     AddressesChanged |= P.second->assignOffsets();
1502 
1503   // Merge all created synthetic ThunkSections back into OutputSection
1504   mergeThunks(OutputSections);
1505   ++Pass;
1506   return AddressesChanged;
1507 }
1508 
1509 template void elf::scanRelocations<ELF32LE>(InputSectionBase &);
1510 template void elf::scanRelocations<ELF32BE>(InputSectionBase &);
1511 template void elf::scanRelocations<ELF64LE>(InputSectionBase &);
1512 template void elf::scanRelocations<ELF64BE>(InputSectionBase &);
1513