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