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;
27 using namespace llvm::support::endian;
28 
29 using namespace lld;
30 using namespace lld::elf;
31 
32 template <class ELFT>
33 static ArrayRef<uint8_t> getSectionContents(elf::ObjectFile<ELFT> *File,
34                                             const typename ELFT::Shdr *Hdr) {
35   if (!File || Hdr->sh_type == SHT_NOBITS)
36     return makeArrayRef<uint8_t>(nullptr, Hdr->sh_size);
37   return check(File->getObj().getSectionContents(Hdr));
38 }
39 
40 // ELF supports ZLIB-compressed section. Returns true if the section
41 // is compressed.
42 template <class ELFT>
43 static bool isCompressed(typename ELFT::uint Flags, StringRef Name) {
44   return (Flags & SHF_COMPRESSED) || Name.startswith(".zdebug");
45 }
46 
47 template <class ELFT>
48 InputSectionBase<ELFT>::InputSectionBase(elf::ObjectFile<ELFT> *File,
49                                          uintX_t Flags, uint32_t Type,
50                                          uintX_t Entsize, uint32_t Link,
51                                          uint32_t Info, uintX_t Addralign,
52                                          ArrayRef<uint8_t> Data, StringRef Name,
53                                          Kind SectionKind)
54     : InputSectionData(SectionKind, Name, Data, isCompressed<ELFT>(Flags, Name),
55                        !Config->GcSections || !(Flags & SHF_ALLOC)),
56       File(File), Flags(Flags), Entsize(Entsize), Type(Type), Link(Link),
57       Info(Info), Repl(this) {
58   // The ELF spec states that a value of 0 means the section has
59   // no alignment constraits.
60   uint64_t V = std::max<uint64_t>(Addralign, 1);
61   if (!isPowerOf2_64(V))
62     fatal(getFilename(File) + ": section sh_addralign is not a power of 2");
63 
64   // We reject object files having insanely large alignments even though
65   // they are allowed by the spec. I think 4GB is a reasonable limitation.
66   // We might want to relax this in the future.
67   if (V > UINT32_MAX)
68     fatal(getFilename(File) + ": section sh_addralign is too large");
69   Alignment = V;
70 }
71 
72 template <class ELFT>
73 InputSectionBase<ELFT>::InputSectionBase(elf::ObjectFile<ELFT> *File,
74                                          const Elf_Shdr *Hdr, StringRef Name,
75                                          Kind SectionKind)
76     : InputSectionBase(File, Hdr->sh_flags, Hdr->sh_type, Hdr->sh_entsize,
77                        Hdr->sh_link, Hdr->sh_info, Hdr->sh_addralign,
78                        getSectionContents(File, Hdr), Name, SectionKind) {
79   this->Offset = Hdr->sh_offset;
80 }
81 
82 template <class ELFT> size_t InputSectionBase<ELFT>::getSize() const {
83   if (auto *D = dyn_cast<InputSection<ELFT>>(this))
84     if (D->getThunksSize() > 0)
85       return D->getThunkOff() + D->getThunksSize();
86   return Data.size();
87 }
88 
89 // Returns a string for an error message.
90 template <class SectionT> static std::string getName(SectionT *Sec) {
91   return (Sec->getFile()->getName() + "(" + Sec->Name + ")").str();
92 }
93 
94 template <class ELFT>
95 typename ELFT::uint InputSectionBase<ELFT>::getOffset(uintX_t Offset) const {
96   switch (kind()) {
97   case Regular:
98     return cast<InputSection<ELFT>>(this)->OutSecOff + Offset;
99   case EHFrame:
100     // The file crtbeginT.o has relocations pointing to the start of an empty
101     // .eh_frame that is known to be the first in the link. It does that to
102     // identify the start of the output .eh_frame.
103     return Offset;
104   case Merge:
105     return cast<MergeInputSection<ELFT>>(this)->getOffset(Offset);
106   case MipsReginfo:
107   case MipsOptions:
108   case MipsAbiFlags:
109     // MIPS .reginfo, .MIPS.options, and .MIPS.abiflags sections are consumed
110     // by the linker, and the linker produces a single output section. It is
111     // possible that input files contain section symbol points to the
112     // corresponding input section. Redirect it to the produced output section.
113     if (Offset != 0)
114       fatal(getName(this) + ": unsupported reference to the middle of '" +
115             Name + "' section");
116     return this->OutSec->getVA();
117   }
118   llvm_unreachable("invalid section kind");
119 }
120 
121 // Returns compressed data and its size when uncompressed.
122 template <class ELFT>
123 std::pair<ArrayRef<uint8_t>, uint64_t>
124 InputSectionBase<ELFT>::getElfCompressedData(ArrayRef<uint8_t> Data) {
125   // Compressed section with Elf_Chdr is the ELF standard.
126   if (Data.size() < sizeof(Elf_Chdr))
127     fatal(getName(this) + ": corrupted compressed section");
128   auto *Hdr = reinterpret_cast<const Elf_Chdr *>(Data.data());
129   if (Hdr->ch_type != ELFCOMPRESS_ZLIB)
130     fatal(getName(this) + ": unsupported compression type");
131   return {Data.slice(sizeof(*Hdr)), Hdr->ch_size};
132 }
133 
134 // Returns compressed data and its size when uncompressed.
135 template <class ELFT>
136 std::pair<ArrayRef<uint8_t>, uint64_t>
137 InputSectionBase<ELFT>::getRawCompressedData(ArrayRef<uint8_t> Data) {
138   // Compressed sections without Elf_Chdr header contain this header
139   // instead. This is a GNU extension.
140   struct ZlibHeader {
141     char Magic[4]; // Should be "ZLIB"
142     char Size[8];  // Uncompressed size in big-endian
143   };
144 
145   if (Data.size() < sizeof(ZlibHeader))
146     fatal(getName(this) + ": corrupted compressed section");
147   auto *Hdr = reinterpret_cast<const ZlibHeader *>(Data.data());
148   if (memcmp(Hdr->Magic, "ZLIB", 4))
149     fatal(getName(this) + ": broken ZLIB-compressed section");
150   return {Data.slice(sizeof(*Hdr)), read64be(Hdr->Size)};
151 }
152 
153 template <class ELFT> void InputSectionBase<ELFT>::uncompress() {
154   if (!zlib::isAvailable())
155     fatal(getName(this) +
156           ": build lld with zlib to enable compressed sections support");
157 
158   // This section is compressed. Here we decompress it. Ideally, all
159   // compressed sections have SHF_COMPRESSED bit and their contents
160   // start with headers of Elf_Chdr type. However, sections whose
161   // names start with ".zdebug_" don't have the bit and contains a raw
162   // ZLIB-compressed data (which is a bad thing because section names
163   // shouldn't be significant in ELF.) We need to be able to read both.
164   ArrayRef<uint8_t> Buf; // Compressed data
165   size_t Size;           // Uncompressed size
166   if (Flags & SHF_COMPRESSED)
167     std::tie(Buf, Size) = getElfCompressedData(Data);
168   else
169     std::tie(Buf, Size) = getRawCompressedData(Data);
170 
171   // Uncompress Buf.
172   UncompressedData.reset(new uint8_t[Size]);
173   if (zlib::uncompress(toStringRef(Buf), (char *)UncompressedData.get(),
174                        Size) != zlib::StatusOK)
175     fatal(getName(this) + ": error while uncompressing section");
176   Data = ArrayRef<uint8_t>(UncompressedData.get(), Size);
177 }
178 
179 template <class ELFT>
180 typename ELFT::uint
181 InputSectionBase<ELFT>::getOffset(const DefinedRegular<ELFT> &Sym) const {
182   return getOffset(Sym.Value);
183 }
184 
185 template <class ELFT>
186 InputSectionBase<ELFT> *InputSectionBase<ELFT>::getLinkOrderDep() const {
187   if ((Flags & SHF_LINK_ORDER) && Link != 0)
188     return getFile()->getSections()[Link];
189   return nullptr;
190 }
191 
192 template <class ELFT>
193 InputSection<ELFT>::InputSection(uintX_t Flags, uint32_t Type,
194                                  uintX_t Addralign, ArrayRef<uint8_t> Data,
195                                  StringRef Name)
196     : InputSectionBase<ELFT>(nullptr, Flags, Type,
197                              /*Entsize*/ 0, /*Link*/ 0, /*Info*/ 0, Addralign,
198                              Data, Name, Base::Regular) {}
199 
200 template <class ELFT>
201 InputSection<ELFT>::InputSection(elf::ObjectFile<ELFT> *F,
202                                  const Elf_Shdr *Header, StringRef Name)
203     : InputSectionBase<ELFT>(F, Header, Name, Base::Regular) {}
204 
205 template <class ELFT>
206 bool InputSection<ELFT>::classof(const InputSectionData *S) {
207   return S->kind() == Base::Regular;
208 }
209 
210 template <class ELFT>
211 InputSectionBase<ELFT> *InputSection<ELFT>::getRelocatedSection() {
212   assert(this->Type == SHT_RELA || this->Type == SHT_REL);
213   ArrayRef<InputSectionBase<ELFT> *> Sections = this->File->getSections();
214   return Sections[this->Info];
215 }
216 
217 template <class ELFT> void InputSection<ELFT>::addThunk(const Thunk<ELFT> *T) {
218   Thunks.push_back(T);
219 }
220 
221 template <class ELFT> uint64_t InputSection<ELFT>::getThunkOff() const {
222   return this->Data.size();
223 }
224 
225 template <class ELFT> uint64_t InputSection<ELFT>::getThunksSize() const {
226   uint64_t Total = 0;
227   for (const Thunk<ELFT> *T : Thunks)
228     Total += T->size();
229   return Total;
230 }
231 
232 // This is used for -r. We can't use memcpy to copy relocations because we need
233 // to update symbol table offset and section index for each relocation. So we
234 // copy relocations one by one.
235 template <class ELFT>
236 template <class RelTy>
237 void InputSection<ELFT>::copyRelocations(uint8_t *Buf, ArrayRef<RelTy> Rels) {
238   InputSectionBase<ELFT> *RelocatedSection = getRelocatedSection();
239 
240   for (const RelTy &Rel : Rels) {
241     uint32_t Type = Rel.getType(Config->Mips64EL);
242     SymbolBody &Body = this->File->getRelocTargetSym(Rel);
243 
244     Elf_Rela *P = reinterpret_cast<Elf_Rela *>(Buf);
245     Buf += sizeof(RelTy);
246 
247     if (Config->Rela)
248       P->r_addend = getAddend<ELFT>(Rel);
249     P->r_offset = RelocatedSection->getOffset(Rel.r_offset);
250     P->setSymbolAndType(Body.DynsymIndex, Type, Config->Mips64EL);
251   }
252 }
253 
254 // Page(Expr) is the page address of the expression Expr, defined
255 // as (Expr & ~0xFFF). (This applies even if the machine page size
256 // supported by the platform has a different value.)
257 static uint64_t getAArch64Page(uint64_t Expr) {
258   return Expr & (~static_cast<uint64_t>(0xFFF));
259 }
260 
261 template <class ELFT>
262 static typename ELFT::uint getSymVA(uint32_t Type, typename ELFT::uint A,
263                                     typename ELFT::uint P,
264                                     const SymbolBody &Body, RelExpr Expr) {
265   switch (Expr) {
266   case R_HINT:
267   case R_TLSDESC_CALL:
268     llvm_unreachable("cannot relocate hint relocs");
269   case R_TLSLD:
270     return Out<ELFT>::Got->getTlsIndexOff() + A - Out<ELFT>::Got->getSize();
271   case R_TLSLD_PC:
272     return Out<ELFT>::Got->getTlsIndexVA() + A - P;
273   case R_THUNK_ABS:
274     return Body.getThunkVA<ELFT>() + A;
275   case R_THUNK_PC:
276   case R_THUNK_PLT_PC:
277     return Body.getThunkVA<ELFT>() + A - P;
278   case R_PPC_TOC:
279     return getPPC64TocBase() + A;
280   case R_TLSGD:
281     return Out<ELFT>::Got->getGlobalDynOffset(Body) + A -
282            Out<ELFT>::Got->getSize();
283   case R_TLSGD_PC:
284     return Out<ELFT>::Got->getGlobalDynAddr(Body) + A - P;
285   case R_TLSDESC:
286     return Out<ELFT>::Got->getGlobalDynAddr(Body) + A;
287   case R_TLSDESC_PAGE:
288     return getAArch64Page(Out<ELFT>::Got->getGlobalDynAddr(Body) + A) -
289            getAArch64Page(P);
290   case R_PLT:
291     return Body.getPltVA<ELFT>() + A;
292   case R_PLT_PC:
293   case R_PPC_PLT_OPD:
294     return Body.getPltVA<ELFT>() + A - P;
295   case R_SIZE:
296     return Body.getSize<ELFT>() + A;
297   case R_GOTREL:
298     return Body.getVA<ELFT>(A) - Out<ELFT>::Got->getVA();
299   case R_GOTREL_FROM_END:
300     return Body.getVA<ELFT>(A) - Out<ELFT>::Got->getVA() -
301            Out<ELFT>::Got->getSize();
302   case R_RELAX_TLS_GD_TO_IE_END:
303   case R_GOT_FROM_END:
304     return Body.getGotOffset<ELFT>() + A - Out<ELFT>::Got->getSize();
305   case R_RELAX_TLS_GD_TO_IE_ABS:
306   case R_GOT:
307     return Body.getGotVA<ELFT>() + A;
308   case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
309   case R_GOT_PAGE_PC:
310     return getAArch64Page(Body.getGotVA<ELFT>() + A) - getAArch64Page(P);
311   case R_RELAX_TLS_GD_TO_IE:
312   case R_GOT_PC:
313     return Body.getGotVA<ELFT>() + A - P;
314   case R_GOTONLY_PC:
315     return Out<ELFT>::Got->getVA() + A - P;
316   case R_GOTONLY_PC_FROM_END:
317     return Out<ELFT>::Got->getVA() + A - P + Out<ELFT>::Got->getSize();
318   case R_RELAX_TLS_LD_TO_LE:
319   case R_RELAX_TLS_IE_TO_LE:
320   case R_RELAX_TLS_GD_TO_LE:
321   case R_TLS:
322     // A weak undefined TLS symbol resolves to the base of the TLS
323     // block, i.e. gets a value of zero. If we pass --gc-sections to
324     // lld and .tbss is not referenced, it gets reclaimed and we don't
325     // create a TLS program header. Therefore, we resolve this
326     // statically to zero.
327     if (Body.isTls() && (Body.isLazy() || Body.isUndefined()) &&
328         Body.symbol()->isWeak())
329       return 0;
330     if (Target->TcbSize)
331       return Body.getVA<ELFT>(A) +
332              alignTo(Target->TcbSize, Out<ELFT>::TlsPhdr->p_align);
333     return Body.getVA<ELFT>(A) - Out<ELFT>::TlsPhdr->p_memsz;
334   case R_RELAX_TLS_GD_TO_LE_NEG:
335   case R_NEG_TLS:
336     return Out<ELF32LE>::TlsPhdr->p_memsz - Body.getVA<ELFT>(A);
337   case R_ABS:
338   case R_RELAX_GOT_PC_NOPIC:
339     return Body.getVA<ELFT>(A);
340   case R_GOT_OFF:
341     return Body.getGotOffset<ELFT>() + A;
342   case R_MIPS_GOT_LOCAL_PAGE:
343     // If relocation against MIPS local symbol requires GOT entry, this entry
344     // should be initialized by 'page address'. This address is high 16-bits
345     // of sum the symbol's value and the addend.
346     return Out<ELFT>::Got->getMipsLocalPageOffset(Body.getVA<ELFT>(A));
347   case R_MIPS_GOT_OFF:
348   case R_MIPS_GOT_OFF32:
349     // In case of MIPS if a GOT relocation has non-zero addend this addend
350     // should be applied to the GOT entry content not to the GOT entry offset.
351     // That is why we use separate expression type.
352     return Out<ELFT>::Got->getMipsGotOffset(Body, A);
353   case R_MIPS_TLSGD:
354     return Out<ELFT>::Got->getGlobalDynOffset(Body) +
355            Out<ELFT>::Got->getMipsTlsOffset() - MipsGPOffset;
356   case R_MIPS_TLSLD:
357     return Out<ELFT>::Got->getTlsIndexOff() +
358            Out<ELFT>::Got->getMipsTlsOffset() - MipsGPOffset;
359   case R_PPC_OPD: {
360     uint64_t SymVA = Body.getVA<ELFT>(A);
361     // If we have an undefined weak symbol, we might get here with a symbol
362     // address of zero. That could overflow, but the code must be unreachable,
363     // so don't bother doing anything at all.
364     if (!SymVA)
365       return 0;
366     if (Out<ELF64BE>::Opd) {
367       // If this is a local call, and we currently have the address of a
368       // function-descriptor, get the underlying code address instead.
369       uint64_t OpdStart = Out<ELF64BE>::Opd->getVA();
370       uint64_t OpdEnd = OpdStart + Out<ELF64BE>::Opd->getSize();
371       bool InOpd = OpdStart <= SymVA && SymVA < OpdEnd;
372       if (InOpd)
373         SymVA = read64be(&Out<ELF64BE>::OpdBuf[SymVA - OpdStart]);
374     }
375     return SymVA - P;
376   }
377   case R_PC:
378   case R_RELAX_GOT_PC:
379     return Body.getVA<ELFT>(A) - P;
380   case R_PLT_PAGE_PC:
381   case R_PAGE_PC:
382     return getAArch64Page(Body.getVA<ELFT>(A)) - getAArch64Page(P);
383   }
384   llvm_unreachable("Invalid expression");
385 }
386 
387 // This function applies relocations to sections without SHF_ALLOC bit.
388 // Such sections are never mapped to memory at runtime. Debug sections are
389 // an example. Relocations in non-alloc sections are much easier to
390 // handle than in allocated sections because it will never need complex
391 // treatement such as GOT or PLT (because at runtime no one refers them).
392 // So, we handle relocations for non-alloc sections directly in this
393 // function as a performance optimization.
394 template <class ELFT>
395 template <class RelTy>
396 void InputSection<ELFT>::relocateNonAlloc(uint8_t *Buf, ArrayRef<RelTy> Rels) {
397   for (const RelTy &Rel : Rels) {
398     uint32_t Type = Rel.getType(Config->Mips64EL);
399     uintX_t Offset = this->getOffset(Rel.r_offset);
400     uint8_t *BufLoc = Buf + Offset;
401     uintX_t Addend = getAddend<ELFT>(Rel);
402     if (!RelTy::IsRela)
403       Addend += Target->getImplicitAddend(BufLoc, Type);
404 
405     SymbolBody &Sym = this->File->getRelocTargetSym(Rel);
406     if (Target->getRelExpr(Type, Sym) != R_ABS) {
407       error(getName(this) + " has non-ABS reloc");
408       return;
409     }
410 
411     uintX_t AddrLoc = this->OutSec->getVA() + Offset;
412     uint64_t SymVA = 0;
413     if (!Sym.isTls() || Out<ELFT>::TlsPhdr)
414       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, check(IS->File->getObj().relas(RelSec)));
430       else
431         IS->relocateNonAlloc(Buf, check(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(check(Obj.relas(RelocSection)));
569     else
570       split(check(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 elf::InputSectionBase<ELF32LE>;
854 template class elf::InputSectionBase<ELF32BE>;
855 template class elf::InputSectionBase<ELF64LE>;
856 template class elf::InputSectionBase<ELF64BE>;
857 
858 template class elf::InputSection<ELF32LE>;
859 template class elf::InputSection<ELF32BE>;
860 template class elf::InputSection<ELF64LE>;
861 template class elf::InputSection<ELF64BE>;
862 
863 template class elf::EhInputSection<ELF32LE>;
864 template class elf::EhInputSection<ELF32BE>;
865 template class elf::EhInputSection<ELF64LE>;
866 template class elf::EhInputSection<ELF64BE>;
867 
868 template class elf::MergeInputSection<ELF32LE>;
869 template class elf::MergeInputSection<ELF32BE>;
870 template class elf::MergeInputSection<ELF64LE>;
871 template class elf::MergeInputSection<ELF64BE>;
872 
873 template class elf::MipsReginfoInputSection<ELF32LE>;
874 template class elf::MipsReginfoInputSection<ELF32BE>;
875 template class elf::MipsReginfoInputSection<ELF64LE>;
876 template class elf::MipsReginfoInputSection<ELF64BE>;
877 
878 template class elf::MipsOptionsInputSection<ELF32LE>;
879 template class elf::MipsOptionsInputSection<ELF32BE>;
880 template class elf::MipsOptionsInputSection<ELF64LE>;
881 template class elf::MipsOptionsInputSection<ELF64BE>;
882 
883 template class elf::MipsAbiFlagsInputSection<ELF32LE>;
884 template class elf::MipsAbiFlagsInputSection<ELF32BE>;
885 template class elf::MipsAbiFlagsInputSection<ELF64LE>;
886 template class elf::MipsAbiFlagsInputSection<ELF64BE>;
887