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