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