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 "Memory.h"
47 #include "OutputSections.h"
48 #include "Strings.h"
49 #include "SymbolTable.h"
50 #include "SyntheticSections.h"
51 #include "Target.h"
52 #include "Thunks.h"
53 
54 #include "llvm/Support/Endian.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include <algorithm>
57 
58 using namespace llvm;
59 using namespace llvm::ELF;
60 using namespace llvm::object;
61 using namespace llvm::support::endian;
62 
63 namespace lld {
64 namespace elf {
65 
66 static bool refersToGotEntry(RelExpr Expr) {
67   return isRelExprOneOf<R_GOT, R_GOT_OFF, R_MIPS_GOT_LOCAL_PAGE, R_MIPS_GOT_OFF,
68                         R_MIPS_GOT_OFF32, R_MIPS_TLSGD, R_MIPS_TLSLD,
69                         R_GOT_PAGE_PC, R_GOT_PC, R_GOT_FROM_END, R_TLSGD,
70                         R_TLSGD_PC, R_TLSDESC, R_TLSDESC_PAGE>(Expr);
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 template <class ELFT, class GOT>
94 static unsigned handleNoRelaxTlsRelocation(
95     GOT *Got, uint32_t Type, SymbolBody &Body, InputSectionBase<ELFT> &C,
96     typename ELFT::uint Offset, typename ELFT::uint Addend, RelExpr Expr) {
97   typedef typename ELFT::uint uintX_t;
98   auto addModuleReloc = [](SymbolBody &Body, GOT *Got, uintX_t Off, bool LD) {
99     // The Dynamic TLS Module Index Relocation can be statically resolved to 1
100     // if we know that we are linking an executable. For ARM we resolve the
101     // relocation when writing the Got. MIPS has a custom Got implementation
102     // that writes the Module index in directly.
103     if (!Body.isPreemptible() && !Config->Pic && Config->EMachine == EM_ARM)
104       Got->Relocations.push_back(
105           {R_ABS, Target->TlsModuleIndexRel, Off, 0, &Body});
106     else {
107       SymbolBody *Dest = LD ? nullptr : &Body;
108       In<ELFT>::RelaDyn->addReloc(
109           {Target->TlsModuleIndexRel, Got, Off, false, Dest, 0});
110     }
111   };
112   if (Expr == R_MIPS_TLSLD || Expr == R_TLSLD_PC) {
113     if (Got->addTlsIndex() && (Config->Pic || Config->EMachine == EM_ARM))
114       addModuleReloc(Body, Got, Got->getTlsIndexOff(), true);
115     C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
116     return 1;
117   }
118   if (Target->isTlsGlobalDynamicRel(Type)) {
119     if (Got->addDynTlsEntry(Body) &&
120         (Body.isPreemptible() || Config->EMachine == EM_ARM)) {
121       uintX_t Off = Got->getGlobalDynOffset(Body);
122       addModuleReloc(Body, Got, Off, false);
123       if (Body.isPreemptible())
124         In<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, Got,
125                                      Off + (uintX_t)sizeof(uintX_t), false,
126                                      &Body, 0});
127     }
128     C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
129     return 1;
130   }
131   return 0;
132 }
133 
134 // Returns the number of relocations processed.
135 template <class ELFT>
136 static unsigned handleTlsRelocation(uint32_t Type, SymbolBody &Body,
137                                     InputSectionBase<ELFT> &C,
138                                     typename ELFT::uint Offset,
139                                     typename ELFT::uint Addend, RelExpr Expr) {
140   if (!(C.Flags & SHF_ALLOC))
141     return 0;
142 
143   if (!Body.isTls())
144     return 0;
145 
146   typedef typename ELFT::uint uintX_t;
147 
148   if (Config->EMachine == EM_ARM)
149     return handleNoRelaxTlsRelocation<ELFT>(In<ELFT>::Got, Type, Body, C,
150                                             Offset, Addend, Expr);
151   if (Config->EMachine == EM_MIPS)
152     return handleNoRelaxTlsRelocation<ELFT>(In<ELFT>::MipsGot, Type, Body, C,
153                                             Offset, Addend, Expr);
154 
155   bool IsPreemptible = isPreemptible(Body, Type);
156   if ((Expr == R_TLSDESC || Expr == R_TLSDESC_PAGE || Expr == R_TLSDESC_CALL) &&
157       Config->Shared) {
158     if (In<ELFT>::Got->addDynTlsEntry(Body)) {
159       uintX_t Off = In<ELFT>::Got->getGlobalDynOffset(Body);
160       In<ELFT>::RelaDyn->addReloc({Target->TlsDescRel, In<ELFT>::Got, Off,
161                                    !IsPreemptible, &Body, 0});
162     }
163     if (Expr != R_TLSDESC_CALL)
164       C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
165     return 1;
166   }
167 
168   if (Expr == R_TLSLD_PC || Expr == R_TLSLD) {
169     // Local-Dynamic relocs can be relaxed to Local-Exec.
170     if (!Config->Shared) {
171       C.Relocations.push_back(
172           {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Body});
173       return 2;
174     }
175     if (In<ELFT>::Got->addTlsIndex())
176       In<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, In<ELFT>::Got,
177                                    In<ELFT>::Got->getTlsIndexOff(), false,
178                                    nullptr, 0});
179     C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
180     return 1;
181   }
182 
183   // Local-Dynamic relocs can be relaxed to Local-Exec.
184   if (Target->isTlsLocalDynamicRel(Type) && !Config->Shared) {
185     C.Relocations.push_back(
186         {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Body});
187     return 1;
188   }
189 
190   if (Expr == R_TLSDESC_PAGE || Expr == R_TLSDESC || Expr == R_TLSDESC_CALL ||
191       Target->isTlsGlobalDynamicRel(Type)) {
192     if (Config->Shared) {
193       if (In<ELFT>::Got->addDynTlsEntry(Body)) {
194         uintX_t Off = In<ELFT>::Got->getGlobalDynOffset(Body);
195         In<ELFT>::RelaDyn->addReloc(
196             {Target->TlsModuleIndexRel, In<ELFT>::Got, Off, false, &Body, 0});
197 
198         // If the symbol is preemptible we need the dynamic linker to write
199         // the offset too.
200         uintX_t OffsetOff = Off + (uintX_t)sizeof(uintX_t);
201         if (IsPreemptible)
202           In<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, In<ELFT>::Got,
203                                        OffsetOff, false, &Body, 0});
204         else
205           In<ELFT>::Got->Relocations.push_back(
206               {R_ABS, Target->TlsOffsetRel, OffsetOff, 0, &Body});
207       }
208       C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
209       return 1;
210     }
211 
212     // Global-Dynamic relocs can be relaxed to Initial-Exec or Local-Exec
213     // depending on the symbol being locally defined or not.
214     if (IsPreemptible) {
215       C.Relocations.push_back(
216           {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_IE), Type,
217            Offset, Addend, &Body});
218       if (!Body.isInGot()) {
219         In<ELFT>::Got->addEntry(Body);
220         In<ELFT>::RelaDyn->addReloc({Target->TlsGotRel, In<ELFT>::Got,
221                                      Body.getGotOffset<ELFT>(), false, &Body,
222                                      0});
223       }
224       return Target->TlsGdRelaxSkip;
225     }
226     C.Relocations.push_back(
227         {Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_LE), Type,
228          Offset, Addend, &Body});
229     return Target->TlsGdRelaxSkip;
230   }
231 
232   // Initial-Exec relocs can be relaxed to Local-Exec if the symbol is locally
233   // defined.
234   if (Target->isTlsInitialExecRel(Type) && !Config->Shared && !IsPreemptible) {
235     C.Relocations.push_back(
236         {R_RELAX_TLS_IE_TO_LE, Type, Offset, Addend, &Body});
237     return 1;
238   }
239   return 0;
240 }
241 
242 template <endianness E> static int16_t readSignedLo16(const uint8_t *Loc) {
243   return read32<E>(Loc) & 0xffff;
244 }
245 
246 template <class RelTy>
247 static uint32_t getMipsPairType(const RelTy *Rel, const SymbolBody &Sym) {
248   switch (Rel->getType(Config->Mips64EL)) {
249   case R_MIPS_HI16:
250     return R_MIPS_LO16;
251   case R_MIPS_GOT16:
252     return Sym.isLocal() ? R_MIPS_LO16 : R_MIPS_NONE;
253   case R_MIPS_PCHI16:
254     return R_MIPS_PCLO16;
255   case R_MICROMIPS_HI16:
256     return R_MICROMIPS_LO16;
257   default:
258     return R_MIPS_NONE;
259   }
260 }
261 
262 template <class ELFT, class RelTy>
263 static int32_t findMipsPairedAddend(const uint8_t *Buf, const uint8_t *BufLoc,
264                                     SymbolBody &Sym, const RelTy *Rel,
265                                     const RelTy *End) {
266   uint32_t SymIndex = Rel->getSymbol(Config->Mips64EL);
267   uint32_t Type = getMipsPairType(Rel, Sym);
268 
269   // Some MIPS relocations use addend calculated from addend of the relocation
270   // itself and addend of paired relocation. ABI requires to compute such
271   // combined addend in case of REL relocation record format only.
272   // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
273   if (RelTy::IsRela || Type == R_MIPS_NONE)
274     return 0;
275 
276   for (const RelTy *RI = Rel; RI != End; ++RI) {
277     if (RI->getType(Config->Mips64EL) != Type)
278       continue;
279     if (RI->getSymbol(Config->Mips64EL) != SymIndex)
280       continue;
281     const endianness E = ELFT::TargetEndianness;
282     return ((read32<E>(BufLoc) & 0xffff) << 16) +
283            readSignedLo16<E>(Buf + RI->r_offset);
284   }
285   warn("can't find matching " + toString(Type) + " relocation for " +
286        toString(Rel->getType(Config->Mips64EL)));
287   return 0;
288 }
289 
290 // True if non-preemptable symbol always has the same value regardless of where
291 // the DSO is loaded.
292 template <class ELFT> static bool isAbsolute(const SymbolBody &Body) {
293   if (Body.isUndefined())
294     return !Body.isLocal() && Body.symbol()->isWeak();
295   if (const auto *DR = dyn_cast<DefinedRegular<ELFT>>(&Body))
296     return DR->Section == nullptr; // Absolute symbol.
297   return false;
298 }
299 
300 template <class ELFT> static bool isAbsoluteValue(const SymbolBody &Body) {
301   return isAbsolute<ELFT>(Body) || Body.isTls();
302 }
303 
304 static bool needsPlt(RelExpr Expr) {
305   return isRelExprOneOf<R_PLT_PC, R_PPC_PLT_OPD, R_PLT, R_PLT_PAGE_PC>(Expr);
306 }
307 
308 // True if this expression is of the form Sym - X, where X is a position in the
309 // file (PC, or GOT for example).
310 static bool isRelExpr(RelExpr Expr) {
311   return isRelExprOneOf<R_PC, R_GOTREL, R_GOTREL_FROM_END, R_MIPS_GOTREL,
312                         R_PAGE_PC, R_RELAX_GOT_PC>(Expr);
313 }
314 
315 template <class ELFT>
316 static bool isStaticLinkTimeConstant(RelExpr E, uint32_t Type,
317                                      const SymbolBody &Body,
318                                      InputSectionBase<ELFT> &S,
319                                      typename ELFT::uint RelOff) {
320   // These expressions always compute a constant
321   if (isRelExprOneOf<R_SIZE, R_GOT_FROM_END, R_GOT_OFF, R_MIPS_GOT_LOCAL_PAGE,
322                      R_MIPS_GOT_OFF, R_MIPS_GOT_OFF32, R_MIPS_TLSGD,
323                      R_GOT_PAGE_PC, R_GOT_PC, R_PLT_PC, R_TLSGD_PC, R_TLSGD,
324                      R_PPC_PLT_OPD, R_TLSDESC_CALL, R_TLSDESC_PAGE, R_HINT>(E))
325     return true;
326 
327   // These never do, except if the entire file is position dependent or if
328   // only the low bits are used.
329   if (E == R_GOT || E == R_PLT || E == R_TLSDESC)
330     return Target->usesOnlyLowPageBits(Type) || !Config->Pic;
331 
332   if (isPreemptible(Body, Type))
333     return false;
334 
335   if (!Config->Pic)
336     return true;
337 
338   bool AbsVal = isAbsoluteValue<ELFT>(Body);
339   bool RelE = isRelExpr(E);
340   if (AbsVal && !RelE)
341     return true;
342   if (!AbsVal && RelE)
343     return true;
344 
345   // Relative relocation to an absolute value. This is normally unrepresentable,
346   // but if the relocation refers to a weak undefined symbol, we allow it to
347   // resolve to the image base. This is a little strange, but it allows us to
348   // link function calls to such symbols. Normally such a call will be guarded
349   // with a comparison, which will load a zero from the GOT.
350   // Another special case is MIPS _gp_disp symbol which represents offset
351   // between start of a function and '_gp' value and defined as absolute just
352   // to simplify the code.
353   if (AbsVal && RelE) {
354     if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak())
355       return true;
356     if (&Body == ElfSym<ELFT>::MipsGpDisp)
357       return true;
358     error(S.getLocation(RelOff) + ": relocation " + toString(Type) +
359           " cannot refer to absolute symbol '" + toString(Body) +
360           "' defined in " + toString(Body.File));
361     return true;
362   }
363 
364   return Target->usesOnlyLowPageBits(Type);
365 }
366 
367 static RelExpr toPlt(RelExpr Expr) {
368   if (Expr == R_PPC_OPD)
369     return R_PPC_PLT_OPD;
370   if (Expr == R_PC)
371     return R_PLT_PC;
372   if (Expr == R_PAGE_PC)
373     return R_PLT_PAGE_PC;
374   if (Expr == R_ABS)
375     return R_PLT;
376   return Expr;
377 }
378 
379 static RelExpr fromPlt(RelExpr Expr) {
380   // We decided not to use a plt. Optimize a reference to the plt to a
381   // reference to the symbol itself.
382   if (Expr == R_PLT_PC)
383     return R_PC;
384   if (Expr == R_PPC_PLT_OPD)
385     return R_PPC_OPD;
386   if (Expr == R_PLT)
387     return R_ABS;
388   return Expr;
389 }
390 
391 template <class ELFT> static uint32_t getAlignment(SharedSymbol<ELFT> *SS) {
392   typedef typename ELFT::uint uintX_t;
393 
394   uintX_t SecAlign = SS->file()->getSection(SS->Sym)->sh_addralign;
395   uintX_t SymValue = SS->Sym.st_value;
396   int TrailingZeros =
397       std::min(countTrailingZeros(SecAlign), countTrailingZeros(SymValue));
398   return 1 << TrailingZeros;
399 }
400 
401 template <class ELFT> static bool isReadOnly(SharedSymbol<ELFT> *SS) {
402   typedef typename ELFT::uint uintX_t;
403   typedef typename ELFT::Phdr Elf_Phdr;
404 
405   // Determine if the symbol is read-only by scanning the DSO's program headers.
406   uintX_t Value = SS->Sym.st_value;
407   for (const Elf_Phdr &Phdr : check(SS->file()->getObj().program_headers()))
408     if ((Phdr.p_type == ELF::PT_LOAD || Phdr.p_type == ELF::PT_GNU_RELRO) &&
409         !(Phdr.p_flags & ELF::PF_W) && Value >= Phdr.p_vaddr &&
410         Value < Phdr.p_vaddr + Phdr.p_memsz)
411       return true;
412   return false;
413 }
414 
415 // Reserve space in .bss or .bss.rel.ro for copy relocation.
416 template <class ELFT> static void addCopyRelSymbol(SharedSymbol<ELFT> *SS) {
417   typedef typename ELFT::uint uintX_t;
418   typedef typename ELFT::Sym Elf_Sym;
419 
420   // Copy relocation against zero-sized symbol doesn't make sense.
421   uintX_t SymSize = SS->template getSize<ELFT>();
422   if (SymSize == 0)
423     fatal("cannot create a copy relocation for symbol " + toString(*SS));
424 
425   // See if this symbol is in a read-only segment. If so, preserve the symbol's
426   // memory protection by reserving space in the .bss.rel.ro section.
427   bool IsReadOnly = isReadOnly(SS);
428   OutputSection<ELFT> *CopySec =
429       IsReadOnly ? Out<ELFT>::BssRelRo : Out<ELFT>::Bss;
430 
431   uintX_t Alignment = getAlignment(SS);
432   uintX_t Off = alignTo(CopySec->Size, Alignment);
433   CopySec->Size = Off + SymSize;
434   CopySec->updateAlignment(Alignment);
435   uintX_t Shndx = SS->Sym.st_shndx;
436   uintX_t Value = SS->Sym.st_value;
437   // Look through the DSO's dynamic symbol table for aliases and create a
438   // dynamic symbol for each one. This causes the copy relocation to correctly
439   // interpose any aliases.
440   for (const Elf_Sym &S : SS->file()->getGlobalSymbols()) {
441     if (S.st_shndx != Shndx || S.st_value != Value)
442       continue;
443     auto *Alias = dyn_cast_or_null<SharedSymbol<ELFT>>(
444         Symtab<ELFT>::X->find(check(S.getName(SS->file()->getStringTable()))));
445     if (!Alias)
446       continue;
447     Alias->CopyIsInBssRelRo = IsReadOnly;
448     Alias->CopyOffset = Off;
449     Alias->NeedsCopyOrPltAddr = true;
450     Alias->symbol()->IsUsedInRegularObj = true;
451   }
452   In<ELFT>::RelaDyn->addReloc({Target->CopyRel, CopySec, Off, false, SS, 0});
453 }
454 
455 template <class ELFT>
456 static RelExpr adjustExpr(const elf::ObjectFile<ELFT> &File, SymbolBody &Body,
457                           bool IsWrite, RelExpr Expr, uint32_t Type,
458                           const uint8_t *Data, InputSectionBase<ELFT> &S,
459                           typename ELFT::uint RelOff) {
460   bool Preemptible = isPreemptible(Body, Type);
461   if (Body.isGnuIFunc()) {
462     Expr = toPlt(Expr);
463   } else if (!Preemptible) {
464     if (needsPlt(Expr))
465       Expr = fromPlt(Expr);
466     if (Expr == R_GOT_PC && !isAbsoluteValue<ELFT>(Body))
467       Expr = Target->adjustRelaxExpr(Type, Data, Expr);
468   }
469 
470   if (IsWrite || isStaticLinkTimeConstant<ELFT>(Expr, Type, Body, S, RelOff))
471     return Expr;
472 
473   // This relocation would require the dynamic linker to write a value to read
474   // only memory. We can hack around it if we are producing an executable and
475   // the refered symbol can be preemepted to refer to the executable.
476   if (Config->Shared || (Config->Pic && !isRelExpr(Expr))) {
477     error(S.getLocation(RelOff) + ": can't create dynamic relocation " +
478           toString(Type) + " against " +
479           (Body.getName().empty() ? "local symbol in readonly segment"
480                                   : "symbol '" + toString(Body) + "'") +
481           " defined in " + toString(Body.File));
482     return Expr;
483   }
484   if (Body.getVisibility() != STV_DEFAULT) {
485     error(S.getLocation(RelOff) + ": cannot preempt symbol '" + toString(Body) +
486           "' defined in " + toString(Body.File));
487     return Expr;
488   }
489   if (Body.isObject()) {
490     // Produce a copy relocation.
491     auto *B = cast<SharedSymbol<ELFT>>(&Body);
492     if (!B->needsCopy())
493       addCopyRelSymbol(B);
494     return Expr;
495   }
496   if (Body.isFunc()) {
497     // This handles a non PIC program call to function in a shared library. In
498     // an ideal world, we could just report an error saying the relocation can
499     // overflow at runtime. In the real world with glibc, crt1.o has a
500     // R_X86_64_PC32 pointing to libc.so.
501     //
502     // The general idea on how to handle such cases is to create a PLT entry and
503     // use that as the function value.
504     //
505     // For the static linking part, we just return a plt expr and everything
506     // else will use the the PLT entry as the address.
507     //
508     // The remaining problem is making sure pointer equality still works. We
509     // need the help of the dynamic linker for that. We let it know that we have
510     // a direct reference to a so symbol by creating an undefined symbol with a
511     // non zero st_value. Seeing that, the dynamic linker resolves the symbol to
512     // the value of the symbol we created. This is true even for got entries, so
513     // pointer equality is maintained. To avoid an infinite loop, the only entry
514     // that points to the real function is a dedicated got entry used by the
515     // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT,
516     // R_386_JMP_SLOT, etc).
517     Body.NeedsCopyOrPltAddr = true;
518     return toPlt(Expr);
519   }
520   error("symbol '" + toString(Body) + "' defined in " + toString(Body.File) +
521         " is missing type");
522 
523   return Expr;
524 }
525 
526 template <class ELFT, class RelTy>
527 static typename ELFT::uint computeAddend(const elf::ObjectFile<ELFT> &File,
528                                          const uint8_t *SectionData,
529                                          const RelTy *End, const RelTy &RI,
530                                          RelExpr Expr, SymbolBody &Body) {
531   typedef typename ELFT::uint uintX_t;
532 
533   uint32_t Type = RI.getType(Config->Mips64EL);
534   uintX_t Addend = getAddend<ELFT>(RI);
535   const uint8_t *BufLoc = SectionData + RI.r_offset;
536   if (!RelTy::IsRela)
537     Addend += Target->getImplicitAddend(BufLoc, Type);
538   if (Config->EMachine == EM_MIPS) {
539     Addend += findMipsPairedAddend<ELFT>(SectionData, BufLoc, Body, &RI, End);
540     if (Type == R_MIPS_LO16 && Expr == R_PC)
541       // R_MIPS_LO16 expression has R_PC type iif the target is _gp_disp
542       // symbol. In that case we should use the following formula for
543       // calculation "AHL + GP - P + 4". Let's add 4 right here.
544       // For details see p. 4-19 at
545       // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
546       Addend += 4;
547     if (Expr == R_MIPS_GOTREL && Body.isLocal())
548       Addend += File.MipsGp0;
549   }
550   if (Config->Pic && Config->EMachine == EM_PPC64 && Type == R_PPC64_TOC)
551     Addend += getPPC64TocBase();
552   return Addend;
553 }
554 
555 template <class ELFT>
556 static void reportUndefined(SymbolBody &Sym, InputSectionBase<ELFT> &S,
557                             typename ELFT::uint Offset) {
558   bool CanBeExternal = Sym.symbol()->computeBinding() != STB_LOCAL &&
559                        Sym.getVisibility() == STV_DEFAULT;
560   if (Config->UnresolvedSymbols == UnresolvedPolicy::IgnoreAll ||
561       (Config->UnresolvedSymbols == UnresolvedPolicy::Ignore && CanBeExternal))
562     return;
563 
564   std::string Msg =
565       S.getLocation(Offset) + ": undefined symbol '" + toString(Sym) + "'";
566 
567   if (Config->UnresolvedSymbols == UnresolvedPolicy::WarnAll ||
568       (Config->UnresolvedSymbols == UnresolvedPolicy::Warn && CanBeExternal))
569     warn(Msg);
570   else
571     error(Msg);
572 }
573 
574 template <class RelTy>
575 static std::pair<uint32_t, uint32_t>
576 mergeMipsN32RelTypes(uint32_t Type, uint32_t Offset, RelTy *I, RelTy *E) {
577   // MIPS N32 ABI treats series of successive relocations with the same offset
578   // as a single relocation. The similar approach used by N64 ABI, but this ABI
579   // packs all relocations into the single relocation record. Here we emulate
580   // this for the N32 ABI. Iterate over relocation with the same offset and put
581   // theirs types into the single bit-set.
582   uint32_t Processed = 0;
583   for (; I != E && Offset == I->r_offset; ++I) {
584     ++Processed;
585     Type |= I->getType(Config->Mips64EL) << (8 * Processed);
586   }
587   return std::make_pair(Type, Processed);
588 }
589 
590 // The reason we have to do this early scan is as follows
591 // * To mmap the output file, we need to know the size
592 // * For that, we need to know how many dynamic relocs we will have.
593 // It might be possible to avoid this by outputting the file with write:
594 // * Write the allocated output sections, computing addresses.
595 // * Apply relocations, recording which ones require a dynamic reloc.
596 // * Write the dynamic relocations.
597 // * Write the rest of the file.
598 // This would have some drawbacks. For example, we would only know if .rela.dyn
599 // is needed after applying relocations. If it is, it will go after rw and rx
600 // sections. Given that it is ro, we will need an extra PT_LOAD. This
601 // complicates things for the dynamic linker and means we would have to reserve
602 // space for the extra PT_LOAD even if we end up not using it.
603 template <class ELFT, class RelTy>
604 static void scanRelocs(InputSectionBase<ELFT> &C, ArrayRef<RelTy> Rels) {
605   typedef typename ELFT::uint uintX_t;
606 
607   bool IsWrite = C.Flags & SHF_WRITE;
608 
609   auto AddDyn = [=](const DynamicReloc<ELFT> &Reloc) {
610     In<ELFT>::RelaDyn->addReloc(Reloc);
611   };
612 
613   const elf::ObjectFile<ELFT> *File = C.getFile();
614   ArrayRef<uint8_t> SectionData = C.Data;
615   const uint8_t *Buf = SectionData.begin();
616 
617   ArrayRef<EhSectionPiece> Pieces;
618   if (auto *Eh = dyn_cast<EhInputSection<ELFT>>(&C))
619     Pieces = Eh->Pieces;
620 
621   ArrayRef<EhSectionPiece>::iterator PieceI = Pieces.begin();
622   ArrayRef<EhSectionPiece>::iterator PieceE = Pieces.end();
623 
624   for (auto I = Rels.begin(), E = Rels.end(); I != E; ++I) {
625     const RelTy &RI = *I;
626     SymbolBody &Body = File->getRelocTargetSym(RI);
627     uint32_t Type = RI.getType(Config->Mips64EL);
628 
629     if (Config->MipsN32Abi) {
630       uint32_t Processed;
631       std::tie(Type, Processed) =
632           mergeMipsN32RelTypes(Type, RI.r_offset, I + 1, E);
633       I += Processed;
634     }
635 
636     // We only report undefined symbols if they are referenced somewhere in the
637     // code.
638     if (!Body.isLocal() && Body.isUndefined() && !Body.symbol()->isWeak())
639       reportUndefined(Body, C, RI.r_offset);
640 
641     RelExpr Expr = Target->getRelExpr(Type, Body);
642     bool Preemptible = isPreemptible(Body, Type);
643     Expr = adjustExpr(*File, Body, IsWrite, Expr, Type, Buf + RI.r_offset, C,
644                       RI.r_offset);
645     if (ErrorCount)
646       continue;
647 
648     // Skip a relocation that points to a dead piece
649     // in a eh_frame section.
650     while (PieceI != PieceE &&
651            (PieceI->InputOff + PieceI->size() <= RI.r_offset))
652       ++PieceI;
653 
654     // Compute the offset of this section in the output section. We do it here
655     // to try to compute it only once.
656     uintX_t Offset;
657     if (PieceI != PieceE) {
658       assert(PieceI->InputOff <= RI.r_offset && "Relocation not in any piece");
659       if (PieceI->OutputOff == -1)
660         continue;
661       Offset = PieceI->OutputOff + RI.r_offset - PieceI->InputOff;
662     } else {
663       Offset = RI.r_offset;
664     }
665 
666     // This relocation does not require got entry, but it is relative to got and
667     // needs it to be created. Here we request for that.
668     if (Expr == R_GOTONLY_PC || Expr == R_GOTONLY_PC_FROM_END ||
669         Expr == R_GOTREL || Expr == R_GOTREL_FROM_END || Expr == R_PPC_TOC)
670       In<ELFT>::Got->HasGotOffRel = true;
671 
672     uintX_t Addend = computeAddend(*File, Buf, E, RI, Expr, Body);
673 
674     if (unsigned Processed =
675             handleTlsRelocation<ELFT>(Type, Body, C, Offset, Addend, Expr)) {
676       I += (Processed - 1);
677       continue;
678     }
679 
680     // Ignore "hint" and TLS Descriptor call relocation because they are
681     // only markers for relaxation.
682     if (isRelExprOneOf<R_HINT, R_TLSDESC_CALL>(Expr))
683       continue;
684 
685     if (needsPlt(Expr) ||
686         refersToGotEntry(Expr) || !isPreemptible(Body, Type)) {
687       // If the relocation points to something in the file, we can process it.
688       bool Constant =
689           isStaticLinkTimeConstant<ELFT>(Expr, Type, Body, C, RI.r_offset);
690 
691       // If the output being produced is position independent, the final value
692       // is still not known. In that case we still need some help from the
693       // dynamic linker. We can however do better than just copying the incoming
694       // relocation. We can process some of it and and just ask the dynamic
695       // linker to add the load address.
696       if (!Constant)
697         AddDyn({Target->RelativeRel, &C, Offset, true, &Body, Addend});
698 
699       // If the produced value is a constant, we just remember to write it
700       // when outputting this section. We also have to do it if the format
701       // uses Elf_Rel, since in that case the written value is the addend.
702       if (Constant || !RelTy::IsRela)
703         C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
704     } else {
705       // We don't know anything about the finaly symbol. Just ask the dynamic
706       // linker to handle the relocation for us.
707       if (!Target->isPicRel(Type))
708         error(C.getLocation(Offset) + ": relocation " + toString(Type) +
709               " cannot be used against shared object; recompile with -fPIC.");
710       AddDyn({Target->getDynRel(Type), &C, Offset, false, &Body, Addend});
711 
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>::MipsGot->addEntry(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 
740       if (Body.isGnuIFunc() && !Preemptible) {
741         In<ELFT>::Iplt->addEntry(Body);
742         In<ELFT>::IgotPlt->addEntry(Body);
743         In<ELFT>::RelaIplt->addReloc({Target->IRelativeRel, In<ELFT>::IgotPlt,
744                                       Body.getGotPltOffset<ELFT>(),
745                                       !Preemptible, &Body, 0});
746       } else {
747         In<ELFT>::Plt->addEntry(Body);
748         In<ELFT>::GotPlt->addEntry(Body);
749         In<ELFT>::RelaPlt->addReloc({Target->PltRel, In<ELFT>::GotPlt,
750                                      Body.getGotPltOffset<ELFT>(), !Preemptible,
751                                      &Body, 0});
752       }
753       continue;
754     }
755 
756     if (refersToGotEntry(Expr)) {
757       if (Config->EMachine == EM_MIPS) {
758         // MIPS ABI has special rules to process GOT entries and doesn't
759         // require relocation entries for them. A special case is TLS
760         // relocations. In that case dynamic loader applies dynamic
761         // relocations to initialize TLS GOT entries.
762         // See "Global Offset Table" in Chapter 5 in the following document
763         // for detailed description:
764         // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
765         In<ELFT>::MipsGot->addEntry(Body, Addend, Expr);
766         if (Body.isTls() && Body.isPreemptible())
767           AddDyn({Target->TlsGotRel, In<ELFT>::MipsGot,
768                   Body.getGotOffset<ELFT>(), false, &Body, 0});
769         continue;
770       }
771 
772       if (Body.isInGot())
773         continue;
774 
775       In<ELFT>::Got->addEntry(Body);
776       uintX_t Off = Body.getGotOffset<ELFT>();
777       uint32_t DynType;
778       RelExpr GotRE = R_ABS;
779       if (Body.isTls()) {
780         DynType = Target->TlsGotRel;
781         GotRE = R_TLS;
782       } else if (!Preemptible && Config->Pic && !isAbsolute<ELFT>(Body))
783         DynType = Target->RelativeRel;
784       else
785         DynType = Target->GotRel;
786 
787       // FIXME: this logic is almost duplicated above.
788       bool Constant = !Preemptible && !(Config->Pic && !isAbsolute<ELFT>(Body));
789       if (!Constant)
790         AddDyn({DynType, In<ELFT>::Got, Off, !Preemptible, &Body, 0});
791       if (Constant || (!RelTy::IsRela && !Preemptible))
792         In<ELFT>::Got->Relocations.push_back({GotRE, DynType, Off, 0, &Body});
793       continue;
794     }
795   }
796 }
797 
798 template <class ELFT> void scanRelocations(InputSectionBase<ELFT> &S) {
799   if (S.AreRelocsRela)
800     scanRelocs(S, S.relas());
801   else
802     scanRelocs(S, S.rels());
803 }
804 
805 // Insert the Thunks for OutputSection OS into their designated place
806 // in the Sections vector, and recalculate the InputSection output section
807 // offsets.
808 // This may invalidate any output section offsets stored outside of InputSection
809 template <class ELFT>
810 static void mergeThunks(OutputSection<ELFT> *OS,
811                         std::vector<ThunkSection<ELFT> *> &Thunks) {
812   // Order Thunks in ascending OutSecOff
813   auto ThunkCmp = [](const ThunkSection<ELFT> *A, const ThunkSection<ELFT> *B) {
814     return A->OutSecOff < B->OutSecOff;
815   };
816   std::stable_sort(Thunks.begin(), Thunks.end(), ThunkCmp);
817 
818   // Merge sorted vectors of Thunks and InputSections by OutSecOff
819   std::vector<InputSection<ELFT> *> Tmp;
820   Tmp.reserve(OS->Sections.size() + Thunks.size());
821   auto MergeCmp = [](const InputSection<ELFT> *A, const InputSection<ELFT> *B) {
822     // std::merge requires a strict weak ordering.
823     if (A->OutSecOff < B->OutSecOff)
824       return true;
825     if (A->OutSecOff == B->OutSecOff)
826       // Check if Thunk is immediately before any specific Target InputSection
827       // for example Mips LA25 Thunks.
828       if (auto *TA = dyn_cast<ThunkSection<ELFT>>(A))
829         if (TA && TA->getTargetInputSection() == B)
830           return true;
831     return false;
832   };
833   std::merge(OS->Sections.begin(), OS->Sections.end(), Thunks.begin(),
834              Thunks.end(), std::back_inserter(Tmp), MergeCmp);
835   OS->Sections = std::move(Tmp);
836   OS->Size = 0;
837   OS->assignOffsets();
838 }
839 
840 // Process all relocations from the InputSections that have been assigned
841 // to OutputSections and redirect through Thunks if needed.
842 //
843 // createThunks must be called after scanRelocs has created the Relocations for
844 // each InputSection. It must be called before the static symbol table is
845 // finalized. If any Thunks are added to an OutputSection the output section
846 // offsets of the InputSections will change.
847 //
848 // FIXME: All Thunks are assumed to be in range of the relocation. Range
849 // extension Thunks are not yet supported.
850 template <class ELFT>
851 void createThunks(ArrayRef<OutputSectionBase *> OutputSections) {
852   // Track Symbols that already have a Thunk
853   DenseMap<SymbolBody *, Thunk<ELFT> *> ThunkedSymbols;
854   // Track InputSections that have a ThunkSection placed in front
855   DenseMap<InputSection<ELFT> *, ThunkSection<ELFT> *> ThunkedSections;
856   // Track the ThunksSections that need to be inserted into an OutputSection
857   std::map<OutputSection<ELFT> *, std::vector<ThunkSection<ELFT> *>>
858       ThunkSections;
859 
860   // Find or create a Thunk for Body for relocation Type
861   auto GetThunk = [&](SymbolBody &Body, uint32_t Type) {
862     auto res = ThunkedSymbols.insert({&Body, nullptr});
863     if (res.second == true)
864       res.first->second = addThunk<ELFT>(Type, Body);
865     return std::make_pair(res.first->second, res.second);
866   };
867 
868   // Find or create a ThunkSection to be placed immediately before IS
869   auto GetISThunkSec = [&](InputSection<ELFT> *IS, OutputSection<ELFT> *OS) {
870     ThunkSection<ELFT> *TS = ThunkedSections.lookup(IS);
871     if (TS)
872       return TS;
873     auto *TOS = cast<OutputSection<ELFT>>(IS->OutSec);
874     TS = make<ThunkSection<ELFT>>(TOS, IS->OutSecOff);
875     ThunkSections[OS].push_back(TS);
876     ThunkedSections[IS] = TS;
877     return TS;
878   };
879   // Find or create a ThunkSection to be placed as last executable section in
880   // OS.
881   auto GetOSThunkSec = [&](ThunkSection<ELFT> *&TS, OutputSection<ELFT> *OS) {
882     if (TS == nullptr) {
883       uint32_t Off = 0;
884       for (auto *IS : OS->Sections) {
885         Off = IS->OutSecOff + IS->getSize();
886         if ((IS->Flags & SHF_EXECINSTR) == 0)
887           break;
888       }
889       TS = make<ThunkSection<ELFT>>(OS, Off);
890       ThunkSections[OS].push_back(TS);
891     }
892     return TS;
893   };
894   // Create all the Thunks and insert them into synthetic ThunkSections. The
895   // ThunkSections are later inserted back into the OutputSection.
896 
897   // We separate the creation of ThunkSections from the insertion of the
898   // ThunkSections back into the OutputSection as ThunkSections are not always
899   // inserted into the same OutputSection as the caller.
900   for (OutputSectionBase *Base : OutputSections) {
901     auto *OS = dyn_cast<OutputSection<ELFT>>(Base);
902     if (OS == nullptr)
903       continue;
904 
905     ThunkSection<ELFT> *OSTS = nullptr;
906     for (InputSection<ELFT> *IS : OS->Sections) {
907       for (Relocation &Rel : IS->Relocations) {
908         SymbolBody &Body = *Rel.Sym;
909         if (Target->needsThunk(Rel.Expr, Rel.Type, IS->getFile(), Body)) {
910           Thunk<ELFT> *T;
911           bool IsNew;
912           std::tie(T, IsNew) = GetThunk(Body, Rel.Type);
913           if (IsNew) {
914             // Find or create a ThunkSection for the new Thunk
915             ThunkSection<ELFT> *TS;
916             if (auto *TIS = T->getTargetInputSection())
917               TS = GetISThunkSec(TIS, OS);
918             else
919               TS = GetOSThunkSec(OSTS, OS);
920             TS->addThunk(T);
921           }
922           // Redirect relocation to Thunk, we never go via the PLT to a Thunk
923           Rel.Sym = T->ThunkSym;
924           Rel.Expr = fromPlt(Rel.Expr);
925         }
926       }
927     }
928   }
929 
930   // Merge all created synthetic ThunkSections back into OutputSection
931   for (auto &KV : ThunkSections)
932     mergeThunks<ELFT>(KV.first, KV.second);
933 }
934 
935 template void scanRelocations<ELF32LE>(InputSectionBase<ELF32LE> &);
936 template void scanRelocations<ELF32BE>(InputSectionBase<ELF32BE> &);
937 template void scanRelocations<ELF64LE>(InputSectionBase<ELF64LE> &);
938 template void scanRelocations<ELF64BE>(InputSectionBase<ELF64BE> &);
939 
940 template void createThunks<ELF32LE>(ArrayRef<OutputSectionBase *>);
941 template void createThunks<ELF32BE>(ArrayRef<OutputSectionBase *>);
942 template void createThunks<ELF64LE>(ArrayRef<OutputSectionBase *>);
943 template void createThunks<ELF64BE>(ArrayRef<OutputSectionBase *>);
944 }
945 }
946