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