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