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