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