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<uint32_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   using Chdr64 = typename ELF64LE::Chdr;
214   using Chdr32 = typename ELF32LE::Chdr;
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     Alignment = std::max<uint32_t>(Hdr->ch_addralign, 1);
256     RawData = RawData.slice(sizeof(*Hdr));
257     return;
258   }
259 
260   // New-style 32-bit header
261   if (RawData.size() < sizeof(Chdr32)) {
262     error(toString(this) + ": corrupted compressed section");
263     return;
264   }
265 
266   auto *Hdr = reinterpret_cast<const Chdr32 *>(RawData.data());
267   if (Hdr->ch_type != ELFCOMPRESS_ZLIB) {
268     error(toString(this) + ": unsupported compression type");
269     return;
270   }
271 
272   UncompressedSize = Hdr->ch_size;
273   Alignment = std::max<uint32_t>(Hdr->ch_addralign, 1);
274   RawData = RawData.slice(sizeof(*Hdr));
275 }
276 
277 InputSection *InputSectionBase::getLinkOrderDep() const {
278   assert(Link);
279   assert(Flags & SHF_LINK_ORDER);
280   return cast<InputSection>(File->getSections()[Link]);
281 }
282 
283 // Find a function symbol that encloses a given location.
284 template <class ELFT>
285 Defined *InputSectionBase::getEnclosingFunction(uint64_t Offset) {
286   for (Symbol *B : File->getSymbols())
287     if (Defined *D = dyn_cast<Defined>(B))
288       if (D->Section == this && D->Type == STT_FUNC && D->Value <= Offset &&
289           Offset < D->Value + D->Size)
290         return D;
291   return nullptr;
292 }
293 
294 // Returns a source location string. Used to construct an error message.
295 template <class ELFT>
296 std::string InputSectionBase::getLocation(uint64_t Offset) {
297   std::string SecAndOffset = (Name + "+0x" + utohexstr(Offset)).str();
298 
299   // We don't have file for synthetic sections.
300   if (getFile<ELFT>() == nullptr)
301     return (Config->OutputFile + ":(" + SecAndOffset + ")")
302         .str();
303 
304   // First check if we can get desired values from debugging information.
305   if (Optional<DILineInfo> Info = getFile<ELFT>()->getDILineInfo(this, Offset))
306     return Info->FileName + ":" + std::to_string(Info->Line) + ":(" +
307            SecAndOffset + ")";
308 
309   // File->SourceFile contains STT_FILE symbol that contains a
310   // source file name. If it's missing, we use an object file name.
311   std::string SrcFile = getFile<ELFT>()->SourceFile;
312   if (SrcFile.empty())
313     SrcFile = toString(File);
314 
315   if (Defined *D = getEnclosingFunction<ELFT>(Offset))
316     return SrcFile + ":(function " + toString(*D) + ": " + SecAndOffset + ")";
317 
318   // If there's no symbol, print out the offset in the section.
319   return (SrcFile + ":(" + SecAndOffset + ")");
320 }
321 
322 // This function is intended to be used for constructing an error message.
323 // The returned message looks like this:
324 //
325 //   foo.c:42 (/home/alice/possibly/very/long/path/foo.c:42)
326 //
327 //  Returns an empty string if there's no way to get line info.
328 std::string InputSectionBase::getSrcMsg(const Symbol &Sym, uint64_t Offset) {
329   return File->getSrcMsg(Sym, *this, Offset);
330 }
331 
332 // Returns a filename string along with an optional section name. This
333 // function is intended to be used for constructing an error
334 // message. The returned message looks like this:
335 //
336 //   path/to/foo.o:(function bar)
337 //
338 // or
339 //
340 //   path/to/foo.o:(function bar) in archive path/to/bar.a
341 std::string InputSectionBase::getObjMsg(uint64_t Off) {
342   std::string Filename = File->getName();
343 
344   std::string Archive;
345   if (!File->ArchiveName.empty())
346     Archive = " in archive " + File->ArchiveName;
347 
348   // Find a symbol that encloses a given location.
349   for (Symbol *B : File->getSymbols())
350     if (auto *D = dyn_cast<Defined>(B))
351       if (D->Section == this && D->Value <= Off && Off < D->Value + D->Size)
352         return Filename + ":(" + toString(*D) + ")" + Archive;
353 
354   // If there's no symbol, print out the offset in the section.
355   return (Filename + ":(" + Name + "+0x" + utohexstr(Off) + ")" + Archive)
356       .str();
357 }
358 
359 InputSection InputSection::Discarded(nullptr, 0, 0, 0, ArrayRef<uint8_t>(), "");
360 
361 InputSection::InputSection(InputFile *F, uint64_t Flags, uint32_t Type,
362                            uint32_t Alignment, ArrayRef<uint8_t> Data,
363                            StringRef Name, Kind K)
364     : InputSectionBase(F, Flags, Type,
365                        /*Entsize*/ 0, /*Link*/ 0, /*Info*/ 0, Alignment, Data,
366                        Name, K) {}
367 
368 template <class ELFT>
369 InputSection::InputSection(ObjFile<ELFT> &F, const typename ELFT::Shdr &Header,
370                            StringRef Name)
371     : InputSectionBase(F, Header, Name, InputSectionBase::Regular) {}
372 
373 bool InputSection::classof(const SectionBase *S) {
374   return S->kind() == SectionBase::Regular ||
375          S->kind() == SectionBase::Synthetic;
376 }
377 
378 OutputSection *InputSection::getParent() const {
379   return cast_or_null<OutputSection>(Parent);
380 }
381 
382 // Copy SHT_GROUP section contents. Used only for the -r option.
383 template <class ELFT> void InputSection::copyShtGroup(uint8_t *Buf) {
384   // ELFT::Word is the 32-bit integral type in the target endianness.
385   using u32 = typename ELFT::Word;
386   ArrayRef<u32> From = getDataAs<u32>();
387   auto *To = reinterpret_cast<u32 *>(Buf);
388 
389   // The first entry is not a section number but a flag.
390   *To++ = From[0];
391 
392   // Adjust section numbers because section numbers in an input object
393   // files are different in the output.
394   ArrayRef<InputSectionBase *> Sections = File->getSections();
395   for (uint32_t Idx : From.slice(1))
396     *To++ = Sections[Idx]->getOutputSection()->SectionIndex;
397 }
398 
399 InputSectionBase *InputSection::getRelocatedSection() const {
400   if (!File || (Type != SHT_RELA && Type != SHT_REL))
401     return nullptr;
402   ArrayRef<InputSectionBase *> Sections = File->getSections();
403   return Sections[Info];
404 }
405 
406 // This is used for -r and --emit-relocs. We can't use memcpy to copy
407 // relocations because we need to update symbol table offset and section index
408 // for each relocation. So we copy relocations one by one.
409 template <class ELFT, class RelTy>
410 void InputSection::copyRelocations(uint8_t *Buf, ArrayRef<RelTy> Rels) {
411   InputSectionBase *Sec = getRelocatedSection();
412 
413   for (const RelTy &Rel : Rels) {
414     RelType Type = Rel.getType(Config->IsMips64EL);
415     Symbol &Sym = getFile<ELFT>()->getRelocTargetSym(Rel);
416 
417     auto *P = reinterpret_cast<typename ELFT::Rela *>(Buf);
418     Buf += sizeof(RelTy);
419 
420     if (RelTy::IsRela)
421       P->r_addend = getAddend<ELFT>(Rel);
422 
423     // Output section VA is zero for -r, so r_offset is an offset within the
424     // section, but for --emit-relocs it is an virtual address.
425     P->r_offset = Sec->getVA(Rel.r_offset);
426     P->setSymbolAndType(In.SymTab->getSymbolIndex(&Sym), Type,
427                         Config->IsMips64EL);
428 
429     if (Sym.Type == STT_SECTION) {
430       // We combine multiple section symbols into only one per
431       // section. This means we have to update the addend. That is
432       // trivial for Elf_Rela, but for Elf_Rel we have to write to the
433       // section data. We do that by adding to the Relocation vector.
434 
435       // .eh_frame is horribly special and can reference discarded sections. To
436       // avoid having to parse and recreate .eh_frame, we just replace any
437       // relocation in it pointing to discarded sections with R_*_NONE, which
438       // hopefully creates a frame that is ignored at runtime.
439       auto *D = dyn_cast<Defined>(&Sym);
440       if (!D) {
441         warn("STT_SECTION symbol should be defined");
442         P->setSymbolAndType(0, 0, false);
443         continue;
444       }
445       SectionBase *Section = D->Section->Repl;
446       if (!Section->isLive()) {
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 && Type != Target->NoneRel)
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(const Symbol &S) {
588   // On targets that support TLSDESC, _TLS_MODULE_BASE_@tpoff = 0.
589   if (&S == ElfSym::TlsModuleBase)
590     return 0;
591 
592   switch (Config->EMachine) {
593   case EM_ARM:
594   case EM_AARCH64:
595     // Variant 1. The thread pointer points to a TCB with a fixed 2-word size,
596     // followed by a variable amount of alignment padding, followed by the TLS
597     // segment.
598     return S.getVA(0) + 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 S.getVA(0) - alignTo(Out::TlsPhdr->p_memsz, Out::TlsPhdr->p_align);
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 S.getVA(0) - 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     // It is not very clear what to return if the symbol is undefined. With
747     // --noinhibit-exec, even a non-weak undefined reference may reach here.
748     // Just return A, which matches R_ABS, and the behavior of some dynamic
749     // loaders.
750     if (Sym.isUndefined())
751       return A;
752     return getTlsTpOffset(Sym) + A;
753   case R_RELAX_TLS_GD_TO_LE_NEG:
754   case R_NEG_TLS:
755     if (Sym.isUndefined())
756       return A;
757     return -getTlsTpOffset(Sym) + A;
758   case R_SIZE:
759     return Sym.getSize() + A;
760   case R_TLSDESC:
761     return In.Got->getGlobalDynAddr(Sym) + A;
762   case R_TLSDESC_PC:
763     return In.Got->getGlobalDynAddr(Sym) + A - P;
764   case R_AARCH64_TLSDESC_PAGE:
765     return getAArch64Page(In.Got->getGlobalDynAddr(Sym) + A) -
766            getAArch64Page(P);
767   case R_TLSGD_GOT:
768     return In.Got->getGlobalDynOffset(Sym) + A;
769   case R_TLSGD_GOTPLT:
770     return In.Got->getVA() + In.Got->getGlobalDynOffset(Sym) + A - In.GotPlt->getVA();
771   case R_TLSGD_PC:
772     return In.Got->getGlobalDynAddr(Sym) + A - P;
773   case R_TLSLD_GOTPLT:
774     return In.Got->getVA() + In.Got->getTlsIndexOff() + A - In.GotPlt->getVA();
775   case R_TLSLD_GOT:
776     return In.Got->getTlsIndexOff() + A;
777   case R_TLSLD_PC:
778     return In.Got->getTlsIndexVA() + A - P;
779   default:
780     llvm_unreachable("invalid expression");
781   }
782 }
783 
784 // This function applies relocations to sections without SHF_ALLOC bit.
785 // Such sections are never mapped to memory at runtime. Debug sections are
786 // an example. Relocations in non-alloc sections are much easier to
787 // handle than in allocated sections because it will never need complex
788 // treatement such as GOT or PLT (because at runtime no one refers them).
789 // So, we handle relocations for non-alloc sections directly in this
790 // function as a performance optimization.
791 template <class ELFT, class RelTy>
792 void InputSection::relocateNonAlloc(uint8_t *Buf, ArrayRef<RelTy> Rels) {
793   const unsigned Bits = sizeof(typename ELFT::uint) * 8;
794 
795   for (const RelTy &Rel : Rels) {
796     RelType Type = Rel.getType(Config->IsMips64EL);
797 
798     // GCC 8.0 or earlier have a bug that they emit R_386_GOTPC relocations
799     // against _GLOBAL_OFFSET_TABLE_ for .debug_info. The bug has been fixed
800     // in 2017 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82630), but we
801     // need to keep this bug-compatible code for a while.
802     if (Config->EMachine == EM_386 && Type == R_386_GOTPC)
803       continue;
804 
805     uint64_t Offset = getOffset(Rel.r_offset);
806     uint8_t *BufLoc = Buf + Offset;
807     int64_t Addend = getAddend<ELFT>(Rel);
808     if (!RelTy::IsRela)
809       Addend += Target->getImplicitAddend(BufLoc, Type);
810 
811     Symbol &Sym = getFile<ELFT>()->getRelocTargetSym(Rel);
812     RelExpr Expr = Target->getRelExpr(Type, Sym, BufLoc);
813     if (Expr == R_NONE)
814       continue;
815 
816     if (Expr != R_ABS && Expr != R_DTPREL) {
817       std::string Msg = getLocation<ELFT>(Offset) +
818                         ": has non-ABS relocation " + toString(Type) +
819                         " against symbol '" + toString(Sym) + "'";
820       if (Expr != R_PC) {
821         error(Msg);
822         return;
823       }
824 
825       // If the control reaches here, we found a PC-relative relocation in a
826       // non-ALLOC section. Since non-ALLOC section is not loaded into memory
827       // at runtime, the notion of PC-relative doesn't make sense here. So,
828       // this is a usage error. However, GNU linkers historically accept such
829       // relocations without any errors and relocate them as if they were at
830       // address 0. For bug-compatibilty, we accept them with warnings. We
831       // know Steel Bank Common Lisp as of 2018 have this bug.
832       warn(Msg);
833       Target->relocateOne(BufLoc, Type,
834                           SignExtend64<Bits>(Sym.getVA(Addend - Offset)));
835       continue;
836     }
837 
838     if (Sym.isTls() && !Out::TlsPhdr)
839       Target->relocateOne(BufLoc, Type, 0);
840     else
841       Target->relocateOne(BufLoc, Type, SignExtend64<Bits>(Sym.getVA(Addend)));
842   }
843 }
844 
845 // This is used when '-r' is given.
846 // For REL targets, InputSection::copyRelocations() may store artificial
847 // relocations aimed to update addends. They are handled in relocateAlloc()
848 // for allocatable sections, and this function does the same for
849 // non-allocatable sections, such as sections with debug information.
850 static void relocateNonAllocForRelocatable(InputSection *Sec, uint8_t *Buf) {
851   const unsigned Bits = Config->Is64 ? 64 : 32;
852 
853   for (const Relocation &Rel : Sec->Relocations) {
854     // InputSection::copyRelocations() adds only R_ABS relocations.
855     assert(Rel.Expr == R_ABS);
856     uint8_t *BufLoc = Buf + Rel.Offset + Sec->OutSecOff;
857     uint64_t TargetVA = SignExtend64(Rel.Sym->getVA(Rel.Addend), Bits);
858     Target->relocateOne(BufLoc, Rel.Type, TargetVA);
859   }
860 }
861 
862 template <class ELFT>
863 void InputSectionBase::relocate(uint8_t *Buf, uint8_t *BufEnd) {
864   if (Flags & SHF_EXECINSTR)
865     adjustSplitStackFunctionPrologues<ELFT>(Buf, BufEnd);
866 
867   if (Flags & SHF_ALLOC) {
868     relocateAlloc(Buf, BufEnd);
869     return;
870   }
871 
872   auto *Sec = cast<InputSection>(this);
873   if (Config->Relocatable)
874     relocateNonAllocForRelocatable(Sec, Buf);
875   else if (Sec->AreRelocsRela)
876     Sec->relocateNonAlloc<ELFT>(Buf, Sec->template relas<ELFT>());
877   else
878     Sec->relocateNonAlloc<ELFT>(Buf, Sec->template rels<ELFT>());
879 }
880 
881 void InputSectionBase::relocateAlloc(uint8_t *Buf, uint8_t *BufEnd) {
882   assert(Flags & SHF_ALLOC);
883   const unsigned Bits = Config->Wordsize * 8;
884 
885   for (const Relocation &Rel : Relocations) {
886     uint64_t Offset = Rel.Offset;
887     if (auto *Sec = dyn_cast<InputSection>(this))
888       Offset += Sec->OutSecOff;
889     uint8_t *BufLoc = Buf + Offset;
890     RelType Type = Rel.Type;
891 
892     uint64_t AddrLoc = getOutputSection()->Addr + Offset;
893     RelExpr Expr = Rel.Expr;
894     uint64_t TargetVA = SignExtend64(
895         getRelocTargetVA(File, Type, Rel.Addend, AddrLoc, *Rel.Sym, Expr),
896         Bits);
897 
898     switch (Expr) {
899     case R_RELAX_GOT_PC:
900     case R_RELAX_GOT_PC_NOPIC:
901       Target->relaxGot(BufLoc, Type, TargetVA);
902       break;
903     case R_PPC64_RELAX_TOC:
904       if (!tryRelaxPPC64TocIndirection(Type, Rel, BufLoc))
905         Target->relocateOne(BufLoc, Type, TargetVA);
906       break;
907     case R_RELAX_TLS_IE_TO_LE:
908       Target->relaxTlsIeToLe(BufLoc, Type, TargetVA);
909       break;
910     case R_RELAX_TLS_LD_TO_LE:
911     case R_RELAX_TLS_LD_TO_LE_ABS:
912       Target->relaxTlsLdToLe(BufLoc, Type, TargetVA);
913       break;
914     case R_RELAX_TLS_GD_TO_LE:
915     case R_RELAX_TLS_GD_TO_LE_NEG:
916       Target->relaxTlsGdToLe(BufLoc, Type, TargetVA);
917       break;
918     case R_AARCH64_RELAX_TLS_GD_TO_IE_PAGE_PC:
919     case R_RELAX_TLS_GD_TO_IE:
920     case R_RELAX_TLS_GD_TO_IE_ABS:
921     case R_RELAX_TLS_GD_TO_IE_GOT_OFF:
922     case R_RELAX_TLS_GD_TO_IE_GOTPLT:
923       Target->relaxTlsGdToIe(BufLoc, Type, TargetVA);
924       break;
925     case R_PPC_CALL:
926       // If this is a call to __tls_get_addr, it may be part of a TLS
927       // sequence that has been relaxed and turned into a nop. In this
928       // case, we don't want to handle it as a call.
929       if (read32(BufLoc) == 0x60000000) // nop
930         break;
931 
932       // Patch a nop (0x60000000) to a ld.
933       if (Rel.Sym->NeedsTocRestore) {
934         if (BufLoc + 8 > BufEnd || read32(BufLoc + 4) != 0x60000000) {
935           error(getErrorLocation(BufLoc) + "call lacks nop, can't restore toc");
936           break;
937         }
938         write32(BufLoc + 4, 0xe8410018); // ld %r2, 24(%r1)
939       }
940       Target->relocateOne(BufLoc, Type, TargetVA);
941       break;
942     default:
943       Target->relocateOne(BufLoc, Type, TargetVA);
944       break;
945     }
946   }
947 }
948 
949 // For each function-defining prologue, find any calls to __morestack,
950 // and replace them with calls to __morestack_non_split.
951 static void switchMorestackCallsToMorestackNonSplit(
952     DenseSet<Defined *> &Prologues, std::vector<Relocation *> &MorestackCalls) {
953 
954   // If the target adjusted a function's prologue, all calls to
955   // __morestack inside that function should be switched to
956   // __morestack_non_split.
957   Symbol *MoreStackNonSplit = Symtab->find("__morestack_non_split");
958   if (!MoreStackNonSplit) {
959     error("Mixing split-stack objects requires a definition of "
960           "__morestack_non_split");
961     return;
962   }
963 
964   // Sort both collections to compare addresses efficiently.
965   llvm::sort(MorestackCalls, [](const Relocation *L, const Relocation *R) {
966     return L->Offset < R->Offset;
967   });
968   std::vector<Defined *> Functions(Prologues.begin(), Prologues.end());
969   llvm::sort(Functions, [](const Defined *L, const Defined *R) {
970     return L->Value < R->Value;
971   });
972 
973   auto It = MorestackCalls.begin();
974   for (Defined *F : Functions) {
975     // Find the first call to __morestack within the function.
976     while (It != MorestackCalls.end() && (*It)->Offset < F->Value)
977       ++It;
978     // Adjust all calls inside the function.
979     while (It != MorestackCalls.end() && (*It)->Offset < F->Value + F->Size) {
980       (*It)->Sym = MoreStackNonSplit;
981       ++It;
982     }
983   }
984 }
985 
986 static bool enclosingPrologueAttempted(uint64_t Offset,
987                                        const DenseSet<Defined *> &Prologues) {
988   for (Defined *F : Prologues)
989     if (F->Value <= Offset && Offset < F->Value + F->Size)
990       return true;
991   return false;
992 }
993 
994 // If a function compiled for split stack calls a function not
995 // compiled for split stack, then the caller needs its prologue
996 // adjusted to ensure that the called function will have enough stack
997 // available. Find those functions, and adjust their prologues.
998 template <class ELFT>
999 void InputSectionBase::adjustSplitStackFunctionPrologues(uint8_t *Buf,
1000                                                          uint8_t *End) {
1001   if (!getFile<ELFT>()->SplitStack)
1002     return;
1003   DenseSet<Defined *> Prologues;
1004   std::vector<Relocation *> MorestackCalls;
1005 
1006   for (Relocation &Rel : Relocations) {
1007     // Local symbols can't possibly be cross-calls, and should have been
1008     // resolved long before this line.
1009     if (Rel.Sym->isLocal())
1010       continue;
1011 
1012     // Ignore calls into the split-stack api.
1013     if (Rel.Sym->getName().startswith("__morestack")) {
1014       if (Rel.Sym->getName().equals("__morestack"))
1015         MorestackCalls.push_back(&Rel);
1016       continue;
1017     }
1018 
1019     // A relocation to non-function isn't relevant. Sometimes
1020     // __morestack is not marked as a function, so this check comes
1021     // after the name check.
1022     if (Rel.Sym->Type != STT_FUNC)
1023       continue;
1024 
1025     // If the callee's-file was compiled with split stack, nothing to do.  In
1026     // this context, a "Defined" symbol is one "defined by the binary currently
1027     // being produced". So an "undefined" symbol might be provided by a shared
1028     // library. It is not possible to tell how such symbols were compiled, so be
1029     // conservative.
1030     if (Defined *D = dyn_cast<Defined>(Rel.Sym))
1031       if (InputSection *IS = cast_or_null<InputSection>(D->Section))
1032         if (!IS || !IS->getFile<ELFT>() || IS->getFile<ELFT>()->SplitStack)
1033           continue;
1034 
1035     if (enclosingPrologueAttempted(Rel.Offset, Prologues))
1036       continue;
1037 
1038     if (Defined *F = getEnclosingFunction<ELFT>(Rel.Offset)) {
1039       Prologues.insert(F);
1040       if (Target->adjustPrologueForCrossSplitStack(Buf + getOffset(F->Value),
1041                                                    End, F->StOther))
1042         continue;
1043       if (!getFile<ELFT>()->SomeNoSplitStack)
1044         error(lld::toString(this) + ": " + F->getName() +
1045               " (with -fsplit-stack) calls " + Rel.Sym->getName() +
1046               " (without -fsplit-stack), but couldn't adjust its prologue");
1047     }
1048   }
1049 
1050   if (Target->NeedsMoreStackNonSplit)
1051     switchMorestackCallsToMorestackNonSplit(Prologues, MorestackCalls);
1052 }
1053 
1054 template <class ELFT> void InputSection::writeTo(uint8_t *Buf) {
1055   if (Type == SHT_NOBITS)
1056     return;
1057 
1058   if (auto *S = dyn_cast<SyntheticSection>(this)) {
1059     S->writeTo(Buf + OutSecOff);
1060     return;
1061   }
1062 
1063   // If -r or --emit-relocs is given, then an InputSection
1064   // may be a relocation section.
1065   if (Type == SHT_RELA) {
1066     copyRelocations<ELFT>(Buf + OutSecOff, getDataAs<typename ELFT::Rela>());
1067     return;
1068   }
1069   if (Type == SHT_REL) {
1070     copyRelocations<ELFT>(Buf + OutSecOff, getDataAs<typename ELFT::Rel>());
1071     return;
1072   }
1073 
1074   // If -r is given, we may have a SHT_GROUP section.
1075   if (Type == SHT_GROUP) {
1076     copyShtGroup<ELFT>(Buf + OutSecOff);
1077     return;
1078   }
1079 
1080   // If this is a compressed section, uncompress section contents directly
1081   // to the buffer.
1082   if (UncompressedSize >= 0) {
1083     size_t Size = UncompressedSize;
1084     if (Error E = zlib::uncompress(toStringRef(RawData),
1085                                    (char *)(Buf + OutSecOff), Size))
1086       fatal(toString(this) +
1087             ": uncompress failed: " + llvm::toString(std::move(E)));
1088     uint8_t *BufEnd = Buf + OutSecOff + Size;
1089     relocate<ELFT>(Buf, BufEnd);
1090     return;
1091   }
1092 
1093   // Copy section contents from source object file to output file
1094   // and then apply relocations.
1095   memcpy(Buf + OutSecOff, data().data(), data().size());
1096   uint8_t *BufEnd = Buf + OutSecOff + data().size();
1097   relocate<ELFT>(Buf, BufEnd);
1098 }
1099 
1100 void InputSection::replace(InputSection *Other) {
1101   Alignment = std::max(Alignment, Other->Alignment);
1102 
1103   // When a section is replaced with another section that was allocated to
1104   // another partition, the replacement section (and its associated sections)
1105   // need to be placed in the main partition so that both partitions will be
1106   // able to access it.
1107   if (Partition != Other->Partition) {
1108     Partition = 1;
1109     for (InputSection *IS : DependentSections)
1110       IS->Partition = 1;
1111   }
1112 
1113   Other->Repl = Repl;
1114   Other->markDead();
1115 }
1116 
1117 template <class ELFT>
1118 EhInputSection::EhInputSection(ObjFile<ELFT> &F,
1119                                const typename ELFT::Shdr &Header,
1120                                StringRef Name)
1121     : InputSectionBase(F, Header, Name, InputSectionBase::EHFrame) {}
1122 
1123 SyntheticSection *EhInputSection::getParent() const {
1124   return cast_or_null<SyntheticSection>(Parent);
1125 }
1126 
1127 // Returns the index of the first relocation that points to a region between
1128 // Begin and Begin+Size.
1129 template <class IntTy, class RelTy>
1130 static unsigned getReloc(IntTy Begin, IntTy Size, const ArrayRef<RelTy> &Rels,
1131                          unsigned &RelocI) {
1132   // Start search from RelocI for fast access. That works because the
1133   // relocations are sorted in .eh_frame.
1134   for (unsigned N = Rels.size(); RelocI < N; ++RelocI) {
1135     const RelTy &Rel = Rels[RelocI];
1136     if (Rel.r_offset < Begin)
1137       continue;
1138 
1139     if (Rel.r_offset < Begin + Size)
1140       return RelocI;
1141     return -1;
1142   }
1143   return -1;
1144 }
1145 
1146 // .eh_frame is a sequence of CIE or FDE records.
1147 // This function splits an input section into records and returns them.
1148 template <class ELFT> void EhInputSection::split() {
1149   if (AreRelocsRela)
1150     split<ELFT>(relas<ELFT>());
1151   else
1152     split<ELFT>(rels<ELFT>());
1153 }
1154 
1155 template <class ELFT, class RelTy>
1156 void EhInputSection::split(ArrayRef<RelTy> Rels) {
1157   unsigned RelI = 0;
1158   for (size_t Off = 0, End = data().size(); Off != End;) {
1159     size_t Size = readEhRecordSize(this, Off);
1160     Pieces.emplace_back(Off, this, Size, getReloc(Off, Size, Rels, RelI));
1161     // The empty record is the end marker.
1162     if (Size == 4)
1163       break;
1164     Off += Size;
1165   }
1166 }
1167 
1168 static size_t findNull(StringRef S, size_t EntSize) {
1169   // Optimize the common case.
1170   if (EntSize == 1)
1171     return S.find(0);
1172 
1173   for (unsigned I = 0, N = S.size(); I != N; I += EntSize) {
1174     const char *B = S.begin() + I;
1175     if (std::all_of(B, B + EntSize, [](char C) { return C == 0; }))
1176       return I;
1177   }
1178   return StringRef::npos;
1179 }
1180 
1181 SyntheticSection *MergeInputSection::getParent() const {
1182   return cast_or_null<SyntheticSection>(Parent);
1183 }
1184 
1185 // Split SHF_STRINGS section. Such section is a sequence of
1186 // null-terminated strings.
1187 void MergeInputSection::splitStrings(ArrayRef<uint8_t> Data, size_t EntSize) {
1188   size_t Off = 0;
1189   bool IsAlloc = Flags & SHF_ALLOC;
1190   StringRef S = toStringRef(Data);
1191 
1192   while (!S.empty()) {
1193     size_t End = findNull(S, EntSize);
1194     if (End == StringRef::npos)
1195       fatal(toString(this) + ": string is not null terminated");
1196     size_t Size = End + EntSize;
1197 
1198     Pieces.emplace_back(Off, xxHash64(S.substr(0, Size)), !IsAlloc);
1199     S = S.substr(Size);
1200     Off += Size;
1201   }
1202 }
1203 
1204 // Split non-SHF_STRINGS section. Such section is a sequence of
1205 // fixed size records.
1206 void MergeInputSection::splitNonStrings(ArrayRef<uint8_t> Data,
1207                                         size_t EntSize) {
1208   size_t Size = Data.size();
1209   assert((Size % EntSize) == 0);
1210   bool IsAlloc = Flags & SHF_ALLOC;
1211 
1212   for (size_t I = 0; I != Size; I += EntSize)
1213     Pieces.emplace_back(I, xxHash64(Data.slice(I, EntSize)), !IsAlloc);
1214 }
1215 
1216 template <class ELFT>
1217 MergeInputSection::MergeInputSection(ObjFile<ELFT> &F,
1218                                      const typename ELFT::Shdr &Header,
1219                                      StringRef Name)
1220     : InputSectionBase(F, Header, Name, InputSectionBase::Merge) {}
1221 
1222 MergeInputSection::MergeInputSection(uint64_t Flags, uint32_t Type,
1223                                      uint64_t Entsize, ArrayRef<uint8_t> Data,
1224                                      StringRef Name)
1225     : InputSectionBase(nullptr, Flags, Type, Entsize, /*Link*/ 0, /*Info*/ 0,
1226                        /*Alignment*/ Entsize, Data, Name, SectionBase::Merge) {}
1227 
1228 // This function is called after we obtain a complete list of input sections
1229 // that need to be linked. This is responsible to split section contents
1230 // into small chunks for further processing.
1231 //
1232 // Note that this function is called from parallelForEach. This must be
1233 // thread-safe (i.e. no memory allocation from the pools).
1234 void MergeInputSection::splitIntoPieces() {
1235   assert(Pieces.empty());
1236 
1237   if (Flags & SHF_STRINGS)
1238     splitStrings(data(), Entsize);
1239   else
1240     splitNonStrings(data(), Entsize);
1241 }
1242 
1243 SectionPiece *MergeInputSection::getSectionPiece(uint64_t Offset) {
1244   if (this->data().size() <= Offset)
1245     fatal(toString(this) + ": offset is outside the section");
1246 
1247   // If Offset is not at beginning of a section piece, it is not in the map.
1248   // In that case we need to  do a binary search of the original section piece vector.
1249   auto It = llvm::bsearch(Pieces,
1250                           [=](SectionPiece P) { return Offset < P.InputOff; });
1251   return &It[-1];
1252 }
1253 
1254 // Returns the offset in an output section for a given input offset.
1255 // Because contents of a mergeable section is not contiguous in output,
1256 // it is not just an addition to a base output offset.
1257 uint64_t MergeInputSection::getParentOffset(uint64_t Offset) const {
1258   // If Offset is not at beginning of a section piece, it is not in the map.
1259   // In that case we need to search from the original section piece vector.
1260   const SectionPiece &Piece =
1261       *(const_cast<MergeInputSection *>(this)->getSectionPiece (Offset));
1262   uint64_t Addend = Offset - Piece.InputOff;
1263   return Piece.OutputOff + Addend;
1264 }
1265 
1266 template InputSection::InputSection(ObjFile<ELF32LE> &, const ELF32LE::Shdr &,
1267                                     StringRef);
1268 template InputSection::InputSection(ObjFile<ELF32BE> &, const ELF32BE::Shdr &,
1269                                     StringRef);
1270 template InputSection::InputSection(ObjFile<ELF64LE> &, const ELF64LE::Shdr &,
1271                                     StringRef);
1272 template InputSection::InputSection(ObjFile<ELF64BE> &, const ELF64BE::Shdr &,
1273                                     StringRef);
1274 
1275 template std::string InputSectionBase::getLocation<ELF32LE>(uint64_t);
1276 template std::string InputSectionBase::getLocation<ELF32BE>(uint64_t);
1277 template std::string InputSectionBase::getLocation<ELF64LE>(uint64_t);
1278 template std::string InputSectionBase::getLocation<ELF64BE>(uint64_t);
1279 
1280 template void InputSection::writeTo<ELF32LE>(uint8_t *);
1281 template void InputSection::writeTo<ELF32BE>(uint8_t *);
1282 template void InputSection::writeTo<ELF64LE>(uint8_t *);
1283 template void InputSection::writeTo<ELF64BE>(uint8_t *);
1284 
1285 template MergeInputSection::MergeInputSection(ObjFile<ELF32LE> &,
1286                                               const ELF32LE::Shdr &, StringRef);
1287 template MergeInputSection::MergeInputSection(ObjFile<ELF32BE> &,
1288                                               const ELF32BE::Shdr &, StringRef);
1289 template MergeInputSection::MergeInputSection(ObjFile<ELF64LE> &,
1290                                               const ELF64LE::Shdr &, StringRef);
1291 template MergeInputSection::MergeInputSection(ObjFile<ELF64BE> &,
1292                                               const ELF64BE::Shdr &, StringRef);
1293 
1294 template EhInputSection::EhInputSection(ObjFile<ELF32LE> &,
1295                                         const ELF32LE::Shdr &, StringRef);
1296 template EhInputSection::EhInputSection(ObjFile<ELF32BE> &,
1297                                         const ELF32BE::Shdr &, StringRef);
1298 template EhInputSection::EhInputSection(ObjFile<ELF64LE> &,
1299                                         const ELF64LE::Shdr &, StringRef);
1300 template EhInputSection::EhInputSection(ObjFile<ELF64BE> &,
1301                                         const ELF64BE::Shdr &, StringRef);
1302 
1303 template void EhInputSection::split<ELF32LE>();
1304 template void EhInputSection::split<ELF32BE>();
1305 template void EhInputSection::split<ELF64LE>();
1306 template void EhInputSection::split<ELF64BE>();
1307