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