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 "InputFiles.h"
14 #include "LinkerScript.h"
15 #include "OutputSections.h"
16 #include "Relocations.h"
17 #include "SymbolTable.h"
18 #include "Symbols.h"
19 #include "SyntheticSections.h"
20 #include "Target.h"
21 #include "Thunks.h"
22 #include "lld/Common/ErrorHandler.h"
23 #include "lld/Common/Memory.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/Compression.h"
26 #include "llvm/Support/Endian.h"
27 #include "llvm/Support/Threading.h"
28 #include "llvm/Support/xxhash.h"
29 #include <algorithm>
30 #include <mutex>
31 #include <set>
32 #include <vector>
33 
34 using namespace llvm;
35 using namespace llvm::ELF;
36 using namespace llvm::object;
37 using namespace llvm::support;
38 using namespace llvm::support::endian;
39 using namespace llvm::sys;
40 
41 using namespace lld;
42 using namespace lld::elf;
43 
44 std::vector<InputSectionBase *> elf::InputSections;
45 
46 // Returns a string to construct an error message.
47 std::string lld::toString(const InputSectionBase *Sec) {
48   return (toString(Sec->File) + ":(" + Sec->Name + ")").str();
49 }
50 
51 template <class ELFT>
52 static ArrayRef<uint8_t> getSectionContents(ObjFile<ELFT> &File,
53                                             const typename ELFT::Shdr &Hdr) {
54   if (Hdr.sh_type == SHT_NOBITS)
55     return makeArrayRef<uint8_t>(nullptr, Hdr.sh_size);
56   return check(File.getObj().getSectionContents(&Hdr));
57 }
58 
59 InputSectionBase::InputSectionBase(InputFile *File, uint64_t Flags,
60                                    uint32_t Type, uint64_t Entsize,
61                                    uint32_t Link, uint32_t Info,
62                                    uint32_t Alignment, ArrayRef<uint8_t> Data,
63                                    StringRef Name, Kind SectionKind)
64     : SectionBase(SectionKind, Name, Flags, Entsize, Alignment, Type, Info,
65                   Link),
66       File(File), RawData(Data) {
67   // In order to reduce memory allocation, we assume that mergeable
68   // sections are smaller than 4 GiB, which is not an unreasonable
69   // assumption as of 2017.
70   if (SectionKind == SectionBase::Merge && RawData.size() > UINT32_MAX)
71     error(toString(this) + ": section too large");
72 
73   NumRelocations = 0;
74   AreRelocsRela = false;
75 
76   // The ELF spec states that a value of 0 means the section has
77   // no alignment constraits.
78   uint32_t V = std::max<uint64_t>(Alignment, 1);
79   if (!isPowerOf2_64(V))
80     fatal(toString(File) + ": section sh_addralign is not a power of 2");
81   this->Alignment = V;
82 
83   // In ELF, each section can be compressed by zlib, and if compressed,
84   // section name may be mangled by appending "z" (e.g. ".zdebug_info").
85   // If that's the case, demangle section name so that we can handle a
86   // section as if it weren't compressed.
87   if ((Flags & SHF_COMPRESSED) || Name.startswith(".zdebug")) {
88     if (!zlib::isAvailable())
89       error(toString(File) + ": contains a compressed section, " +
90             "but zlib is not available");
91     parseCompressedHeader();
92   }
93 }
94 
95 // Drop SHF_GROUP bit unless we are producing a re-linkable object file.
96 // SHF_GROUP is a marker that a section belongs to some comdat group.
97 // That flag doesn't make sense in an executable.
98 static uint64_t getFlags(uint64_t Flags) {
99   Flags &= ~(uint64_t)SHF_INFO_LINK;
100   if (!Config->Relocatable)
101     Flags &= ~(uint64_t)SHF_GROUP;
102   return Flags;
103 }
104 
105 // GNU assembler 2.24 and LLVM 4.0.0's MC (the newest release as of
106 // March 2017) fail to infer section types for sections starting with
107 // ".init_array." or ".fini_array.". They set SHT_PROGBITS instead of
108 // SHF_INIT_ARRAY. As a result, the following assembler directive
109 // creates ".init_array.100" with SHT_PROGBITS, for example.
110 //
111 //   .section .init_array.100, "aw"
112 //
113 // This function forces SHT_{INIT,FINI}_ARRAY so that we can handle
114 // incorrect inputs as if they were correct from the beginning.
115 static uint64_t getType(uint64_t Type, StringRef Name) {
116   if (Type == SHT_PROGBITS && Name.startswith(".init_array."))
117     return SHT_INIT_ARRAY;
118   if (Type == SHT_PROGBITS && Name.startswith(".fini_array."))
119     return SHT_FINI_ARRAY;
120   return Type;
121 }
122 
123 template <class ELFT>
124 InputSectionBase::InputSectionBase(ObjFile<ELFT> &File,
125                                    const typename ELFT::Shdr &Hdr,
126                                    StringRef Name, Kind SectionKind)
127     : InputSectionBase(&File, getFlags(Hdr.sh_flags),
128                        getType(Hdr.sh_type, Name), Hdr.sh_entsize, Hdr.sh_link,
129                        Hdr.sh_info, Hdr.sh_addralign,
130                        getSectionContents(File, Hdr), Name, SectionKind) {
131   // We reject object files having insanely large alignments even though
132   // they are allowed by the spec. I think 4GB is a reasonable limitation.
133   // We might want to relax this in the future.
134   if (Hdr.sh_addralign > UINT32_MAX)
135     fatal(toString(&File) + ": section sh_addralign is too large");
136 }
137 
138 size_t InputSectionBase::getSize() const {
139   if (auto *S = dyn_cast<SyntheticSection>(this))
140     return S->getSize();
141   if (UncompressedSize >= 0)
142     return UncompressedSize;
143   return RawData.size();
144 }
145 
146 void InputSectionBase::uncompress() const {
147   size_t Size = UncompressedSize;
148   UncompressedBuf.reset(new char[Size]);
149 
150   if (Error E =
151           zlib::uncompress(toStringRef(RawData), UncompressedBuf.get(), Size))
152     fatal(toString(this) +
153           ": uncompress failed: " + llvm::toString(std::move(E)));
154   RawData = makeArrayRef((uint8_t *)UncompressedBuf.get(), Size);
155 }
156 
157 uint64_t InputSectionBase::getOffsetInFile() const {
158   const uint8_t *FileStart = (const uint8_t *)File->MB.getBufferStart();
159   const uint8_t *SecStart = data().begin();
160   return SecStart - FileStart;
161 }
162 
163 uint64_t SectionBase::getOffset(uint64_t Offset) const {
164   switch (kind()) {
165   case Output: {
166     auto *OS = cast<OutputSection>(this);
167     // For output sections we treat offset -1 as the end of the section.
168     return Offset == uint64_t(-1) ? OS->Size : Offset;
169   }
170   case Regular:
171   case Synthetic:
172     return cast<InputSection>(this)->getOffset(Offset);
173   case EHFrame:
174     // The file crtbeginT.o has relocations pointing to the start of an empty
175     // .eh_frame that is known to be the first in the link. It does that to
176     // identify the start of the output .eh_frame.
177     return Offset;
178   case Merge:
179     const MergeInputSection *MS = cast<MergeInputSection>(this);
180     if (InputSection *IS = MS->getParent())
181       return IS->getOffset(MS->getParentOffset(Offset));
182     return MS->getParentOffset(Offset);
183   }
184   llvm_unreachable("invalid section kind");
185 }
186 
187 uint64_t SectionBase::getVA(uint64_t Offset) const {
188   const OutputSection *Out = getOutputSection();
189   return (Out ? Out->Addr : 0) + getOffset(Offset);
190 }
191 
192 OutputSection *SectionBase::getOutputSection() {
193   InputSection *Sec;
194   if (auto *IS = dyn_cast<InputSection>(this))
195     Sec = IS;
196   else if (auto *MS = dyn_cast<MergeInputSection>(this))
197     Sec = MS->getParent();
198   else if (auto *EH = dyn_cast<EhInputSection>(this))
199     Sec = EH->getParent();
200   else
201     return cast<OutputSection>(this);
202   return Sec ? Sec->getParent() : nullptr;
203 }
204 
205 // When a section is compressed, `RawData` consists with a header followed
206 // by zlib-compressed data. This function parses a header to initialize
207 // `UncompressedSize` member and remove the header from `RawData`.
208 void InputSectionBase::parseCompressedHeader() {
209   typedef typename ELF64LE::Chdr Chdr64;
210   typedef typename ELF32LE::Chdr Chdr32;
211 
212   // Old-style header
213   if (Name.startswith(".zdebug")) {
214     if (!toStringRef(RawData).startswith("ZLIB")) {
215       error(toString(this) + ": corrupted compressed section header");
216       return;
217     }
218     RawData = RawData.slice(4);
219 
220     if (RawData.size() < 8) {
221       error(toString(this) + ": corrupted compressed section header");
222       return;
223     }
224 
225     UncompressedSize = read64be(RawData.data());
226     RawData = RawData.slice(8);
227 
228     // Restore the original section name.
229     // (e.g. ".zdebug_info" -> ".debug_info")
230     Name = Saver.save("." + Name.substr(2));
231     return;
232   }
233 
234   assert(Flags & SHF_COMPRESSED);
235   Flags &= ~(uint64_t)SHF_COMPRESSED;
236 
237   // New-style 64-bit header
238   if (Config->Is64) {
239     if (RawData.size() < sizeof(Chdr64)) {
240       error(toString(this) + ": corrupted compressed section");
241       return;
242     }
243 
244     auto *Hdr = reinterpret_cast<const Chdr64 *>(RawData.data());
245     if (Hdr->ch_type != ELFCOMPRESS_ZLIB) {
246       error(toString(this) + ": unsupported compression type");
247       return;
248     }
249 
250     UncompressedSize = Hdr->ch_size;
251     RawData = RawData.slice(sizeof(*Hdr));
252     return;
253   }
254 
255   // New-style 32-bit header
256   if (RawData.size() < sizeof(Chdr32)) {
257     error(toString(this) + ": corrupted compressed section");
258     return;
259   }
260 
261   auto *Hdr = reinterpret_cast<const Chdr32 *>(RawData.data());
262   if (Hdr->ch_type != ELFCOMPRESS_ZLIB) {
263     error(toString(this) + ": unsupported compression type");
264     return;
265   }
266 
267   UncompressedSize = Hdr->ch_size;
268   RawData = RawData.slice(sizeof(*Hdr));
269 }
270 
271 InputSection *InputSectionBase::getLinkOrderDep() const {
272   assert(Link);
273   assert(Flags & SHF_LINK_ORDER);
274   return cast<InputSection>(File->getSections()[Link]);
275 }
276 
277 // Find a function symbol that encloses a given location.
278 template <class ELFT>
279 Defined *InputSectionBase::getEnclosingFunction(uint64_t Offset) {
280   for (Symbol *B : File->getSymbols())
281     if (Defined *D = dyn_cast<Defined>(B))
282       if (D->Section == this && D->Type == STT_FUNC && D->Value <= Offset &&
283           Offset < D->Value + D->Size)
284         return D;
285   return nullptr;
286 }
287 
288 // Returns a source location string. Used to construct an error message.
289 template <class ELFT>
290 std::string InputSectionBase::getLocation(uint64_t Offset) {
291   // We don't have file for synthetic sections.
292   if (getFile<ELFT>() == nullptr)
293     return (Config->OutputFile + ":(" + Name + "+0x" + utohexstr(Offset) + ")")
294         .str();
295 
296   // First check if we can get desired values from debugging information.
297   if (Optional<DILineInfo> Info = getFile<ELFT>()->getDILineInfo(this, Offset))
298     return Info->FileName + ":" + std::to_string(Info->Line);
299 
300   // File->SourceFile contains STT_FILE symbol that contains a
301   // source file name. If it's missing, we use an object file name.
302   std::string SrcFile = getFile<ELFT>()->SourceFile;
303   if (SrcFile.empty())
304     SrcFile = toString(File);
305 
306   if (Defined *D = getEnclosingFunction<ELFT>(Offset))
307     return SrcFile + ":(function " + toString(*D) + ")";
308 
309   // If there's no symbol, print out the offset in the section.
310   return (SrcFile + ":(" + Name + "+0x" + utohexstr(Offset) + ")").str();
311 }
312 
313 // This function is intended to be used for constructing an error message.
314 // The returned message looks like this:
315 //
316 //   foo.c:42 (/home/alice/possibly/very/long/path/foo.c:42)
317 //
318 //  Returns an empty string if there's no way to get line info.
319 std::string InputSectionBase::getSrcMsg(const Symbol &Sym, uint64_t Offset) {
320   return File->getSrcMsg(Sym, *this, Offset);
321 }
322 
323 // Returns a filename string along with an optional section name. This
324 // function is intended to be used for constructing an error
325 // message. The returned message looks like this:
326 //
327 //   path/to/foo.o:(function bar)
328 //
329 // or
330 //
331 //   path/to/foo.o:(function bar) in archive path/to/bar.a
332 std::string InputSectionBase::getObjMsg(uint64_t Off) {
333   std::string Filename = File->getName();
334 
335   std::string Archive;
336   if (!File->ArchiveName.empty())
337     Archive = " in archive " + File->ArchiveName;
338 
339   // Find a symbol that encloses a given location.
340   for (Symbol *B : File->getSymbols())
341     if (auto *D = dyn_cast<Defined>(B))
342       if (D->Section == this && D->Value <= Off && Off < D->Value + D->Size)
343         return Filename + ":(" + toString(*D) + ")" + Archive;
344 
345   // If there's no symbol, print out the offset in the section.
346   return (Filename + ":(" + Name + "+0x" + utohexstr(Off) + ")" + Archive)
347       .str();
348 }
349 
350 InputSection InputSection::Discarded(nullptr, 0, 0, 0, ArrayRef<uint8_t>(), "");
351 
352 InputSection::InputSection(InputFile *F, uint64_t Flags, uint32_t Type,
353                            uint32_t Alignment, ArrayRef<uint8_t> Data,
354                            StringRef Name, Kind K)
355     : InputSectionBase(F, Flags, Type,
356                        /*Entsize*/ 0, /*Link*/ 0, /*Info*/ 0, Alignment, Data,
357                        Name, K) {}
358 
359 template <class ELFT>
360 InputSection::InputSection(ObjFile<ELFT> &F, const typename ELFT::Shdr &Header,
361                            StringRef Name)
362     : InputSectionBase(F, Header, Name, InputSectionBase::Regular) {}
363 
364 bool InputSection::classof(const SectionBase *S) {
365   return S->kind() == SectionBase::Regular ||
366          S->kind() == SectionBase::Synthetic;
367 }
368 
369 OutputSection *InputSection::getParent() const {
370   return cast_or_null<OutputSection>(Parent);
371 }
372 
373 // Copy SHT_GROUP section contents. Used only for the -r option.
374 template <class ELFT> void InputSection::copyShtGroup(uint8_t *Buf) {
375   // ELFT::Word is the 32-bit integral type in the target endianness.
376   typedef typename ELFT::Word u32;
377   ArrayRef<u32> From = getDataAs<u32>();
378   auto *To = reinterpret_cast<u32 *>(Buf);
379 
380   // The first entry is not a section number but a flag.
381   *To++ = From[0];
382 
383   // Adjust section numbers because section numbers in an input object
384   // files are different in the output.
385   ArrayRef<InputSectionBase *> Sections = File->getSections();
386   for (uint32_t Idx : From.slice(1))
387     *To++ = Sections[Idx]->getOutputSection()->SectionIndex;
388 }
389 
390 InputSectionBase *InputSection::getRelocatedSection() const {
391   if (!File || (Type != SHT_RELA && Type != SHT_REL))
392     return nullptr;
393   ArrayRef<InputSectionBase *> Sections = File->getSections();
394   return Sections[Info];
395 }
396 
397 // This is used for -r and --emit-relocs. We can't use memcpy to copy
398 // relocations because we need to update symbol table offset and section index
399 // for each relocation. So we copy relocations one by one.
400 template <class ELFT, class RelTy>
401 void InputSection::copyRelocations(uint8_t *Buf, ArrayRef<RelTy> Rels) {
402   InputSectionBase *Sec = getRelocatedSection();
403 
404   for (const RelTy &Rel : Rels) {
405     RelType Type = Rel.getType(Config->IsMips64EL);
406     Symbol &Sym = getFile<ELFT>()->getRelocTargetSym(Rel);
407 
408     auto *P = reinterpret_cast<typename ELFT::Rela *>(Buf);
409     Buf += sizeof(RelTy);
410 
411     if (RelTy::IsRela)
412       P->r_addend = getAddend<ELFT>(Rel);
413 
414     // Output section VA is zero for -r, so r_offset is an offset within the
415     // section, but for --emit-relocs it is an virtual address.
416     P->r_offset = Sec->getVA(Rel.r_offset);
417     P->setSymbolAndType(In.SymTab->getSymbolIndex(&Sym), Type,
418                         Config->IsMips64EL);
419 
420     if (Sym.Type == STT_SECTION) {
421       // We combine multiple section symbols into only one per
422       // section. This means we have to update the addend. That is
423       // trivial for Elf_Rela, but for Elf_Rel we have to write to the
424       // section data. We do that by adding to the Relocation vector.
425 
426       // .eh_frame is horribly special and can reference discarded sections. To
427       // avoid having to parse and recreate .eh_frame, we just replace any
428       // relocation in it pointing to discarded sections with R_*_NONE, which
429       // hopefully creates a frame that is ignored at runtime.
430       auto *D = dyn_cast<Defined>(&Sym);
431       if (!D) {
432         error("STT_SECTION symbol should be defined");
433         continue;
434       }
435       SectionBase *Section = D->Section->Repl;
436       if (!Section->Live) {
437         P->setSymbolAndType(0, 0, false);
438         continue;
439       }
440 
441       int64_t Addend = getAddend<ELFT>(Rel);
442       const uint8_t *BufLoc = Sec->data().begin() + Rel.r_offset;
443       if (!RelTy::IsRela)
444         Addend = Target->getImplicitAddend(BufLoc, Type);
445 
446       if (Config->EMachine == EM_MIPS && Config->Relocatable &&
447           Target->getRelExpr(Type, Sym, BufLoc) == R_MIPS_GOTREL) {
448         // Some MIPS relocations depend on "gp" value. By default,
449         // this value has 0x7ff0 offset from a .got section. But
450         // relocatable files produced by a complier or a linker
451         // might redefine this default value and we must use it
452         // for a calculation of the relocation result. When we
453         // generate EXE or DSO it's trivial. Generating a relocatable
454         // output is more difficult case because the linker does
455         // not calculate relocations in this mode and loses
456         // individual "gp" values used by each input object file.
457         // As a workaround we add the "gp" value to the relocation
458         // addend and save it back to the file.
459         Addend += Sec->getFile<ELFT>()->MipsGp0;
460       }
461 
462       if (RelTy::IsRela)
463         P->r_addend = Sym.getVA(Addend) - Section->getOutputSection()->Addr;
464       else if (Config->Relocatable)
465         Sec->Relocations.push_back({R_ABS, Type, Rel.r_offset, Addend, &Sym});
466     }
467   }
468 }
469 
470 // The ARM and AArch64 ABI handle pc-relative relocations to undefined weak
471 // references specially. The general rule is that the value of the symbol in
472 // this context is the address of the place P. A further special case is that
473 // branch relocations to an undefined weak reference resolve to the next
474 // instruction.
475 static uint32_t getARMUndefinedRelativeWeakVA(RelType Type, uint32_t A,
476                                               uint32_t P) {
477   switch (Type) {
478   // Unresolved branch relocations to weak references resolve to next
479   // instruction, this will be either 2 or 4 bytes on from P.
480   case R_ARM_THM_JUMP11:
481     return P + 2 + A;
482   case R_ARM_CALL:
483   case R_ARM_JUMP24:
484   case R_ARM_PC24:
485   case R_ARM_PLT32:
486   case R_ARM_PREL31:
487   case R_ARM_THM_JUMP19:
488   case R_ARM_THM_JUMP24:
489     return P + 4 + A;
490   case R_ARM_THM_CALL:
491     // We don't want an interworking BLX to ARM
492     return P + 5 + A;
493   // Unresolved non branch pc-relative relocations
494   // R_ARM_TARGET2 which can be resolved relatively is not present as it never
495   // targets a weak-reference.
496   case R_ARM_MOVW_PREL_NC:
497   case R_ARM_MOVT_PREL:
498   case R_ARM_REL32:
499   case R_ARM_THM_MOVW_PREL_NC:
500   case R_ARM_THM_MOVT_PREL:
501     return P + A;
502   }
503   llvm_unreachable("ARM pc-relative relocation expected\n");
504 }
505 
506 // The comment above getARMUndefinedRelativeWeakVA applies to this function.
507 static uint64_t getAArch64UndefinedRelativeWeakVA(uint64_t Type, uint64_t A,
508                                                   uint64_t P) {
509   switch (Type) {
510   // Unresolved branch relocations to weak references resolve to next
511   // instruction, this is 4 bytes on from P.
512   case R_AARCH64_CALL26:
513   case R_AARCH64_CONDBR19:
514   case R_AARCH64_JUMP26:
515   case R_AARCH64_TSTBR14:
516     return P + 4 + A;
517   // Unresolved non branch pc-relative relocations
518   case R_AARCH64_PREL16:
519   case R_AARCH64_PREL32:
520   case R_AARCH64_PREL64:
521   case R_AARCH64_ADR_PREL_LO21:
522   case R_AARCH64_LD_PREL_LO19:
523     return P + A;
524   }
525   llvm_unreachable("AArch64 pc-relative relocation expected\n");
526 }
527 
528 // ARM SBREL relocations are of the form S + A - B where B is the static base
529 // The ARM ABI defines base to be "addressing origin of the output segment
530 // defining the symbol S". We defined the "addressing origin"/static base to be
531 // the base of the PT_LOAD segment containing the Sym.
532 // The procedure call standard only defines a Read Write Position Independent
533 // RWPI variant so in practice we should expect the static base to be the base
534 // of the RW segment.
535 static uint64_t getARMStaticBase(const Symbol &Sym) {
536   OutputSection *OS = Sym.getOutputSection();
537   if (!OS || !OS->PtLoad || !OS->PtLoad->FirstSec)
538     fatal("SBREL relocation to " + Sym.getName() + " without static base");
539   return OS->PtLoad->FirstSec->Addr;
540 }
541 
542 // For R_RISCV_PC_INDIRECT (R_RISCV_PCREL_LO12_{I,S}), the symbol actually
543 // points the corresponding R_RISCV_PCREL_HI20 relocation, and the target VA
544 // is calculated using PCREL_HI20's symbol.
545 //
546 // This function returns the R_RISCV_PCREL_HI20 relocation from
547 // R_RISCV_PCREL_LO12's symbol and addend.
548 Relocation *lld::elf::getRISCVPCRelHi20(const Symbol *Sym, uint64_t Addend) {
549   const Defined *D = cast<Defined>(Sym);
550   InputSection *IS = cast<InputSection>(D->Section);
551 
552   if (Addend != 0)
553     warn("Non-zero addend in R_RISCV_PCREL_LO12 relocation to " +
554          IS->getObjMsg(D->Value) + " is ignored");
555 
556   // Relocations are sorted by offset, so we can use std::equal_range to do
557   // binary search.
558   auto Range = std::equal_range(IS->Relocations.begin(), IS->Relocations.end(),
559                                 D->Value, RelocationOffsetComparator{});
560   for (auto It = std::get<0>(Range); It != std::get<1>(Range); ++It)
561     if (isRelExprOneOf<R_PC>(It->Expr))
562       return &*It;
563 
564   error("R_RISCV_PCREL_LO12 relocation points to " + IS->getObjMsg(D->Value) +
565         " without an associated R_RISCV_PCREL_HI20 relocation");
566   return nullptr;
567 }
568 
569 // A TLS symbol's virtual address is relative to the TLS segment. Add a
570 // target-specific adjustment to produce a thread-pointer-relative offset.
571 static int64_t getTlsTpOffset() {
572   switch (Config->EMachine) {
573   case EM_ARM:
574   case EM_AARCH64:
575     // Variant 1. The thread pointer points to a TCB with a fixed 2-word size,
576     // followed by a variable amount of alignment padding, followed by the TLS
577     // segment.
578     return alignTo(Config->Wordsize * 2, Out::TlsPhdr->p_align);
579   case EM_386:
580   case EM_X86_64:
581     // Variant 2. The TLS segment is located just before the thread pointer.
582     return -Out::TlsPhdr->p_memsz;
583   case EM_PPC64:
584     // The thread pointer points to a fixed offset from the start of the
585     // executable's TLS segment. An offset of 0x7000 allows a signed 16-bit
586     // offset to reach 0x1000 of TCB/thread-library data and 0xf000 of the
587     // program's TLS segment.
588     return -0x7000;
589   default:
590     llvm_unreachable("unhandled Config->EMachine");
591   }
592 }
593 
594 static uint64_t getRelocTargetVA(const InputFile *File, RelType Type, int64_t A,
595                                  uint64_t P, const Symbol &Sym, RelExpr Expr) {
596   switch (Expr) {
597   case R_INVALID:
598     return 0;
599   case R_ABS:
600   case R_RELAX_TLS_LD_TO_LE_ABS:
601   case R_RELAX_GOT_PC_NOPIC:
602     return Sym.getVA(A);
603   case R_ADDEND:
604     return A;
605   case R_ARM_SBREL:
606     return Sym.getVA(A) - getARMStaticBase(Sym);
607   case R_GOT:
608   case R_RELAX_TLS_GD_TO_IE_ABS:
609     return Sym.getGotVA() + A;
610   case R_GOTONLY_PC:
611     return In.Got->getVA() + A - P;
612   case R_GOTONLY_PC_FROM_END:
613     return In.Got->getVA() + A - P + In.Got->getSize();
614   case R_GOTREL:
615     return Sym.getVA(A) - In.Got->getVA();
616   case R_GOTREL_FROM_END:
617     return Sym.getVA(A) - In.Got->getVA() - In.Got->getSize();
618   case R_GOT_FROM_END:
619   case R_RELAX_TLS_GD_TO_IE_END:
620     return Sym.getGotOffset() + A - In.Got->getSize();
621   case R_TLSLD_GOT_OFF:
622   case R_GOT_OFF:
623   case R_RELAX_TLS_GD_TO_IE_GOT_OFF:
624     return Sym.getGotOffset() + A;
625   case R_GOT_PAGE_PC:
626   case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
627     return getAArch64Page(Sym.getGotVA() + A) - getAArch64Page(P);
628   case R_GOT_PC:
629   case R_RELAX_TLS_GD_TO_IE:
630     return Sym.getGotVA() + A - P;
631   case R_HEXAGON_GOT:
632     return Sym.getGotVA() - In.GotPlt->getVA();
633   case R_MIPS_GOTREL:
634     return Sym.getVA(A) - In.MipsGot->getGp(File);
635   case R_MIPS_GOT_GP:
636     return In.MipsGot->getGp(File) + A;
637   case R_MIPS_GOT_GP_PC: {
638     // R_MIPS_LO16 expression has R_MIPS_GOT_GP_PC type iif the target
639     // is _gp_disp symbol. In that case we should use the following
640     // formula for calculation "AHL + GP - P + 4". For details see p. 4-19 at
641     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
642     // microMIPS variants of these relocations use slightly different
643     // expressions: AHL + GP - P + 3 for %lo() and AHL + GP - P - 1 for %hi()
644     // to correctly handle less-sugnificant bit of the microMIPS symbol.
645     uint64_t V = In.MipsGot->getGp(File) + A - P;
646     if (Type == R_MIPS_LO16 || Type == R_MICROMIPS_LO16)
647       V += 4;
648     if (Type == R_MICROMIPS_LO16 || Type == R_MICROMIPS_HI16)
649       V -= 1;
650     return V;
651   }
652   case R_MIPS_GOT_LOCAL_PAGE:
653     // If relocation against MIPS local symbol requires GOT entry, this entry
654     // should be initialized by 'page address'. This address is high 16-bits
655     // of sum the symbol's value and the addend.
656     return In.MipsGot->getVA() + In.MipsGot->getPageEntryOffset(File, Sym, A) -
657            In.MipsGot->getGp(File);
658   case R_MIPS_GOT_OFF:
659   case R_MIPS_GOT_OFF32:
660     // In case of MIPS if a GOT relocation has non-zero addend this addend
661     // should be applied to the GOT entry content not to the GOT entry offset.
662     // That is why we use separate expression type.
663     return In.MipsGot->getVA() + In.MipsGot->getSymEntryOffset(File, Sym, A) -
664            In.MipsGot->getGp(File);
665   case R_MIPS_TLSGD:
666     return In.MipsGot->getVA() + In.MipsGot->getGlobalDynOffset(File, Sym) -
667            In.MipsGot->getGp(File);
668   case R_MIPS_TLSLD:
669     return In.MipsGot->getVA() + In.MipsGot->getTlsIndexOffset(File) -
670            In.MipsGot->getGp(File);
671   case R_PAGE_PC:
672   case R_PLT_PAGE_PC: {
673     uint64_t Dest;
674     if (Sym.isUndefWeak())
675       Dest = getAArch64Page(A);
676     else
677       Dest = getAArch64Page(Sym.getVA(A));
678     return Dest - getAArch64Page(P);
679   }
680   case R_RISCV_PC_INDIRECT: {
681     const Relocation *HiRel = getRISCVPCRelHi20(&Sym, A);
682     if (!HiRel)
683       return 0;
684     return getRelocTargetVA(File, HiRel->Type, HiRel->Addend, Sym.getVA(),
685                             *HiRel->Sym, HiRel->Expr);
686   }
687   case R_PC: {
688     uint64_t Dest;
689     if (Sym.isUndefWeak()) {
690       // On ARM and AArch64 a branch to an undefined weak resolves to the
691       // next instruction, otherwise the place.
692       if (Config->EMachine == EM_ARM)
693         Dest = getARMUndefinedRelativeWeakVA(Type, A, P);
694       else if (Config->EMachine == EM_AARCH64)
695         Dest = getAArch64UndefinedRelativeWeakVA(Type, A, P);
696       else
697         Dest = Sym.getVA(A);
698     } else {
699       Dest = Sym.getVA(A);
700     }
701     return Dest - P;
702   }
703   case R_PLT:
704     return Sym.getPltVA() + A;
705   case R_PLT_PC:
706   case R_PPC_CALL_PLT:
707     return Sym.getPltVA() + A - P;
708   case R_PPC_CALL: {
709     uint64_t SymVA = Sym.getVA(A);
710     // If we have an undefined weak symbol, we might get here with a symbol
711     // address of zero. That could overflow, but the code must be unreachable,
712     // so don't bother doing anything at all.
713     if (!SymVA)
714       return 0;
715 
716     // PPC64 V2 ABI describes two entry points to a function. The global entry
717     // point is used for calls where the caller and callee (may) have different
718     // TOC base pointers and r2 needs to be modified to hold the TOC base for
719     // the callee. For local calls the caller and callee share the same
720     // TOC base and so the TOC pointer initialization code should be skipped by
721     // branching to the local entry point.
722     return SymVA - P + getPPC64GlobalEntryToLocalEntryOffset(Sym.StOther);
723   }
724   case R_PPC_TOC:
725     return getPPC64TocBase() + A;
726   case R_RELAX_GOT_PC:
727     return Sym.getVA(A) - P;
728   case R_RELAX_TLS_GD_TO_LE:
729   case R_RELAX_TLS_IE_TO_LE:
730   case R_RELAX_TLS_LD_TO_LE:
731   case R_TLS:
732     // A weak undefined TLS symbol resolves to the base of the TLS
733     // block, i.e. gets a value of zero. If we pass --gc-sections to
734     // lld and .tbss is not referenced, it gets reclaimed and we don't
735     // create a TLS program header. Therefore, we resolve this
736     // statically to zero.
737     if (Sym.isTls() && Sym.isUndefWeak())
738       return 0;
739     return Sym.getVA(A) + getTlsTpOffset();
740   case R_RELAX_TLS_GD_TO_LE_NEG:
741   case R_NEG_TLS:
742     return Out::TlsPhdr->p_memsz - Sym.getVA(A);
743   case R_SIZE:
744     return Sym.getSize() + A;
745   case R_TLSDESC:
746     return In.Got->getGlobalDynAddr(Sym) + A;
747   case R_TLSDESC_PAGE:
748     return getAArch64Page(In.Got->getGlobalDynAddr(Sym) + A) -
749            getAArch64Page(P);
750   case R_TLSGD_GOT:
751     return In.Got->getGlobalDynOffset(Sym) + A;
752   case R_TLSGD_GOT_FROM_END:
753     return In.Got->getGlobalDynOffset(Sym) + A - In.Got->getSize();
754   case R_TLSGD_PC:
755     return In.Got->getGlobalDynAddr(Sym) + A - P;
756   case R_TLSLD_GOT_FROM_END:
757     return In.Got->getTlsIndexOff() + A - In.Got->getSize();
758   case R_TLSLD_GOT:
759     return In.Got->getTlsIndexOff() + A;
760   case R_TLSLD_PC:
761     return In.Got->getTlsIndexVA() + A - P;
762   default:
763     llvm_unreachable("invalid expression");
764   }
765 }
766 
767 // This function applies relocations to sections without SHF_ALLOC bit.
768 // Such sections are never mapped to memory at runtime. Debug sections are
769 // an example. Relocations in non-alloc sections are much easier to
770 // handle than in allocated sections because it will never need complex
771 // treatement such as GOT or PLT (because at runtime no one refers them).
772 // So, we handle relocations for non-alloc sections directly in this
773 // function as a performance optimization.
774 template <class ELFT, class RelTy>
775 void InputSection::relocateNonAlloc(uint8_t *Buf, ArrayRef<RelTy> Rels) {
776   const unsigned Bits = sizeof(typename ELFT::uint) * 8;
777 
778   for (const RelTy &Rel : Rels) {
779     RelType Type = Rel.getType(Config->IsMips64EL);
780 
781     // GCC 8.0 or earlier have a bug that they emit R_386_GOTPC relocations
782     // against _GLOBAL_OFFSET_TABLE_ for .debug_info. The bug has been fixed
783     // in 2017 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82630), but we
784     // need to keep this bug-compatible code for a while.
785     if (Config->EMachine == EM_386 && Type == R_386_GOTPC)
786       continue;
787 
788     uint64_t Offset = getOffset(Rel.r_offset);
789     uint8_t *BufLoc = Buf + Offset;
790     int64_t Addend = getAddend<ELFT>(Rel);
791     if (!RelTy::IsRela)
792       Addend += Target->getImplicitAddend(BufLoc, Type);
793 
794     Symbol &Sym = getFile<ELFT>()->getRelocTargetSym(Rel);
795     RelExpr Expr = Target->getRelExpr(Type, Sym, BufLoc);
796     if (Expr == R_NONE)
797       continue;
798 
799     if (Expr != R_ABS) {
800       std::string Msg = getLocation<ELFT>(Offset) +
801                         ": has non-ABS relocation " + toString(Type) +
802                         " against symbol '" + toString(Sym) + "'";
803       if (Expr != R_PC) {
804         error(Msg);
805         return;
806       }
807 
808       // If the control reaches here, we found a PC-relative relocation in a
809       // non-ALLOC section. Since non-ALLOC section is not loaded into memory
810       // at runtime, the notion of PC-relative doesn't make sense here. So,
811       // this is a usage error. However, GNU linkers historically accept such
812       // relocations without any errors and relocate them as if they were at
813       // address 0. For bug-compatibilty, we accept them with warnings. We
814       // know Steel Bank Common Lisp as of 2018 have this bug.
815       warn(Msg);
816       Target->relocateOne(BufLoc, Type,
817                           SignExtend64<Bits>(Sym.getVA(Addend - Offset)));
818       continue;
819     }
820 
821     if (Sym.isTls() && !Out::TlsPhdr)
822       Target->relocateOne(BufLoc, Type, 0);
823     else
824       Target->relocateOne(BufLoc, Type, SignExtend64<Bits>(Sym.getVA(Addend)));
825   }
826 }
827 
828 // This is used when '-r' is given.
829 // For REL targets, InputSection::copyRelocations() may store artificial
830 // relocations aimed to update addends. They are handled in relocateAlloc()
831 // for allocatable sections, and this function does the same for
832 // non-allocatable sections, such as sections with debug information.
833 static void relocateNonAllocForRelocatable(InputSection *Sec, uint8_t *Buf) {
834   const unsigned Bits = Config->Is64 ? 64 : 32;
835 
836   for (const Relocation &Rel : Sec->Relocations) {
837     // InputSection::copyRelocations() adds only R_ABS relocations.
838     assert(Rel.Expr == R_ABS);
839     uint8_t *BufLoc = Buf + Rel.Offset + Sec->OutSecOff;
840     uint64_t TargetVA = SignExtend64(Rel.Sym->getVA(Rel.Addend), Bits);
841     Target->relocateOne(BufLoc, Rel.Type, TargetVA);
842   }
843 }
844 
845 template <class ELFT>
846 void InputSectionBase::relocate(uint8_t *Buf, uint8_t *BufEnd) {
847   if (Flags & SHF_EXECINSTR)
848     adjustSplitStackFunctionPrologues<ELFT>(Buf, BufEnd);
849 
850   if (Flags & SHF_ALLOC) {
851     relocateAlloc(Buf, BufEnd);
852     return;
853   }
854 
855   auto *Sec = cast<InputSection>(this);
856   if (Config->Relocatable)
857     relocateNonAllocForRelocatable(Sec, Buf);
858   else if (Sec->AreRelocsRela)
859     Sec->relocateNonAlloc<ELFT>(Buf, Sec->template relas<ELFT>());
860   else
861     Sec->relocateNonAlloc<ELFT>(Buf, Sec->template rels<ELFT>());
862 }
863 
864 void InputSectionBase::relocateAlloc(uint8_t *Buf, uint8_t *BufEnd) {
865   assert(Flags & SHF_ALLOC);
866   const unsigned Bits = Config->Wordsize * 8;
867 
868   for (const Relocation &Rel : Relocations) {
869     uint64_t Offset = Rel.Offset;
870     if (auto *Sec = dyn_cast<InputSection>(this))
871       Offset += Sec->OutSecOff;
872     uint8_t *BufLoc = Buf + Offset;
873     RelType Type = Rel.Type;
874 
875     uint64_t AddrLoc = getOutputSection()->Addr + Offset;
876     RelExpr Expr = Rel.Expr;
877     uint64_t TargetVA = SignExtend64(
878         getRelocTargetVA(File, Type, Rel.Addend, AddrLoc, *Rel.Sym, Expr),
879         Bits);
880 
881     switch (Expr) {
882     case R_RELAX_GOT_PC:
883     case R_RELAX_GOT_PC_NOPIC:
884       Target->relaxGot(BufLoc, TargetVA);
885       break;
886     case R_RELAX_TLS_IE_TO_LE:
887       Target->relaxTlsIeToLe(BufLoc, Type, TargetVA);
888       break;
889     case R_RELAX_TLS_LD_TO_LE:
890     case R_RELAX_TLS_LD_TO_LE_ABS:
891       Target->relaxTlsLdToLe(BufLoc, Type, TargetVA);
892       break;
893     case R_RELAX_TLS_GD_TO_LE:
894     case R_RELAX_TLS_GD_TO_LE_NEG:
895       Target->relaxTlsGdToLe(BufLoc, Type, TargetVA);
896       break;
897     case R_RELAX_TLS_GD_TO_IE:
898     case R_RELAX_TLS_GD_TO_IE_ABS:
899     case R_RELAX_TLS_GD_TO_IE_GOT_OFF:
900     case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
901     case R_RELAX_TLS_GD_TO_IE_END:
902       Target->relaxTlsGdToIe(BufLoc, Type, TargetVA);
903       break;
904     case R_PPC_CALL:
905       // If this is a call to __tls_get_addr, it may be part of a TLS
906       // sequence that has been relaxed and turned into a nop. In this
907       // case, we don't want to handle it as a call.
908       if (read32(BufLoc) == 0x60000000) // nop
909         break;
910 
911       // Patch a nop (0x60000000) to a ld.
912       if (Rel.Sym->NeedsTocRestore) {
913         if (BufLoc + 8 > BufEnd || read32(BufLoc + 4) != 0x60000000) {
914           error(getErrorLocation(BufLoc) + "call lacks nop, can't restore toc");
915           break;
916         }
917         write32(BufLoc + 4, 0xe8410018); // ld %r2, 24(%r1)
918       }
919       Target->relocateOne(BufLoc, Type, TargetVA);
920       break;
921     default:
922       Target->relocateOne(BufLoc, Type, TargetVA);
923       break;
924     }
925   }
926 }
927 
928 // For each function-defining prologue, find any calls to __morestack,
929 // and replace them with calls to __morestack_non_split.
930 static void switchMorestackCallsToMorestackNonSplit(
931     DenseSet<Defined *> &Prologues, std::vector<Relocation *> &MorestackCalls) {
932 
933   // If the target adjusted a function's prologue, all calls to
934   // __morestack inside that function should be switched to
935   // __morestack_non_split.
936   Symbol *MoreStackNonSplit = Symtab->find("__morestack_non_split");
937   if (!MoreStackNonSplit) {
938     error("Mixing split-stack objects requires a definition of "
939           "__morestack_non_split");
940     return;
941   }
942 
943   // Sort both collections to compare addresses efficiently.
944   llvm::sort(MorestackCalls, [](const Relocation *L, const Relocation *R) {
945     return L->Offset < R->Offset;
946   });
947   std::vector<Defined *> Functions(Prologues.begin(), Prologues.end());
948   llvm::sort(Functions, [](const Defined *L, const Defined *R) {
949     return L->Value < R->Value;
950   });
951 
952   auto It = MorestackCalls.begin();
953   for (Defined *F : Functions) {
954     // Find the first call to __morestack within the function.
955     while (It != MorestackCalls.end() && (*It)->Offset < F->Value)
956       ++It;
957     // Adjust all calls inside the function.
958     while (It != MorestackCalls.end() && (*It)->Offset < F->Value + F->Size) {
959       (*It)->Sym = MoreStackNonSplit;
960       ++It;
961     }
962   }
963 }
964 
965 static bool enclosingPrologueAttempted(uint64_t Offset,
966                                        const DenseSet<Defined *> &Prologues) {
967   for (Defined *F : Prologues)
968     if (F->Value <= Offset && Offset < F->Value + F->Size)
969       return true;
970   return false;
971 }
972 
973 // If a function compiled for split stack calls a function not
974 // compiled for split stack, then the caller needs its prologue
975 // adjusted to ensure that the called function will have enough stack
976 // available. Find those functions, and adjust their prologues.
977 template <class ELFT>
978 void InputSectionBase::adjustSplitStackFunctionPrologues(uint8_t *Buf,
979                                                          uint8_t *End) {
980   if (!getFile<ELFT>()->SplitStack)
981     return;
982   DenseSet<Defined *> Prologues;
983   std::vector<Relocation *> MorestackCalls;
984 
985   for (Relocation &Rel : Relocations) {
986     // Local symbols can't possibly be cross-calls, and should have been
987     // resolved long before this line.
988     if (Rel.Sym->isLocal())
989       continue;
990 
991     // Ignore calls into the split-stack api.
992     if (Rel.Sym->getName().startswith("__morestack")) {
993       if (Rel.Sym->getName().equals("__morestack"))
994         MorestackCalls.push_back(&Rel);
995       continue;
996     }
997 
998     // A relocation to non-function isn't relevant. Sometimes
999     // __morestack is not marked as a function, so this check comes
1000     // after the name check.
1001     if (Rel.Sym->Type != STT_FUNC)
1002       continue;
1003 
1004     // If the callee's-file was compiled with split stack, nothing to do.  In
1005     // this context, a "Defined" symbol is one "defined by the binary currently
1006     // being produced". So an "undefined" symbol might be provided by a shared
1007     // library. It is not possible to tell how such symbols were compiled, so be
1008     // conservative.
1009     if (Defined *D = dyn_cast<Defined>(Rel.Sym))
1010       if (InputSection *IS = cast_or_null<InputSection>(D->Section))
1011         if (!IS || !IS->getFile<ELFT>() || IS->getFile<ELFT>()->SplitStack)
1012           continue;
1013 
1014     if (enclosingPrologueAttempted(Rel.Offset, Prologues))
1015       continue;
1016 
1017     if (Defined *F = getEnclosingFunction<ELFT>(Rel.Offset)) {
1018       Prologues.insert(F);
1019       if (Target->adjustPrologueForCrossSplitStack(Buf + getOffset(F->Value),
1020                                                    End, F->StOther))
1021         continue;
1022       if (!getFile<ELFT>()->SomeNoSplitStack)
1023         error(lld::toString(this) + ": " + F->getName() +
1024               " (with -fsplit-stack) calls " + Rel.Sym->getName() +
1025               " (without -fsplit-stack), but couldn't adjust its prologue");
1026     }
1027   }
1028 
1029   if (Target->NeedsMoreStackNonSplit)
1030     switchMorestackCallsToMorestackNonSplit(Prologues, MorestackCalls);
1031 }
1032 
1033 template <class ELFT> void InputSection::writeTo(uint8_t *Buf) {
1034   if (Type == SHT_NOBITS)
1035     return;
1036 
1037   if (auto *S = dyn_cast<SyntheticSection>(this)) {
1038     S->writeTo(Buf + OutSecOff);
1039     return;
1040   }
1041 
1042   // If -r or --emit-relocs is given, then an InputSection
1043   // may be a relocation section.
1044   if (Type == SHT_RELA) {
1045     copyRelocations<ELFT>(Buf + OutSecOff, getDataAs<typename ELFT::Rela>());
1046     return;
1047   }
1048   if (Type == SHT_REL) {
1049     copyRelocations<ELFT>(Buf + OutSecOff, getDataAs<typename ELFT::Rel>());
1050     return;
1051   }
1052 
1053   // If -r is given, we may have a SHT_GROUP section.
1054   if (Type == SHT_GROUP) {
1055     copyShtGroup<ELFT>(Buf + OutSecOff);
1056     return;
1057   }
1058 
1059   // If this is a compressed section, uncompress section contents directly
1060   // to the buffer.
1061   if (UncompressedSize >= 0 && !UncompressedBuf) {
1062     size_t Size = UncompressedSize;
1063     if (Error E = zlib::uncompress(toStringRef(RawData),
1064                                    (char *)(Buf + OutSecOff), Size))
1065       fatal(toString(this) +
1066             ": uncompress failed: " + llvm::toString(std::move(E)));
1067     uint8_t *BufEnd = Buf + OutSecOff + Size;
1068     relocate<ELFT>(Buf, BufEnd);
1069     return;
1070   }
1071 
1072   // Copy section contents from source object file to output file
1073   // and then apply relocations.
1074   memcpy(Buf + OutSecOff, data().data(), data().size());
1075   uint8_t *BufEnd = Buf + OutSecOff + data().size();
1076   relocate<ELFT>(Buf, BufEnd);
1077 }
1078 
1079 void InputSection::replace(InputSection *Other) {
1080   Alignment = std::max(Alignment, Other->Alignment);
1081   Other->Repl = Repl;
1082   Other->Live = false;
1083 }
1084 
1085 template <class ELFT>
1086 EhInputSection::EhInputSection(ObjFile<ELFT> &F,
1087                                const typename ELFT::Shdr &Header,
1088                                StringRef Name)
1089     : InputSectionBase(F, Header, Name, InputSectionBase::EHFrame) {}
1090 
1091 SyntheticSection *EhInputSection::getParent() const {
1092   return cast_or_null<SyntheticSection>(Parent);
1093 }
1094 
1095 // Returns the index of the first relocation that points to a region between
1096 // Begin and Begin+Size.
1097 template <class IntTy, class RelTy>
1098 static unsigned getReloc(IntTy Begin, IntTy Size, const ArrayRef<RelTy> &Rels,
1099                          unsigned &RelocI) {
1100   // Start search from RelocI for fast access. That works because the
1101   // relocations are sorted in .eh_frame.
1102   for (unsigned N = Rels.size(); RelocI < N; ++RelocI) {
1103     const RelTy &Rel = Rels[RelocI];
1104     if (Rel.r_offset < Begin)
1105       continue;
1106 
1107     if (Rel.r_offset < Begin + Size)
1108       return RelocI;
1109     return -1;
1110   }
1111   return -1;
1112 }
1113 
1114 // .eh_frame is a sequence of CIE or FDE records.
1115 // This function splits an input section into records and returns them.
1116 template <class ELFT> void EhInputSection::split() {
1117   if (AreRelocsRela)
1118     split<ELFT>(relas<ELFT>());
1119   else
1120     split<ELFT>(rels<ELFT>());
1121 }
1122 
1123 template <class ELFT, class RelTy>
1124 void EhInputSection::split(ArrayRef<RelTy> Rels) {
1125   unsigned RelI = 0;
1126   for (size_t Off = 0, End = data().size(); Off != End;) {
1127     size_t Size = readEhRecordSize(this, Off);
1128     Pieces.emplace_back(Off, this, Size, getReloc(Off, Size, Rels, RelI));
1129     // The empty record is the end marker.
1130     if (Size == 4)
1131       break;
1132     Off += Size;
1133   }
1134 }
1135 
1136 static size_t findNull(StringRef S, size_t EntSize) {
1137   // Optimize the common case.
1138   if (EntSize == 1)
1139     return S.find(0);
1140 
1141   for (unsigned I = 0, N = S.size(); I != N; I += EntSize) {
1142     const char *B = S.begin() + I;
1143     if (std::all_of(B, B + EntSize, [](char C) { return C == 0; }))
1144       return I;
1145   }
1146   return StringRef::npos;
1147 }
1148 
1149 SyntheticSection *MergeInputSection::getParent() const {
1150   return cast_or_null<SyntheticSection>(Parent);
1151 }
1152 
1153 // Split SHF_STRINGS section. Such section is a sequence of
1154 // null-terminated strings.
1155 void MergeInputSection::splitStrings(ArrayRef<uint8_t> Data, size_t EntSize) {
1156   size_t Off = 0;
1157   bool IsAlloc = Flags & SHF_ALLOC;
1158   StringRef S = toStringRef(Data);
1159 
1160   while (!S.empty()) {
1161     size_t End = findNull(S, EntSize);
1162     if (End == StringRef::npos)
1163       fatal(toString(this) + ": string is not null terminated");
1164     size_t Size = End + EntSize;
1165 
1166     Pieces.emplace_back(Off, xxHash64(S.substr(0, Size)), !IsAlloc);
1167     S = S.substr(Size);
1168     Off += Size;
1169   }
1170 }
1171 
1172 // Split non-SHF_STRINGS section. Such section is a sequence of
1173 // fixed size records.
1174 void MergeInputSection::splitNonStrings(ArrayRef<uint8_t> Data,
1175                                         size_t EntSize) {
1176   size_t Size = Data.size();
1177   assert((Size % EntSize) == 0);
1178   bool IsAlloc = Flags & SHF_ALLOC;
1179 
1180   for (size_t I = 0; I != Size; I += EntSize)
1181     Pieces.emplace_back(I, xxHash64(Data.slice(I, EntSize)), !IsAlloc);
1182 }
1183 
1184 template <class ELFT>
1185 MergeInputSection::MergeInputSection(ObjFile<ELFT> &F,
1186                                      const typename ELFT::Shdr &Header,
1187                                      StringRef Name)
1188     : InputSectionBase(F, Header, Name, InputSectionBase::Merge) {}
1189 
1190 MergeInputSection::MergeInputSection(uint64_t Flags, uint32_t Type,
1191                                      uint64_t Entsize, ArrayRef<uint8_t> Data,
1192                                      StringRef Name)
1193     : InputSectionBase(nullptr, Flags, Type, Entsize, /*Link*/ 0, /*Info*/ 0,
1194                        /*Alignment*/ Entsize, Data, Name, SectionBase::Merge) {}
1195 
1196 // This function is called after we obtain a complete list of input sections
1197 // that need to be linked. This is responsible to split section contents
1198 // into small chunks for further processing.
1199 //
1200 // Note that this function is called from parallelForEach. This must be
1201 // thread-safe (i.e. no memory allocation from the pools).
1202 void MergeInputSection::splitIntoPieces() {
1203   assert(Pieces.empty());
1204 
1205   if (Flags & SHF_STRINGS)
1206     splitStrings(data(), Entsize);
1207   else
1208     splitNonStrings(data(), Entsize);
1209 
1210   OffsetMap.reserve(Pieces.size());
1211   for (size_t I = 0, E = Pieces.size(); I != E; ++I)
1212     OffsetMap[Pieces[I].InputOff] = I;
1213 }
1214 
1215 template <class It, class T, class Compare>
1216 static It fastUpperBound(It First, It Last, const T &Value, Compare Comp) {
1217   size_t Size = std::distance(First, Last);
1218   assert(Size != 0);
1219   while (Size != 1) {
1220     size_t H = Size / 2;
1221     const It MI = First + H;
1222     Size -= H;
1223     First = Comp(Value, *MI) ? First : First + H;
1224   }
1225   return Comp(Value, *First) ? First : First + 1;
1226 }
1227 
1228 SectionPiece *MergeInputSection::getSectionPiece(uint64_t Offset) {
1229   if (this->data().size() <= Offset)
1230     fatal(toString(this) + ": offset is outside the section");
1231 
1232   // Find a piece starting at a given offset.
1233   auto It = OffsetMap.find(Offset);
1234   if (It != OffsetMap.end())
1235     return &Pieces[It->second];
1236 
1237   // If Offset is not at beginning of a section piece, it is not in the map.
1238   // In that case we need to  do a binary search of the original section piece vector.
1239   auto I = fastUpperBound(
1240       Pieces.begin(), Pieces.end(), Offset,
1241       [](const uint64_t &A, const SectionPiece &B) { return A < B.InputOff; });
1242   --I;
1243   return &*I;
1244 }
1245 
1246 // Returns the offset in an output section for a given input offset.
1247 // Because contents of a mergeable section is not contiguous in output,
1248 // it is not just an addition to a base output offset.
1249 uint64_t MergeInputSection::getParentOffset(uint64_t Offset) const {
1250   // If Offset is not at beginning of a section piece, it is not in the map.
1251   // In that case we need to search from the original section piece vector.
1252   const SectionPiece &Piece =
1253       *(const_cast<MergeInputSection *>(this)->getSectionPiece (Offset));
1254   uint64_t Addend = Offset - Piece.InputOff;
1255   return Piece.OutputOff + Addend;
1256 }
1257 
1258 template InputSection::InputSection(ObjFile<ELF32LE> &, const ELF32LE::Shdr &,
1259                                     StringRef);
1260 template InputSection::InputSection(ObjFile<ELF32BE> &, const ELF32BE::Shdr &,
1261                                     StringRef);
1262 template InputSection::InputSection(ObjFile<ELF64LE> &, const ELF64LE::Shdr &,
1263                                     StringRef);
1264 template InputSection::InputSection(ObjFile<ELF64BE> &, const ELF64BE::Shdr &,
1265                                     StringRef);
1266 
1267 template std::string InputSectionBase::getLocation<ELF32LE>(uint64_t);
1268 template std::string InputSectionBase::getLocation<ELF32BE>(uint64_t);
1269 template std::string InputSectionBase::getLocation<ELF64LE>(uint64_t);
1270 template std::string InputSectionBase::getLocation<ELF64BE>(uint64_t);
1271 
1272 template void InputSection::writeTo<ELF32LE>(uint8_t *);
1273 template void InputSection::writeTo<ELF32BE>(uint8_t *);
1274 template void InputSection::writeTo<ELF64LE>(uint8_t *);
1275 template void InputSection::writeTo<ELF64BE>(uint8_t *);
1276 
1277 template MergeInputSection::MergeInputSection(ObjFile<ELF32LE> &,
1278                                               const ELF32LE::Shdr &, StringRef);
1279 template MergeInputSection::MergeInputSection(ObjFile<ELF32BE> &,
1280                                               const ELF32BE::Shdr &, StringRef);
1281 template MergeInputSection::MergeInputSection(ObjFile<ELF64LE> &,
1282                                               const ELF64LE::Shdr &, StringRef);
1283 template MergeInputSection::MergeInputSection(ObjFile<ELF64BE> &,
1284                                               const ELF64BE::Shdr &, StringRef);
1285 
1286 template EhInputSection::EhInputSection(ObjFile<ELF32LE> &,
1287                                         const ELF32LE::Shdr &, StringRef);
1288 template EhInputSection::EhInputSection(ObjFile<ELF32BE> &,
1289                                         const ELF32BE::Shdr &, StringRef);
1290 template EhInputSection::EhInputSection(ObjFile<ELF64LE> &,
1291                                         const ELF64LE::Shdr &, StringRef);
1292 template EhInputSection::EhInputSection(ObjFile<ELF64BE> &,
1293                                         const ELF64BE::Shdr &, StringRef);
1294 
1295 template void EhInputSection::split<ELF32LE>();
1296 template void EhInputSection::split<ELF32BE>();
1297 template void EhInputSection::split<ELF64LE>();
1298 template void EhInputSection::split<ELF64BE>();
1299