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