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