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 "OutputSections.h"
17 #include "Target.h"
18 #include "Thunks.h"
19 
20 #include "llvm/Support/Compression.h"
21 #include "llvm/Support/Endian.h"
22 #include "llvm/Support/RandomNumberGenerator.h"
23 #include "llvm/Support/xxhash.h"
24 
25 using namespace llvm;
26 using namespace llvm::ELF;
27 using namespace llvm::object;
28 using namespace llvm::support;
29 using namespace llvm::support::endian;
30 
31 using namespace lld;
32 using namespace lld::elf;
33 
34 template <class ELFT>
35 static ArrayRef<uint8_t> getSectionContents(elf::ObjectFile<ELFT> *File,
36                                             const typename ELFT::Shdr *Hdr) {
37   if (!File || Hdr->sh_type == SHT_NOBITS)
38     return makeArrayRef<uint8_t>(nullptr, Hdr->sh_size);
39   return check(File->getObj().getSectionContents(Hdr));
40 }
41 
42 // ELF supports ZLIB-compressed section. Returns true if the section
43 // is compressed.
44 template <class ELFT>
45 static bool isCompressed(typename ELFT::uint Flags, StringRef Name) {
46   return (Flags & SHF_COMPRESSED) || Name.startswith(".zdebug");
47 }
48 
49 template <class ELFT>
50 InputSectionBase<ELFT>::InputSectionBase(elf::ObjectFile<ELFT> *File,
51                                          uintX_t Flags, uint32_t Type,
52                                          uintX_t Entsize, uint32_t Link,
53                                          uint32_t Info, uintX_t Addralign,
54                                          ArrayRef<uint8_t> Data, StringRef Name,
55                                          Kind SectionKind)
56     : InputSectionData(SectionKind, Name, Data, isCompressed<ELFT>(Flags, Name),
57                        !Config->GcSections || !(Flags & SHF_ALLOC)),
58       File(File), Flags(Flags), Entsize(Entsize), Type(Type), Link(Link),
59       Info(Info), Repl(this) {
60   // The ELF spec states that a value of 0 means the section has
61   // no alignment constraits.
62   uint64_t V = std::max<uint64_t>(Addralign, 1);
63   if (!isPowerOf2_64(V))
64     fatal(getFilename(File) + ": section sh_addralign is not a power of 2");
65 
66   // We reject object files having insanely large alignments even though
67   // they are allowed by the spec. I think 4GB is a reasonable limitation.
68   // We might want to relax this in the future.
69   if (V > UINT32_MAX)
70     fatal(getFilename(File) + ": section sh_addralign is too large");
71   Alignment = V;
72 }
73 
74 template <class ELFT>
75 InputSectionBase<ELFT>::InputSectionBase(elf::ObjectFile<ELFT> *File,
76                                          const Elf_Shdr *Hdr, StringRef Name,
77                                          Kind SectionKind)
78     : InputSectionBase(File, Hdr->sh_flags, Hdr->sh_type, Hdr->sh_entsize,
79                        Hdr->sh_link, Hdr->sh_info, Hdr->sh_addralign,
80                        getSectionContents(File, Hdr), Name, SectionKind) {
81   this->Offset = Hdr->sh_offset;
82 }
83 
84 template <class ELFT> size_t InputSectionBase<ELFT>::getSize() const {
85   if (auto *D = dyn_cast<InputSection<ELFT>>(this))
86     if (D->getThunksSize() > 0)
87       return D->getThunkOff() + D->getThunksSize();
88   return Data.size();
89 }
90 
91 // Returns a string for an error message.
92 template <class SectionT> static std::string getName(SectionT *Sec) {
93   return (Sec->getFile()->getName() + "(" + Sec->Name + ")").str();
94 }
95 
96 template <class ELFT>
97 typename ELFT::uint InputSectionBase<ELFT>::getOffset(uintX_t Offset) const {
98   switch (kind()) {
99   case Regular:
100     return cast<InputSection<ELFT>>(this)->OutSecOff + Offset;
101   case EHFrame:
102     // The file crtbeginT.o has relocations pointing to the start of an empty
103     // .eh_frame that is known to be the first in the link. It does that to
104     // identify the start of the output .eh_frame.
105     return Offset;
106   case Merge:
107     return cast<MergeInputSection<ELFT>>(this)->getOffset(Offset);
108   case MipsReginfo:
109   case MipsOptions:
110   case MipsAbiFlags:
111     // MIPS .reginfo, .MIPS.options, and .MIPS.abiflags sections are consumed
112     // by the linker, and the linker produces a single output section. It is
113     // possible that input files contain section symbol points to the
114     // corresponding input section. Redirect it to the produced output section.
115     if (Offset != 0)
116       fatal(getName(this) + ": unsupported reference to the middle of '" +
117             Name + "' section");
118     return this->OutSec->getVA();
119   }
120   llvm_unreachable("invalid section kind");
121 }
122 
123 // Returns compressed data and its size when uncompressed.
124 template <class ELFT>
125 std::pair<ArrayRef<uint8_t>, uint64_t>
126 InputSectionBase<ELFT>::getElfCompressedData(ArrayRef<uint8_t> Data) {
127   // Compressed section with Elf_Chdr is the ELF standard.
128   if (Data.size() < sizeof(Elf_Chdr))
129     fatal(getName(this) + ": corrupted compressed section");
130   auto *Hdr = reinterpret_cast<const Elf_Chdr *>(Data.data());
131   if (Hdr->ch_type != ELFCOMPRESS_ZLIB)
132     fatal(getName(this) + ": unsupported compression type");
133   return {Data.slice(sizeof(*Hdr)), Hdr->ch_size};
134 }
135 
136 // Returns compressed data and its size when uncompressed.
137 template <class ELFT>
138 std::pair<ArrayRef<uint8_t>, uint64_t>
139 InputSectionBase<ELFT>::getRawCompressedData(ArrayRef<uint8_t> Data) {
140   // Compressed sections without Elf_Chdr header contain this header
141   // instead. This is a GNU extension.
142   struct ZlibHeader {
143     char Magic[4]; // Should be "ZLIB"
144     char Size[8];  // Uncompressed size in big-endian
145   };
146 
147   if (Data.size() < sizeof(ZlibHeader))
148     fatal(getName(this) + ": corrupted compressed section");
149   auto *Hdr = reinterpret_cast<const ZlibHeader *>(Data.data());
150   if (memcmp(Hdr->Magic, "ZLIB", 4))
151     fatal(getName(this) + ": broken ZLIB-compressed section");
152   return {Data.slice(sizeof(*Hdr)), read64be(Hdr->Size)};
153 }
154 
155 template <class ELFT> void InputSectionBase<ELFT>::uncompress() {
156   if (!zlib::isAvailable())
157     fatal(getName(this) +
158           ": build lld with zlib to enable compressed sections support");
159 
160   // This section is compressed. Here we decompress it. Ideally, all
161   // compressed sections have SHF_COMPRESSED bit and their contents
162   // start with headers of Elf_Chdr type. However, sections whose
163   // names start with ".zdebug_" don't have the bit and contains a raw
164   // ZLIB-compressed data (which is a bad thing because section names
165   // shouldn't be significant in ELF.) We need to be able to read both.
166   ArrayRef<uint8_t> Buf; // Compressed data
167   size_t Size;           // Uncompressed size
168   if (Flags & SHF_COMPRESSED)
169     std::tie(Buf, Size) = getElfCompressedData(Data);
170   else
171     std::tie(Buf, Size) = getRawCompressedData(Data);
172 
173   // Uncompress Buf.
174   UncompressedData.reset(new uint8_t[Size]);
175   if (zlib::uncompress(toStringRef(Buf), (char *)UncompressedData.get(),
176                        Size) != zlib::StatusOK)
177     fatal(getName(this) + ": error while uncompressing section");
178   Data = ArrayRef<uint8_t>(UncompressedData.get(), Size);
179 }
180 
181 template <class ELFT>
182 typename ELFT::uint
183 InputSectionBase<ELFT>::getOffset(const DefinedRegular<ELFT> &Sym) const {
184   return getOffset(Sym.Value);
185 }
186 
187 template <class ELFT>
188 InputSectionBase<ELFT> *InputSectionBase<ELFT>::getLinkOrderDep() const {
189   if ((Flags & SHF_LINK_ORDER) && Link != 0)
190     return getFile()->getSections()[Link];
191   return nullptr;
192 }
193 
194 template <class ELFT>
195 InputSection<ELFT>::InputSection(uintX_t Flags, uint32_t Type,
196                                  uintX_t Addralign, ArrayRef<uint8_t> Data,
197                                  StringRef Name)
198     : InputSectionBase<ELFT>(nullptr, Flags, Type,
199                              /*Entsize*/ 0, /*Link*/ 0, /*Info*/ 0, Addralign,
200                              Data, Name, Base::Regular) {}
201 
202 template <class ELFT>
203 InputSection<ELFT>::InputSection(elf::ObjectFile<ELFT> *F,
204                                  const Elf_Shdr *Header, StringRef Name)
205     : InputSectionBase<ELFT>(F, Header, Name, Base::Regular) {}
206 
207 template <class ELFT>
208 bool InputSection<ELFT>::classof(const InputSectionData *S) {
209   return S->kind() == Base::Regular;
210 }
211 
212 template <class ELFT>
213 InputSectionBase<ELFT> *InputSection<ELFT>::getRelocatedSection() {
214   assert(this->Type == SHT_RELA || this->Type == SHT_REL);
215   ArrayRef<InputSectionBase<ELFT> *> Sections = this->File->getSections();
216   return Sections[this->Info];
217 }
218 
219 template <class ELFT> void InputSection<ELFT>::addThunk(const Thunk<ELFT> *T) {
220   Thunks.push_back(T);
221 }
222 
223 template <class ELFT> uint64_t InputSection<ELFT>::getThunkOff() const {
224   return this->Data.size();
225 }
226 
227 template <class ELFT> uint64_t InputSection<ELFT>::getThunksSize() const {
228   uint64_t Total = 0;
229   for (const Thunk<ELFT> *T : Thunks)
230     Total += T->size();
231   return Total;
232 }
233 
234 // This is used for -r. We can't use memcpy to copy relocations because we need
235 // to update symbol table offset and section index for each relocation. So we
236 // copy relocations one by one.
237 template <class ELFT>
238 template <class RelTy>
239 void InputSection<ELFT>::copyRelocations(uint8_t *Buf, ArrayRef<RelTy> Rels) {
240   InputSectionBase<ELFT> *RelocatedSection = getRelocatedSection();
241 
242   for (const RelTy &Rel : Rels) {
243     uint32_t Type = Rel.getType(Config->Mips64EL);
244     SymbolBody &Body = this->File->getRelocTargetSym(Rel);
245 
246     Elf_Rela *P = reinterpret_cast<Elf_Rela *>(Buf);
247     Buf += sizeof(RelTy);
248 
249     if (Config->Rela)
250       P->r_addend = getAddend<ELFT>(Rel);
251     P->r_offset = RelocatedSection->getOffset(Rel.r_offset);
252     P->setSymbolAndType(Body.DynsymIndex, Type, Config->Mips64EL);
253   }
254 }
255 
256 // Page(Expr) is the page address of the expression Expr, defined
257 // as (Expr & ~0xFFF). (This applies even if the machine page size
258 // supported by the platform has a different value.)
259 static uint64_t getAArch64Page(uint64_t Expr) {
260   return Expr & (~static_cast<uint64_t>(0xFFF));
261 }
262 
263 template <class ELFT>
264 static typename ELFT::uint getSymVA(uint32_t Type, typename ELFT::uint A,
265                                     typename ELFT::uint P,
266                                     const SymbolBody &Body, RelExpr Expr) {
267   switch (Expr) {
268   case R_HINT:
269   case R_TLSDESC_CALL:
270     llvm_unreachable("cannot relocate hint relocs");
271   case R_TLSLD:
272     return Out<ELFT>::Got->getTlsIndexOff() + A - Out<ELFT>::Got->getSize();
273   case R_TLSLD_PC:
274     return Out<ELFT>::Got->getTlsIndexVA() + A - P;
275   case R_THUNK_ABS:
276     return Body.getThunkVA<ELFT>() + A;
277   case R_THUNK_PC:
278   case R_THUNK_PLT_PC:
279     return Body.getThunkVA<ELFT>() + A - P;
280   case R_PPC_TOC:
281     return getPPC64TocBase() + A;
282   case R_TLSGD:
283     return Out<ELFT>::Got->getGlobalDynOffset(Body) + A -
284            Out<ELFT>::Got->getSize();
285   case R_TLSGD_PC:
286     return Out<ELFT>::Got->getGlobalDynAddr(Body) + A - P;
287   case R_TLSDESC:
288     return Out<ELFT>::Got->getGlobalDynAddr(Body) + A;
289   case R_TLSDESC_PAGE:
290     return getAArch64Page(Out<ELFT>::Got->getGlobalDynAddr(Body) + A) -
291            getAArch64Page(P);
292   case R_PLT:
293     return Body.getPltVA<ELFT>() + A;
294   case R_PLT_PC:
295   case R_PPC_PLT_OPD:
296     return Body.getPltVA<ELFT>() + A - P;
297   case R_SIZE:
298     return Body.getSize<ELFT>() + A;
299   case R_GOTREL:
300     return Body.getVA<ELFT>(A) - Out<ELFT>::Got->getVA();
301   case R_GOTREL_FROM_END:
302     return Body.getVA<ELFT>(A) - Out<ELFT>::Got->getVA() -
303            Out<ELFT>::Got->getSize();
304   case R_RELAX_TLS_GD_TO_IE_END:
305   case R_GOT_FROM_END:
306     return Body.getGotOffset<ELFT>() + A - Out<ELFT>::Got->getSize();
307   case R_RELAX_TLS_GD_TO_IE_ABS:
308   case R_GOT:
309     return Body.getGotVA<ELFT>() + A;
310   case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
311   case R_GOT_PAGE_PC:
312     return getAArch64Page(Body.getGotVA<ELFT>() + A) - getAArch64Page(P);
313   case R_RELAX_TLS_GD_TO_IE:
314   case R_GOT_PC:
315     return Body.getGotVA<ELFT>() + A - P;
316   case R_GOTONLY_PC:
317     return Out<ELFT>::Got->getVA() + A - P;
318   case R_GOTONLY_PC_FROM_END:
319     return Out<ELFT>::Got->getVA() + A - P + Out<ELFT>::Got->getSize();
320   case R_RELAX_TLS_LD_TO_LE:
321   case R_RELAX_TLS_IE_TO_LE:
322   case R_RELAX_TLS_GD_TO_LE:
323   case R_TLS:
324     // A weak undefined TLS symbol resolves to the base of the TLS
325     // block, i.e. gets a value of zero. If we pass --gc-sections to
326     // lld and .tbss is not referenced, it gets reclaimed and we don't
327     // create a TLS program header. Therefore, we resolve this
328     // statically to zero.
329     if (Body.isTls() && (Body.isLazy() || Body.isUndefined()) &&
330         Body.symbol()->isWeak())
331       return 0;
332     if (Target->TcbSize)
333       return Body.getVA<ELFT>(A) +
334              alignTo(Target->TcbSize, Out<ELFT>::TlsPhdr->p_align);
335     return Body.getVA<ELFT>(A) - Out<ELFT>::TlsPhdr->p_memsz;
336   case R_RELAX_TLS_GD_TO_LE_NEG:
337   case R_NEG_TLS:
338     return Out<ELF32LE>::TlsPhdr->p_memsz - Body.getVA<ELFT>(A);
339   case R_ABS:
340   case R_RELAX_GOT_PC_NOPIC:
341     return Body.getVA<ELFT>(A);
342   case R_GOT_OFF:
343     return Body.getGotOffset<ELFT>() + A;
344   case R_MIPS_GOT_LOCAL_PAGE:
345     // If relocation against MIPS local symbol requires GOT entry, this entry
346     // should be initialized by 'page address'. This address is high 16-bits
347     // of sum the symbol's value and the addend.
348     return Out<ELFT>::Got->getMipsLocalPageOffset(Body.getVA<ELFT>(A));
349   case R_MIPS_GOT_OFF:
350   case R_MIPS_GOT_OFF32:
351     // In case of MIPS if a GOT relocation has non-zero addend this addend
352     // should be applied to the GOT entry content not to the GOT entry offset.
353     // That is why we use separate expression type.
354     return Out<ELFT>::Got->getMipsGotOffset(Body, A);
355   case R_MIPS_TLSGD:
356     return Out<ELFT>::Got->getGlobalDynOffset(Body) +
357            Out<ELFT>::Got->getMipsTlsOffset() - MipsGPOffset;
358   case R_MIPS_TLSLD:
359     return Out<ELFT>::Got->getTlsIndexOff() +
360            Out<ELFT>::Got->getMipsTlsOffset() - MipsGPOffset;
361   case R_PPC_OPD: {
362     uint64_t SymVA = Body.getVA<ELFT>(A);
363     // If we have an undefined weak symbol, we might get here with a symbol
364     // address of zero. That could overflow, but the code must be unreachable,
365     // so don't bother doing anything at all.
366     if (!SymVA)
367       return 0;
368     if (Out<ELF64BE>::Opd) {
369       // If this is a local call, and we currently have the address of a
370       // function-descriptor, get the underlying code address instead.
371       uint64_t OpdStart = Out<ELF64BE>::Opd->getVA();
372       uint64_t OpdEnd = OpdStart + Out<ELF64BE>::Opd->getSize();
373       bool InOpd = OpdStart <= SymVA && SymVA < OpdEnd;
374       if (InOpd)
375         SymVA = read64be(&Out<ELF64BE>::OpdBuf[SymVA - OpdStart]);
376     }
377     return SymVA - P;
378   }
379   case R_PC:
380   case R_RELAX_GOT_PC:
381     return Body.getVA<ELFT>(A) - P;
382   case R_PLT_PAGE_PC:
383   case R_PAGE_PC:
384     return getAArch64Page(Body.getVA<ELFT>(A)) - getAArch64Page(P);
385   }
386   llvm_unreachable("Invalid expression");
387 }
388 
389 // This function applies relocations to sections without SHF_ALLOC bit.
390 // Such sections are never mapped to memory at runtime. Debug sections are
391 // an example. Relocations in non-alloc sections are much easier to
392 // handle than in allocated sections because it will never need complex
393 // treatement such as GOT or PLT (because at runtime no one refers them).
394 // So, we handle relocations for non-alloc sections directly in this
395 // function as a performance optimization.
396 template <class ELFT>
397 template <class RelTy>
398 void InputSection<ELFT>::relocateNonAlloc(uint8_t *Buf, ArrayRef<RelTy> Rels) {
399   for (const RelTy &Rel : Rels) {
400     uint32_t Type = Rel.getType(Config->Mips64EL);
401     uintX_t Offset = this->getOffset(Rel.r_offset);
402     uint8_t *BufLoc = Buf + Offset;
403     uintX_t Addend = getAddend<ELFT>(Rel);
404     if (!RelTy::IsRela)
405       Addend += Target->getImplicitAddend(BufLoc, Type);
406 
407     SymbolBody &Sym = this->File->getRelocTargetSym(Rel);
408     if (Target->getRelExpr(Type, Sym) != R_ABS) {
409       error(getName(this) + " has non-ABS reloc");
410       return;
411     }
412 
413     uintX_t AddrLoc = this->OutSec->getVA() + Offset;
414     uint64_t SymVA = SignExtend64<sizeof(uintX_t) * 8>(
415         getSymVA<ELFT>(Type, Addend, AddrLoc, Sym, R_ABS));
416     Target->relocateOne(BufLoc, Type, SymVA);
417   }
418 }
419 
420 template <class ELFT>
421 void InputSectionBase<ELFT>::relocate(uint8_t *Buf, uint8_t *BufEnd) {
422   // scanReloc function in Writer.cpp constructs Relocations
423   // vector only for SHF_ALLOC'ed sections. For other sections,
424   // we handle relocations directly here.
425   auto *IS = dyn_cast<InputSection<ELFT>>(this);
426   if (IS && !(IS->Flags & SHF_ALLOC)) {
427     for (const Elf_Shdr *RelSec : IS->RelocSections) {
428       if (RelSec->sh_type == SHT_RELA)
429         IS->relocateNonAlloc(Buf, IS->File->getObj().relas(RelSec));
430       else
431         IS->relocateNonAlloc(Buf, IS->File->getObj().rels(RelSec));
432     }
433     return;
434   }
435 
436   const unsigned Bits = sizeof(uintX_t) * 8;
437   for (const Relocation &Rel : Relocations) {
438     uintX_t Offset = getOffset(Rel.Offset);
439     uint8_t *BufLoc = Buf + Offset;
440     uint32_t Type = Rel.Type;
441     uintX_t A = Rel.Addend;
442 
443     uintX_t AddrLoc = OutSec->getVA() + Offset;
444     RelExpr Expr = Rel.Expr;
445     uint64_t SymVA =
446         SignExtend64<Bits>(getSymVA<ELFT>(Type, A, AddrLoc, *Rel.Sym, Expr));
447 
448     switch (Expr) {
449     case R_RELAX_GOT_PC:
450     case R_RELAX_GOT_PC_NOPIC:
451       Target->relaxGot(BufLoc, SymVA);
452       break;
453     case R_RELAX_TLS_IE_TO_LE:
454       Target->relaxTlsIeToLe(BufLoc, Type, SymVA);
455       break;
456     case R_RELAX_TLS_LD_TO_LE:
457       Target->relaxTlsLdToLe(BufLoc, Type, SymVA);
458       break;
459     case R_RELAX_TLS_GD_TO_LE:
460     case R_RELAX_TLS_GD_TO_LE_NEG:
461       Target->relaxTlsGdToLe(BufLoc, Type, SymVA);
462       break;
463     case R_RELAX_TLS_GD_TO_IE:
464     case R_RELAX_TLS_GD_TO_IE_ABS:
465     case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
466     case R_RELAX_TLS_GD_TO_IE_END:
467       Target->relaxTlsGdToIe(BufLoc, Type, SymVA);
468       break;
469     case R_PPC_PLT_OPD:
470       // Patch a nop (0x60000000) to a ld.
471       if (BufLoc + 8 <= BufEnd && read32be(BufLoc + 4) == 0x60000000)
472         write32be(BufLoc + 4, 0xe8410028); // ld %r2, 40(%r1)
473     // fallthrough
474     default:
475       Target->relocateOne(BufLoc, Type, SymVA);
476       break;
477     }
478   }
479 }
480 
481 template <class ELFT> void InputSection<ELFT>::writeTo(uint8_t *Buf) {
482   if (this->Type == SHT_NOBITS)
483     return;
484 
485   // If -r is given, then an InputSection may be a relocation section.
486   if (this->Type == SHT_RELA) {
487     copyRelocations(Buf + OutSecOff, this->template getDataAs<Elf_Rela>());
488     return;
489   }
490   if (this->Type == SHT_REL) {
491     copyRelocations(Buf + OutSecOff, this->template getDataAs<Elf_Rel>());
492     return;
493   }
494 
495   // Copy section contents from source object file to output file.
496   ArrayRef<uint8_t> Data = this->Data;
497   memcpy(Buf + OutSecOff, Data.data(), Data.size());
498 
499   // Iterate over all relocation sections that apply to this section.
500   uint8_t *BufEnd = Buf + OutSecOff + Data.size();
501   this->relocate(Buf, BufEnd);
502 
503   // The section might have a data/code generated by the linker and need
504   // to be written after the section. Usually these are thunks - small piece
505   // of code used to jump between "incompatible" functions like PIC and non-PIC
506   // or if the jump target too far and its address does not fit to the short
507   // jump istruction.
508   if (!Thunks.empty()) {
509     Buf += OutSecOff + getThunkOff();
510     for (const Thunk<ELFT> *T : Thunks) {
511       T->writeTo(Buf);
512       Buf += T->size();
513     }
514   }
515 }
516 
517 template <class ELFT>
518 void InputSection<ELFT>::replace(InputSection<ELFT> *Other) {
519   assert(Other->Alignment <= this->Alignment);
520   Other->Repl = this->Repl;
521   Other->Live = false;
522 }
523 
524 template <class ELFT>
525 EhInputSection<ELFT>::EhInputSection(elf::ObjectFile<ELFT> *F,
526                                      const Elf_Shdr *Header, StringRef Name)
527     : InputSectionBase<ELFT>(F, Header, Name, InputSectionBase<ELFT>::EHFrame) {
528   // Mark .eh_frame sections as live by default because there are
529   // usually no relocations that point to .eh_frames. Otherwise,
530   // the garbage collector would drop all .eh_frame sections.
531   this->Live = true;
532 }
533 
534 template <class ELFT>
535 bool EhInputSection<ELFT>::classof(const InputSectionData *S) {
536   return S->kind() == InputSectionBase<ELFT>::EHFrame;
537 }
538 
539 // Returns the index of the first relocation that points to a region between
540 // Begin and Begin+Size.
541 template <class IntTy, class RelTy>
542 static unsigned getReloc(IntTy Begin, IntTy Size, const ArrayRef<RelTy> &Rels,
543                          unsigned &RelocI) {
544   // Start search from RelocI for fast access. That works because the
545   // relocations are sorted in .eh_frame.
546   for (unsigned N = Rels.size(); RelocI < N; ++RelocI) {
547     const RelTy &Rel = Rels[RelocI];
548     if (Rel.r_offset < Begin)
549       continue;
550 
551     if (Rel.r_offset < Begin + Size)
552       return RelocI;
553     return -1;
554   }
555   return -1;
556 }
557 
558 // .eh_frame is a sequence of CIE or FDE records.
559 // This function splits an input section into records and returns them.
560 template <class ELFT> void EhInputSection<ELFT>::split() {
561   // Early exit if already split.
562   if (!this->Pieces.empty())
563     return;
564 
565   if (RelocSection) {
566     ELFFile<ELFT> &Obj = this->File->getObj();
567     if (RelocSection->sh_type == SHT_RELA)
568       split(Obj.relas(RelocSection));
569     else
570       split(Obj.rels(RelocSection));
571     return;
572   }
573   split(makeArrayRef<typename ELFT::Rela>(nullptr, nullptr));
574 }
575 
576 template <class ELFT>
577 template <class RelTy>
578 void EhInputSection<ELFT>::split(ArrayRef<RelTy> Rels) {
579   ArrayRef<uint8_t> Data = this->Data;
580   unsigned RelI = 0;
581   for (size_t Off = 0, End = Data.size(); Off != End;) {
582     size_t Size = readEhRecordSize<ELFT>(Data.slice(Off));
583     this->Pieces.emplace_back(Off, Data.slice(Off, Size),
584                               getReloc(Off, Size, Rels, RelI));
585     // The empty record is the end marker.
586     if (Size == 4)
587       break;
588     Off += Size;
589   }
590 }
591 
592 static size_t findNull(ArrayRef<uint8_t> A, size_t EntSize) {
593   // Optimize the common case.
594   StringRef S((const char *)A.data(), A.size());
595   if (EntSize == 1)
596     return S.find(0);
597 
598   for (unsigned I = 0, N = S.size(); I != N; I += EntSize) {
599     const char *B = S.begin() + I;
600     if (std::all_of(B, B + EntSize, [](char C) { return C == 0; }))
601       return I;
602   }
603   return StringRef::npos;
604 }
605 
606 // Split SHF_STRINGS section. Such section is a sequence of
607 // null-terminated strings.
608 template <class ELFT>
609 std::vector<SectionPiece>
610 MergeInputSection<ELFT>::splitStrings(ArrayRef<uint8_t> Data, size_t EntSize) {
611   std::vector<SectionPiece> V;
612   size_t Off = 0;
613   bool IsAlloca = this->Flags & SHF_ALLOC;
614   while (!Data.empty()) {
615     size_t End = findNull(Data, EntSize);
616     if (End == StringRef::npos)
617       fatal(getName(this) + ": string is not null terminated");
618     size_t Size = End + EntSize;
619     V.emplace_back(Off, !IsAlloca);
620     Hashes.push_back(hash_value(toStringRef(Data.slice(0, Size))));
621     Data = Data.slice(Size);
622     Off += Size;
623   }
624   return V;
625 }
626 
627 template <class ELFT>
628 ArrayRef<uint8_t> MergeInputSection<ELFT>::getData(
629     std::vector<SectionPiece>::const_iterator I) const {
630   auto Next = I + 1;
631   size_t End = Next == Pieces.end() ? this->Data.size() : Next->InputOff;
632   return this->Data.slice(I->InputOff, End - I->InputOff);
633 }
634 
635 // Split non-SHF_STRINGS section. Such section is a sequence of
636 // fixed size records.
637 template <class ELFT>
638 std::vector<SectionPiece>
639 MergeInputSection<ELFT>::splitNonStrings(ArrayRef<uint8_t> Data,
640                                          size_t EntSize) {
641   std::vector<SectionPiece> V;
642   size_t Size = Data.size();
643   assert((Size % EntSize) == 0);
644   bool IsAlloca = this->Flags & SHF_ALLOC;
645   for (unsigned I = 0, N = Size; I != N; I += EntSize) {
646     Hashes.push_back(hash_value(toStringRef(Data.slice(I, EntSize))));
647     V.emplace_back(I, !IsAlloca);
648   }
649   return V;
650 }
651 
652 template <class ELFT>
653 MergeInputSection<ELFT>::MergeInputSection(elf::ObjectFile<ELFT> *F,
654                                            const Elf_Shdr *Header,
655                                            StringRef Name)
656     : InputSectionBase<ELFT>(F, Header, Name, InputSectionBase<ELFT>::Merge) {}
657 
658 template <class ELFT> void MergeInputSection<ELFT>::splitIntoPieces() {
659   ArrayRef<uint8_t> Data = this->Data;
660   uintX_t EntSize = this->Entsize;
661   if (this->Flags & SHF_STRINGS)
662     this->Pieces = splitStrings(Data, EntSize);
663   else
664     this->Pieces = splitNonStrings(Data, EntSize);
665 
666   if (Config->GcSections && (this->Flags & SHF_ALLOC))
667     for (uintX_t Off : LiveOffsets)
668       this->getSectionPiece(Off)->Live = true;
669 }
670 
671 template <class ELFT>
672 bool MergeInputSection<ELFT>::classof(const InputSectionData *S) {
673   return S->kind() == InputSectionBase<ELFT>::Merge;
674 }
675 
676 // Do binary search to get a section piece at a given input offset.
677 template <class ELFT>
678 SectionPiece *MergeInputSection<ELFT>::getSectionPiece(uintX_t Offset) {
679   auto *This = static_cast<const MergeInputSection<ELFT> *>(this);
680   return const_cast<SectionPiece *>(This->getSectionPiece(Offset));
681 }
682 
683 template <class It, class T, class Compare>
684 static It fastUpperBound(It First, It Last, const T &Value, Compare Comp) {
685   size_t Size = std::distance(First, Last);
686   assert(Size != 0);
687   while (Size != 1) {
688     size_t H = Size / 2;
689     const It MI = First + H;
690     Size -= H;
691     First = Comp(Value, *MI) ? First : First + H;
692   }
693   return Comp(Value, *First) ? First : First + 1;
694 }
695 
696 template <class ELFT>
697 const SectionPiece *
698 MergeInputSection<ELFT>::getSectionPiece(uintX_t Offset) const {
699   uintX_t Size = this->Data.size();
700   if (Offset >= Size)
701     fatal(getName(this) + ": entry is past the end of the section");
702 
703   // Find the element this offset points to.
704   auto I = fastUpperBound(
705       Pieces.begin(), Pieces.end(), Offset,
706       [](const uintX_t &A, const SectionPiece &B) { return A < B.InputOff; });
707   --I;
708   return &*I;
709 }
710 
711 // Returns the offset in an output section for a given input offset.
712 // Because contents of a mergeable section is not contiguous in output,
713 // it is not just an addition to a base output offset.
714 template <class ELFT>
715 typename ELFT::uint MergeInputSection<ELFT>::getOffset(uintX_t Offset) const {
716   auto It = OffsetMap.find(Offset);
717   if (It != OffsetMap.end())
718     return It->second;
719 
720   if (!this->Live)
721     return 0;
722 
723   // If Offset is not at beginning of a section piece, it is not in the map.
724   // In that case we need to search from the original section piece vector.
725   const SectionPiece &Piece = *this->getSectionPiece(Offset);
726   if (!Piece.Live)
727     return 0;
728 
729   uintX_t Addend = Offset - Piece.InputOff;
730   return Piece.OutputOff + Addend;
731 }
732 
733 // Create a map from input offsets to output offsets for all section pieces.
734 // It is called after finalize().
735 template <class ELFT> void MergeInputSection<ELFT>::finalizePieces() {
736   OffsetMap.reserve(this->Pieces.size());
737   auto HashI = Hashes.begin();
738   for (auto I = Pieces.begin(), E = Pieces.end(); I != E; ++I) {
739     uint32_t Hash = *HashI;
740     ++HashI;
741     SectionPiece &Piece = *I;
742     if (!Piece.Live)
743       continue;
744     if (Piece.OutputOff == -1) {
745       // Offsets of tail-merged strings are computed lazily.
746       auto *OutSec = static_cast<MergeOutputSection<ELFT> *>(this->OutSec);
747       ArrayRef<uint8_t> D = this->getData(I);
748       StringRef S((const char *)D.data(), D.size());
749       CachedHashStringRef V(S, Hash);
750       Piece.OutputOff = OutSec->getOffset(V);
751     }
752     OffsetMap[Piece.InputOff] = Piece.OutputOff;
753   }
754 }
755 
756 template <class ELFT>
757 MipsReginfoInputSection<ELFT>::MipsReginfoInputSection(elf::ObjectFile<ELFT> *F,
758                                                        const Elf_Shdr *Hdr,
759                                                        StringRef Name)
760     : InputSectionBase<ELFT>(F, Hdr, Name,
761                              InputSectionBase<ELFT>::MipsReginfo) {
762   ArrayRef<uint8_t> Data = this->Data;
763   // Initialize this->Reginfo.
764   if (Data.size() != sizeof(Elf_Mips_RegInfo<ELFT>)) {
765     error(getName(this) + ": invalid size of .reginfo section");
766     return;
767   }
768   Reginfo = reinterpret_cast<const Elf_Mips_RegInfo<ELFT> *>(Data.data());
769   if (Config->Relocatable && Reginfo->ri_gp_value)
770     error(getName(this) + ": unsupported non-zero ri_gp_value");
771 }
772 
773 template <class ELFT>
774 bool MipsReginfoInputSection<ELFT>::classof(const InputSectionData *S) {
775   return S->kind() == InputSectionBase<ELFT>::MipsReginfo;
776 }
777 
778 template <class ELFT>
779 MipsOptionsInputSection<ELFT>::MipsOptionsInputSection(elf::ObjectFile<ELFT> *F,
780                                                        const Elf_Shdr *Hdr,
781                                                        StringRef Name)
782     : InputSectionBase<ELFT>(F, Hdr, Name,
783                              InputSectionBase<ELFT>::MipsOptions) {
784   // Find ODK_REGINFO option in the section's content.
785   ArrayRef<uint8_t> D = this->Data;
786   while (!D.empty()) {
787     if (D.size() < sizeof(Elf_Mips_Options<ELFT>)) {
788       error(getName(this) + ": invalid size of .MIPS.options section");
789       break;
790     }
791     auto *O = reinterpret_cast<const Elf_Mips_Options<ELFT> *>(D.data());
792     if (O->kind == ODK_REGINFO) {
793       Reginfo = &O->getRegInfo();
794       if (Config->Relocatable && Reginfo->ri_gp_value)
795         error(getName(this) + ": unsupported non-zero ri_gp_value");
796       break;
797     }
798     if (!O->size)
799       fatal(getName(this) + ": zero option descriptor size");
800     D = D.slice(O->size);
801   }
802 }
803 
804 template <class ELFT>
805 bool MipsOptionsInputSection<ELFT>::classof(const InputSectionData *S) {
806   return S->kind() == InputSectionBase<ELFT>::MipsOptions;
807 }
808 
809 template <class ELFT>
810 MipsAbiFlagsInputSection<ELFT>::MipsAbiFlagsInputSection(
811     elf::ObjectFile<ELFT> *F, const Elf_Shdr *Hdr, StringRef Name)
812     : InputSectionBase<ELFT>(F, Hdr, Name,
813                              InputSectionBase<ELFT>::MipsAbiFlags) {
814   // Initialize this->Flags.
815   ArrayRef<uint8_t> Data = this->Data;
816   if (Data.size() != sizeof(Elf_Mips_ABIFlags<ELFT>)) {
817     error("invalid size of .MIPS.abiflags section");
818     return;
819   }
820   Flags = reinterpret_cast<const Elf_Mips_ABIFlags<ELFT> *>(Data.data());
821 }
822 
823 template <class ELFT>
824 bool MipsAbiFlagsInputSection<ELFT>::classof(const InputSectionData *S) {
825   return S->kind() == InputSectionBase<ELFT>::MipsAbiFlags;
826 }
827 
828 template <class ELFT>
829 InputSection<ELFT> InputSection<ELFT>::createCommonInputSection(
830     std::vector<DefinedCommon *> Syms) {
831   // Sort the common symbols by alignment as an heuristic to pack them better.
832   std::stable_sort(Syms.begin(), Syms.end(),
833                    [](const DefinedCommon *A, const DefinedCommon *B) {
834                      return A->Alignment > B->Alignment;
835                    });
836 
837   size_t Size = 0;
838   uintX_t Alignment = 1;
839   for (DefinedCommon *Sym : Syms) {
840     Alignment = std::max<uintX_t>(Alignment, Sym->Alignment);
841     Size = alignTo(Size, Sym->Alignment);
842 
843     // Compute symbol offset relative to beginning of input section.
844     Sym->Offset = Size;
845     Size += Sym->Size;
846   }
847   ArrayRef<uint8_t> Data = makeArrayRef<uint8_t>(nullptr, Size);
848   InputSection Ret(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, Alignment, Data, "");
849   Ret.Live = true;
850   return Ret;
851 }
852 
853 template <class ELFT>
854 BuildIdSection<ELFT>::BuildIdSection(size_t HashSize)
855     : InputSection<ELFT>(SHF_ALLOC, SHT_NOTE, 1, ArrayRef<uint8_t>(),
856                          ".note.gnu.build-id") {
857   Buf.resize(16 + HashSize);
858   const endianness E = ELFT::TargetEndianness;
859   write32<E>(Buf.data(), 4);                   // Name size
860   write32<E>(Buf.data() + 4, HashSize);        // Content size
861   write32<E>(Buf.data() + 8, NT_GNU_BUILD_ID); // Type
862   memcpy(Buf.data() + 12, "GNU", 4);           // Name string
863   this->Data = ArrayRef<uint8_t>(Buf);
864 }
865 
866 template <class ELFT>
867 uint8_t *BuildIdSection<ELFT>::getOutputLoc(uint8_t *Start) const {
868   return Start + this->OutSec->getFileOffset() + this->OutSecOff;
869 }
870 
871 template <class ELFT>
872 void BuildIdFastHash<ELFT>::writeBuildId(MutableArrayRef<uint8_t> Buf) {
873   const endianness E = ELFT::TargetEndianness;
874 
875   // 64-bit xxhash
876   uint64_t Hash = xxHash64(toStringRef(Buf));
877   write64<E>(this->getOutputLoc(Buf.begin()) + 16, Hash);
878 }
879 
880 template <class ELFT>
881 void BuildIdMd5<ELFT>::writeBuildId(MutableArrayRef<uint8_t> Buf) {
882   MD5 Hash;
883   Hash.update(Buf);
884   MD5::MD5Result Res;
885   Hash.final(Res);
886   memcpy(this->getOutputLoc(Buf.begin()) + 16, Res, 16);
887 }
888 
889 template <class ELFT>
890 void BuildIdSha1<ELFT>::writeBuildId(MutableArrayRef<uint8_t> Buf) {
891   SHA1 Hash;
892   Hash.update(Buf);
893   memcpy(this->getOutputLoc(Buf.begin()) + 16, Hash.final().data(), 20);
894 }
895 
896 template <class ELFT>
897 void BuildIdUuid<ELFT>::writeBuildId(MutableArrayRef<uint8_t> Buf) {
898   if (getRandomBytes(this->getOutputLoc(Buf.begin()) + 16, 16))
899     error("entropy source failure");
900 }
901 
902 template <class ELFT>
903 BuildIdHexstring<ELFT>::BuildIdHexstring()
904     : BuildIdSection<ELFT>(Config->BuildIdVector.size()) {}
905 
906 template <class ELFT>
907 void BuildIdHexstring<ELFT>::writeBuildId(MutableArrayRef<uint8_t> Buf) {
908   memcpy(this->getOutputLoc(Buf.begin()) + 16, Config->BuildIdVector.data(),
909          Config->BuildIdVector.size());
910 }
911 
912 template class elf::InputSectionBase<ELF32LE>;
913 template class elf::InputSectionBase<ELF32BE>;
914 template class elf::InputSectionBase<ELF64LE>;
915 template class elf::InputSectionBase<ELF64BE>;
916 
917 template class elf::InputSection<ELF32LE>;
918 template class elf::InputSection<ELF32BE>;
919 template class elf::InputSection<ELF64LE>;
920 template class elf::InputSection<ELF64BE>;
921 
922 template class elf::EhInputSection<ELF32LE>;
923 template class elf::EhInputSection<ELF32BE>;
924 template class elf::EhInputSection<ELF64LE>;
925 template class elf::EhInputSection<ELF64BE>;
926 
927 template class elf::MergeInputSection<ELF32LE>;
928 template class elf::MergeInputSection<ELF32BE>;
929 template class elf::MergeInputSection<ELF64LE>;
930 template class elf::MergeInputSection<ELF64BE>;
931 
932 template class elf::MipsReginfoInputSection<ELF32LE>;
933 template class elf::MipsReginfoInputSection<ELF32BE>;
934 template class elf::MipsReginfoInputSection<ELF64LE>;
935 template class elf::MipsReginfoInputSection<ELF64BE>;
936 
937 template class elf::MipsOptionsInputSection<ELF32LE>;
938 template class elf::MipsOptionsInputSection<ELF32BE>;
939 template class elf::MipsOptionsInputSection<ELF64LE>;
940 template class elf::MipsOptionsInputSection<ELF64BE>;
941 
942 template class elf::MipsAbiFlagsInputSection<ELF32LE>;
943 template class elf::MipsAbiFlagsInputSection<ELF32BE>;
944 template class elf::MipsAbiFlagsInputSection<ELF64LE>;
945 template class elf::MipsAbiFlagsInputSection<ELF64BE>;
946 
947 template class elf::BuildIdSection<ELF32LE>;
948 template class elf::BuildIdSection<ELF32BE>;
949 template class elf::BuildIdSection<ELF64LE>;
950 template class elf::BuildIdSection<ELF64BE>;
951 
952 template class elf::BuildIdFastHash<ELF32LE>;
953 template class elf::BuildIdFastHash<ELF32BE>;
954 template class elf::BuildIdFastHash<ELF64LE>;
955 template class elf::BuildIdFastHash<ELF64BE>;
956 
957 template class elf::BuildIdMd5<ELF32LE>;
958 template class elf::BuildIdMd5<ELF32BE>;
959 template class elf::BuildIdMd5<ELF64LE>;
960 template class elf::BuildIdMd5<ELF64BE>;
961 
962 template class elf::BuildIdSha1<ELF32LE>;
963 template class elf::BuildIdSha1<ELF32BE>;
964 template class elf::BuildIdSha1<ELF64LE>;
965 template class elf::BuildIdSha1<ELF64BE>;
966 
967 template class elf::BuildIdUuid<ELF32LE>;
968 template class elf::BuildIdUuid<ELF32BE>;
969 template class elf::BuildIdUuid<ELF64LE>;
970 template class elf::BuildIdUuid<ELF64BE>;
971 
972 template class elf::BuildIdHexstring<ELF32LE>;
973 template class elf::BuildIdHexstring<ELF32BE>;
974 template class elf::BuildIdHexstring<ELF64LE>;
975 template class elf::BuildIdHexstring<ELF64BE>;
976