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