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