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     return P + A;
491   }
492   llvm_unreachable("AArch64 pc-relative relocation expected\n");
493 }
494 
495 // ARM SBREL relocations are of the form S + A - B where B is the static base
496 // The ARM ABI defines base to be "addressing origin of the output segment
497 // defining the symbol S". We defined the "addressing origin"/static base to be
498 // the base of the PT_LOAD segment containing the Body.
499 // The procedure call standard only defines a Read Write Position Independent
500 // RWPI variant so in practice we should expect the static base to be the base
501 // of the RW segment.
502 static uint64_t getARMStaticBase(const SymbolBody &Body) {
503   OutputSection *OS = Body.getOutputSection();
504   if (!OS || !OS->PtLoad || !OS->PtLoad->FirstSec)
505     fatal("SBREL relocation to " + Body.getName() + " without static base");
506   return OS->PtLoad->FirstSec->Addr;
507 }
508 
509 static uint64_t getRelocTargetVA(uint32_t Type, int64_t A, uint64_t P,
510                                  const SymbolBody &Body, RelExpr Expr) {
511   switch (Expr) {
512   case R_ABS:
513   case R_RELAX_GOT_PC_NOPIC:
514     return Body.getVA(A);
515   case R_ARM_SBREL:
516     return Body.getVA(A) - getARMStaticBase(Body);
517   case R_GOT:
518   case R_RELAX_TLS_GD_TO_IE_ABS:
519     return Body.getGotVA() + A;
520   case R_GOTONLY_PC:
521     return InX::Got->getVA() + A - P;
522   case R_GOTONLY_PC_FROM_END:
523     return InX::Got->getVA() + A - P + InX::Got->getSize();
524   case R_GOTREL:
525     return Body.getVA(A) - InX::Got->getVA();
526   case R_GOTREL_FROM_END:
527     return Body.getVA(A) - InX::Got->getVA() - InX::Got->getSize();
528   case R_GOT_FROM_END:
529   case R_RELAX_TLS_GD_TO_IE_END:
530     return Body.getGotOffset() + A - InX::Got->getSize();
531   case R_GOT_OFF:
532     return Body.getGotOffset() + A;
533   case R_GOT_PAGE_PC:
534   case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
535     return getAArch64Page(Body.getGotVA() + A) - getAArch64Page(P);
536   case R_GOT_PC:
537   case R_RELAX_TLS_GD_TO_IE:
538     return Body.getGotVA() + A - P;
539   case R_HINT:
540   case R_NONE:
541   case R_TLSDESC_CALL:
542     llvm_unreachable("cannot relocate hint relocs");
543   case R_MIPS_GOTREL:
544     return Body.getVA(A) - InX::MipsGot->getGp();
545   case R_MIPS_GOT_GP:
546     return InX::MipsGot->getGp() + A;
547   case R_MIPS_GOT_GP_PC: {
548     // R_MIPS_LO16 expression has R_MIPS_GOT_GP_PC type iif the target
549     // is _gp_disp symbol. In that case we should use the following
550     // formula for calculation "AHL + GP - P + 4". For details see p. 4-19 at
551     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
552     uint64_t V = InX::MipsGot->getGp() + A - P;
553     if (Type == R_MIPS_LO16 || Type == R_MICROMIPS_LO16)
554       V += 4;
555     return V;
556   }
557   case R_MIPS_GOT_LOCAL_PAGE:
558     // If relocation against MIPS local symbol requires GOT entry, this entry
559     // should be initialized by 'page address'. This address is high 16-bits
560     // of sum the symbol's value and the addend.
561     return InX::MipsGot->getVA() + InX::MipsGot->getPageEntryOffset(Body, A) -
562            InX::MipsGot->getGp();
563   case R_MIPS_GOT_OFF:
564   case R_MIPS_GOT_OFF32:
565     // In case of MIPS if a GOT relocation has non-zero addend this addend
566     // should be applied to the GOT entry content not to the GOT entry offset.
567     // That is why we use separate expression type.
568     return InX::MipsGot->getVA() + InX::MipsGot->getBodyEntryOffset(Body, A) -
569            InX::MipsGot->getGp();
570   case R_MIPS_TLSGD:
571     return InX::MipsGot->getVA() + InX::MipsGot->getTlsOffset() +
572            InX::MipsGot->getGlobalDynOffset(Body) - InX::MipsGot->getGp();
573   case R_MIPS_TLSLD:
574     return InX::MipsGot->getVA() + InX::MipsGot->getTlsOffset() +
575            InX::MipsGot->getTlsIndexOff() - InX::MipsGot->getGp();
576   case R_PAGE_PC:
577   case R_PLT_PAGE_PC: {
578     uint64_t Dest;
579     if (Body.isUndefWeak())
580       Dest = getAArch64Page(A);
581     else
582       Dest = getAArch64Page(Body.getVA(A));
583     return Dest - getAArch64Page(P);
584   }
585   case R_PC: {
586     uint64_t Dest;
587     if (Body.isUndefWeak()) {
588       // On ARM and AArch64 a branch to an undefined weak resolves to the
589       // next instruction, otherwise the place.
590       if (Config->EMachine == EM_ARM)
591         Dest = getARMUndefinedRelativeWeakVA(Type, A, P);
592       else if (Config->EMachine == EM_AARCH64)
593         Dest = getAArch64UndefinedRelativeWeakVA(Type, A, P);
594       else
595         Dest = Body.getVA(A);
596     } else {
597       Dest = Body.getVA(A);
598     }
599     return Dest - P;
600   }
601   case R_PLT:
602     return Body.getPltVA() + A;
603   case R_PLT_PC:
604   case R_PPC_PLT_OPD:
605     return Body.getPltVA() + A - P;
606   case R_PPC_OPD: {
607     uint64_t SymVA = Body.getVA(A);
608     // If we have an undefined weak symbol, we might get here with a symbol
609     // address of zero. That could overflow, but the code must be unreachable,
610     // so don't bother doing anything at all.
611     if (!SymVA)
612       return 0;
613     if (Out::Opd) {
614       // If this is a local call, and we currently have the address of a
615       // function-descriptor, get the underlying code address instead.
616       uint64_t OpdStart = Out::Opd->Addr;
617       uint64_t OpdEnd = OpdStart + Out::Opd->Size;
618       bool InOpd = OpdStart <= SymVA && SymVA < OpdEnd;
619       if (InOpd)
620         SymVA = read64be(&Out::OpdBuf[SymVA - OpdStart]);
621     }
622     return SymVA - P;
623   }
624   case R_PPC_TOC:
625     return getPPC64TocBase() + A;
626   case R_RELAX_GOT_PC:
627     return Body.getVA(A) - P;
628   case R_RELAX_TLS_GD_TO_LE:
629   case R_RELAX_TLS_IE_TO_LE:
630   case R_RELAX_TLS_LD_TO_LE:
631   case R_TLS:
632     // A weak undefined TLS symbol resolves to the base of the TLS
633     // block, i.e. gets a value of zero. If we pass --gc-sections to
634     // lld and .tbss is not referenced, it gets reclaimed and we don't
635     // create a TLS program header. Therefore, we resolve this
636     // statically to zero.
637     if (Body.isTls() && (Body.isLazy() || Body.isUndefined()) &&
638         Body.symbol()->isWeak())
639       return 0;
640     if (Target->TcbSize)
641       return Body.getVA(A) + alignTo(Target->TcbSize, Out::TlsPhdr->p_align);
642     return Body.getVA(A) - Out::TlsPhdr->p_memsz;
643   case R_RELAX_TLS_GD_TO_LE_NEG:
644   case R_NEG_TLS:
645     return Out::TlsPhdr->p_memsz - Body.getVA(A);
646   case R_SIZE:
647     return A; // Body.getSize was already folded into the addend.
648   case R_TLSDESC:
649     return InX::Got->getGlobalDynAddr(Body) + A;
650   case R_TLSDESC_PAGE:
651     return getAArch64Page(InX::Got->getGlobalDynAddr(Body) + A) -
652            getAArch64Page(P);
653   case R_TLSGD:
654     return InX::Got->getGlobalDynOffset(Body) + A - InX::Got->getSize();
655   case R_TLSGD_PC:
656     return InX::Got->getGlobalDynAddr(Body) + A - P;
657   case R_TLSLD:
658     return InX::Got->getTlsIndexOff() + A - InX::Got->getSize();
659   case R_TLSLD_PC:
660     return InX::Got->getTlsIndexVA() + A - P;
661   }
662   llvm_unreachable("Invalid expression");
663 }
664 
665 // This function applies relocations to sections without SHF_ALLOC bit.
666 // Such sections are never mapped to memory at runtime. Debug sections are
667 // an example. Relocations in non-alloc sections are much easier to
668 // handle than in allocated sections because it will never need complex
669 // treatement such as GOT or PLT (because at runtime no one refers them).
670 // So, we handle relocations for non-alloc sections directly in this
671 // function as a performance optimization.
672 template <class ELFT, class RelTy>
673 void InputSection::relocateNonAlloc(uint8_t *Buf, ArrayRef<RelTy> Rels) {
674   for (const RelTy &Rel : Rels) {
675     uint32_t Type = Rel.getType(Config->IsMips64EL);
676     uint64_t Offset = getOffset(Rel.r_offset);
677     uint8_t *BufLoc = Buf + Offset;
678     int64_t Addend = getAddend<ELFT>(Rel);
679     if (!RelTy::IsRela)
680       Addend += Target->getImplicitAddend(BufLoc, Type);
681 
682     SymbolBody &Sym = this->getFile<ELFT>()->getRelocTargetSym(Rel);
683     RelExpr Expr = Target->getRelExpr(Type, Sym, *File, BufLoc);
684     if (Expr == R_NONE)
685       continue;
686     if (Expr != R_ABS) {
687       error(this->getLocation<ELFT>(Offset) + ": has non-ABS reloc");
688       return;
689     }
690 
691     uint64_t AddrLoc = getParent()->Addr + Offset;
692     uint64_t SymVA = 0;
693     if (!Sym.isTls() || Out::TlsPhdr)
694       SymVA = SignExtend64<sizeof(typename ELFT::uint) * 8>(
695           getRelocTargetVA(Type, Addend, AddrLoc, Sym, R_ABS));
696     Target->relocateOne(BufLoc, Type, SymVA);
697   }
698 }
699 
700 template <class ELFT> ObjFile<ELFT> *InputSectionBase::getFile() const {
701   return cast_or_null<ObjFile<ELFT>>(File);
702 }
703 
704 template <class ELFT>
705 void InputSectionBase::relocate(uint8_t *Buf, uint8_t *BufEnd) {
706   if (Flags & SHF_ALLOC)
707     relocateAlloc(Buf, BufEnd);
708   else
709     relocateNonAlloc<ELFT>(Buf, BufEnd);
710 }
711 
712 template <class ELFT>
713 void InputSectionBase::relocateNonAlloc(uint8_t *Buf, uint8_t *BufEnd) {
714   // scanReloc function in Writer.cpp constructs Relocations
715   // vector only for SHF_ALLOC'ed sections. For other sections,
716   // we handle relocations directly here.
717   auto *IS = cast<InputSection>(this);
718   assert(!(IS->Flags & SHF_ALLOC));
719   if (IS->AreRelocsRela)
720     IS->relocateNonAlloc<ELFT>(Buf, IS->template relas<ELFT>());
721   else
722     IS->relocateNonAlloc<ELFT>(Buf, IS->template rels<ELFT>());
723 }
724 
725 void InputSectionBase::relocateAlloc(uint8_t *Buf, uint8_t *BufEnd) {
726   assert(Flags & SHF_ALLOC);
727   const unsigned Bits = Config->Wordsize * 8;
728   for (const Relocation &Rel : Relocations) {
729     uint64_t Offset = getOffset(Rel.Offset);
730     uint8_t *BufLoc = Buf + Offset;
731     uint32_t Type = Rel.Type;
732 
733     uint64_t AddrLoc = getOutputSection()->Addr + Offset;
734     RelExpr Expr = Rel.Expr;
735     uint64_t TargetVA = SignExtend64(
736         getRelocTargetVA(Type, Rel.Addend, AddrLoc, *Rel.Sym, Expr), Bits);
737 
738     switch (Expr) {
739     case R_RELAX_GOT_PC:
740     case R_RELAX_GOT_PC_NOPIC:
741       Target->relaxGot(BufLoc, TargetVA);
742       break;
743     case R_RELAX_TLS_IE_TO_LE:
744       Target->relaxTlsIeToLe(BufLoc, Type, TargetVA);
745       break;
746     case R_RELAX_TLS_LD_TO_LE:
747       Target->relaxTlsLdToLe(BufLoc, Type, TargetVA);
748       break;
749     case R_RELAX_TLS_GD_TO_LE:
750     case R_RELAX_TLS_GD_TO_LE_NEG:
751       Target->relaxTlsGdToLe(BufLoc, Type, TargetVA);
752       break;
753     case R_RELAX_TLS_GD_TO_IE:
754     case R_RELAX_TLS_GD_TO_IE_ABS:
755     case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
756     case R_RELAX_TLS_GD_TO_IE_END:
757       Target->relaxTlsGdToIe(BufLoc, Type, TargetVA);
758       break;
759     case R_PPC_PLT_OPD:
760       // Patch a nop (0x60000000) to a ld.
761       if (BufLoc + 8 <= BufEnd && read32be(BufLoc + 4) == 0x60000000)
762         write32be(BufLoc + 4, 0xe8410028); // ld %r2, 40(%r1)
763       LLVM_FALLTHROUGH;
764     default:
765       Target->relocateOne(BufLoc, Type, TargetVA);
766       break;
767     }
768   }
769 }
770 
771 template <class ELFT> void InputSection::writeTo(uint8_t *Buf) {
772   if (this->Type == SHT_NOBITS)
773     return;
774 
775   if (auto *S = dyn_cast<SyntheticSection>(this)) {
776     S->writeTo(Buf + OutSecOff);
777     return;
778   }
779 
780   // If -r or --emit-relocs is given, then an InputSection
781   // may be a relocation section.
782   if (this->Type == SHT_RELA) {
783     copyRelocations<ELFT>(Buf + OutSecOff,
784                           this->template getDataAs<typename ELFT::Rela>());
785     return;
786   }
787   if (this->Type == SHT_REL) {
788     copyRelocations<ELFT>(Buf + OutSecOff,
789                           this->template getDataAs<typename ELFT::Rel>());
790     return;
791   }
792 
793   // If -r is given, we may have a SHT_GROUP section.
794   if (this->Type == SHT_GROUP) {
795     copyShtGroup<ELFT>(Buf + OutSecOff);
796     return;
797   }
798 
799   // Copy section contents from source object file to output file
800   // and then apply relocations.
801   memcpy(Buf + OutSecOff, Data.data(), Data.size());
802   uint8_t *BufEnd = Buf + OutSecOff + Data.size();
803   this->relocate<ELFT>(Buf, BufEnd);
804 }
805 
806 void InputSection::replace(InputSection *Other) {
807   this->Alignment = std::max(this->Alignment, Other->Alignment);
808   Other->Repl = this->Repl;
809   Other->Live = false;
810 }
811 
812 template <class ELFT>
813 EhInputSection::EhInputSection(ObjFile<ELFT> *F,
814                                const typename ELFT::Shdr *Header,
815                                StringRef Name)
816     : InputSectionBase(F, Header, Name, InputSectionBase::EHFrame) {
817   // Mark .eh_frame sections as live by default because there are
818   // usually no relocations that point to .eh_frames. Otherwise,
819   // the garbage collector would drop all .eh_frame sections.
820   this->Live = true;
821 }
822 
823 SyntheticSection *EhInputSection::getParent() const {
824   return cast_or_null<SyntheticSection>(Parent);
825 }
826 
827 bool EhInputSection::classof(const SectionBase *S) {
828   return S->kind() == InputSectionBase::EHFrame;
829 }
830 
831 // Returns the index of the first relocation that points to a region between
832 // Begin and Begin+Size.
833 template <class IntTy, class RelTy>
834 static unsigned getReloc(IntTy Begin, IntTy Size, const ArrayRef<RelTy> &Rels,
835                          unsigned &RelocI) {
836   // Start search from RelocI for fast access. That works because the
837   // relocations are sorted in .eh_frame.
838   for (unsigned N = Rels.size(); RelocI < N; ++RelocI) {
839     const RelTy &Rel = Rels[RelocI];
840     if (Rel.r_offset < Begin)
841       continue;
842 
843     if (Rel.r_offset < Begin + Size)
844       return RelocI;
845     return -1;
846   }
847   return -1;
848 }
849 
850 // .eh_frame is a sequence of CIE or FDE records.
851 // This function splits an input section into records and returns them.
852 template <class ELFT> void EhInputSection::split() {
853   // Early exit if already split.
854   if (!this->Pieces.empty())
855     return;
856 
857   if (this->NumRelocations) {
858     if (this->AreRelocsRela)
859       split<ELFT>(this->relas<ELFT>());
860     else
861       split<ELFT>(this->rels<ELFT>());
862     return;
863   }
864   split<ELFT>(makeArrayRef<typename ELFT::Rela>(nullptr, nullptr));
865 }
866 
867 template <class ELFT, class RelTy>
868 void EhInputSection::split(ArrayRef<RelTy> Rels) {
869   ArrayRef<uint8_t> Data = this->Data;
870   unsigned RelI = 0;
871   for (size_t Off = 0, End = Data.size(); Off != End;) {
872     size_t Size = readEhRecordSize<ELFT>(this, Off);
873     this->Pieces.emplace_back(Off, this, Size, getReloc(Off, Size, Rels, RelI));
874     // The empty record is the end marker.
875     if (Size == 4)
876       break;
877     Off += Size;
878   }
879 }
880 
881 static size_t findNull(ArrayRef<uint8_t> A, size_t EntSize) {
882   // Optimize the common case.
883   StringRef S((const char *)A.data(), A.size());
884   if (EntSize == 1)
885     return S.find(0);
886 
887   for (unsigned I = 0, N = S.size(); I != N; I += EntSize) {
888     const char *B = S.begin() + I;
889     if (std::all_of(B, B + EntSize, [](char C) { return C == 0; }))
890       return I;
891   }
892   return StringRef::npos;
893 }
894 
895 SyntheticSection *MergeInputSection::getParent() const {
896   return cast_or_null<SyntheticSection>(Parent);
897 }
898 
899 // Split SHF_STRINGS section. Such section is a sequence of
900 // null-terminated strings.
901 void MergeInputSection::splitStrings(ArrayRef<uint8_t> Data, size_t EntSize) {
902   size_t Off = 0;
903   bool IsAlloc = this->Flags & SHF_ALLOC;
904   while (!Data.empty()) {
905     size_t End = findNull(Data, EntSize);
906     if (End == StringRef::npos)
907       fatal(toString(this) + ": string is not null terminated");
908     size_t Size = End + EntSize;
909     Pieces.emplace_back(Off, !IsAlloc);
910     Hashes.push_back(hash_value(toStringRef(Data.slice(0, Size))));
911     Data = Data.slice(Size);
912     Off += Size;
913   }
914 }
915 
916 // Split non-SHF_STRINGS section. Such section is a sequence of
917 // fixed size records.
918 void MergeInputSection::splitNonStrings(ArrayRef<uint8_t> Data,
919                                         size_t EntSize) {
920   size_t Size = Data.size();
921   assert((Size % EntSize) == 0);
922   bool IsAlloc = this->Flags & SHF_ALLOC;
923   for (unsigned I = 0, N = Size; I != N; I += EntSize) {
924     Hashes.push_back(hash_value(toStringRef(Data.slice(I, EntSize))));
925     Pieces.emplace_back(I, !IsAlloc);
926   }
927 }
928 
929 template <class ELFT>
930 MergeInputSection::MergeInputSection(ObjFile<ELFT> *F,
931                                      const typename ELFT::Shdr *Header,
932                                      StringRef Name)
933     : InputSectionBase(F, Header, Name, InputSectionBase::Merge) {}
934 
935 // This function is called after we obtain a complete list of input sections
936 // that need to be linked. This is responsible to split section contents
937 // into small chunks for further processing.
938 //
939 // Note that this function is called from parallelForEach. This must be
940 // thread-safe (i.e. no memory allocation from the pools).
941 void MergeInputSection::splitIntoPieces() {
942   assert(Pieces.empty());
943   ArrayRef<uint8_t> Data = this->Data;
944   uint64_t EntSize = this->Entsize;
945   if (this->Flags & SHF_STRINGS)
946     splitStrings(Data, EntSize);
947   else
948     splitNonStrings(Data, EntSize);
949 
950   if (Config->GcSections && (this->Flags & SHF_ALLOC))
951     for (uint64_t Off : LiveOffsets)
952       this->getSectionPiece(Off)->Live = true;
953 }
954 
955 bool MergeInputSection::classof(const SectionBase *S) {
956   return S->kind() == InputSectionBase::Merge;
957 }
958 
959 // Do binary search to get a section piece at a given input offset.
960 SectionPiece *MergeInputSection::getSectionPiece(uint64_t Offset) {
961   auto *This = static_cast<const MergeInputSection *>(this);
962   return const_cast<SectionPiece *>(This->getSectionPiece(Offset));
963 }
964 
965 template <class It, class T, class Compare>
966 static It fastUpperBound(It First, It Last, const T &Value, Compare Comp) {
967   size_t Size = std::distance(First, Last);
968   assert(Size != 0);
969   while (Size != 1) {
970     size_t H = Size / 2;
971     const It MI = First + H;
972     Size -= H;
973     First = Comp(Value, *MI) ? First : First + H;
974   }
975   return Comp(Value, *First) ? First : First + 1;
976 }
977 
978 const SectionPiece *MergeInputSection::getSectionPiece(uint64_t Offset) const {
979   uint64_t Size = this->Data.size();
980   if (Offset >= Size)
981     fatal(toString(this) + ": entry is past the end of the section");
982 
983   // Find the element this offset points to.
984   auto I = fastUpperBound(
985       Pieces.begin(), Pieces.end(), Offset,
986       [](const uint64_t &A, const SectionPiece &B) { return A < B.InputOff; });
987   --I;
988   return &*I;
989 }
990 
991 // Returns the offset in an output section for a given input offset.
992 // Because contents of a mergeable section is not contiguous in output,
993 // it is not just an addition to a base output offset.
994 uint64_t MergeInputSection::getOffset(uint64_t Offset) const {
995   // Initialize OffsetMap lazily.
996   llvm::call_once(InitOffsetMap, [&] {
997     OffsetMap.reserve(Pieces.size());
998     for (const SectionPiece &Piece : Pieces)
999       OffsetMap[Piece.InputOff] = Piece.OutputOff;
1000   });
1001 
1002   // Find a string starting at a given offset.
1003   auto It = OffsetMap.find(Offset);
1004   if (It != OffsetMap.end())
1005     return It->second;
1006 
1007   if (!this->Live)
1008     return 0;
1009 
1010   // If Offset is not at beginning of a section piece, it is not in the map.
1011   // In that case we need to search from the original section piece vector.
1012   const SectionPiece &Piece = *this->getSectionPiece(Offset);
1013   if (!Piece.Live)
1014     return 0;
1015 
1016   uint64_t Addend = Offset - Piece.InputOff;
1017   return Piece.OutputOff + Addend;
1018 }
1019 
1020 template InputSection::InputSection(ObjFile<ELF32LE> *, const ELF32LE::Shdr *,
1021                                     StringRef);
1022 template InputSection::InputSection(ObjFile<ELF32BE> *, const ELF32BE::Shdr *,
1023                                     StringRef);
1024 template InputSection::InputSection(ObjFile<ELF64LE> *, const ELF64LE::Shdr *,
1025                                     StringRef);
1026 template InputSection::InputSection(ObjFile<ELF64BE> *, const ELF64BE::Shdr *,
1027                                     StringRef);
1028 
1029 template std::string InputSectionBase::getLocation<ELF32LE>(uint64_t);
1030 template std::string InputSectionBase::getLocation<ELF32BE>(uint64_t);
1031 template std::string InputSectionBase::getLocation<ELF64LE>(uint64_t);
1032 template std::string InputSectionBase::getLocation<ELF64BE>(uint64_t);
1033 
1034 template std::string InputSectionBase::getSrcMsg<ELF32LE>(uint64_t);
1035 template std::string InputSectionBase::getSrcMsg<ELF32BE>(uint64_t);
1036 template std::string InputSectionBase::getSrcMsg<ELF64LE>(uint64_t);
1037 template std::string InputSectionBase::getSrcMsg<ELF64BE>(uint64_t);
1038 
1039 template std::string InputSectionBase::getObjMsg<ELF32LE>(uint64_t);
1040 template std::string InputSectionBase::getObjMsg<ELF32BE>(uint64_t);
1041 template std::string InputSectionBase::getObjMsg<ELF64LE>(uint64_t);
1042 template std::string InputSectionBase::getObjMsg<ELF64BE>(uint64_t);
1043 
1044 template void InputSection::writeTo<ELF32LE>(uint8_t *);
1045 template void InputSection::writeTo<ELF32BE>(uint8_t *);
1046 template void InputSection::writeTo<ELF64LE>(uint8_t *);
1047 template void InputSection::writeTo<ELF64BE>(uint8_t *);
1048 
1049 template ObjFile<ELF32LE> *InputSectionBase::getFile<ELF32LE>() const;
1050 template ObjFile<ELF32BE> *InputSectionBase::getFile<ELF32BE>() const;
1051 template ObjFile<ELF64LE> *InputSectionBase::getFile<ELF64LE>() const;
1052 template ObjFile<ELF64BE> *InputSectionBase::getFile<ELF64BE>() const;
1053 
1054 template MergeInputSection::MergeInputSection(ObjFile<ELF32LE> *,
1055                                               const ELF32LE::Shdr *, StringRef);
1056 template MergeInputSection::MergeInputSection(ObjFile<ELF32BE> *,
1057                                               const ELF32BE::Shdr *, StringRef);
1058 template MergeInputSection::MergeInputSection(ObjFile<ELF64LE> *,
1059                                               const ELF64LE::Shdr *, StringRef);
1060 template MergeInputSection::MergeInputSection(ObjFile<ELF64BE> *,
1061                                               const ELF64BE::Shdr *, StringRef);
1062 
1063 template EhInputSection::EhInputSection(ObjFile<ELF32LE> *,
1064                                         const ELF32LE::Shdr *, StringRef);
1065 template EhInputSection::EhInputSection(ObjFile<ELF32BE> *,
1066                                         const ELF32BE::Shdr *, StringRef);
1067 template EhInputSection::EhInputSection(ObjFile<ELF64LE> *,
1068                                         const ELF64LE::Shdr *, StringRef);
1069 template EhInputSection::EhInputSection(ObjFile<ELF64BE> *,
1070                                         const ELF64BE::Shdr *, StringRef);
1071 
1072 template void EhInputSection::split<ELF32LE>();
1073 template void EhInputSection::split<ELF32BE>();
1074 template void EhInputSection::split<ELF64LE>();
1075 template void EhInputSection::split<ELF64BE>();
1076