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