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 "Error.h"
14 #include "InputFiles.h"
15 #include "LinkerScript.h"
16 #include "Memory.h"
17 #include "OutputSections.h"
18 #include "Relocations.h"
19 #include "SyntheticSections.h"
20 #include "Target.h"
21 #include "Thunks.h"
22 #include "llvm/Object/Decompressor.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Support/Compression.h"
25 #include "llvm/Support/Endian.h"
26 #include "llvm/Support/Path.h"
27 #include "llvm/Support/Threading.h"
28 #include <mutex>
29 
30 using namespace llvm;
31 using namespace llvm::ELF;
32 using namespace llvm::object;
33 using namespace llvm::support;
34 using namespace llvm::support::endian;
35 using namespace llvm::sys;
36 
37 using namespace lld;
38 using namespace lld::elf;
39 
40 std::vector<InputSectionBase *> elf::InputSections;
41 
42 // Returns a string to construct an error message.
43 std::string lld::toString(const InputSectionBase *Sec) {
44   return (toString(Sec->File) + ":(" + Sec->Name + ")").str();
45 }
46 
47 template <class ELFT> DenseMap<SectionBase *, int> elf::buildSectionOrder() {
48   // Build a map from symbols to their priorities. Symbols that didn't
49   // appear in the symbol ordering file have the lowest priority 0.
50   // All explicitly mentioned symbols have negative (higher) priorities.
51   DenseMap<StringRef, int> SymbolOrder;
52   int Priority = -Config->SymbolOrderingFile.size();
53   for (StringRef S : Config->SymbolOrderingFile)
54     SymbolOrder.insert({S, Priority++});
55 
56   // Build a map from sections to their priorities.
57   DenseMap<SectionBase *, int> SectionOrder;
58   for (ObjFile<ELFT> *File : ObjFile<ELFT>::Instances) {
59     for (SymbolBody *Body : File->getSymbols()) {
60       auto *D = dyn_cast<DefinedRegular>(Body);
61       if (!D || !D->Section)
62         continue;
63       int &Priority = SectionOrder[D->Section];
64       Priority = std::min(Priority, SymbolOrder.lookup(D->getName()));
65     }
66   }
67   return SectionOrder;
68 }
69 
70 template <class ELFT>
71 static ArrayRef<uint8_t> getSectionContents(ObjFile<ELFT> *File,
72                                             const typename ELFT::Shdr *Hdr) {
73   if (!File || Hdr->sh_type == SHT_NOBITS)
74     return makeArrayRef<uint8_t>(nullptr, Hdr->sh_size);
75   return check(File->getObj().getSectionContents(Hdr));
76 }
77 
78 InputSectionBase::InputSectionBase(InputFile *File, uint64_t Flags,
79                                    uint32_t Type, uint64_t Entsize,
80                                    uint32_t Link, uint32_t Info,
81                                    uint32_t Alignment, ArrayRef<uint8_t> Data,
82                                    StringRef Name, Kind SectionKind)
83     : SectionBase(SectionKind, Name, Flags, Entsize, Alignment, Type, Info,
84                   Link),
85       File(File), Data(Data), Repl(this) {
86   Live = !Config->GcSections || !(Flags & SHF_ALLOC);
87   Assigned = false;
88   NumRelocations = 0;
89   AreRelocsRela = false;
90 
91   // The ELF spec states that a value of 0 means the section has
92   // no alignment constraits.
93   uint32_t V = std::max<uint64_t>(Alignment, 1);
94   if (!isPowerOf2_64(V))
95     fatal(toString(File) + ": section sh_addralign is not a power of 2");
96   this->Alignment = V;
97 }
98 
99 // Drop SHF_GROUP bit unless we are producing a re-linkable object file.
100 // SHF_GROUP is a marker that a section belongs to some comdat group.
101 // That flag doesn't make sense in an executable.
102 static uint64_t getFlags(uint64_t Flags) {
103   Flags &= ~(uint64_t)SHF_INFO_LINK;
104   if (!Config->Relocatable)
105     Flags &= ~(uint64_t)SHF_GROUP;
106   return Flags;
107 }
108 
109 // GNU assembler 2.24 and LLVM 4.0.0's MC (the newest release as of
110 // March 2017) fail to infer section types for sections starting with
111 // ".init_array." or ".fini_array.". They set SHT_PROGBITS instead of
112 // SHF_INIT_ARRAY. As a result, the following assembler directive
113 // creates ".init_array.100" with SHT_PROGBITS, for example.
114 //
115 //   .section .init_array.100, "aw"
116 //
117 // This function forces SHT_{INIT,FINI}_ARRAY so that we can handle
118 // incorrect inputs as if they were correct from the beginning.
119 static uint64_t getType(uint64_t Type, StringRef Name) {
120   if (Type == SHT_PROGBITS && Name.startswith(".init_array."))
121     return SHT_INIT_ARRAY;
122   if (Type == SHT_PROGBITS && Name.startswith(".fini_array."))
123     return SHT_FINI_ARRAY;
124   return Type;
125 }
126 
127 template <class ELFT>
128 InputSectionBase::InputSectionBase(ObjFile<ELFT> *File,
129                                    const typename ELFT::Shdr *Hdr,
130                                    StringRef Name, Kind SectionKind)
131     : InputSectionBase(File, getFlags(Hdr->sh_flags),
132                        getType(Hdr->sh_type, Name), Hdr->sh_entsize,
133                        Hdr->sh_link, Hdr->sh_info, Hdr->sh_addralign,
134                        getSectionContents(File, Hdr), Name, SectionKind) {
135   // We reject object files having insanely large alignments even though
136   // they are allowed by the spec. I think 4GB is a reasonable limitation.
137   // We might want to relax this in the future.
138   if (Hdr->sh_addralign > UINT32_MAX)
139     fatal(toString(File) + ": section sh_addralign is too large");
140 }
141 
142 size_t InputSectionBase::getSize() const {
143   if (auto *S = dyn_cast<SyntheticSection>(this))
144     return S->getSize();
145 
146   return Data.size();
147 }
148 
149 uint64_t InputSectionBase::getOffsetInFile() const {
150   const uint8_t *FileStart = (const uint8_t *)File->MB.getBufferStart();
151   const uint8_t *SecStart = Data.begin();
152   return SecStart - FileStart;
153 }
154 
155 uint64_t SectionBase::getOffset(uint64_t Offset) const {
156   switch (kind()) {
157   case Output: {
158     auto *OS = cast<OutputSection>(this);
159     // For output sections we treat offset -1 as the end of the section.
160     return Offset == uint64_t(-1) ? OS->Size : Offset;
161   }
162   case Regular:
163     return cast<InputSection>(this)->OutSecOff + Offset;
164   case Synthetic: {
165     auto *IS = cast<InputSection>(this);
166     // For synthetic sections we treat offset -1 as the end of the section.
167     return IS->OutSecOff + (Offset == uint64_t(-1) ? IS->getSize() : Offset);
168   }
169   case EHFrame:
170     // The file crtbeginT.o has relocations pointing to the start of an empty
171     // .eh_frame that is known to be the first in the link. It does that to
172     // identify the start of the output .eh_frame.
173     return Offset;
174   case Merge:
175     const MergeInputSection *MS = cast<MergeInputSection>(this);
176     if (InputSection *IS = MS->getParent())
177       return IS->OutSecOff + MS->getOffset(Offset);
178     return MS->getOffset(Offset);
179   }
180   llvm_unreachable("invalid section kind");
181 }
182 
183 OutputSection *SectionBase::getOutputSection() {
184   InputSection *Sec;
185   if (auto *IS = dyn_cast<InputSection>(this))
186     Sec = cast<InputSection>(IS->Repl);
187   else if (auto *MS = dyn_cast<MergeInputSection>(this))
188     Sec = MS->getParent();
189   else if (auto *EH = dyn_cast<EhInputSection>(this))
190     Sec = EH->getParent();
191   else
192     return cast<OutputSection>(this);
193   return Sec ? Sec->getParent() : nullptr;
194 }
195 
196 // Uncompress section contents. Note that this function is called
197 // from parallelForEach, so it must be thread-safe.
198 void InputSectionBase::uncompress() {
199   Decompressor Dec = check(Decompressor::create(Name, toStringRef(Data),
200                                                 Config->IsLE, Config->Is64));
201 
202   size_t Size = Dec.getDecompressedSize();
203   UncompressBuf.reset(new char[Size]());
204   if (Error E = Dec.decompress({UncompressBuf.get(), Size}))
205     fatal(toString(this) +
206           ": decompress failed: " + llvm::toString(std::move(E)));
207 
208   this->Data = makeArrayRef((uint8_t *)UncompressBuf.get(), Size);
209   this->Flags &= ~(uint64_t)SHF_COMPRESSED;
210 }
211 
212 uint64_t SectionBase::getOffset(const DefinedRegular &Sym) const {
213   return getOffset(Sym.Value);
214 }
215 
216 InputSection *InputSectionBase::getLinkOrderDep() const {
217   if ((Flags & SHF_LINK_ORDER) && Link != 0) {
218     InputSectionBase *L = File->getSections()[Link];
219     if (auto *IS = dyn_cast<InputSection>(L))
220       return IS;
221     error(
222         "Merge and .eh_frame sections are not supported with SHF_LINK_ORDER " +
223         toString(L));
224   }
225   return nullptr;
226 }
227 
228 // Returns a source location string. Used to construct an error message.
229 template <class ELFT>
230 std::string InputSectionBase::getLocation(uint64_t Offset) {
231   // We don't have file for synthetic sections.
232   if (getFile<ELFT>() == nullptr)
233     return (Config->OutputFile + ":(" + Name + "+0x" + utohexstr(Offset) + ")")
234         .str();
235 
236   // First check if we can get desired values from debugging information.
237   std::string LineInfo = getFile<ELFT>()->getLineInfo(this, Offset);
238   if (!LineInfo.empty())
239     return LineInfo;
240 
241   // File->SourceFile contains STT_FILE symbol that contains a
242   // source file name. If it's missing, we use an object file name.
243   std::string SrcFile = getFile<ELFT>()->SourceFile;
244   if (SrcFile.empty())
245     SrcFile = toString(File);
246 
247   // Find a function symbol that encloses a given location.
248   for (SymbolBody *B : getFile<ELFT>()->getSymbols())
249     if (auto *D = dyn_cast<DefinedRegular>(B))
250       if (D->Section == this && D->Type == STT_FUNC)
251         if (D->Value <= Offset && Offset < D->Value + D->Size)
252           return SrcFile + ":(function " + toString(*D) + ")";
253 
254   // If there's no symbol, print out the offset in the section.
255   return (SrcFile + ":(" + Name + "+0x" + utohexstr(Offset) + ")").str();
256 }
257 
258 // Returns a source location string. This function is intended to be
259 // used for constructing an error message. The returned message looks
260 // like this:
261 //
262 //   foo.c:42 (/home/alice/possibly/very/long/path/foo.c:42)
263 //
264 // Returns an empty string if there's no way to get line info.
265 template <class ELFT> std::string InputSectionBase::getSrcMsg(uint64_t Offset) {
266   // Synthetic sections don't have input files.
267   ObjFile<ELFT> *File = getFile<ELFT>();
268   if (!File)
269     return "";
270 
271   Optional<DILineInfo> Info = File->getDILineInfo(this, Offset);
272 
273   // File->SourceFile contains STT_FILE symbol, and that is a last resort.
274   if (!Info)
275     return File->SourceFile;
276 
277   std::string Path = Info->FileName;
278   std::string Filename = path::filename(Path);
279   std::string Lineno = ":" + std::to_string(Info->Line);
280   if (Filename == Path)
281     return Filename + Lineno;
282   return Filename + Lineno + " (" + Path + Lineno + ")";
283 }
284 
285 // Returns a filename string along with an optional section name. This
286 // function is intended to be used for constructing an error
287 // message. The returned message looks like this:
288 //
289 //   path/to/foo.o:(function bar)
290 //
291 // or
292 //
293 //   path/to/foo.o:(function bar) in archive path/to/bar.a
294 template <class ELFT> std::string InputSectionBase::getObjMsg(uint64_t Off) {
295   // Synthetic sections don't have input files.
296   ObjFile<ELFT> *File = getFile<ELFT>();
297   if (!File)
298     return ("(internal):(" + Name + "+0x" + utohexstr(Off) + ")").str();
299   std::string Filename = File->getName();
300 
301   std::string Archive;
302   if (!File->ArchiveName.empty())
303     Archive = (" in archive " + File->ArchiveName).str();
304 
305   // Find a symbol that encloses a given location.
306   for (SymbolBody *B : getFile<ELFT>()->getSymbols())
307     if (auto *D = dyn_cast<DefinedRegular>(B))
308       if (D->Section == this && D->Value <= Off && Off < D->Value + D->Size)
309         return Filename + ":(" + toString(*D) + ")" + Archive;
310 
311   // If there's no symbol, print out the offset in the section.
312   return (Filename + ":(" + Name + "+0x" + utohexstr(Off) + ")" + Archive)
313       .str();
314 }
315 
316 InputSectionBase InputSectionBase::Discarded;
317 
318 InputSection::InputSection(uint64_t Flags, uint32_t Type, uint32_t Alignment,
319                            ArrayRef<uint8_t> Data, StringRef Name, Kind K)
320     : InputSectionBase(nullptr, Flags, Type,
321                        /*Entsize*/ 0, /*Link*/ 0, /*Info*/ 0, Alignment, Data,
322                        Name, K) {}
323 
324 template <class ELFT>
325 InputSection::InputSection(ObjFile<ELFT> *F, const typename ELFT::Shdr *Header,
326                            StringRef Name)
327     : InputSectionBase(F, Header, Name, InputSectionBase::Regular) {}
328 
329 bool InputSection::classof(const SectionBase *S) {
330   return S->kind() == SectionBase::Regular ||
331          S->kind() == SectionBase::Synthetic;
332 }
333 
334 bool InputSectionBase::classof(const SectionBase *S) {
335   return S->kind() != Output;
336 }
337 
338 OutputSection *InputSection::getParent() const {
339   return cast_or_null<OutputSection>(Parent);
340 }
341 
342 // Copy SHT_GROUP section contents. Used only for the -r option.
343 template <class ELFT> void InputSection::copyShtGroup(uint8_t *Buf) {
344   // ELFT::Word is the 32-bit integral type in the target endianness.
345   typedef typename ELFT::Word u32;
346   ArrayRef<u32> From = getDataAs<u32>();
347   auto *To = reinterpret_cast<u32 *>(Buf);
348 
349   // The first entry is not a section number but a flag.
350   *To++ = From[0];
351 
352   // Adjust section numbers because section numbers in an input object
353   // files are different in the output.
354   ArrayRef<InputSectionBase *> Sections = this->File->getSections();
355   for (uint32_t Idx : From.slice(1))
356     *To++ = Sections[Idx]->getOutputSection()->SectionIndex;
357 }
358 
359 InputSectionBase *InputSection::getRelocatedSection() {
360   assert(this->Type == SHT_RELA || this->Type == SHT_REL);
361   ArrayRef<InputSectionBase *> Sections = this->File->getSections();
362   return Sections[this->Info];
363 }
364 
365 // This is used for -r and --emit-relocs. We can't use memcpy to copy
366 // relocations because we need to update symbol table offset and section index
367 // for each relocation. So we copy relocations one by one.
368 template <class ELFT, class RelTy>
369 void InputSection::copyRelocations(uint8_t *Buf, ArrayRef<RelTy> Rels) {
370   InputSectionBase *RelocatedSection = getRelocatedSection();
371 
372   // Loop is slow and have complexity O(N*M), where N - amount of
373   // relocations and M - amount of symbols in symbol table.
374   // That happens because getSymbolIndex(...) call below performs
375   // simple linear search.
376   for (const RelTy &Rel : Rels) {
377     uint32_t Type = Rel.getType(Config->IsMips64EL);
378     SymbolBody &Body = this->getFile<ELFT>()->getRelocTargetSym(Rel);
379 
380     auto *P = reinterpret_cast<typename ELFT::Rela *>(Buf);
381     Buf += sizeof(RelTy);
382 
383     if (Config->IsRela)
384       P->r_addend = getAddend<ELFT>(Rel);
385 
386     // Output section VA is zero for -r, so r_offset is an offset within the
387     // section, but for --emit-relocs it is an virtual address.
388     P->r_offset = RelocatedSection->getOutputSection()->Addr +
389                   RelocatedSection->getOffset(Rel.r_offset);
390     P->setSymbolAndType(InX::SymTab->getSymbolIndex(&Body), Type,
391                         Config->IsMips64EL);
392 
393     if (Body.Type == STT_SECTION) {
394       // We combine multiple section symbols into only one per
395       // section. This means we have to update the addend. That is
396       // trivial for Elf_Rela, but for Elf_Rel we have to write to the
397       // section data. We do that by adding to the Relocation vector.
398 
399       // .eh_frame is horribly special and can reference discarded sections. To
400       // avoid having to parse and recreate .eh_frame, we just replace any
401       // relocation in it pointing to discarded sections with R_*_NONE, which
402       // hopefully creates a frame that is ignored at runtime.
403       SectionBase *Section = cast<DefinedRegular>(Body).Section;
404       if (Section == &InputSection::Discarded) {
405         P->setSymbolAndType(0, 0, false);
406         continue;
407       }
408 
409       if (Config->IsRela) {
410         P->r_addend += Body.getVA() - Section->getOutputSection()->Addr;
411       } else if (Config->Relocatable) {
412         const uint8_t *BufLoc = RelocatedSection->Data.begin() + Rel.r_offset;
413         RelocatedSection->Relocations.push_back(
414             {R_ABS, Type, Rel.r_offset, Target->getImplicitAddend(BufLoc, Type),
415              &Body});
416       }
417     }
418 
419   }
420 }
421 
422 // The ARM and AArch64 ABI handle pc-relative relocations to undefined weak
423 // references specially. The general rule is that the value of the symbol in
424 // this context is the address of the place P. A further special case is that
425 // branch relocations to an undefined weak reference resolve to the next
426 // instruction.
427 static uint32_t getARMUndefinedRelativeWeakVA(uint32_t Type, uint32_t A,
428                                               uint32_t P) {
429   switch (Type) {
430   // Unresolved branch relocations to weak references resolve to next
431   // instruction, this will be either 2 or 4 bytes on from P.
432   case R_ARM_THM_JUMP11:
433     return P + 2 + A;
434   case R_ARM_CALL:
435   case R_ARM_JUMP24:
436   case R_ARM_PC24:
437   case R_ARM_PLT32:
438   case R_ARM_PREL31:
439   case R_ARM_THM_JUMP19:
440   case R_ARM_THM_JUMP24:
441     return P + 4 + A;
442   case R_ARM_THM_CALL:
443     // We don't want an interworking BLX to ARM
444     return P + 5 + A;
445   // Unresolved non branch pc-relative relocations
446   // R_ARM_TARGET2 which can be resolved relatively is not present as it never
447   // targets a weak-reference.
448   case R_ARM_MOVW_PREL_NC:
449   case R_ARM_MOVT_PREL:
450   case R_ARM_REL32:
451   case R_ARM_THM_MOVW_PREL_NC:
452   case R_ARM_THM_MOVT_PREL:
453     return P + A;
454   }
455   llvm_unreachable("ARM pc-relative relocation expected\n");
456 }
457 
458 // The comment above getARMUndefinedRelativeWeakVA applies to this function.
459 static uint64_t getAArch64UndefinedRelativeWeakVA(uint64_t Type, uint64_t A,
460                                                   uint64_t P) {
461   switch (Type) {
462   // Unresolved branch relocations to weak references resolve to next
463   // instruction, this is 4 bytes on from P.
464   case R_AARCH64_CALL26:
465   case R_AARCH64_CONDBR19:
466   case R_AARCH64_JUMP26:
467   case R_AARCH64_TSTBR14:
468     return P + 4 + A;
469   // Unresolved non branch pc-relative relocations
470   case R_AARCH64_PREL16:
471   case R_AARCH64_PREL32:
472   case R_AARCH64_PREL64:
473   case R_AARCH64_ADR_PREL_LO21:
474     return P + A;
475   }
476   llvm_unreachable("AArch64 pc-relative relocation expected\n");
477 }
478 
479 // ARM SBREL relocations are of the form S + A - B where B is the static base
480 // The ARM ABI defines base to be "addressing origin of the output segment
481 // defining the symbol S". We defined the "addressing origin"/static base to be
482 // the base of the PT_LOAD segment containing the Body.
483 // The procedure call standard only defines a Read Write Position Independent
484 // RWPI variant so in practice we should expect the static base to be the base
485 // of the RW segment.
486 static uint64_t getARMStaticBase(const SymbolBody &Body) {
487   OutputSection *OS = Body.getOutputSection();
488   if (!OS || !OS->PtLoad || !OS->PtLoad->FirstSec)
489     fatal("SBREL relocation to " + Body.getName() + " without static base");
490   return OS->PtLoad->FirstSec->Addr;
491 }
492 
493 static uint64_t getRelocTargetVA(uint32_t Type, int64_t A, uint64_t P,
494                                  const SymbolBody &Body, RelExpr Expr) {
495   switch (Expr) {
496   case R_ABS:
497   case R_RELAX_GOT_PC_NOPIC:
498     return Body.getVA(A);
499   case R_ARM_SBREL:
500     return Body.getVA(A) - getARMStaticBase(Body);
501   case R_GOT:
502   case R_RELAX_TLS_GD_TO_IE_ABS:
503     return Body.getGotVA() + A;
504   case R_GOTONLY_PC:
505     return InX::Got->getVA() + A - P;
506   case R_GOTONLY_PC_FROM_END:
507     return InX::Got->getVA() + A - P + InX::Got->getSize();
508   case R_GOTREL:
509     return Body.getVA(A) - InX::Got->getVA();
510   case R_GOTREL_FROM_END:
511     return Body.getVA(A) - InX::Got->getVA() - InX::Got->getSize();
512   case R_GOT_FROM_END:
513   case R_RELAX_TLS_GD_TO_IE_END:
514     return Body.getGotOffset() + A - InX::Got->getSize();
515   case R_GOT_OFF:
516     return Body.getGotOffset() + A;
517   case R_GOT_PAGE_PC:
518   case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
519     return getAArch64Page(Body.getGotVA() + A) - getAArch64Page(P);
520   case R_GOT_PC:
521   case R_RELAX_TLS_GD_TO_IE:
522     return Body.getGotVA() + A - P;
523   case R_HINT:
524   case R_NONE:
525   case R_TLSDESC_CALL:
526     llvm_unreachable("cannot relocate hint relocs");
527   case R_MIPS_GOTREL:
528     return Body.getVA(A) - InX::MipsGot->getGp();
529   case R_MIPS_GOT_GP:
530     return InX::MipsGot->getGp() + A;
531   case R_MIPS_GOT_GP_PC: {
532     // R_MIPS_LO16 expression has R_MIPS_GOT_GP_PC type iif the target
533     // is _gp_disp symbol. In that case we should use the following
534     // formula for calculation "AHL + GP - P + 4". For details see p. 4-19 at
535     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
536     uint64_t V = InX::MipsGot->getGp() + A - P;
537     if (Type == R_MIPS_LO16)
538       V += 4;
539     return V;
540   }
541   case R_MIPS_GOT_LOCAL_PAGE:
542     // If relocation against MIPS local symbol requires GOT entry, this entry
543     // should be initialized by 'page address'. This address is high 16-bits
544     // of sum the symbol's value and the addend.
545     return InX::MipsGot->getVA() + InX::MipsGot->getPageEntryOffset(Body, A) -
546            InX::MipsGot->getGp();
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() + InX::MipsGot->getBodyEntryOffset(Body, A) -
553            InX::MipsGot->getGp();
554   case R_MIPS_TLSGD:
555     return InX::MipsGot->getVA() + InX::MipsGot->getTlsOffset() +
556            InX::MipsGot->getGlobalDynOffset(Body) - InX::MipsGot->getGp();
557   case R_MIPS_TLSLD:
558     return InX::MipsGot->getVA() + InX::MipsGot->getTlsOffset() +
559            InX::MipsGot->getTlsIndexOff() - InX::MipsGot->getGp();
560   case R_PAGE_PC:
561   case R_PLT_PAGE_PC: {
562     uint64_t Dest;
563     if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak())
564       Dest = getAArch64Page(A);
565     else
566       Dest = getAArch64Page(Body.getVA(A));
567     return Dest - getAArch64Page(P);
568   }
569   case R_PC: {
570     uint64_t Dest;
571     if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak()) {
572       // On ARM and AArch64 a branch to an undefined weak resolves to the
573       // next instruction, otherwise the place.
574       if (Config->EMachine == EM_ARM)
575         Dest = getARMUndefinedRelativeWeakVA(Type, A, P);
576       else if (Config->EMachine == EM_AARCH64)
577         Dest = getAArch64UndefinedRelativeWeakVA(Type, A, P);
578       else
579         Dest = Body.getVA(A);
580     } else {
581       Dest = Body.getVA(A);
582     }
583     return Dest - P;
584   }
585   case R_PLT:
586     return Body.getPltVA() + A;
587   case R_PLT_PC:
588   case R_PPC_PLT_OPD:
589     return Body.getPltVA() + A - P;
590   case R_PPC_OPD: {
591     uint64_t SymVA = Body.getVA(A);
592     // If we have an undefined weak symbol, we might get here with a symbol
593     // address of zero. That could overflow, but the code must be unreachable,
594     // so don't bother doing anything at all.
595     if (!SymVA)
596       return 0;
597     if (Out::Opd) {
598       // If this is a local call, and we currently have the address of a
599       // function-descriptor, get the underlying code address instead.
600       uint64_t OpdStart = Out::Opd->Addr;
601       uint64_t OpdEnd = OpdStart + Out::Opd->Size;
602       bool InOpd = OpdStart <= SymVA && SymVA < OpdEnd;
603       if (InOpd)
604         SymVA = read64be(&Out::OpdBuf[SymVA - OpdStart]);
605     }
606     return SymVA - P;
607   }
608   case R_PPC_TOC:
609     return getPPC64TocBase() + A;
610   case R_RELAX_GOT_PC:
611     return Body.getVA(A) - P;
612   case R_RELAX_TLS_GD_TO_LE:
613   case R_RELAX_TLS_IE_TO_LE:
614   case R_RELAX_TLS_LD_TO_LE:
615   case R_TLS:
616     // A weak undefined TLS symbol resolves to the base of the TLS
617     // block, i.e. gets a value of zero. If we pass --gc-sections to
618     // lld and .tbss is not referenced, it gets reclaimed and we don't
619     // create a TLS program header. Therefore, we resolve this
620     // statically to zero.
621     if (Body.isTls() && (Body.isLazy() || Body.isUndefined()) &&
622         Body.symbol()->isWeak())
623       return 0;
624     if (Target->TcbSize)
625       return Body.getVA(A) + alignTo(Target->TcbSize, Out::TlsPhdr->p_align);
626     return Body.getVA(A) - Out::TlsPhdr->p_memsz;
627   case R_RELAX_TLS_GD_TO_LE_NEG:
628   case R_NEG_TLS:
629     return Out::TlsPhdr->p_memsz - Body.getVA(A);
630   case R_SIZE:
631     return A; // Body.getSize was already folded into the addend.
632   case R_TLSDESC:
633     return InX::Got->getGlobalDynAddr(Body) + A;
634   case R_TLSDESC_PAGE:
635     return getAArch64Page(InX::Got->getGlobalDynAddr(Body) + A) -
636            getAArch64Page(P);
637   case R_TLSGD:
638     return InX::Got->getGlobalDynOffset(Body) + A - InX::Got->getSize();
639   case R_TLSGD_PC:
640     return InX::Got->getGlobalDynAddr(Body) + A - P;
641   case R_TLSLD:
642     return InX::Got->getTlsIndexOff() + A - InX::Got->getSize();
643   case R_TLSLD_PC:
644     return InX::Got->getTlsIndexVA() + A - P;
645   }
646   llvm_unreachable("Invalid expression");
647 }
648 
649 // This function applies relocations to sections without SHF_ALLOC bit.
650 // Such sections are never mapped to memory at runtime. Debug sections are
651 // an example. Relocations in non-alloc sections are much easier to
652 // handle than in allocated sections because it will never need complex
653 // treatement such as GOT or PLT (because at runtime no one refers them).
654 // So, we handle relocations for non-alloc sections directly in this
655 // function as a performance optimization.
656 template <class ELFT, class RelTy>
657 void InputSection::relocateNonAlloc(uint8_t *Buf, ArrayRef<RelTy> Rels) {
658   for (const RelTy &Rel : Rels) {
659     uint32_t Type = Rel.getType(Config->IsMips64EL);
660     uint64_t Offset = getOffset(Rel.r_offset);
661     uint8_t *BufLoc = Buf + Offset;
662     int64_t Addend = getAddend<ELFT>(Rel);
663     if (!RelTy::IsRela)
664       Addend += Target->getImplicitAddend(BufLoc, Type);
665 
666     SymbolBody &Sym = this->getFile<ELFT>()->getRelocTargetSym(Rel);
667     RelExpr Expr = Target->getRelExpr(Type, Sym, *File, BufLoc);
668     if (Expr == R_NONE)
669       continue;
670     if (Expr != R_ABS) {
671       error(this->getLocation<ELFT>(Offset) + ": has non-ABS reloc");
672       return;
673     }
674 
675     uint64_t AddrLoc = getParent()->Addr + Offset;
676     uint64_t SymVA = 0;
677     if (!Sym.isTls() || Out::TlsPhdr)
678       SymVA = SignExtend64<sizeof(typename ELFT::uint) * 8>(
679           getRelocTargetVA(Type, Addend, AddrLoc, Sym, R_ABS));
680     Target->relocateOne(BufLoc, Type, SymVA);
681   }
682 }
683 
684 template <class ELFT> ObjFile<ELFT> *InputSectionBase::getFile() const {
685   return cast_or_null<ObjFile<ELFT>>(File);
686 }
687 
688 template <class ELFT>
689 void InputSectionBase::relocate(uint8_t *Buf, uint8_t *BufEnd) {
690   if (Flags & SHF_ALLOC)
691     relocateAlloc(Buf, BufEnd);
692   else
693     relocateNonAlloc<ELFT>(Buf, BufEnd);
694 }
695 
696 template <class ELFT>
697 void InputSectionBase::relocateNonAlloc(uint8_t *Buf, uint8_t *BufEnd) {
698   // scanReloc function in Writer.cpp constructs Relocations
699   // vector only for SHF_ALLOC'ed sections. For other sections,
700   // we handle relocations directly here.
701   auto *IS = cast<InputSection>(this);
702   assert(!(IS->Flags & SHF_ALLOC));
703   if (IS->AreRelocsRela)
704     IS->relocateNonAlloc<ELFT>(Buf, IS->template relas<ELFT>());
705   else
706     IS->relocateNonAlloc<ELFT>(Buf, IS->template rels<ELFT>());
707 }
708 
709 void InputSectionBase::relocateAlloc(uint8_t *Buf, uint8_t *BufEnd) {
710   assert(Flags & SHF_ALLOC);
711   const unsigned Bits = Config->Wordsize * 8;
712   for (const Relocation &Rel : Relocations) {
713     uint64_t Offset = getOffset(Rel.Offset);
714     uint8_t *BufLoc = Buf + Offset;
715     uint32_t Type = Rel.Type;
716 
717     uint64_t AddrLoc = getOutputSection()->Addr + Offset;
718     RelExpr Expr = Rel.Expr;
719     uint64_t TargetVA = SignExtend64(
720         getRelocTargetVA(Type, Rel.Addend, AddrLoc, *Rel.Sym, Expr), Bits);
721 
722     switch (Expr) {
723     case R_RELAX_GOT_PC:
724     case R_RELAX_GOT_PC_NOPIC:
725       Target->relaxGot(BufLoc, TargetVA);
726       break;
727     case R_RELAX_TLS_IE_TO_LE:
728       Target->relaxTlsIeToLe(BufLoc, Type, TargetVA);
729       break;
730     case R_RELAX_TLS_LD_TO_LE:
731       Target->relaxTlsLdToLe(BufLoc, Type, TargetVA);
732       break;
733     case R_RELAX_TLS_GD_TO_LE:
734     case R_RELAX_TLS_GD_TO_LE_NEG:
735       Target->relaxTlsGdToLe(BufLoc, Type, TargetVA);
736       break;
737     case R_RELAX_TLS_GD_TO_IE:
738     case R_RELAX_TLS_GD_TO_IE_ABS:
739     case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
740     case R_RELAX_TLS_GD_TO_IE_END:
741       Target->relaxTlsGdToIe(BufLoc, Type, TargetVA);
742       break;
743     case R_PPC_PLT_OPD:
744       // Patch a nop (0x60000000) to a ld.
745       if (BufLoc + 8 <= BufEnd && read32be(BufLoc + 4) == 0x60000000)
746         write32be(BufLoc + 4, 0xe8410028); // ld %r2, 40(%r1)
747       LLVM_FALLTHROUGH;
748     default:
749       Target->relocateOne(BufLoc, Type, TargetVA);
750       break;
751     }
752   }
753 }
754 
755 template <class ELFT> void InputSection::writeTo(uint8_t *Buf) {
756   if (this->Type == SHT_NOBITS)
757     return;
758 
759   if (auto *S = dyn_cast<SyntheticSection>(this)) {
760     S->writeTo(Buf + OutSecOff);
761     return;
762   }
763 
764   // If -r or --emit-relocs is given, then an InputSection
765   // may be a relocation section.
766   if (this->Type == SHT_RELA) {
767     copyRelocations<ELFT>(Buf + OutSecOff,
768                           this->template getDataAs<typename ELFT::Rela>());
769     return;
770   }
771   if (this->Type == SHT_REL) {
772     copyRelocations<ELFT>(Buf + OutSecOff,
773                           this->template getDataAs<typename ELFT::Rel>());
774     return;
775   }
776 
777   // If -r is given, we may have a SHT_GROUP section.
778   if (this->Type == SHT_GROUP) {
779     copyShtGroup<ELFT>(Buf + OutSecOff);
780     return;
781   }
782 
783   // Copy section contents from source object file to output file
784   // and then apply relocations.
785   memcpy(Buf + OutSecOff, Data.data(), Data.size());
786   uint8_t *BufEnd = Buf + OutSecOff + Data.size();
787   this->relocate<ELFT>(Buf, BufEnd);
788 }
789 
790 void InputSection::replace(InputSection *Other) {
791   this->Alignment = std::max(this->Alignment, Other->Alignment);
792   Other->Repl = this->Repl;
793   Other->Live = false;
794 }
795 
796 template <class ELFT>
797 EhInputSection::EhInputSection(ObjFile<ELFT> *F,
798                                const typename ELFT::Shdr *Header,
799                                StringRef Name)
800     : InputSectionBase(F, Header, Name, InputSectionBase::EHFrame) {
801   // Mark .eh_frame sections as live by default because there are
802   // usually no relocations that point to .eh_frames. Otherwise,
803   // the garbage collector would drop all .eh_frame sections.
804   this->Live = true;
805 }
806 
807 SyntheticSection *EhInputSection::getParent() const {
808   return cast_or_null<SyntheticSection>(Parent);
809 }
810 
811 bool EhInputSection::classof(const SectionBase *S) {
812   return S->kind() == InputSectionBase::EHFrame;
813 }
814 
815 // Returns the index of the first relocation that points to a region between
816 // Begin and Begin+Size.
817 template <class IntTy, class RelTy>
818 static unsigned getReloc(IntTy Begin, IntTy Size, const ArrayRef<RelTy> &Rels,
819                          unsigned &RelocI) {
820   // Start search from RelocI for fast access. That works because the
821   // relocations are sorted in .eh_frame.
822   for (unsigned N = Rels.size(); RelocI < N; ++RelocI) {
823     const RelTy &Rel = Rels[RelocI];
824     if (Rel.r_offset < Begin)
825       continue;
826 
827     if (Rel.r_offset < Begin + Size)
828       return RelocI;
829     return -1;
830   }
831   return -1;
832 }
833 
834 // .eh_frame is a sequence of CIE or FDE records.
835 // This function splits an input section into records and returns them.
836 template <class ELFT> void EhInputSection::split() {
837   // Early exit if already split.
838   if (!this->Pieces.empty())
839     return;
840 
841   if (this->NumRelocations) {
842     if (this->AreRelocsRela)
843       split<ELFT>(this->relas<ELFT>());
844     else
845       split<ELFT>(this->rels<ELFT>());
846     return;
847   }
848   split<ELFT>(makeArrayRef<typename ELFT::Rela>(nullptr, nullptr));
849 }
850 
851 template <class ELFT, class RelTy>
852 void EhInputSection::split(ArrayRef<RelTy> Rels) {
853   ArrayRef<uint8_t> Data = this->Data;
854   unsigned RelI = 0;
855   for (size_t Off = 0, End = Data.size(); Off != End;) {
856     size_t Size = readEhRecordSize<ELFT>(this, Off);
857     this->Pieces.emplace_back(Off, this, Size, getReloc(Off, Size, Rels, RelI));
858     // The empty record is the end marker.
859     if (Size == 4)
860       break;
861     Off += Size;
862   }
863 }
864 
865 static size_t findNull(ArrayRef<uint8_t> A, size_t EntSize) {
866   // Optimize the common case.
867   StringRef S((const char *)A.data(), A.size());
868   if (EntSize == 1)
869     return S.find(0);
870 
871   for (unsigned I = 0, N = S.size(); I != N; I += EntSize) {
872     const char *B = S.begin() + I;
873     if (std::all_of(B, B + EntSize, [](char C) { return C == 0; }))
874       return I;
875   }
876   return StringRef::npos;
877 }
878 
879 SyntheticSection *MergeInputSection::getParent() const {
880   return cast_or_null<SyntheticSection>(Parent);
881 }
882 
883 // Split SHF_STRINGS section. Such section is a sequence of
884 // null-terminated strings.
885 void MergeInputSection::splitStrings(ArrayRef<uint8_t> Data, size_t EntSize) {
886   size_t Off = 0;
887   bool IsAlloc = this->Flags & SHF_ALLOC;
888   while (!Data.empty()) {
889     size_t End = findNull(Data, EntSize);
890     if (End == StringRef::npos)
891       fatal(toString(this) + ": string is not null terminated");
892     size_t Size = End + EntSize;
893     Pieces.emplace_back(Off, !IsAlloc);
894     Hashes.push_back(hash_value(toStringRef(Data.slice(0, Size))));
895     Data = Data.slice(Size);
896     Off += Size;
897   }
898 }
899 
900 // Split non-SHF_STRINGS section. Such section is a sequence of
901 // fixed size records.
902 void MergeInputSection::splitNonStrings(ArrayRef<uint8_t> Data,
903                                         size_t EntSize) {
904   size_t Size = Data.size();
905   assert((Size % EntSize) == 0);
906   bool IsAlloc = this->Flags & SHF_ALLOC;
907   for (unsigned I = 0, N = Size; I != N; I += EntSize) {
908     Hashes.push_back(hash_value(toStringRef(Data.slice(I, EntSize))));
909     Pieces.emplace_back(I, !IsAlloc);
910   }
911 }
912 
913 template <class ELFT>
914 MergeInputSection::MergeInputSection(ObjFile<ELFT> *F,
915                                      const typename ELFT::Shdr *Header,
916                                      StringRef Name)
917     : InputSectionBase(F, Header, Name, InputSectionBase::Merge) {}
918 
919 // This function is called after we obtain a complete list of input sections
920 // that need to be linked. This is responsible to split section contents
921 // into small chunks for further processing.
922 //
923 // Note that this function is called from parallelForEach. This must be
924 // thread-safe (i.e. no memory allocation from the pools).
925 void MergeInputSection::splitIntoPieces() {
926   assert(Pieces.empty());
927   ArrayRef<uint8_t> Data = this->Data;
928   uint64_t EntSize = this->Entsize;
929   if (this->Flags & SHF_STRINGS)
930     splitStrings(Data, EntSize);
931   else
932     splitNonStrings(Data, EntSize);
933 
934   if (Config->GcSections && (this->Flags & SHF_ALLOC))
935     for (uint64_t Off : LiveOffsets)
936       this->getSectionPiece(Off)->Live = true;
937 }
938 
939 bool MergeInputSection::classof(const SectionBase *S) {
940   return S->kind() == InputSectionBase::Merge;
941 }
942 
943 // Do binary search to get a section piece at a given input offset.
944 SectionPiece *MergeInputSection::getSectionPiece(uint64_t Offset) {
945   auto *This = static_cast<const MergeInputSection *>(this);
946   return const_cast<SectionPiece *>(This->getSectionPiece(Offset));
947 }
948 
949 template <class It, class T, class Compare>
950 static It fastUpperBound(It First, It Last, const T &Value, Compare Comp) {
951   size_t Size = std::distance(First, Last);
952   assert(Size != 0);
953   while (Size != 1) {
954     size_t H = Size / 2;
955     const It MI = First + H;
956     Size -= H;
957     First = Comp(Value, *MI) ? First : First + H;
958   }
959   return Comp(Value, *First) ? First : First + 1;
960 }
961 
962 const SectionPiece *MergeInputSection::getSectionPiece(uint64_t Offset) const {
963   uint64_t Size = this->Data.size();
964   if (Offset >= Size)
965     fatal(toString(this) + ": entry is past the end of the section");
966 
967   // Find the element this offset points to.
968   auto I = fastUpperBound(
969       Pieces.begin(), Pieces.end(), Offset,
970       [](const uint64_t &A, const SectionPiece &B) { return A < B.InputOff; });
971   --I;
972   return &*I;
973 }
974 
975 // Returns the offset in an output section for a given input offset.
976 // Because contents of a mergeable section is not contiguous in output,
977 // it is not just an addition to a base output offset.
978 uint64_t MergeInputSection::getOffset(uint64_t Offset) const {
979   // Initialize OffsetMap lazily.
980   llvm::call_once(InitOffsetMap, [&] {
981     OffsetMap.reserve(Pieces.size());
982     for (const SectionPiece &Piece : Pieces)
983       OffsetMap[Piece.InputOff] = Piece.OutputOff;
984   });
985 
986   // Find a string starting at a given offset.
987   auto It = OffsetMap.find(Offset);
988   if (It != OffsetMap.end())
989     return It->second;
990 
991   if (!this->Live)
992     return 0;
993 
994   // If Offset is not at beginning of a section piece, it is not in the map.
995   // In that case we need to search from the original section piece vector.
996   const SectionPiece &Piece = *this->getSectionPiece(Offset);
997   if (!Piece.Live)
998     return 0;
999 
1000   uint64_t Addend = Offset - Piece.InputOff;
1001   return Piece.OutputOff + Addend;
1002 }
1003 
1004 template DenseMap<SectionBase *, int> elf::buildSectionOrder<ELF32LE>();
1005 template DenseMap<SectionBase *, int> elf::buildSectionOrder<ELF32BE>();
1006 template DenseMap<SectionBase *, int> elf::buildSectionOrder<ELF64LE>();
1007 template DenseMap<SectionBase *, int> elf::buildSectionOrder<ELF64BE>();
1008 
1009 template InputSection::InputSection(ObjFile<ELF32LE> *, const ELF32LE::Shdr *,
1010                                     StringRef);
1011 template InputSection::InputSection(ObjFile<ELF32BE> *, const ELF32BE::Shdr *,
1012                                     StringRef);
1013 template InputSection::InputSection(ObjFile<ELF64LE> *, const ELF64LE::Shdr *,
1014                                     StringRef);
1015 template InputSection::InputSection(ObjFile<ELF64BE> *, const ELF64BE::Shdr *,
1016                                     StringRef);
1017 
1018 template std::string InputSectionBase::getLocation<ELF32LE>(uint64_t);
1019 template std::string InputSectionBase::getLocation<ELF32BE>(uint64_t);
1020 template std::string InputSectionBase::getLocation<ELF64LE>(uint64_t);
1021 template std::string InputSectionBase::getLocation<ELF64BE>(uint64_t);
1022 
1023 template std::string InputSectionBase::getSrcMsg<ELF32LE>(uint64_t);
1024 template std::string InputSectionBase::getSrcMsg<ELF32BE>(uint64_t);
1025 template std::string InputSectionBase::getSrcMsg<ELF64LE>(uint64_t);
1026 template std::string InputSectionBase::getSrcMsg<ELF64BE>(uint64_t);
1027 
1028 template std::string InputSectionBase::getObjMsg<ELF32LE>(uint64_t);
1029 template std::string InputSectionBase::getObjMsg<ELF32BE>(uint64_t);
1030 template std::string InputSectionBase::getObjMsg<ELF64LE>(uint64_t);
1031 template std::string InputSectionBase::getObjMsg<ELF64BE>(uint64_t);
1032 
1033 template void InputSection::writeTo<ELF32LE>(uint8_t *);
1034 template void InputSection::writeTo<ELF32BE>(uint8_t *);
1035 template void InputSection::writeTo<ELF64LE>(uint8_t *);
1036 template void InputSection::writeTo<ELF64BE>(uint8_t *);
1037 
1038 template ObjFile<ELF32LE> *InputSectionBase::getFile<ELF32LE>() const;
1039 template ObjFile<ELF32BE> *InputSectionBase::getFile<ELF32BE>() const;
1040 template ObjFile<ELF64LE> *InputSectionBase::getFile<ELF64LE>() const;
1041 template ObjFile<ELF64BE> *InputSectionBase::getFile<ELF64BE>() const;
1042 
1043 template MergeInputSection::MergeInputSection(ObjFile<ELF32LE> *,
1044                                               const ELF32LE::Shdr *, StringRef);
1045 template MergeInputSection::MergeInputSection(ObjFile<ELF32BE> *,
1046                                               const ELF32BE::Shdr *, StringRef);
1047 template MergeInputSection::MergeInputSection(ObjFile<ELF64LE> *,
1048                                               const ELF64LE::Shdr *, StringRef);
1049 template MergeInputSection::MergeInputSection(ObjFile<ELF64BE> *,
1050                                               const ELF64BE::Shdr *, StringRef);
1051 
1052 template EhInputSection::EhInputSection(ObjFile<ELF32LE> *,
1053                                         const ELF32LE::Shdr *, StringRef);
1054 template EhInputSection::EhInputSection(ObjFile<ELF32BE> *,
1055                                         const ELF32BE::Shdr *, StringRef);
1056 template EhInputSection::EhInputSection(ObjFile<ELF64LE> *,
1057                                         const ELF64LE::Shdr *, StringRef);
1058 template EhInputSection::EhInputSection(ObjFile<ELF64BE> *,
1059                                         const ELF64BE::Shdr *, StringRef);
1060 
1061 template void EhInputSection::split<ELF32LE>();
1062 template void EhInputSection::split<ELF32BE>();
1063 template void EhInputSection::split<ELF64LE>();
1064 template void EhInputSection::split<ELF64BE>();
1065