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