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 
23 using namespace llvm;
24 using namespace llvm::ELF;
25 using namespace llvm::object;
26 using namespace llvm::support::endian;
27 
28 using namespace lld;
29 using namespace lld::elf;
30 
31 template <class ELFT>
32 static ArrayRef<uint8_t> getSectionContents(elf::ObjectFile<ELFT> *File,
33                                             const typename ELFT::Shdr *Hdr) {
34   if (!File || Hdr->sh_type == SHT_NOBITS)
35     return {};
36   return check(File->getObj().getSectionContents(Hdr));
37 }
38 
39 template <class ELFT>
40 InputSectionBase<ELFT>::InputSectionBase(elf::ObjectFile<ELFT> *File,
41                                          const Elf_Shdr *Hdr, StringRef Name,
42                                          Kind SectionKind)
43     : InputSectionData(SectionKind, Name, getSectionContents(File, Hdr),
44                        Hdr->sh_flags & SHF_COMPRESSED, !Config->GcSections),
45       Header(Hdr), File(File), Repl(this) {
46   // The ELF spec states that a value of 0 means the section has
47   // no alignment constraits.
48   Alignment = std::max<uintX_t>(Header->sh_addralign, 1);
49 }
50 
51 template <class ELFT> size_t InputSectionBase<ELFT>::getSize() const {
52   if (auto *D = dyn_cast<InputSection<ELFT>>(this))
53     if (D->getThunksSize() > 0)
54       return D->getThunkOff() + D->getThunksSize();
55   return Header->sh_size;
56 }
57 
58 // Returns a string for an error message.
59 template <class SectionT> static std::string getName(SectionT *Sec) {
60   return (Sec->getFile()->getName() + "(" + Sec->Name + ")").str();
61 }
62 
63 template <class ELFT>
64 typename ELFT::uint InputSectionBase<ELFT>::getOffset(uintX_t Offset) const {
65   switch (kind()) {
66   case Regular:
67     return cast<InputSection<ELFT>>(this)->OutSecOff + Offset;
68   case EHFrame:
69     // The file crtbeginT.o has relocations pointing to the start of an empty
70     // .eh_frame that is known to be the first in the link. It does that to
71     // identify the start of the output .eh_frame.
72     return Offset;
73   case Merge:
74     return cast<MergeInputSection<ELFT>>(this)->getOffset(Offset);
75   case MipsReginfo:
76   case MipsOptions:
77   case MipsAbiFlags:
78     // MIPS .reginfo, .MIPS.options, and .MIPS.abiflags sections are consumed
79     // by the linker, and the linker produces a single output section. It is
80     // possible that input files contain section symbol points to the
81     // corresponding input section. Redirect it to the produced output section.
82     if (Offset != 0)
83       fatal(getName(this) + ": unsupported reference to the middle of '" +
84             Name + "' section");
85     return this->OutSec->getVA();
86   }
87   llvm_unreachable("invalid section kind");
88 }
89 
90 template <class ELFT> void InputSectionBase<ELFT>::uncompress() {
91   if (!zlib::isAvailable())
92     fatal(getName(this) +
93           ": build lld with zlib to enable compressed sections support");
94 
95   // A compressed section consists of a header of Elf_Chdr type
96   // followed by compressed data.
97   if (Data.size() < sizeof(Elf_Chdr))
98     fatal("corrupt compressed section");
99 
100   auto *Hdr = reinterpret_cast<const Elf_Chdr *>(Data.data());
101   Data = Data.slice(sizeof(Elf_Chdr));
102 
103   if (Hdr->ch_type != ELFCOMPRESS_ZLIB)
104     fatal(getName(this) + ": unsupported compression type");
105 
106   StringRef Buf((const char *)Data.data(), Data.size());
107   size_t UncompressedDataSize = Hdr->ch_size;
108   UncompressedData.reset(new char[UncompressedDataSize]);
109   if (zlib::uncompress(Buf, UncompressedData.get(), UncompressedDataSize) !=
110       zlib::StatusOK)
111     fatal(getName(this) + ": error uncompressing section");
112   Data = ArrayRef<uint8_t>((uint8_t *)UncompressedData.get(),
113                            UncompressedDataSize);
114 }
115 
116 template <class ELFT>
117 typename ELFT::uint
118 InputSectionBase<ELFT>::getOffset(const DefinedRegular<ELFT> &Sym) const {
119   return getOffset(Sym.Value);
120 }
121 
122 template <class ELFT>
123 InputSection<ELFT>::InputSection(elf::ObjectFile<ELFT> *F,
124                                  const Elf_Shdr *Header, StringRef Name)
125     : InputSectionBase<ELFT>(F, Header, Name, Base::Regular) {}
126 
127 template <class ELFT>
128 bool InputSection<ELFT>::classof(const InputSectionBase<ELFT> *S) {
129   return S->kind() == Base::Regular;
130 }
131 
132 template <class ELFT>
133 InputSectionBase<ELFT> *InputSection<ELFT>::getRelocatedSection() {
134   assert(this->Header->sh_type == SHT_RELA || this->Header->sh_type == SHT_REL);
135   ArrayRef<InputSectionBase<ELFT> *> Sections = this->File->getSections();
136   return Sections[this->Header->sh_info];
137 }
138 
139 template <class ELFT>
140 void InputSection<ELFT>::addThunk(const Thunk<ELFT> *T) {
141   Thunks.push_back(T);
142 }
143 
144 template <class ELFT> uint64_t InputSection<ELFT>::getThunkOff() const {
145   return this->Header->sh_size;
146 }
147 
148 template <class ELFT> uint64_t InputSection<ELFT>::getThunksSize() const {
149   uint64_t Total = 0;
150   for (const Thunk<ELFT> *T : Thunks)
151     Total += T->size();
152   return Total;
153 }
154 
155 // This is used for -r. We can't use memcpy to copy relocations because we need
156 // to update symbol table offset and section index for each relocation. So we
157 // copy relocations one by one.
158 template <class ELFT>
159 template <class RelTy>
160 void InputSection<ELFT>::copyRelocations(uint8_t *Buf, ArrayRef<RelTy> Rels) {
161   InputSectionBase<ELFT> *RelocatedSection = getRelocatedSection();
162 
163   for (const RelTy &Rel : Rels) {
164     uint32_t Type = Rel.getType(Config->Mips64EL);
165     SymbolBody &Body = this->File->getRelocTargetSym(Rel);
166 
167     Elf_Rela *P = reinterpret_cast<Elf_Rela *>(Buf);
168     Buf += sizeof(RelTy);
169 
170     if (Config->Rela)
171       P->r_addend = getAddend<ELFT>(Rel);
172     P->r_offset = RelocatedSection->getOffset(Rel.r_offset);
173     P->setSymbolAndType(Body.DynsymIndex, Type, Config->Mips64EL);
174   }
175 }
176 
177 // Page(Expr) is the page address of the expression Expr, defined
178 // as (Expr & ~0xFFF). (This applies even if the machine page size
179 // supported by the platform has a different value.)
180 static uint64_t getAArch64Page(uint64_t Expr) {
181   return Expr & (~static_cast<uint64_t>(0xFFF));
182 }
183 
184 template <class ELFT>
185 static typename ELFT::uint getSymVA(uint32_t Type, typename ELFT::uint A,
186                                     typename ELFT::uint P,
187                                     const SymbolBody &Body, RelExpr Expr) {
188   switch (Expr) {
189   case R_HINT:
190     llvm_unreachable("cannot relocate hint relocs");
191   case R_TLSLD:
192     return Out<ELFT>::Got->getTlsIndexOff() + A - Out<ELFT>::Got->getSize();
193   case R_TLSLD_PC:
194     return Out<ELFT>::Got->getTlsIndexVA() + A - P;
195   case R_THUNK_ABS:
196     return Body.getThunkVA<ELFT>() + A;
197   case R_THUNK_PC:
198   case R_THUNK_PLT_PC:
199     return Body.getThunkVA<ELFT>() + A - P;
200   case R_PPC_TOC:
201     return getPPC64TocBase() + A;
202   case R_TLSGD:
203     return Out<ELFT>::Got->getGlobalDynOffset(Body) + A -
204            Out<ELFT>::Got->getSize();
205   case R_TLSGD_PC:
206     return Out<ELFT>::Got->getGlobalDynAddr(Body) + A - P;
207   case R_TLSDESC:
208     return Out<ELFT>::Got->getGlobalDynAddr(Body) + A;
209   case R_TLSDESC_PAGE:
210     return getAArch64Page(Out<ELFT>::Got->getGlobalDynAddr(Body) + A) -
211            getAArch64Page(P);
212   case R_PLT:
213     return Body.getPltVA<ELFT>() + A;
214   case R_PLT_PC:
215   case R_PPC_PLT_OPD:
216     return Body.getPltVA<ELFT>() + A - P;
217   case R_SIZE:
218     return Body.getSize<ELFT>() + A;
219   case R_GOTREL:
220     return Body.getVA<ELFT>(A) - Out<ELFT>::Got->getVA();
221   case R_GOTREL_FROM_END:
222     return Body.getVA<ELFT>(A) - Out<ELFT>::Got->getVA() -
223            Out<ELFT>::Got->getSize();
224   case R_RELAX_TLS_GD_TO_IE_END:
225   case R_GOT_FROM_END:
226     return Body.getGotOffset<ELFT>() + A - Out<ELFT>::Got->getSize();
227   case R_RELAX_TLS_GD_TO_IE_ABS:
228   case R_GOT:
229     return Body.getGotVA<ELFT>() + A;
230   case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
231   case R_GOT_PAGE_PC:
232     return getAArch64Page(Body.getGotVA<ELFT>() + A) - getAArch64Page(P);
233   case R_RELAX_TLS_GD_TO_IE:
234   case R_GOT_PC:
235     return Body.getGotVA<ELFT>() + A - P;
236   case R_GOTONLY_PC:
237     return Out<ELFT>::Got->getVA() + A - P;
238   case R_GOTONLY_PC_FROM_END:
239     return Out<ELFT>::Got->getVA() + A - P + Out<ELFT>::Got->getSize();
240   case R_RELAX_TLS_LD_TO_LE:
241   case R_RELAX_TLS_IE_TO_LE:
242   case R_RELAX_TLS_GD_TO_LE:
243   case R_TLS:
244     if (Target->TcbSize)
245       return Body.getVA<ELFT>(A) +
246              alignTo(Target->TcbSize, Out<ELFT>::TlsPhdr->p_align);
247     return Body.getVA<ELFT>(A) - Out<ELFT>::TlsPhdr->p_memsz;
248   case R_RELAX_TLS_GD_TO_LE_NEG:
249   case R_NEG_TLS:
250     return Out<ELF32LE>::TlsPhdr->p_memsz - Body.getVA<ELFT>(A);
251   case R_ABS:
252   case R_RELAX_GOT_PC_NOPIC:
253     return Body.getVA<ELFT>(A);
254   case R_GOT_OFF:
255     return Body.getGotOffset<ELFT>() + A;
256   case R_MIPS_GOT_LOCAL_PAGE:
257     // If relocation against MIPS local symbol requires GOT entry, this entry
258     // should be initialized by 'page address'. This address is high 16-bits
259     // of sum the symbol's value and the addend.
260     return Out<ELFT>::Got->getMipsLocalPageOffset(Body.getVA<ELFT>(A));
261   case R_MIPS_GOT_OFF:
262     // In case of MIPS if a GOT relocation has non-zero addend this addend
263     // should be applied to the GOT entry content not to the GOT entry offset.
264     // That is why we use separate expression type.
265     return Out<ELFT>::Got->getMipsGotOffset(Body, A);
266   case R_MIPS_TLSGD:
267     return Out<ELFT>::Got->getGlobalDynOffset(Body) +
268            Out<ELFT>::Got->getMipsTlsOffset() - MipsGPOffset;
269   case R_MIPS_TLSLD:
270     return Out<ELFT>::Got->getTlsIndexOff() +
271            Out<ELFT>::Got->getMipsTlsOffset() - MipsGPOffset;
272   case R_PPC_OPD: {
273     uint64_t SymVA = Body.getVA<ELFT>(A);
274     // If we have an undefined weak symbol, we might get here with a symbol
275     // address of zero. That could overflow, but the code must be unreachable,
276     // so don't bother doing anything at all.
277     if (!SymVA)
278       return 0;
279     if (Out<ELF64BE>::Opd) {
280       // If this is a local call, and we currently have the address of a
281       // function-descriptor, get the underlying code address instead.
282       uint64_t OpdStart = Out<ELF64BE>::Opd->getVA();
283       uint64_t OpdEnd = OpdStart + Out<ELF64BE>::Opd->getSize();
284       bool InOpd = OpdStart <= SymVA && SymVA < OpdEnd;
285       if (InOpd)
286         SymVA = read64be(&Out<ELF64BE>::OpdBuf[SymVA - OpdStart]);
287     }
288     return SymVA - P;
289   }
290   case R_PC:
291   case R_RELAX_GOT_PC:
292     return Body.getVA<ELFT>(A) - P;
293   case R_PLT_PAGE_PC:
294   case R_PAGE_PC:
295     return getAArch64Page(Body.getVA<ELFT>(A)) - getAArch64Page(P);
296   }
297   llvm_unreachable("Invalid expression");
298 }
299 
300 // This function applies relocations to sections without SHF_ALLOC bit.
301 // Such sections are never mapped to memory at runtime. Debug sections are
302 // an example. Relocations in non-alloc sections are much easier to
303 // handle than in allocated sections because it will never need complex
304 // treatement such as GOT or PLT (because at runtime no one refers them).
305 // So, we handle relocations for non-alloc sections directly in this
306 // function as a performance optimization.
307 template <class ELFT>
308 template <class RelTy>
309 void InputSection<ELFT>::relocateNonAlloc(uint8_t *Buf, ArrayRef<RelTy> Rels) {
310   const unsigned Bits = sizeof(uintX_t) * 8;
311   for (const RelTy &Rel : Rels) {
312     uint32_t Type = Rel.getType(Config->Mips64EL);
313     uintX_t Offset = this->getOffset(Rel.r_offset);
314     uint8_t *BufLoc = Buf + Offset;
315     uintX_t Addend = getAddend<ELFT>(Rel);
316     if (!RelTy::IsRela)
317       Addend += Target->getImplicitAddend(BufLoc, Type);
318 
319     SymbolBody &Sym = this->File->getRelocTargetSym(Rel);
320     if (Target->getRelExpr(Type, Sym) != R_ABS) {
321       error(getName(this) + " has non-ABS reloc");
322       return;
323     }
324 
325     uintX_t AddrLoc = this->OutSec->getVA() + Offset;
326     uint64_t SymVA =
327         SignExtend64<Bits>(getSymVA<ELFT>(Type, Addend, AddrLoc, Sym, R_ABS));
328     Target->relocateOne(BufLoc, Type, SymVA);
329   }
330 }
331 
332 template <class ELFT>
333 void InputSectionBase<ELFT>::relocate(uint8_t *Buf, uint8_t *BufEnd) {
334   // scanReloc function in Writer.cpp constructs Relocations
335   // vector only for SHF_ALLOC'ed sections. For other sections,
336   // we handle relocations directly here.
337   auto *IS = dyn_cast<InputSection<ELFT>>(this);
338   if (IS && !(IS->Header->sh_flags & SHF_ALLOC)) {
339     for (const Elf_Shdr *RelSec : IS->RelocSections) {
340       if (RelSec->sh_type == SHT_RELA)
341         IS->relocateNonAlloc(Buf, IS->File->getObj().relas(RelSec));
342       else
343         IS->relocateNonAlloc(Buf, IS->File->getObj().rels(RelSec));
344     }
345     return;
346   }
347 
348   const unsigned Bits = sizeof(uintX_t) * 8;
349   for (const Relocation &Rel : Relocations) {
350     uintX_t Offset = getOffset(Rel.Offset);
351     uint8_t *BufLoc = Buf + Offset;
352     uint32_t Type = Rel.Type;
353     uintX_t A = Rel.Addend;
354 
355     uintX_t AddrLoc = OutSec->getVA() + Offset;
356     RelExpr Expr = Rel.Expr;
357     uint64_t SymVA =
358         SignExtend64<Bits>(getSymVA<ELFT>(Type, A, AddrLoc, *Rel.Sym, Expr));
359 
360     switch (Expr) {
361     case R_RELAX_GOT_PC:
362     case R_RELAX_GOT_PC_NOPIC:
363       Target->relaxGot(BufLoc, SymVA);
364       break;
365     case R_RELAX_TLS_IE_TO_LE:
366       Target->relaxTlsIeToLe(BufLoc, Type, SymVA);
367       break;
368     case R_RELAX_TLS_LD_TO_LE:
369       Target->relaxTlsLdToLe(BufLoc, Type, SymVA);
370       break;
371     case R_RELAX_TLS_GD_TO_LE:
372     case R_RELAX_TLS_GD_TO_LE_NEG:
373       Target->relaxTlsGdToLe(BufLoc, Type, SymVA);
374       break;
375     case R_RELAX_TLS_GD_TO_IE:
376     case R_RELAX_TLS_GD_TO_IE_ABS:
377     case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
378     case R_RELAX_TLS_GD_TO_IE_END:
379       Target->relaxTlsGdToIe(BufLoc, Type, SymVA);
380       break;
381     case R_PPC_PLT_OPD:
382       // Patch a nop (0x60000000) to a ld.
383       if (BufLoc + 8 <= BufEnd && read32be(BufLoc + 4) == 0x60000000)
384         write32be(BufLoc + 4, 0xe8410028); // ld %r2, 40(%r1)
385       // fallthrough
386     default:
387       Target->relocateOne(BufLoc, Type, SymVA);
388       break;
389     }
390   }
391 }
392 
393 template <class ELFT> void InputSection<ELFT>::writeTo(uint8_t *Buf) {
394   if (this->Header->sh_type == SHT_NOBITS)
395     return;
396   ELFFile<ELFT> &EObj = this->File->getObj();
397 
398   // If -r is given, then an InputSection may be a relocation section.
399   if (this->Header->sh_type == SHT_RELA) {
400     copyRelocations(Buf + OutSecOff, EObj.relas(this->Header));
401     return;
402   }
403   if (this->Header->sh_type == SHT_REL) {
404     copyRelocations(Buf + OutSecOff, EObj.rels(this->Header));
405     return;
406   }
407 
408   // Copy section contents from source object file to output file.
409   ArrayRef<uint8_t> Data = this->Data;
410   memcpy(Buf + OutSecOff, Data.data(), Data.size());
411 
412   // Iterate over all relocation sections that apply to this section.
413   uint8_t *BufEnd = Buf + OutSecOff + Data.size();
414   this->relocate(Buf, BufEnd);
415 
416   // The section might have a data/code generated by the linker and need
417   // to be written after the section. Usually these are thunks - small piece
418   // of code used to jump between "incompatible" functions like PIC and non-PIC
419   // or if the jump target too far and its address does not fit to the short
420   // jump istruction.
421   if (!Thunks.empty()) {
422     Buf += OutSecOff + getThunkOff();
423     for (const Thunk<ELFT> *T : Thunks) {
424       T->writeTo(Buf);
425       Buf += T->size();
426     }
427   }
428 }
429 
430 template <class ELFT>
431 void InputSection<ELFT>::replace(InputSection<ELFT> *Other) {
432   assert(Other->Alignment <= this->Alignment);
433   Other->Repl = this->Repl;
434   Other->Live = false;
435 }
436 
437 template <class ELFT>
438 EhInputSection<ELFT>::EhInputSection(elf::ObjectFile<ELFT> *F,
439                                      const Elf_Shdr *Header, StringRef Name)
440     : InputSectionBase<ELFT>(F, Header, Name, InputSectionBase<ELFT>::EHFrame) {
441   // Mark .eh_frame sections as live by default because there are
442   // usually no relocations that point to .eh_frames. Otherwise,
443   // the garbage collector would drop all .eh_frame sections.
444   this->Live = true;
445 }
446 
447 template <class ELFT>
448 bool EhInputSection<ELFT>::classof(const InputSectionBase<ELFT> *S) {
449   return S->kind() == InputSectionBase<ELFT>::EHFrame;
450 }
451 
452 // Returns the index of the first relocation that points to a region between
453 // Begin and Begin+Size.
454 template <class IntTy, class RelTy>
455 static unsigned getReloc(IntTy Begin, IntTy Size, const ArrayRef<RelTy> &Rels,
456                          unsigned &RelocI) {
457   // Start search from RelocI for fast access. That works because the
458   // relocations are sorted in .eh_frame.
459   for (unsigned N = Rels.size(); RelocI < N; ++RelocI) {
460     const RelTy &Rel = Rels[RelocI];
461     if (Rel.r_offset < Begin)
462       continue;
463 
464     if (Rel.r_offset < Begin + Size)
465       return RelocI;
466     return -1;
467   }
468   return -1;
469 }
470 
471 // .eh_frame is a sequence of CIE or FDE records.
472 // This function splits an input section into records and returns them.
473 template <class ELFT>
474 void EhInputSection<ELFT>::split() {
475   // Early exit if already split.
476   if (!this->Pieces.empty())
477     return;
478 
479   if (RelocSection) {
480     ELFFile<ELFT> &Obj = this->File->getObj();
481     if (RelocSection->sh_type == SHT_RELA)
482       split(Obj.relas(RelocSection));
483     else
484       split(Obj.rels(RelocSection));
485     return;
486   }
487   split(makeArrayRef<typename ELFT::Rela>(nullptr, nullptr));
488 }
489 
490 template <class ELFT>
491 template <class RelTy>
492 void EhInputSection<ELFT>::split(ArrayRef<RelTy> Rels) {
493   ArrayRef<uint8_t> Data = this->Data;
494   unsigned RelI = 0;
495   for (size_t Off = 0, End = Data.size(); Off != End;) {
496     size_t Size = readEhRecordSize<ELFT>(Data.slice(Off));
497     this->Pieces.emplace_back(Off, Data.slice(Off, Size),
498                               getReloc(Off, Size, Rels, RelI));
499     // The empty record is the end marker.
500     if (Size == 4)
501       break;
502     Off += Size;
503   }
504 }
505 
506 static size_t findNull(ArrayRef<uint8_t> A, size_t EntSize) {
507   // Optimize the common case.
508   StringRef S((const char *)A.data(), A.size());
509   if (EntSize == 1)
510     return S.find(0);
511 
512   for (unsigned I = 0, N = S.size(); I != N; I += EntSize) {
513     const char *B = S.begin() + I;
514     if (std::all_of(B, B + EntSize, [](char C) { return C == 0; }))
515       return I;
516   }
517   return StringRef::npos;
518 }
519 
520 // Split SHF_STRINGS section. Such section is a sequence of
521 // null-terminated strings.
522 template <class ELFT>
523 std::vector<SectionPiece>
524 MergeInputSection<ELFT>::splitStrings(ArrayRef<uint8_t> Data, size_t EntSize) {
525   std::vector<SectionPiece> V;
526   size_t Off = 0;
527   while (!Data.empty()) {
528     size_t End = findNull(Data, EntSize);
529     if (End == StringRef::npos)
530       fatal(getName(this) + ": string is not null terminated");
531     size_t Size = End + EntSize;
532     V.emplace_back(Off, Data.slice(0, Size));
533     Data = Data.slice(Size);
534     Off += Size;
535   }
536   return V;
537 }
538 
539 // Split non-SHF_STRINGS section. Such section is a sequence of
540 // fixed size records.
541 template <class ELFT>
542 std::vector<SectionPiece>
543 MergeInputSection<ELFT>::splitNonStrings(ArrayRef<uint8_t> Data,
544                                          size_t EntSize) {
545   std::vector<SectionPiece> V;
546   size_t Size = Data.size();
547   assert((Size % EntSize) == 0);
548   for (unsigned I = 0, N = Size; I != N; I += EntSize)
549     V.emplace_back(I, Data.slice(I, EntSize));
550   return V;
551 }
552 
553 template <class ELFT>
554 MergeInputSection<ELFT>::MergeInputSection(elf::ObjectFile<ELFT> *F,
555                                            const Elf_Shdr *Header,
556                                            StringRef Name)
557     : InputSectionBase<ELFT>(F, Header, Name, InputSectionBase<ELFT>::Merge) {}
558 
559 template <class ELFT> void MergeInputSection<ELFT>::splitIntoPieces() {
560   ArrayRef<uint8_t> Data = this->Data;
561   uintX_t EntSize = this->Header->sh_entsize;
562   if (this->Header->sh_flags & SHF_STRINGS)
563     this->Pieces = splitStrings(Data, EntSize);
564   else
565     this->Pieces = splitNonStrings(Data, EntSize);
566 
567   if (Config->GcSections)
568     for (uintX_t Off : LiveOffsets)
569       this->getSectionPiece(Off)->Live = true;
570 }
571 
572 template <class ELFT>
573 bool MergeInputSection<ELFT>::classof(const InputSectionBase<ELFT> *S) {
574   return S->kind() == InputSectionBase<ELFT>::Merge;
575 }
576 
577 // Do binary search to get a section piece at a given input offset.
578 template <class ELFT>
579 SectionPiece *MergeInputSection<ELFT>::getSectionPiece(uintX_t Offset) {
580   auto *This = static_cast<const MergeInputSection<ELFT> *>(this);
581   return const_cast<SectionPiece *>(This->getSectionPiece(Offset));
582 }
583 
584 template <class ELFT>
585 const SectionPiece *
586 MergeInputSection<ELFT>::getSectionPiece(uintX_t Offset) const {
587   uintX_t Size = this->Data.size();
588   if (Offset >= Size)
589     fatal(getName(this) + ": entry is past the end of the section");
590 
591   // Find the element this offset points to.
592   auto I = std::upper_bound(
593       Pieces.begin(), Pieces.end(), Offset,
594       [](const uintX_t &A, const SectionPiece &B) { return A < B.InputOff; });
595   --I;
596   return &*I;
597 }
598 
599 // Returns the offset in an output section for a given input offset.
600 // Because contents of a mergeable section is not contiguous in output,
601 // it is not just an addition to a base output offset.
602 template <class ELFT>
603 typename ELFT::uint MergeInputSection<ELFT>::getOffset(uintX_t Offset) const {
604   auto It = OffsetMap.find(Offset);
605   if (It != OffsetMap.end())
606     return It->second;
607 
608   // If Offset is not at beginning of a section piece, it is not in the map.
609   // In that case we need to search from the original section piece vector.
610   const SectionPiece &Piece = *this->getSectionPiece(Offset);
611   assert(Piece.Live);
612   uintX_t Addend = Offset - Piece.InputOff;
613   return Piece.OutputOff + Addend;
614 }
615 
616 // Create a map from input offsets to output offsets for all section pieces.
617 // It is called after finalize().
618 template <class ELFT> void  MergeInputSection<ELFT>::finalizePieces() {
619   OffsetMap.grow(this->Pieces.size());
620   for (SectionPiece &Piece : this->Pieces) {
621     if (!Piece.Live)
622       continue;
623     if (Piece.OutputOff == size_t(-1)) {
624       // Offsets of tail-merged strings are computed lazily.
625       auto *OutSec = static_cast<MergeOutputSection<ELFT> *>(this->OutSec);
626       ArrayRef<uint8_t> D = Piece.data();
627       StringRef S((const char *)D.data(), D.size());
628       Piece.OutputOff = OutSec->getOffset(S);
629     }
630     OffsetMap[Piece.InputOff] = Piece.OutputOff;
631   }
632 }
633 
634 template <class ELFT>
635 MipsReginfoInputSection<ELFT>::MipsReginfoInputSection(elf::ObjectFile<ELFT> *F,
636                                                        const Elf_Shdr *Hdr,
637                                                        StringRef Name)
638     : InputSectionBase<ELFT>(F, Hdr, Name,
639                              InputSectionBase<ELFT>::MipsReginfo) {
640   ArrayRef<uint8_t> Data = this->Data;
641   // Initialize this->Reginfo.
642   if (Data.size() != sizeof(Elf_Mips_RegInfo<ELFT>)) {
643     error(getName(this) + ": invalid size of .reginfo section");
644     return;
645   }
646   Reginfo = reinterpret_cast<const Elf_Mips_RegInfo<ELFT> *>(Data.data());
647 }
648 
649 template <class ELFT>
650 bool MipsReginfoInputSection<ELFT>::classof(const InputSectionBase<ELFT> *S) {
651   return S->kind() == InputSectionBase<ELFT>::MipsReginfo;
652 }
653 
654 template <class ELFT>
655 MipsOptionsInputSection<ELFT>::MipsOptionsInputSection(elf::ObjectFile<ELFT> *F,
656                                                        const Elf_Shdr *Hdr,
657                                                        StringRef Name)
658     : InputSectionBase<ELFT>(F, Hdr, Name,
659                              InputSectionBase<ELFT>::MipsOptions) {
660   // Find ODK_REGINFO option in the section's content.
661   ArrayRef<uint8_t> D = this->Data;
662   while (!D.empty()) {
663     if (D.size() < sizeof(Elf_Mips_Options<ELFT>)) {
664       error(getName(this) + ": invalid size of .MIPS.options section");
665       break;
666     }
667     auto *O = reinterpret_cast<const Elf_Mips_Options<ELFT> *>(D.data());
668     if (O->kind == ODK_REGINFO) {
669       Reginfo = &O->getRegInfo();
670       break;
671     }
672     D = D.slice(O->size);
673   }
674 }
675 
676 template <class ELFT>
677 bool MipsOptionsInputSection<ELFT>::classof(const InputSectionBase<ELFT> *S) {
678   return S->kind() == InputSectionBase<ELFT>::MipsOptions;
679 }
680 
681 template <class ELFT>
682 MipsAbiFlagsInputSection<ELFT>::MipsAbiFlagsInputSection(
683     elf::ObjectFile<ELFT> *F, const Elf_Shdr *Hdr, StringRef Name)
684     : InputSectionBase<ELFT>(F, Hdr, Name,
685                              InputSectionBase<ELFT>::MipsAbiFlags) {
686   // Initialize this->Flags.
687   ArrayRef<uint8_t> Data = this->Data;
688   if (Data.size() != sizeof(Elf_Mips_ABIFlags<ELFT>)) {
689     error("invalid size of .MIPS.abiflags section");
690     return;
691   }
692   Flags = reinterpret_cast<const Elf_Mips_ABIFlags<ELFT> *>(Data.data());
693 }
694 
695 template <class ELFT>
696 bool MipsAbiFlagsInputSection<ELFT>::classof(const InputSectionBase<ELFT> *S) {
697   return S->kind() == InputSectionBase<ELFT>::MipsAbiFlags;
698 }
699 
700 template <class ELFT>
701 CommonInputSection<ELFT>::CommonInputSection(std::vector<DefinedCommon *> Syms)
702     : InputSection<ELFT>(nullptr, &Hdr, "") {
703   Hdr.sh_size = 0;
704   Hdr.sh_type = SHT_NOBITS;
705   Hdr.sh_flags = SHF_ALLOC | SHF_WRITE;
706   this->Live = true;
707 
708   // Sort the common symbols by alignment as an heuristic to pack them better.
709   std::stable_sort(Syms.begin(), Syms.end(),
710                    [](const DefinedCommon *A, const DefinedCommon *B) {
711                      return A->Alignment > B->Alignment;
712                    });
713 
714   for (DefinedCommon *Sym : Syms) {
715     this->Alignment = std::max<uintX_t>(this->Alignment, Sym->Alignment);
716     Hdr.sh_size = alignTo(Hdr.sh_size, Sym->Alignment);
717 
718     // Compute symbol offset relative to beginning of input section.
719     Sym->Offset = Hdr.sh_size;
720     Hdr.sh_size += Sym->Size;
721   }
722 }
723 
724 template class elf::InputSectionBase<ELF32LE>;
725 template class elf::InputSectionBase<ELF32BE>;
726 template class elf::InputSectionBase<ELF64LE>;
727 template class elf::InputSectionBase<ELF64BE>;
728 
729 template class elf::InputSection<ELF32LE>;
730 template class elf::InputSection<ELF32BE>;
731 template class elf::InputSection<ELF64LE>;
732 template class elf::InputSection<ELF64BE>;
733 
734 template class elf::EhInputSection<ELF32LE>;
735 template class elf::EhInputSection<ELF32BE>;
736 template class elf::EhInputSection<ELF64LE>;
737 template class elf::EhInputSection<ELF64BE>;
738 
739 template class elf::MergeInputSection<ELF32LE>;
740 template class elf::MergeInputSection<ELF32BE>;
741 template class elf::MergeInputSection<ELF64LE>;
742 template class elf::MergeInputSection<ELF64BE>;
743 
744 template class elf::MipsReginfoInputSection<ELF32LE>;
745 template class elf::MipsReginfoInputSection<ELF32BE>;
746 template class elf::MipsReginfoInputSection<ELF64LE>;
747 template class elf::MipsReginfoInputSection<ELF64BE>;
748 
749 template class elf::MipsOptionsInputSection<ELF32LE>;
750 template class elf::MipsOptionsInputSection<ELF32BE>;
751 template class elf::MipsOptionsInputSection<ELF64LE>;
752 template class elf::MipsOptionsInputSection<ELF64BE>;
753 
754 template class elf::MipsAbiFlagsInputSection<ELF32LE>;
755 template class elf::MipsAbiFlagsInputSection<ELF32BE>;
756 template class elf::MipsAbiFlagsInputSection<ELF64LE>;
757 template class elf::MipsAbiFlagsInputSection<ELF64BE>;
758 
759 template class elf::CommonInputSection<ELF32LE>;
760 template class elf::CommonInputSection<ELF32BE>;
761 template class elf::CommonInputSection<ELF64LE>;
762 template class elf::CommonInputSection<ELF64BE>;
763