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