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