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