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