1 //===- InputSection.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 #include "InputSection.h"
11 #include "Config.h"
12 #include "EhFrame.h"
13 #include "Error.h"
14 #include "InputFiles.h"
15 #include "LinkerScript.h"
16 #include "Memory.h"
17 #include "OutputSections.h"
18 #include "Relocations.h"
19 #include "SyntheticSections.h"
20 #include "Target.h"
21 #include "Thunks.h"
22 #include "llvm/Object/Decompressor.h"
23 #include "llvm/Support/Compression.h"
24 #include "llvm/Support/Endian.h"
25 #include <mutex>
26 
27 using namespace llvm;
28 using namespace llvm::ELF;
29 using namespace llvm::object;
30 using namespace llvm::support;
31 using namespace llvm::support::endian;
32 
33 using namespace lld;
34 using namespace lld::elf;
35 
36 std::vector<InputSectionBase *> elf::InputSections;
37 
38 // Returns a string to construct an error message.
39 std::string lld::toString(const InputSectionBase *Sec) {
40   // File can be absent if section is synthetic.
41   std::string FileName = Sec->File ? Sec->File->getName() : "<internal>";
42   return (FileName + ":(" + Sec->Name + ")").str();
43 }
44 
45 template <class ELFT>
46 static ArrayRef<uint8_t> getSectionContents(elf::ObjectFile<ELFT> *File,
47                                             const typename ELFT::Shdr *Hdr) {
48   if (!File || Hdr->sh_type == SHT_NOBITS)
49     return makeArrayRef<uint8_t>(nullptr, Hdr->sh_size);
50   return check(File->getObj().getSectionContents(Hdr));
51 }
52 
53 InputSectionBase::InputSectionBase(InputFile *File, uint64_t Flags,
54                                    uint32_t Type, uint64_t Entsize,
55                                    uint32_t Link, uint32_t Info,
56                                    uint64_t Addralign, ArrayRef<uint8_t> Data,
57                                    StringRef Name, Kind SectionKind)
58     : File(File), Data(Data), Name(Name), SectionKind(SectionKind),
59       Live(!Config->GcSections || !(Flags & SHF_ALLOC)), Assigned(false),
60       Flags(Flags), Entsize(Entsize), Type(Type), Link(Link), Info(Info),
61       Repl(this) {
62   NumRelocations = 0;
63   AreRelocsRela = false;
64 
65   // The ELF spec states that a value of 0 means the section has
66   // no alignment constraits.
67   uint64_t V = std::max<uint64_t>(Addralign, 1);
68   if (!isPowerOf2_64(V))
69     fatal(toString(File) + ": section sh_addralign is not a power of 2");
70 
71   // We reject object files having insanely large alignments even though
72   // they are allowed by the spec. I think 4GB is a reasonable limitation.
73   // We might want to relax this in the future.
74   if (V > UINT32_MAX)
75     fatal(toString(File) + ": section sh_addralign is too large");
76   Alignment = V;
77 }
78 
79 template <class ELFT>
80 InputSectionBase::InputSectionBase(elf::ObjectFile<ELFT> *File,
81                                    const typename ELFT::Shdr *Hdr,
82                                    StringRef Name, Kind SectionKind)
83     : InputSectionBase(File, Hdr->sh_flags & ~SHF_INFO_LINK, Hdr->sh_type,
84                        Hdr->sh_entsize, Hdr->sh_link, Hdr->sh_info,
85                        Hdr->sh_addralign, getSectionContents(File, Hdr), Name,
86                        SectionKind) {
87   this->Offset = Hdr->sh_offset;
88 }
89 
90 template <class ELFT> size_t InputSectionBase::getSize() const {
91   if (auto *S = dyn_cast<SyntheticSection>(this))
92     return S->getSize();
93 
94   return Data.size();
95 }
96 
97 template <class ELFT>
98 uint64_t InputSectionBase::getOffset(uint64_t Offset) const {
99   typedef typename ELFT::uint uintX_t;
100   switch (kind()) {
101   case Regular:
102     return cast<InputSection>(this)->OutSecOff + Offset;
103   case Synthetic:
104     // For synthetic sections we treat offset -1 as the end of the section.
105     // The same approach is used for synthetic symbols (DefinedSynthetic).
106     return cast<InputSection>(this)->OutSecOff +
107            (Offset == uintX_t(-1) ? getSize<ELFT>() : Offset);
108   case EHFrame:
109     // The file crtbeginT.o has relocations pointing to the start of an empty
110     // .eh_frame that is known to be the first in the link. It does that to
111     // identify the start of the output .eh_frame.
112     return Offset;
113   case Merge:
114     const MergeInputSection<ELFT> *MS = cast<MergeInputSection<ELFT>>(this);
115     if (MS->MergeSec)
116       return MS->MergeSec->OutSecOff + MS->getOffset(Offset);
117     return MS->getOffset(Offset);
118   }
119   llvm_unreachable("invalid section kind");
120 }
121 
122 template <class ELFT>
123 OutputSection *InputSectionBase::getOutputSection() const {
124   if (auto *MS = dyn_cast<MergeInputSection<ELFT>>(this))
125     return MS->MergeSec ? MS->MergeSec->OutSec : nullptr;
126   if (auto *EH = dyn_cast<EhInputSection<ELFT>>(this))
127     return EH->EHSec->OutSec;
128   return OutSec;
129 }
130 
131 // Uncompress section contents. Note that this function is called
132 // from parallel_for_each, so it must be thread-safe.
133 template <class ELFT> void InputSectionBase::uncompress() {
134   Decompressor Dec = check(Decompressor::create(
135       Name, toStringRef(Data), ELFT::TargetEndianness == llvm::support::little,
136       ELFT::Is64Bits));
137 
138   size_t Size = Dec.getDecompressedSize();
139   char *OutputBuf;
140   {
141     static std::mutex Mu;
142     std::lock_guard<std::mutex> Lock(Mu);
143     OutputBuf = BAlloc.Allocate<char>(Size);
144   }
145 
146   if (Error E = Dec.decompress({OutputBuf, Size}))
147     fatal(toString(this) +
148           ": decompress failed: " + llvm::toString(std::move(E)));
149   Data = ArrayRef<uint8_t>((uint8_t *)OutputBuf, Size);
150 }
151 
152 template <class ELFT>
153 uint64_t InputSectionBase::getOffset(const DefinedRegular &Sym) const {
154   return getOffset<ELFT>(Sym.Value);
155 }
156 
157 template <class ELFT>
158 InputSectionBase *InputSectionBase::getLinkOrderDep() const {
159   if ((Flags & SHF_LINK_ORDER) && Link != 0)
160     return getFile<ELFT>()->getSections()[Link];
161   return nullptr;
162 }
163 
164 // Returns a source location string. Used to construct an error message.
165 template <class ELFT>
166 std::string InputSectionBase::getLocation(uint64_t Offset) {
167   // First check if we can get desired values from debugging information.
168   std::string LineInfo = getFile<ELFT>()->getLineInfo(this, Offset);
169   if (!LineInfo.empty())
170     return LineInfo;
171 
172   // File->SourceFile contains STT_FILE symbol that contains a
173   // source file name. If it's missing, we use an object file name.
174   std::string SrcFile = getFile<ELFT>()->SourceFile;
175   if (SrcFile.empty())
176     SrcFile = toString(File);
177 
178   // Find a function symbol that encloses a given location.
179   for (SymbolBody *B : getFile<ELFT>()->getSymbols())
180     if (auto *D = dyn_cast<DefinedRegular>(B))
181       if (D->Section == this && D->Type == STT_FUNC)
182         if (D->Value <= Offset && Offset < D->Value + D->Size)
183           return SrcFile + ":(function " + toString(*D) + ")";
184 
185   // If there's no symbol, print out the offset in the section.
186   return (SrcFile + ":(" + Name + "+0x" + utohexstr(Offset) + ")").str();
187 }
188 
189 InputSection InputSection::Discarded;
190 
191 InputSection::InputSection() : InputSectionBase() {}
192 
193 InputSection::InputSection(uint64_t Flags, uint32_t Type, uint64_t Addralign,
194                            ArrayRef<uint8_t> Data, StringRef Name, Kind K)
195     : InputSectionBase(nullptr, Flags, Type,
196                        /*Entsize*/ 0, /*Link*/ 0, /*Info*/ 0, Addralign, Data,
197                        Name, K) {}
198 
199 template <class ELFT>
200 InputSection::InputSection(elf::ObjectFile<ELFT> *F,
201                            const typename ELFT::Shdr *Header, StringRef Name)
202     : InputSectionBase(F, Header, Name, InputSectionBase::Regular) {}
203 
204 bool InputSection::classof(const InputSectionBase *S) {
205   return S->kind() == InputSectionBase::Regular ||
206          S->kind() == InputSectionBase::Synthetic;
207 }
208 
209 template <class ELFT> InputSectionBase *InputSection::getRelocatedSection() {
210   assert(this->Type == SHT_RELA || this->Type == SHT_REL);
211   ArrayRef<InputSectionBase *> Sections = this->getFile<ELFT>()->getSections();
212   return Sections[this->Info];
213 }
214 
215 // This is used for -r and --emit-relocs. We can't use memcpy to copy
216 // relocations because we need to update symbol table offset and section index
217 // for each relocation. So we copy relocations one by one.
218 template <class ELFT, class RelTy>
219 void InputSection::copyRelocations(uint8_t *Buf, ArrayRef<RelTy> Rels) {
220   InputSectionBase *RelocatedSection = getRelocatedSection<ELFT>();
221 
222   // Loop is slow and have complexity O(N*M), where N - amount of
223   // relocations and M - amount of symbols in symbol table.
224   // That happens because getSymbolIndex(...) call below performs
225   // simple linear search.
226   for (const RelTy &Rel : Rels) {
227     uint32_t Type = Rel.getType(Config->Mips64EL);
228     SymbolBody &Body = this->getFile<ELFT>()->getRelocTargetSym(Rel);
229 
230     auto *P = reinterpret_cast<typename ELFT::Rela *>(Buf);
231     Buf += sizeof(RelTy);
232 
233     if (Config->Rela)
234       P->r_addend = getAddend<ELFT>(Rel);
235 
236     // Output section VA is zero for -r, so r_offset is an offset within the
237     // section, but for --emit-relocs it is an virtual address.
238     P->r_offset = RelocatedSection->OutSec->Addr +
239                   RelocatedSection->getOffset<ELFT>(Rel.r_offset);
240     P->setSymbolAndType(In<ELFT>::SymTab->getSymbolIndex(&Body), Type,
241                         Config->Mips64EL);
242 
243     if (Body.Type == STT_SECTION) {
244       // We combine multiple section symbols into only one per
245       // section. This means we have to update the addend. That is
246       // trivial for Elf_Rela, but for Elf_Rel we have to write to the
247       // section data. We do that by adding to the Relocation vector.
248 
249       // .eh_frame is horribly special and can reference discarded sections. To
250       // avoid having to parse and recreate .eh_frame, we just replace any
251       // relocation in it pointing to discarded sections with R_*_NONE, which
252       // hopefully creates a frame that is ignored at runtime.
253       InputSectionBase *Section = cast<DefinedRegular>(Body).Section;
254       if (Section == &InputSection::Discarded) {
255         P->setSymbolAndType(0, 0, false);
256         continue;
257       }
258 
259       if (Config->Rela) {
260         P->r_addend += Body.getVA<ELFT>() - Section->OutSec->Addr;
261       } else if (Config->Relocatable) {
262         const uint8_t *BufLoc = RelocatedSection->Data.begin() + Rel.r_offset;
263         RelocatedSection->Relocations.push_back(
264             {R_ABS, Type, Rel.r_offset, Target->getImplicitAddend(BufLoc, Type),
265              &Body});
266       }
267     }
268 
269   }
270 }
271 
272 static uint32_t getARMUndefinedRelativeWeakVA(uint32_t Type, uint32_t A,
273                                               uint32_t P) {
274   switch (Type) {
275   case R_ARM_THM_JUMP11:
276     return P + 2;
277   case R_ARM_CALL:
278   case R_ARM_JUMP24:
279   case R_ARM_PC24:
280   case R_ARM_PLT32:
281   case R_ARM_PREL31:
282   case R_ARM_THM_JUMP19:
283   case R_ARM_THM_JUMP24:
284     return P + 4;
285   case R_ARM_THM_CALL:
286     // We don't want an interworking BLX to ARM
287     return P + 5;
288   default:
289     return A;
290   }
291 }
292 
293 static uint64_t getAArch64UndefinedRelativeWeakVA(uint64_t Type, uint64_t A,
294                                                   uint64_t P) {
295   switch (Type) {
296   case R_AARCH64_CALL26:
297   case R_AARCH64_CONDBR19:
298   case R_AARCH64_JUMP26:
299   case R_AARCH64_TSTBR14:
300     return P + 4;
301   default:
302     return A;
303   }
304 }
305 
306 template <class ELFT>
307 static typename ELFT::uint
308 getRelocTargetVA(uint32_t Type, int64_t A, typename ELFT::uint P,
309                  const SymbolBody &Body, RelExpr Expr) {
310   switch (Expr) {
311   case R_HINT:
312   case R_NONE:
313   case R_TLSDESC_CALL:
314     llvm_unreachable("cannot relocate hint relocs");
315   case R_TLSLD:
316     return In<ELFT>::Got->getTlsIndexOff() + A - In<ELFT>::Got->getSize();
317   case R_TLSLD_PC:
318     return In<ELFT>::Got->getTlsIndexVA() + A - P;
319   case R_PPC_TOC:
320     return getPPC64TocBase() + A;
321   case R_TLSGD:
322     return In<ELFT>::Got->getGlobalDynOffset(Body) + A -
323            In<ELFT>::Got->getSize();
324   case R_TLSGD_PC:
325     return In<ELFT>::Got->getGlobalDynAddr(Body) + A - P;
326   case R_TLSDESC:
327     return In<ELFT>::Got->getGlobalDynAddr(Body) + A;
328   case R_TLSDESC_PAGE:
329     return getAArch64Page(In<ELFT>::Got->getGlobalDynAddr(Body) + A) -
330            getAArch64Page(P);
331   case R_PLT:
332     return Body.getPltVA<ELFT>() + A;
333   case R_PLT_PC:
334   case R_PPC_PLT_OPD:
335     return Body.getPltVA<ELFT>() + A - P;
336   case R_SIZE:
337     return Body.getSize<ELFT>() + A;
338   case R_GOTREL:
339     return Body.getVA<ELFT>(A) - In<ELFT>::Got->getVA();
340   case R_GOTREL_FROM_END:
341     return Body.getVA<ELFT>(A) - In<ELFT>::Got->getVA() -
342            In<ELFT>::Got->getSize();
343   case R_RELAX_TLS_GD_TO_IE_END:
344   case R_GOT_FROM_END:
345     return Body.getGotOffset<ELFT>() + A - In<ELFT>::Got->getSize();
346   case R_RELAX_TLS_GD_TO_IE_ABS:
347   case R_GOT:
348     return Body.getGotVA<ELFT>() + A;
349   case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
350   case R_GOT_PAGE_PC:
351     return getAArch64Page(Body.getGotVA<ELFT>() + A) - getAArch64Page(P);
352   case R_RELAX_TLS_GD_TO_IE:
353   case R_GOT_PC:
354     return Body.getGotVA<ELFT>() + A - P;
355   case R_GOTONLY_PC:
356     return In<ELFT>::Got->getVA() + A - P;
357   case R_GOTONLY_PC_FROM_END:
358     return In<ELFT>::Got->getVA() + A - P + In<ELFT>::Got->getSize();
359   case R_RELAX_TLS_LD_TO_LE:
360   case R_RELAX_TLS_IE_TO_LE:
361   case R_RELAX_TLS_GD_TO_LE:
362   case R_TLS:
363     // A weak undefined TLS symbol resolves to the base of the TLS
364     // block, i.e. gets a value of zero. If we pass --gc-sections to
365     // lld and .tbss is not referenced, it gets reclaimed and we don't
366     // create a TLS program header. Therefore, we resolve this
367     // statically to zero.
368     if (Body.isTls() && (Body.isLazy() || Body.isUndefined()) &&
369         Body.symbol()->isWeak())
370       return 0;
371     if (Target->TcbSize)
372       return Body.getVA<ELFT>(A) +
373              alignTo(Target->TcbSize, Out::TlsPhdr->p_align);
374     return Body.getVA<ELFT>(A) - Out::TlsPhdr->p_memsz;
375   case R_RELAX_TLS_GD_TO_LE_NEG:
376   case R_NEG_TLS:
377     return Out::TlsPhdr->p_memsz - Body.getVA<ELFT>(A);
378   case R_ABS:
379   case R_RELAX_GOT_PC_NOPIC:
380     return Body.getVA<ELFT>(A);
381   case R_GOT_OFF:
382     return Body.getGotOffset<ELFT>() + A;
383   case R_MIPS_GOT_LOCAL_PAGE:
384     // If relocation against MIPS local symbol requires GOT entry, this entry
385     // should be initialized by 'page address'. This address is high 16-bits
386     // of sum the symbol's value and the addend.
387     return In<ELFT>::MipsGot->getVA() +
388            In<ELFT>::MipsGot->getPageEntryOffset(Body, A) -
389            In<ELFT>::MipsGot->getGp();
390   case R_MIPS_GOT_OFF:
391   case R_MIPS_GOT_OFF32:
392     // In case of MIPS if a GOT relocation has non-zero addend this addend
393     // should be applied to the GOT entry content not to the GOT entry offset.
394     // That is why we use separate expression type.
395     return In<ELFT>::MipsGot->getVA() +
396            In<ELFT>::MipsGot->getBodyEntryOffset(Body, A) -
397            In<ELFT>::MipsGot->getGp();
398   case R_MIPS_GOTREL:
399     return Body.getVA<ELFT>(A) - In<ELFT>::MipsGot->getGp();
400   case R_MIPS_TLSGD:
401     return In<ELFT>::MipsGot->getVA() + In<ELFT>::MipsGot->getTlsOffset() +
402            In<ELFT>::MipsGot->getGlobalDynOffset(Body) -
403            In<ELFT>::MipsGot->getGp();
404   case R_MIPS_TLSLD:
405     return In<ELFT>::MipsGot->getVA() + In<ELFT>::MipsGot->getTlsOffset() +
406            In<ELFT>::MipsGot->getTlsIndexOff() - In<ELFT>::MipsGot->getGp();
407   case R_PPC_OPD: {
408     uint64_t SymVA = Body.getVA<ELFT>(A);
409     // If we have an undefined weak symbol, we might get here with a symbol
410     // address of zero. That could overflow, but the code must be unreachable,
411     // so don't bother doing anything at all.
412     if (!SymVA)
413       return 0;
414     if (Out::Opd) {
415       // If this is a local call, and we currently have the address of a
416       // function-descriptor, get the underlying code address instead.
417       uint64_t OpdStart = Out::Opd->Addr;
418       uint64_t OpdEnd = OpdStart + Out::Opd->Size;
419       bool InOpd = OpdStart <= SymVA && SymVA < OpdEnd;
420       if (InOpd)
421         SymVA = read64be(&Out::OpdBuf[SymVA - OpdStart]);
422     }
423     return SymVA - P;
424   }
425   case R_PC:
426     if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak()) {
427       // On ARM and AArch64 a branch to an undefined weak resolves to the
428       // next instruction, otherwise the place.
429       if (Config->EMachine == EM_ARM)
430         return getARMUndefinedRelativeWeakVA(Type, A, P);
431       if (Config->EMachine == EM_AARCH64)
432         return getAArch64UndefinedRelativeWeakVA(Type, A, P);
433     }
434   case R_RELAX_GOT_PC:
435     return Body.getVA<ELFT>(A) - P;
436   case R_PLT_PAGE_PC:
437   case R_PAGE_PC:
438     if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak())
439       return getAArch64Page(A);
440     return getAArch64Page(Body.getVA<ELFT>(A)) - getAArch64Page(P);
441   }
442   llvm_unreachable("Invalid expression");
443 }
444 
445 // This function applies relocations to sections without SHF_ALLOC bit.
446 // Such sections are never mapped to memory at runtime. Debug sections are
447 // an example. Relocations in non-alloc sections are much easier to
448 // handle than in allocated sections because it will never need complex
449 // treatement such as GOT or PLT (because at runtime no one refers them).
450 // So, we handle relocations for non-alloc sections directly in this
451 // function as a performance optimization.
452 template <class ELFT, class RelTy>
453 void InputSection::relocateNonAlloc(uint8_t *Buf, ArrayRef<RelTy> Rels) {
454   typedef typename ELFT::uint uintX_t;
455   for (const RelTy &Rel : Rels) {
456     uint32_t Type = Rel.getType(Config->Mips64EL);
457     uintX_t Offset = this->getOffset<ELFT>(Rel.r_offset);
458     uint8_t *BufLoc = Buf + Offset;
459     int64_t Addend = getAddend<ELFT>(Rel);
460     if (!RelTy::IsRela)
461       Addend += Target->getImplicitAddend(BufLoc, Type);
462 
463     SymbolBody &Sym = this->getFile<ELFT>()->getRelocTargetSym(Rel);
464     RelExpr Expr = Target->getRelExpr(Type, Sym);
465     if (Expr == R_NONE)
466       continue;
467     if (Expr != R_ABS) {
468       error(this->getLocation<ELFT>(Offset) + ": has non-ABS reloc");
469       return;
470     }
471 
472     uintX_t AddrLoc = this->OutSec->Addr + Offset;
473     uint64_t SymVA = 0;
474     if (!Sym.isTls() || Out::TlsPhdr)
475       SymVA = SignExtend64<sizeof(uintX_t) * 8>(
476           getRelocTargetVA<ELFT>(Type, Addend, AddrLoc, Sym, R_ABS));
477     Target->relocateOne(BufLoc, Type, SymVA);
478   }
479 }
480 
481 template <class ELFT> elf::ObjectFile<ELFT> *InputSectionBase::getFile() const {
482   return cast_or_null<elf::ObjectFile<ELFT>>(File);
483 }
484 
485 template <class ELFT>
486 void InputSectionBase::relocate(uint8_t *Buf, uint8_t *BufEnd) {
487   // scanReloc function in Writer.cpp constructs Relocations
488   // vector only for SHF_ALLOC'ed sections. For other sections,
489   // we handle relocations directly here.
490   auto *IS = dyn_cast<InputSection>(this);
491   if (IS && !(IS->Flags & SHF_ALLOC)) {
492     if (IS->AreRelocsRela)
493       IS->relocateNonAlloc<ELFT>(Buf, IS->template relas<ELFT>());
494     else
495       IS->relocateNonAlloc<ELFT>(Buf, IS->template rels<ELFT>());
496     return;
497   }
498 
499   typedef typename ELFT::uint uintX_t;
500   const unsigned Bits = sizeof(uintX_t) * 8;
501   for (const Relocation &Rel : Relocations) {
502     uintX_t Offset = getOffset<ELFT>(Rel.Offset);
503     uint8_t *BufLoc = Buf + Offset;
504     uint32_t Type = Rel.Type;
505 
506     uintX_t AddrLoc = getOutputSection<ELFT>()->Addr + Offset;
507     RelExpr Expr = Rel.Expr;
508     uint64_t TargetVA = SignExtend64<Bits>(
509         getRelocTargetVA<ELFT>(Type, Rel.Addend, AddrLoc, *Rel.Sym, Expr));
510 
511     switch (Expr) {
512     case R_RELAX_GOT_PC:
513     case R_RELAX_GOT_PC_NOPIC:
514       Target->relaxGot(BufLoc, TargetVA);
515       break;
516     case R_RELAX_TLS_IE_TO_LE:
517       Target->relaxTlsIeToLe(BufLoc, Type, TargetVA);
518       break;
519     case R_RELAX_TLS_LD_TO_LE:
520       Target->relaxTlsLdToLe(BufLoc, Type, TargetVA);
521       break;
522     case R_RELAX_TLS_GD_TO_LE:
523     case R_RELAX_TLS_GD_TO_LE_NEG:
524       Target->relaxTlsGdToLe(BufLoc, Type, TargetVA);
525       break;
526     case R_RELAX_TLS_GD_TO_IE:
527     case R_RELAX_TLS_GD_TO_IE_ABS:
528     case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
529     case R_RELAX_TLS_GD_TO_IE_END:
530       Target->relaxTlsGdToIe(BufLoc, Type, TargetVA);
531       break;
532     case R_PPC_PLT_OPD:
533       // Patch a nop (0x60000000) to a ld.
534       if (BufLoc + 8 <= BufEnd && read32be(BufLoc + 4) == 0x60000000)
535         write32be(BufLoc + 4, 0xe8410028); // ld %r2, 40(%r1)
536     // fallthrough
537     default:
538       Target->relocateOne(BufLoc, Type, TargetVA);
539       break;
540     }
541   }
542 }
543 
544 template <class ELFT> void InputSection::writeTo(uint8_t *Buf) {
545   if (this->Type == SHT_NOBITS)
546     return;
547 
548   if (auto *S = dyn_cast<SyntheticSection>(this)) {
549     S->writeTo(Buf + OutSecOff);
550     return;
551   }
552 
553   // If -r or --emit-relocs is given, then an InputSection
554   // may be a relocation section.
555   if (this->Type == SHT_RELA) {
556     copyRelocations<ELFT>(Buf + OutSecOff,
557                           this->template getDataAs<typename ELFT::Rela>());
558     return;
559   }
560   if (this->Type == SHT_REL) {
561     copyRelocations<ELFT>(Buf + OutSecOff,
562                           this->template getDataAs<typename ELFT::Rel>());
563     return;
564   }
565 
566   // Copy section contents from source object file to output file.
567   ArrayRef<uint8_t> Data = this->Data;
568   memcpy(Buf + OutSecOff, Data.data(), Data.size());
569 
570   // Iterate over all relocation sections that apply to this section.
571   uint8_t *BufEnd = Buf + OutSecOff + Data.size();
572   this->relocate<ELFT>(Buf, BufEnd);
573 }
574 
575 void InputSection::replace(InputSection *Other) {
576   this->Alignment = std::max(this->Alignment, Other->Alignment);
577   Other->Repl = this->Repl;
578   Other->Live = false;
579 }
580 
581 template <class ELFT>
582 EhInputSection<ELFT>::EhInputSection(elf::ObjectFile<ELFT> *F,
583                                      const Elf_Shdr *Header, StringRef Name)
584     : InputSectionBase(F, Header, Name, InputSectionBase::EHFrame) {
585   // Mark .eh_frame sections as live by default because there are
586   // usually no relocations that point to .eh_frames. Otherwise,
587   // the garbage collector would drop all .eh_frame sections.
588   this->Live = true;
589 }
590 
591 template <class ELFT>
592 bool EhInputSection<ELFT>::classof(const InputSectionBase *S) {
593   return S->kind() == InputSectionBase::EHFrame;
594 }
595 
596 // Returns the index of the first relocation that points to a region between
597 // Begin and Begin+Size.
598 template <class IntTy, class RelTy>
599 static unsigned getReloc(IntTy Begin, IntTy Size, const ArrayRef<RelTy> &Rels,
600                          unsigned &RelocI) {
601   // Start search from RelocI for fast access. That works because the
602   // relocations are sorted in .eh_frame.
603   for (unsigned N = Rels.size(); RelocI < N; ++RelocI) {
604     const RelTy &Rel = Rels[RelocI];
605     if (Rel.r_offset < Begin)
606       continue;
607 
608     if (Rel.r_offset < Begin + Size)
609       return RelocI;
610     return -1;
611   }
612   return -1;
613 }
614 
615 // .eh_frame is a sequence of CIE or FDE records.
616 // This function splits an input section into records and returns them.
617 template <class ELFT> void EhInputSection<ELFT>::split() {
618   // Early exit if already split.
619   if (!this->Pieces.empty())
620     return;
621 
622   if (this->NumRelocations) {
623     if (this->AreRelocsRela)
624       split(this->relas<ELFT>());
625     else
626       split(this->rels<ELFT>());
627     return;
628   }
629   split(makeArrayRef<typename ELFT::Rela>(nullptr, nullptr));
630 }
631 
632 template <class ELFT>
633 template <class RelTy>
634 void EhInputSection<ELFT>::split(ArrayRef<RelTy> Rels) {
635   ArrayRef<uint8_t> Data = this->Data;
636   unsigned RelI = 0;
637   for (size_t Off = 0, End = Data.size(); Off != End;) {
638     size_t Size = readEhRecordSize<ELFT>(this, Off);
639     this->Pieces.emplace_back(Off, this, Size, getReloc(Off, Size, Rels, RelI));
640     // The empty record is the end marker.
641     if (Size == 4)
642       break;
643     Off += Size;
644   }
645 }
646 
647 static size_t findNull(ArrayRef<uint8_t> A, size_t EntSize) {
648   // Optimize the common case.
649   StringRef S((const char *)A.data(), A.size());
650   if (EntSize == 1)
651     return S.find(0);
652 
653   for (unsigned I = 0, N = S.size(); I != N; I += EntSize) {
654     const char *B = S.begin() + I;
655     if (std::all_of(B, B + EntSize, [](char C) { return C == 0; }))
656       return I;
657   }
658   return StringRef::npos;
659 }
660 
661 // Split SHF_STRINGS section. Such section is a sequence of
662 // null-terminated strings.
663 template <class ELFT>
664 void MergeInputSection<ELFT>::splitStrings(ArrayRef<uint8_t> Data,
665                                            size_t EntSize) {
666   size_t Off = 0;
667   bool IsAlloc = this->Flags & SHF_ALLOC;
668   while (!Data.empty()) {
669     size_t End = findNull(Data, EntSize);
670     if (End == StringRef::npos)
671       fatal(toString(this) + ": string is not null terminated");
672     size_t Size = End + EntSize;
673     Pieces.emplace_back(Off, !IsAlloc);
674     Hashes.push_back(hash_value(toStringRef(Data.slice(0, Size))));
675     Data = Data.slice(Size);
676     Off += Size;
677   }
678 }
679 
680 // Split non-SHF_STRINGS section. Such section is a sequence of
681 // fixed size records.
682 template <class ELFT>
683 void MergeInputSection<ELFT>::splitNonStrings(ArrayRef<uint8_t> Data,
684                                               size_t EntSize) {
685   size_t Size = Data.size();
686   assert((Size % EntSize) == 0);
687   bool IsAlloc = this->Flags & SHF_ALLOC;
688   for (unsigned I = 0, N = Size; I != N; I += EntSize) {
689     Hashes.push_back(hash_value(toStringRef(Data.slice(I, EntSize))));
690     Pieces.emplace_back(I, !IsAlloc);
691   }
692 }
693 
694 template <class ELFT>
695 MergeInputSection<ELFT>::MergeInputSection(elf::ObjectFile<ELFT> *F,
696                                            const Elf_Shdr *Header,
697                                            StringRef Name)
698     : InputSectionBase(F, Header, Name, InputSectionBase::Merge) {}
699 
700 // This function is called after we obtain a complete list of input sections
701 // that need to be linked. This is responsible to split section contents
702 // into small chunks for further processing.
703 //
704 // Note that this function is called from parallel_for_each. This must be
705 // thread-safe (i.e. no memory allocation from the pools).
706 template <class ELFT> void MergeInputSection<ELFT>::splitIntoPieces() {
707   ArrayRef<uint8_t> Data = this->Data;
708   uintX_t EntSize = this->Entsize;
709   if (this->Flags & SHF_STRINGS)
710     splitStrings(Data, EntSize);
711   else
712     splitNonStrings(Data, EntSize);
713 
714   if (Config->GcSections && (this->Flags & SHF_ALLOC))
715     for (uintX_t Off : LiveOffsets)
716       this->getSectionPiece(Off)->Live = true;
717 }
718 
719 template <class ELFT>
720 bool MergeInputSection<ELFT>::classof(const InputSectionBase *S) {
721   return S->kind() == InputSectionBase::Merge;
722 }
723 
724 // Do binary search to get a section piece at a given input offset.
725 template <class ELFT>
726 SectionPiece *MergeInputSection<ELFT>::getSectionPiece(uintX_t Offset) {
727   auto *This = static_cast<const MergeInputSection<ELFT> *>(this);
728   return const_cast<SectionPiece *>(This->getSectionPiece(Offset));
729 }
730 
731 template <class It, class T, class Compare>
732 static It fastUpperBound(It First, It Last, const T &Value, Compare Comp) {
733   size_t Size = std::distance(First, Last);
734   assert(Size != 0);
735   while (Size != 1) {
736     size_t H = Size / 2;
737     const It MI = First + H;
738     Size -= H;
739     First = Comp(Value, *MI) ? First : First + H;
740   }
741   return Comp(Value, *First) ? First : First + 1;
742 }
743 
744 template <class ELFT>
745 const SectionPiece *
746 MergeInputSection<ELFT>::getSectionPiece(uintX_t Offset) const {
747   uintX_t Size = this->Data.size();
748   if (Offset >= Size)
749     fatal(toString(this) + ": entry is past the end of the section");
750 
751   // Find the element this offset points to.
752   auto I = fastUpperBound(
753       Pieces.begin(), Pieces.end(), Offset,
754       [](const uintX_t &A, const SectionPiece &B) { return A < B.InputOff; });
755   --I;
756   return &*I;
757 }
758 
759 // Returns the offset in an output section for a given input offset.
760 // Because contents of a mergeable section is not contiguous in output,
761 // it is not just an addition to a base output offset.
762 template <class ELFT>
763 typename ELFT::uint MergeInputSection<ELFT>::getOffset(uintX_t Offset) const {
764   // Initialize OffsetMap lazily.
765   std::call_once(InitOffsetMap, [&] {
766     OffsetMap.reserve(Pieces.size());
767     for (const SectionPiece &Piece : Pieces)
768       OffsetMap[Piece.InputOff] = Piece.OutputOff;
769   });
770 
771   // Find a string starting at a given offset.
772   auto It = OffsetMap.find(Offset);
773   if (It != OffsetMap.end())
774     return It->second;
775 
776   if (!this->Live)
777     return 0;
778 
779   // If Offset is not at beginning of a section piece, it is not in the map.
780   // In that case we need to search from the original section piece vector.
781   const SectionPiece &Piece = *this->getSectionPiece(Offset);
782   if (!Piece.Live)
783     return 0;
784 
785   uintX_t Addend = Offset - Piece.InputOff;
786   return Piece.OutputOff + Addend;
787 }
788 
789 template InputSection::InputSection(elf::ObjectFile<ELF32LE> *F,
790                                     const ELF32LE::Shdr *Header,
791                                     StringRef Name);
792 template InputSection::InputSection(elf::ObjectFile<ELF32BE> *F,
793                                     const ELF32BE::Shdr *Header,
794                                     StringRef Name);
795 template InputSection::InputSection(elf::ObjectFile<ELF64LE> *F,
796                                     const ELF64LE::Shdr *Header,
797                                     StringRef Name);
798 template InputSection::InputSection(elf::ObjectFile<ELF64BE> *F,
799                                     const ELF64BE::Shdr *Header,
800                                     StringRef Name);
801 
802 template std::string InputSectionBase::getLocation<ELF32LE>(uint64_t Offset);
803 template std::string InputSectionBase::getLocation<ELF32BE>(uint64_t Offset);
804 template std::string InputSectionBase::getLocation<ELF64LE>(uint64_t Offset);
805 template std::string InputSectionBase::getLocation<ELF64BE>(uint64_t Offset);
806 
807 template void InputSection::writeTo<ELF32LE>(uint8_t *Buf);
808 template void InputSection::writeTo<ELF32BE>(uint8_t *Buf);
809 template void InputSection::writeTo<ELF64LE>(uint8_t *Buf);
810 template void InputSection::writeTo<ELF64BE>(uint8_t *Buf);
811 
812 template class elf::EhInputSection<ELF32LE>;
813 template class elf::EhInputSection<ELF32BE>;
814 template class elf::EhInputSection<ELF64LE>;
815 template class elf::EhInputSection<ELF64BE>;
816 
817 template class elf::MergeInputSection<ELF32LE>;
818 template class elf::MergeInputSection<ELF32BE>;
819 template class elf::MergeInputSection<ELF64LE>;
820 template class elf::MergeInputSection<ELF64BE>;
821 
822 template void InputSectionBase::uncompress<ELF32LE>();
823 template void InputSectionBase::uncompress<ELF32BE>();
824 template void InputSectionBase::uncompress<ELF64LE>();
825 template void InputSectionBase::uncompress<ELF64BE>();
826 
827 template InputSectionBase *InputSectionBase::getLinkOrderDep<ELF32LE>() const;
828 template InputSectionBase *InputSectionBase::getLinkOrderDep<ELF32BE>() const;
829 template InputSectionBase *InputSectionBase::getLinkOrderDep<ELF64LE>() const;
830 template InputSectionBase *InputSectionBase::getLinkOrderDep<ELF64BE>() const;
831 
832 template OutputSection *InputSectionBase::getOutputSection<ELF32LE>() const;
833 template OutputSection *InputSectionBase::getOutputSection<ELF32BE>() const;
834 template OutputSection *InputSectionBase::getOutputSection<ELF64LE>() const;
835 template OutputSection *InputSectionBase::getOutputSection<ELF64BE>() const;
836 
837 template InputSectionBase *InputSection::getRelocatedSection<ELF32LE>();
838 template InputSectionBase *InputSection::getRelocatedSection<ELF32BE>();
839 template InputSectionBase *InputSection::getRelocatedSection<ELF64LE>();
840 template InputSectionBase *InputSection::getRelocatedSection<ELF64BE>();
841 
842 template uint64_t
843 InputSectionBase::getOffset<ELF32LE>(const DefinedRegular &Sym) const;
844 template uint64_t
845 InputSectionBase::getOffset<ELF32BE>(const DefinedRegular &Sym) const;
846 template uint64_t
847 InputSectionBase::getOffset<ELF64LE>(const DefinedRegular &Sym) const;
848 template uint64_t
849 InputSectionBase::getOffset<ELF64BE>(const DefinedRegular &Sym) const;
850 
851 template uint64_t InputSectionBase::getOffset<ELF32LE>(uint64_t Offset) const;
852 template uint64_t InputSectionBase::getOffset<ELF32BE>(uint64_t Offset) const;
853 template uint64_t InputSectionBase::getOffset<ELF64LE>(uint64_t Offset) const;
854 template uint64_t InputSectionBase::getOffset<ELF64BE>(uint64_t Offset) const;
855 
856 template size_t InputSectionBase::getSize<ELF32LE>() const;
857 template size_t InputSectionBase::getSize<ELF32BE>() const;
858 template size_t InputSectionBase::getSize<ELF64LE>() const;
859 template size_t InputSectionBase::getSize<ELF64BE>() const;
860 
861 template elf::ObjectFile<ELF32LE> *InputSectionBase::getFile<ELF32LE>() const;
862 template elf::ObjectFile<ELF32BE> *InputSectionBase::getFile<ELF32BE>() const;
863 template elf::ObjectFile<ELF64LE> *InputSectionBase::getFile<ELF64LE>() const;
864 template elf::ObjectFile<ELF64BE> *InputSectionBase::getFile<ELF64BE>() const;
865