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