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