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