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