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