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