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