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