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 "OutputSections.h"
47 #include "Strings.h"
48 #include "SymbolTable.h"
49 #include "SyntheticSections.h"
50 #include "Target.h"
51 #include "Thunks.h"
52 
53 #include "llvm/Support/Endian.h"
54 #include "llvm/Support/raw_ostream.h"
55 
56 using namespace llvm;
57 using namespace llvm::ELF;
58 using namespace llvm::object;
59 using namespace llvm::support::endian;
60 
61 namespace lld {
62 namespace elf {
63 
64 static bool refersToGotEntry(RelExpr Expr) {
65   return Expr == R_GOT || Expr == R_GOT_OFF || Expr == R_MIPS_GOT_LOCAL_PAGE ||
66          Expr == R_MIPS_GOT_OFF || Expr == R_MIPS_GOT_OFF32 ||
67          Expr == R_MIPS_TLSGD || Expr == R_MIPS_TLSLD ||
68          Expr == R_GOT_PAGE_PC || Expr == R_GOT_PC || Expr == R_GOT_FROM_END ||
69          Expr == R_TLSGD || Expr == R_TLSGD_PC || Expr == R_TLSDESC ||
70          Expr == R_TLSDESC_PAGE;
71 }
72 
73 static bool isPreemptible(const SymbolBody &Body, uint32_t Type) {
74   // In case of MIPS GP-relative relocations always resolve to a definition
75   // in a regular input file, ignoring the one-definition rule. So we,
76   // for example, should not attempt to create a dynamic relocation even
77   // if the target symbol is preemptible. There are two two MIPS GP-relative
78   // relocations R_MIPS_GPREL16 and R_MIPS_GPREL32. But only R_MIPS_GPREL16
79   // can be against a preemptible symbol.
80   // To get MIPS relocation type we apply 0xff mask. In case of O32 ABI all
81   // relocation types occupy eight bit. In case of N64 ABI we extract first
82   // relocation from 3-in-1 packet because only the first relocation can
83   // be against a real symbol.
84   if (Config->EMachine == EM_MIPS && (Type & 0xff) == R_MIPS_GPREL16)
85     return false;
86   return Body.isPreemptible();
87 }
88 
89 // This function is similar to the `handleTlsRelocation`. ARM and MIPS do not
90 // support any relaxations for TLS relocations so by factoring out ARM and MIPS
91 // handling in to the separate function we can simplify the code and do not
92 // pollute `handleTlsRelocation` by ARM and MIPS `ifs` statements.
93 // FIXME: The ARM implementation always adds the module index dynamic
94 // relocation even for non-preemptible symbols in applications. For static
95 // linking support we must either resolve the module index relocation at static
96 // link time, or hard code the module index (1) for the application in the GOT.
97 template <class ELFT>
98 static unsigned handleNoRelaxTlsRelocation(uint32_t Type, SymbolBody &Body,
99                                            InputSectionBase<ELFT> &C,
100                                            typename ELFT::uint Offset,
101                                            typename ELFT::uint Addend,
102                                            RelExpr Expr) {
103   if (Expr == R_MIPS_TLSLD || Expr == R_TLSLD_PC) {
104     if (In<ELFT>::Got->addTlsIndex() &&
105         (Config->Pic || Config->EMachine == EM_ARM))
106       Out<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, In<ELFT>::Got,
107                                     In<ELFT>::Got->getTlsIndexOff(), false,
108                                     nullptr, 0});
109     C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
110     return 1;
111   }
112   typedef typename ELFT::uint uintX_t;
113   if (Target->isTlsGlobalDynamicRel(Type)) {
114     if (In<ELFT>::Got->addDynTlsEntry(Body) &&
115         (Body.isPreemptible() || Config->EMachine == EM_ARM)) {
116       uintX_t Off = In<ELFT>::Got->getGlobalDynOffset(Body);
117       Out<ELFT>::RelaDyn->addReloc(
118           {Target->TlsModuleIndexRel, In<ELFT>::Got, Off, false, &Body, 0});
119       if (Body.isPreemptible())
120         Out<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, In<ELFT>::Got,
121                                       Off + (uintX_t)sizeof(uintX_t), false,
122                                       &Body, 0});
123     }
124     C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
125     return 1;
126   }
127   return 0;
128 }
129 
130 // Returns the number of relocations processed.
131 template <class ELFT>
132 static unsigned handleTlsRelocation(uint32_t Type, SymbolBody &Body,
133                                     InputSectionBase<ELFT> &C,
134                                     typename ELFT::uint Offset,
135                                     typename ELFT::uint Addend, RelExpr Expr) {
136   if (!(C.Flags & SHF_ALLOC))
137     return 0;
138 
139   if (!Body.isTls())
140     return 0;
141 
142   typedef typename ELFT::uint uintX_t;
143 
144   if (Config->EMachine == EM_MIPS || Config->EMachine == EM_ARM)
145     return handleNoRelaxTlsRelocation<ELFT>(Type, Body, C, Offset, Addend,
146                                             Expr);
147 
148   if ((Expr == R_TLSDESC || Expr == R_TLSDESC_PAGE || Expr == R_TLSDESC_CALL) &&
149       Config->Shared) {
150     if (In<ELFT>::Got->addDynTlsEntry(Body)) {
151       uintX_t Off = In<ELFT>::Got->getGlobalDynOffset(Body);
152       Out<ELFT>::RelaDyn->addReloc(
153           {Target->TlsDescRel, In<ELFT>::Got, Off, false, &Body, 0});
154     }
155     if (Expr != R_TLSDESC_CALL)
156       C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
157     return 1;
158   }
159 
160   if (Expr == R_TLSLD_PC || Expr == R_TLSLD) {
161     // Local-Dynamic relocs can be relaxed to Local-Exec.
162     if (!Config->Shared) {
163       C.Relocations.push_back(
164           {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Body});
165       return 2;
166     }
167     if (In<ELFT>::Got->addTlsIndex())
168       Out<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, In<ELFT>::Got,
169                                     In<ELFT>::Got->getTlsIndexOff(), false,
170                                     nullptr, 0});
171     C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
172     return 1;
173   }
174 
175   // Local-Dynamic relocs can be relaxed to Local-Exec.
176   if (Target->isTlsLocalDynamicRel(Type) && !Config->Shared) {
177     C.Relocations.push_back(
178         {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Body});
179     return 1;
180   }
181 
182   if (Expr == R_TLSDESC_PAGE || Expr == R_TLSDESC || Expr == R_TLSDESC_CALL ||
183       Target->isTlsGlobalDynamicRel(Type)) {
184     if (Config->Shared) {
185       if (In<ELFT>::Got->addDynTlsEntry(Body)) {
186         uintX_t Off = In<ELFT>::Got->getGlobalDynOffset(Body);
187         Out<ELFT>::RelaDyn->addReloc(
188             {Target->TlsModuleIndexRel, In<ELFT>::Got, Off, false, &Body, 0});
189 
190         // If the symbol is preemptible we need the dynamic linker to write
191         // the offset too.
192         if (isPreemptible(Body, Type))
193           Out<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, In<ELFT>::Got,
194                                         Off + (uintX_t)sizeof(uintX_t), false,
195                                         &Body, 0});
196       }
197       C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
198       return 1;
199     }
200 
201     // Global-Dynamic relocs can be relaxed to Initial-Exec or Local-Exec
202     // depending on the symbol being locally defined or not.
203     if (isPreemptible(Body, Type)) {
204       C.Relocations.push_back(
205           {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_IE), Type,
206            Offset, Addend, &Body});
207       if (!Body.isInGot()) {
208         In<ELFT>::Got->addEntry(Body);
209         Out<ELFT>::RelaDyn->addReloc({Target->TlsGotRel, In<ELFT>::Got,
210                                       Body.getGotOffset<ELFT>(), false, &Body,
211                                       0});
212       }
213       return Target->TlsGdRelaxSkip;
214     }
215     C.Relocations.push_back(
216         {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_LE), Type,
217          Offset, Addend, &Body});
218     return Target->TlsGdRelaxSkip;
219   }
220 
221   // Initial-Exec relocs can be relaxed to Local-Exec if the symbol is locally
222   // defined.
223   if (Target->isTlsInitialExecRel(Type) && !Config->Shared &&
224       !isPreemptible(Body, Type)) {
225     C.Relocations.push_back(
226         {R_RELAX_TLS_IE_TO_LE, Type, Offset, Addend, &Body});
227     return 1;
228   }
229   return 0;
230 }
231 
232 template <endianness E> static int16_t readSignedLo16(const uint8_t *Loc) {
233   return read32<E>(Loc) & 0xffff;
234 }
235 
236 template <class RelTy>
237 static uint32_t getMipsPairType(const RelTy *Rel, const SymbolBody &Sym) {
238   switch (Rel->getType(Config->Mips64EL)) {
239   case R_MIPS_HI16:
240     return R_MIPS_LO16;
241   case R_MIPS_GOT16:
242     return Sym.isLocal() ? R_MIPS_LO16 : R_MIPS_NONE;
243   case R_MIPS_PCHI16:
244     return R_MIPS_PCLO16;
245   case R_MICROMIPS_HI16:
246     return R_MICROMIPS_LO16;
247   default:
248     return R_MIPS_NONE;
249   }
250 }
251 
252 template <class ELFT, class RelTy>
253 static int32_t findMipsPairedAddend(const uint8_t *Buf, const uint8_t *BufLoc,
254                                     SymbolBody &Sym, const RelTy *Rel,
255                                     const RelTy *End) {
256   uint32_t SymIndex = Rel->getSymbol(Config->Mips64EL);
257   uint32_t Type = getMipsPairType(Rel, Sym);
258 
259   // Some MIPS relocations use addend calculated from addend of the relocation
260   // itself and addend of paired relocation. ABI requires to compute such
261   // combined addend in case of REL relocation record format only.
262   // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
263   if (RelTy::IsRela || Type == R_MIPS_NONE)
264     return 0;
265 
266   for (const RelTy *RI = Rel; RI != End; ++RI) {
267     if (RI->getType(Config->Mips64EL) != Type)
268       continue;
269     if (RI->getSymbol(Config->Mips64EL) != SymIndex)
270       continue;
271     const endianness E = ELFT::TargetEndianness;
272     return ((read32<E>(BufLoc) & 0xffff) << 16) +
273            readSignedLo16<E>(Buf + RI->r_offset);
274   }
275   warn("can't find matching " + getRelName(Type) + " relocation for " +
276        getRelName(Rel->getType(Config->Mips64EL)));
277   return 0;
278 }
279 
280 // True if non-preemptable symbol always has the same value regardless of where
281 // the DSO is loaded.
282 template <class ELFT> static bool isAbsolute(const SymbolBody &Body) {
283   if (Body.isUndefined())
284     return !Body.isLocal() && Body.symbol()->isWeak();
285   if (const auto *DR = dyn_cast<DefinedRegular<ELFT>>(&Body))
286     return DR->Section == nullptr; // Absolute symbol.
287   return false;
288 }
289 
290 template <class ELFT> static bool isAbsoluteValue(const SymbolBody &Body) {
291   return isAbsolute<ELFT>(Body) || Body.isTls();
292 }
293 
294 static bool needsPlt(RelExpr Expr) {
295   return Expr == R_PLT_PC || Expr == R_PPC_PLT_OPD || Expr == R_PLT ||
296          Expr == R_PLT_PAGE_PC || Expr == R_THUNK_PLT_PC;
297 }
298 
299 // True if this expression is of the form Sym - X, where X is a position in the
300 // file (PC, or GOT for example).
301 static bool isRelExpr(RelExpr Expr) {
302   return Expr == R_PC || Expr == R_GOTREL || Expr == R_GOTREL_FROM_END ||
303          Expr == R_PAGE_PC || Expr == R_RELAX_GOT_PC || Expr == R_THUNK_PC ||
304          Expr == R_THUNK_PLT_PC;
305 }
306 
307 template <class ELFT>
308 static bool isStaticLinkTimeConstant(RelExpr E, uint32_t Type,
309                                      const SymbolBody &Body) {
310   // These expressions always compute a constant
311   if (E == R_SIZE || E == R_GOT_FROM_END || E == R_GOT_OFF ||
312       E == R_MIPS_GOT_LOCAL_PAGE || E == R_MIPS_GOT_OFF ||
313       E == R_MIPS_GOT_OFF32 || E == R_MIPS_TLSGD || E == R_GOT_PAGE_PC ||
314       E == R_GOT_PC || E == R_PLT_PC || E == R_TLSGD_PC || E == R_TLSGD ||
315       E == R_PPC_PLT_OPD || E == R_TLSDESC_CALL || E == R_TLSDESC_PAGE ||
316       E == R_HINT || E == R_THUNK_PC || E == R_THUNK_PLT_PC)
317     return true;
318 
319   // These never do, except if the entire file is position dependent or if
320   // only the low bits are used.
321   if (E == R_GOT || E == R_PLT || E == R_TLSDESC)
322     return Target->usesOnlyLowPageBits(Type) || !Config->Pic;
323 
324   if (isPreemptible(Body, Type))
325     return false;
326 
327   if (!Config->Pic)
328     return true;
329 
330   bool AbsVal = isAbsoluteValue<ELFT>(Body);
331   bool RelE = isRelExpr(E);
332   if (AbsVal && !RelE)
333     return true;
334   if (!AbsVal && RelE)
335     return true;
336 
337   // Relative relocation to an absolute value. This is normally unrepresentable,
338   // but if the relocation refers to a weak undefined symbol, we allow it to
339   // resolve to the image base. This is a little strange, but it allows us to
340   // link function calls to such symbols. Normally such a call will be guarded
341   // with a comparison, which will load a zero from the GOT.
342   if (AbsVal && RelE) {
343     if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak())
344       return true;
345     error("relocation " + getRelName(Type) +
346           " cannot refer to absolute symbol " + Body.getName());
347     return true;
348   }
349 
350   return Target->usesOnlyLowPageBits(Type);
351 }
352 
353 static RelExpr toPlt(RelExpr Expr) {
354   if (Expr == R_PPC_OPD)
355     return R_PPC_PLT_OPD;
356   if (Expr == R_PC)
357     return R_PLT_PC;
358   if (Expr == R_PAGE_PC)
359     return R_PLT_PAGE_PC;
360   if (Expr == R_ABS)
361     return R_PLT;
362   return Expr;
363 }
364 
365 static RelExpr fromPlt(RelExpr Expr) {
366   // We decided not to use a plt. Optimize a reference to the plt to a
367   // reference to the symbol itself.
368   if (Expr == R_PLT_PC)
369     return R_PC;
370   if (Expr == R_PPC_PLT_OPD)
371     return R_PPC_OPD;
372   if (Expr == R_PLT)
373     return R_ABS;
374   return Expr;
375 }
376 
377 template <class ELFT> static uint32_t getAlignment(SharedSymbol<ELFT> *SS) {
378   typedef typename ELFT::uint uintX_t;
379 
380   uintX_t SecAlign = SS->file()->getSection(SS->Sym)->sh_addralign;
381   uintX_t SymValue = SS->Sym.st_value;
382   int TrailingZeros =
383       std::min(countTrailingZeros(SecAlign), countTrailingZeros(SymValue));
384   return 1 << TrailingZeros;
385 }
386 
387 // Reserve space in .bss for copy relocation.
388 template <class ELFT> static void addCopyRelSymbol(SharedSymbol<ELFT> *SS) {
389   typedef typename ELFT::uint uintX_t;
390   typedef typename ELFT::Sym Elf_Sym;
391 
392   // Copy relocation against zero-sized symbol doesn't make sense.
393   uintX_t SymSize = SS->template getSize<ELFT>();
394   if (SymSize == 0)
395     fatal("cannot create a copy relocation for symbol " + SS->getName());
396 
397   uintX_t Alignment = getAlignment(SS);
398   uintX_t Off = alignTo(Out<ELFT>::Bss->Size, Alignment);
399   Out<ELFT>::Bss->Size = Off + SymSize;
400   Out<ELFT>::Bss->updateAlignment(Alignment);
401   uintX_t Shndx = SS->Sym.st_shndx;
402   uintX_t Value = SS->Sym.st_value;
403   // Look through the DSO's dynamic symbol table for aliases and create a
404   // dynamic symbol for each one. This causes the copy relocation to correctly
405   // interpose any aliases.
406   for (const Elf_Sym &S : SS->file()->getGlobalSymbols()) {
407     if (S.st_shndx != Shndx || S.st_value != Value)
408       continue;
409     auto *Alias = dyn_cast_or_null<SharedSymbol<ELFT>>(
410         Symtab<ELFT>::X->find(check(S.getName(SS->file()->getStringTable()))));
411     if (!Alias)
412       continue;
413     Alias->OffsetInBss = Off;
414     Alias->NeedsCopyOrPltAddr = true;
415     Alias->symbol()->IsUsedInRegularObj = true;
416   }
417   Out<ELFT>::RelaDyn->addReloc(
418       {Target->CopyRel, Out<ELFT>::Bss, SS->OffsetInBss, false, SS, 0});
419 }
420 
421 template <class ELFT>
422 static RelExpr adjustExpr(const elf::ObjectFile<ELFT> &File, SymbolBody &Body,
423                           bool IsWrite, RelExpr Expr, uint32_t Type,
424                           const uint8_t *Data) {
425   bool Preemptible = isPreemptible(Body, Type);
426   if (Body.isGnuIFunc()) {
427     Expr = toPlt(Expr);
428   } else if (!Preemptible) {
429     if (needsPlt(Expr))
430       Expr = fromPlt(Expr);
431     if (Expr == R_GOT_PC && !isAbsoluteValue<ELFT>(Body))
432       Expr = Target->adjustRelaxExpr(Type, Data, Expr);
433   }
434   Expr = Target->getThunkExpr(Expr, Type, File, Body);
435 
436   if (IsWrite || isStaticLinkTimeConstant<ELFT>(Expr, Type, Body))
437     return Expr;
438 
439   // This relocation would require the dynamic linker to write a value to read
440   // only memory. We can hack around it if we are producing an executable and
441   // the refered symbol can be preemepted to refer to the executable.
442   if (Config->Shared || (Config->Pic && !isRelExpr(Expr))) {
443     StringRef Name = getSymbolName(File.getStringTable(), Body);
444     error("can't create dynamic relocation " + getRelName(Type) + " against " +
445           (Name.empty() ? "readonly segment" : "symbol " + Name));
446     return Expr;
447   }
448   if (Body.getVisibility() != STV_DEFAULT) {
449     error("cannot preempt symbol " + Body.getName());
450     return Expr;
451   }
452   if (Body.isObject()) {
453     // Produce a copy relocation.
454     auto *B = cast<SharedSymbol<ELFT>>(&Body);
455     if (!B->needsCopy())
456       addCopyRelSymbol(B);
457     return Expr;
458   }
459   if (Body.isFunc()) {
460     // This handles a non PIC program call to function in a shared library. In
461     // an ideal world, we could just report an error saying the relocation can
462     // overflow at runtime. In the real world with glibc, crt1.o has a
463     // R_X86_64_PC32 pointing to libc.so.
464     //
465     // The general idea on how to handle such cases is to create a PLT entry and
466     // use that as the function value.
467     //
468     // For the static linking part, we just return a plt expr and everything
469     // else will use the the PLT entry as the address.
470     //
471     // The remaining problem is making sure pointer equality still works. We
472     // need the help of the dynamic linker for that. We let it know that we have
473     // a direct reference to a so symbol by creating an undefined symbol with a
474     // non zero st_value. Seeing that, the dynamic linker resolves the symbol to
475     // the value of the symbol we created. This is true even for got entries, so
476     // pointer equality is maintained. To avoid an infinite loop, the only entry
477     // that points to the real function is a dedicated got entry used by the
478     // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT,
479     // R_386_JMP_SLOT, etc).
480     Body.NeedsCopyOrPltAddr = true;
481     return toPlt(Expr);
482   }
483   error("symbol " + Body.getName() + " is missing type");
484 
485   return Expr;
486 }
487 
488 template <class ELFT, class RelTy>
489 static typename ELFT::uint computeAddend(const elf::ObjectFile<ELFT> &File,
490                                          const uint8_t *SectionData,
491                                          const RelTy *End, const RelTy &RI,
492                                          RelExpr Expr, SymbolBody &Body) {
493   typedef typename ELFT::uint uintX_t;
494 
495   uint32_t Type = RI.getType(Config->Mips64EL);
496   uintX_t Addend = getAddend<ELFT>(RI);
497   const uint8_t *BufLoc = SectionData + RI.r_offset;
498   if (!RelTy::IsRela)
499     Addend += Target->getImplicitAddend(BufLoc, Type);
500   if (Config->EMachine == EM_MIPS) {
501     Addend += findMipsPairedAddend<ELFT>(SectionData, BufLoc, Body, &RI, End);
502     if (Type == R_MIPS_LO16 && Expr == R_PC)
503       // R_MIPS_LO16 expression has R_PC type iif the target is _gp_disp
504       // symbol. In that case we should use the following formula for
505       // calculation "AHL + GP - P + 4". Let's add 4 right here.
506       // For details see p. 4-19 at
507       // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
508       Addend += 4;
509     if (Expr == R_GOTREL) {
510       Addend -= MipsGPOffset;
511       if (Body.isLocal())
512         Addend += File.MipsGp0;
513     }
514   }
515   if (Config->Pic && Config->EMachine == EM_PPC64 && Type == R_PPC64_TOC)
516     Addend += getPPC64TocBase();
517   return Addend;
518 }
519 
520 // Find symbol that encloses given offset. Used for error reporting.
521 template <class ELFT>
522 static DefinedRegular<ELFT> *getSymbolAt(InputSectionBase<ELFT> *S,
523                                          typename ELFT::uint Offset) {
524   for (SymbolBody *B : S->getFile()->getSymbols())
525     if (auto *D = dyn_cast<DefinedRegular<ELFT>>(B))
526       if (D->Value <= Offset && D->Value + D->Size > Offset && D->Section == S)
527         return D;
528 
529   return nullptr;
530 }
531 
532 template <class ELFT>
533 std::string getLocation(InputSectionBase<ELFT> &S, typename ELFT::uint Offset) {
534   ObjectFile<ELFT> *File = S.getFile();
535 
536   // First check if we can get desired values from debugging information.
537   std::string LineInfo = File->getLineInfo(&S, Offset);
538   if (!LineInfo.empty())
539     return LineInfo;
540 
541   // File->SourceFile contains STT_FILE symbol contents which is a
542   // filename. Compilers usually create STT_FILE symbols. If it's
543   // missing, we use an actual filename.
544   std::string SrcFile = File->SourceFile;
545   if (SrcFile.empty())
546     SrcFile = getFilename(File);
547 
548   // Find a symbol at a given location.
549   DefinedRegular<ELFT> *Encl = getSymbolAt(&S, Offset);
550   if (Encl && Encl->Type == STT_FUNC) {
551     StringRef Func = getSymbolName(File->getStringTable(), *Encl);
552     return SrcFile + " (function " + maybeDemangle(Func) + ")";
553   }
554 
555   // If there's no symbol, print out the offset instead of a symbol name.
556   return (SrcFile + " (" + S.Name + "+0x" + Twine::utohexstr(Offset) + ")")
557       .str();
558 }
559 
560 template <class ELFT>
561 static void reportUndefined(SymbolBody &Sym, InputSectionBase<ELFT> &S,
562                             typename ELFT::uint Offset) {
563   if (Config->UnresolvedSymbols == UnresolvedPolicy::Ignore)
564     return;
565 
566   if (Config->Shared && Sym.symbol()->Visibility == STV_DEFAULT &&
567       Config->UnresolvedSymbols != UnresolvedPolicy::NoUndef)
568     return;
569 
570   std::string Msg = getLocation(S, Offset) + ": undefined symbol '" +
571                     maybeDemangle(Sym.getName()) + "'";
572 
573   if (Config->UnresolvedSymbols == UnresolvedPolicy::Warn)
574     warn(Msg);
575   else
576     error(Msg);
577 }
578 
579 template <class RelTy>
580 static std::pair<uint32_t, uint32_t>
581 mergeMipsN32RelTypes(uint32_t Type, uint32_t Offset, RelTy *I, RelTy *E) {
582   // MIPS N32 ABI treats series of successive relocations with the same offset
583   // as a single relocation. The similar approach used by N64 ABI, but this ABI
584   // packs all relocations into the single relocation record. Here we emulate
585   // this for the N32 ABI. Iterate over relocation with the same offset and put
586   // theirs types into the single bit-set.
587   uint32_t Processed = 0;
588   for (; I != E && Offset == I->r_offset; ++I) {
589     ++Processed;
590     Type |= I->getType(Config->Mips64EL) << (8 * Processed);
591   }
592   return std::make_pair(Type, Processed);
593 }
594 
595 // The reason we have to do this early scan is as follows
596 // * To mmap the output file, we need to know the size
597 // * For that, we need to know how many dynamic relocs we will have.
598 // It might be possible to avoid this by outputting the file with write:
599 // * Write the allocated output sections, computing addresses.
600 // * Apply relocations, recording which ones require a dynamic reloc.
601 // * Write the dynamic relocations.
602 // * Write the rest of the file.
603 // This would have some drawbacks. For example, we would only know if .rela.dyn
604 // is needed after applying relocations. If it is, it will go after rw and rx
605 // sections. Given that it is ro, we will need an extra PT_LOAD. This
606 // complicates things for the dynamic linker and means we would have to reserve
607 // space for the extra PT_LOAD even if we end up not using it.
608 template <class ELFT, class RelTy>
609 static void scanRelocs(InputSectionBase<ELFT> &C, ArrayRef<RelTy> Rels) {
610   typedef typename ELFT::uint uintX_t;
611 
612   bool IsWrite = C.Flags & SHF_WRITE;
613 
614   auto AddDyn = [=](const DynamicReloc<ELFT> &Reloc) {
615     Out<ELFT>::RelaDyn->addReloc(Reloc);
616   };
617 
618   const elf::ObjectFile<ELFT> &File = *C.getFile();
619   ArrayRef<uint8_t> SectionData = C.Data;
620   const uint8_t *Buf = SectionData.begin();
621 
622   ArrayRef<EhSectionPiece> Pieces;
623   if (auto *Eh = dyn_cast<EhInputSection<ELFT>>(&C))
624     Pieces = Eh->Pieces;
625 
626   ArrayRef<EhSectionPiece>::iterator PieceI = Pieces.begin();
627   ArrayRef<EhSectionPiece>::iterator PieceE = Pieces.end();
628 
629   for (auto I = Rels.begin(), E = Rels.end(); I != E; ++I) {
630     const RelTy &RI = *I;
631     SymbolBody &Body = File.getRelocTargetSym(RI);
632     uint32_t Type = RI.getType(Config->Mips64EL);
633 
634     if (Config->MipsN32Abi) {
635       uint32_t Processed;
636       std::tie(Type, Processed) =
637           mergeMipsN32RelTypes(Type, RI.r_offset, I + 1, E);
638       I += Processed;
639     }
640 
641     // We only report undefined symbols if they are referenced somewhere in the
642     // code.
643     if (!Body.isLocal() && Body.isUndefined() && !Body.symbol()->isWeak())
644       reportUndefined(Body, C, RI.r_offset);
645 
646     RelExpr Expr = Target->getRelExpr(Type, Body);
647     bool Preemptible = isPreemptible(Body, Type);
648     Expr = adjustExpr(File, Body, IsWrite, Expr, Type, Buf + RI.r_offset);
649     if (HasError)
650       continue;
651 
652     // Skip a relocation that points to a dead piece
653     // in a eh_frame section.
654     while (PieceI != PieceE &&
655            (PieceI->InputOff + PieceI->size() <= RI.r_offset))
656       ++PieceI;
657 
658     // Compute the offset of this section in the output section. We do it here
659     // to try to compute it only once.
660     uintX_t Offset;
661     if (PieceI != PieceE) {
662       assert(PieceI->InputOff <= RI.r_offset && "Relocation not in any piece");
663       if (PieceI->OutputOff == -1)
664         continue;
665       Offset = PieceI->OutputOff + RI.r_offset - PieceI->InputOff;
666     } else {
667       Offset = RI.r_offset;
668     }
669 
670     // This relocation does not require got entry, but it is relative to got and
671     // needs it to be created. Here we request for that.
672     if (Expr == R_GOTONLY_PC || Expr == R_GOTONLY_PC_FROM_END ||
673         Expr == R_GOTREL || Expr == R_GOTREL_FROM_END || Expr == R_PPC_TOC)
674       In<ELFT>::Got->HasGotOffRel = true;
675 
676     uintX_t Addend = computeAddend(File, Buf, E, RI, Expr, Body);
677 
678     if (unsigned Processed =
679             handleTlsRelocation<ELFT>(Type, Body, C, Offset, Addend, Expr)) {
680       I += (Processed - 1);
681       continue;
682     }
683 
684     // Ignore "hint" and TLS Descriptor call relocation because they are
685     // only markers for relaxation.
686     if (Expr == R_HINT || Expr == R_TLSDESC_CALL)
687       continue;
688 
689     if (needsPlt(Expr) || Expr == R_THUNK_ABS || Expr == R_THUNK_PC ||
690         Expr == R_THUNK_PLT_PC || refersToGotEntry(Expr) ||
691         !isPreemptible(Body, Type)) {
692       // If the relocation points to something in the file, we can process it.
693       bool Constant = isStaticLinkTimeConstant<ELFT>(Expr, Type, Body);
694 
695       // If the output being produced is position independent, the final value
696       // is still not known. In that case we still need some help from the
697       // dynamic linker. We can however do better than just copying the incoming
698       // relocation. We can process some of it and and just ask the dynamic
699       // linker to add the load address.
700       if (!Constant)
701         AddDyn({Target->RelativeRel, &C, Offset, true, &Body, Addend});
702 
703       // If the produced value is a constant, we just remember to write it
704       // when outputting this section. We also have to do it if the format
705       // uses Elf_Rel, since in that case the written value is the addend.
706       if (Constant || !RelTy::IsRela)
707         C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
708     } else {
709       // We don't know anything about the finaly symbol. Just ask the dynamic
710       // linker to handle the relocation for us.
711       AddDyn({Target->getDynRel(Type), &C, Offset, false, &Body, Addend});
712       // MIPS ABI turns using of GOT and dynamic relocations inside out.
713       // While regular ABI uses dynamic relocations to fill up GOT entries
714       // MIPS ABI requires dynamic linker to fills up GOT entries using
715       // specially sorted dynamic symbol table. This affects even dynamic
716       // relocations against symbols which do not require GOT entries
717       // creation explicitly, i.e. do not have any GOT-relocations. So if
718       // a preemptible symbol has a dynamic relocation we anyway have
719       // to create a GOT entry for it.
720       // If a non-preemptible symbol has a dynamic relocation against it,
721       // dynamic linker takes it st_value, adds offset and writes down
722       // result of the dynamic relocation. In case of preemptible symbol
723       // dynamic linker performs symbol resolution, writes the symbol value
724       // to the GOT entry and reads the GOT entry when it needs to perform
725       // a dynamic relocation.
726       // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19
727       if (Config->EMachine == EM_MIPS)
728         In<ELFT>::Got->addMipsEntry(Body, Addend, Expr);
729       continue;
730     }
731 
732     // At this point we are done with the relocated position. Some relocations
733     // also require us to create a got or plt entry.
734 
735     // If a relocation needs PLT, we create a PLT and a GOT slot for the symbol.
736     if (needsPlt(Expr)) {
737       if (Body.isInPlt())
738         continue;
739       Out<ELFT>::Plt->addEntry(Body);
740 
741       uint32_t Rel;
742       if (Body.isGnuIFunc() && !Preemptible)
743         Rel = Target->IRelativeRel;
744       else
745         Rel = Target->PltRel;
746 
747       In<ELFT>::GotPlt->addEntry(Body);
748       Out<ELFT>::RelaPlt->addReloc({Rel, In<ELFT>::GotPlt,
749                                     Body.getGotPltOffset<ELFT>(), !Preemptible,
750                                     &Body, 0});
751       continue;
752     }
753 
754     if (refersToGotEntry(Expr)) {
755       if (Config->EMachine == EM_MIPS) {
756         // MIPS ABI has special rules to process GOT entries and doesn't
757         // require relocation entries for them. A special case is TLS
758         // relocations. In that case dynamic loader applies dynamic
759         // relocations to initialize TLS GOT entries.
760         // See "Global Offset Table" in Chapter 5 in the following document
761         // for detailed description:
762         // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
763         In<ELFT>::Got->addMipsEntry(Body, Addend, Expr);
764         if (Body.isTls() && Body.isPreemptible())
765           AddDyn({Target->TlsGotRel, In<ELFT>::Got, Body.getGotOffset<ELFT>(),
766                   false, &Body, 0});
767         continue;
768       }
769 
770       if (Body.isInGot())
771         continue;
772 
773       In<ELFT>::Got->addEntry(Body);
774       if (Preemptible || (Config->Pic && !isAbsolute<ELFT>(Body))) {
775         uint32_t DynType;
776         if (Body.isTls())
777           DynType = Target->TlsGotRel;
778         else if (Preemptible)
779           DynType = Target->GotRel;
780         else
781           DynType = Target->RelativeRel;
782         AddDyn({DynType, In<ELFT>::Got, Body.getGotOffset<ELFT>(), !Preemptible,
783                 &Body, 0});
784       }
785       continue;
786     }
787   }
788 }
789 
790 template <class ELFT> void scanRelocations(InputSectionBase<ELFT> &S) {
791   if (S.AreRelocsRela)
792     scanRelocs(S, S.relas());
793   else
794     scanRelocs(S, S.rels());
795 }
796 
797 template <class ELFT, class RelTy>
798 static void createThunks(InputSectionBase<ELFT> &C, ArrayRef<RelTy> Rels) {
799   const elf::ObjectFile<ELFT> &File = *C.getFile();
800   for (const RelTy &Rel : Rels) {
801     SymbolBody &Body = File.getRelocTargetSym(Rel);
802     uint32_t Type = Rel.getType(Config->Mips64EL);
803     RelExpr Expr = Target->getRelExpr(Type, Body);
804     if (!isPreemptible(Body, Type) && needsPlt(Expr))
805       Expr = fromPlt(Expr);
806     Expr = Target->getThunkExpr(Expr, Type, File, Body);
807     // Some targets might require creation of thunks for relocations.
808     // Now we support only MIPS which requires LA25 thunk to call PIC
809     // code from non-PIC one, and ARM which requires interworking.
810     if (Expr == R_THUNK_ABS || Expr == R_THUNK_PC || Expr == R_THUNK_PLT_PC) {
811       auto *Sec = cast<InputSection<ELFT>>(&C);
812       addThunk<ELFT>(Type, Body, *Sec);
813     }
814   }
815 }
816 
817 template <class ELFT> void createThunks(InputSectionBase<ELFT> &S) {
818   if (S.AreRelocsRela)
819     createThunks(S, S.relas());
820   else
821     createThunks(S, S.rels());
822 }
823 
824 template void scanRelocations<ELF32LE>(InputSectionBase<ELF32LE> &);
825 template void scanRelocations<ELF32BE>(InputSectionBase<ELF32BE> &);
826 template void scanRelocations<ELF64LE>(InputSectionBase<ELF64LE> &);
827 template void scanRelocations<ELF64BE>(InputSectionBase<ELF64BE> &);
828 
829 template void createThunks<ELF32LE>(InputSectionBase<ELF32LE> &);
830 template void createThunks<ELF32BE>(InputSectionBase<ELF32BE> &);
831 template void createThunks<ELF64LE>(InputSectionBase<ELF64LE> &);
832 template void createThunks<ELF64BE>(InputSectionBase<ELF64BE> &);
833 
834 template std::string getLocation<ELF32LE>(InputSectionBase<ELF32LE> &S,
835                                           uint32_t Offset);
836 template std::string getLocation<ELF32BE>(InputSectionBase<ELF32BE> &S,
837                                           uint32_t Offset);
838 template std::string getLocation<ELF64LE>(InputSectionBase<ELF64LE> &S,
839                                           uint64_t Offset);
840 template std::string getLocation<ELF64BE>(InputSectionBase<ELF64BE> &S,
841                                           uint64_t Offset);
842 }
843 }
844