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