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