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