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