]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/ELF/InputSection.cpp
Merge ACPICA 20170929 (take 2).
[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   if (!File)
280     return ("(internal):(" + Name + "+0x" + utohexstr(Off) + ")").str();
281   std::string Filename = File->getName();
282
283   std::string Archive;
284   if (!File->ArchiveName.empty())
285     Archive = (" in archive " + File->ArchiveName).str();
286
287   // Find a symbol that encloses a given location.
288   for (SymbolBody *B : getFile<ELFT>()->getSymbols())
289     if (auto *D = dyn_cast<DefinedRegular>(B))
290       if (D->Section == this && D->Value <= Off && Off < D->Value + D->Size)
291         return Filename + ":(" + toString(*D) + ")" + Archive;
292
293   // If there's no symbol, print out the offset in the section.
294   return (Filename + ":(" + Name + "+0x" + utohexstr(Off) + ")" + Archive)
295       .str();
296 }
297
298 InputSectionBase InputSectionBase::Discarded;
299
300 InputSection::InputSection(uint64_t Flags, uint32_t Type, uint32_t Alignment,
301                            ArrayRef<uint8_t> Data, StringRef Name, Kind K)
302     : InputSectionBase(nullptr, Flags, Type,
303                        /*Entsize*/ 0, /*Link*/ 0, /*Info*/ 0, Alignment, Data,
304                        Name, K) {}
305
306 template <class ELFT>
307 InputSection::InputSection(elf::ObjectFile<ELFT> *F,
308                            const typename ELFT::Shdr *Header, StringRef Name)
309     : InputSectionBase(F, Header, Name, InputSectionBase::Regular) {}
310
311 bool InputSection::classof(const SectionBase *S) {
312   return S->kind() == SectionBase::Regular ||
313          S->kind() == SectionBase::Synthetic;
314 }
315
316 bool InputSectionBase::classof(const SectionBase *S) {
317   return S->kind() != Output;
318 }
319
320 OutputSection *InputSection::getParent() const {
321   return cast_or_null<OutputSection>(Parent);
322 }
323
324 // Copy SHT_GROUP section contents. Used only for the -r option.
325 template <class ELFT> void InputSection::copyShtGroup(uint8_t *Buf) {
326   // ELFT::Word is the 32-bit integral type in the target endianness.
327   typedef typename ELFT::Word u32;
328   ArrayRef<u32> From = getDataAs<u32>();
329   auto *To = reinterpret_cast<u32 *>(Buf);
330
331   // The first entry is not a section number but a flag.
332   *To++ = From[0];
333
334   // Adjust section numbers because section numbers in an input object
335   // files are different in the output.
336   ArrayRef<InputSectionBase *> Sections = this->File->getSections();
337   for (uint32_t Idx : From.slice(1))
338     *To++ = Sections[Idx]->getOutputSection()->SectionIndex;
339 }
340
341 InputSectionBase *InputSection::getRelocatedSection() {
342   assert(this->Type == SHT_RELA || this->Type == SHT_REL);
343   ArrayRef<InputSectionBase *> Sections = this->File->getSections();
344   return Sections[this->Info];
345 }
346
347 // This is used for -r and --emit-relocs. We can't use memcpy to copy
348 // relocations because we need to update symbol table offset and section index
349 // for each relocation. So we copy relocations one by one.
350 template <class ELFT, class RelTy>
351 void InputSection::copyRelocations(uint8_t *Buf, ArrayRef<RelTy> Rels) {
352   InputSectionBase *RelocatedSection = getRelocatedSection();
353
354   // Loop is slow and have complexity O(N*M), where N - amount of
355   // relocations and M - amount of symbols in symbol table.
356   // That happens because getSymbolIndex(...) call below performs
357   // simple linear search.
358   for (const RelTy &Rel : Rels) {
359     uint32_t Type = Rel.getType(Config->IsMips64EL);
360     SymbolBody &Body = this->getFile<ELFT>()->getRelocTargetSym(Rel);
361
362     auto *P = reinterpret_cast<typename ELFT::Rela *>(Buf);
363     Buf += sizeof(RelTy);
364
365     if (Config->IsRela)
366       P->r_addend = getAddend<ELFT>(Rel);
367
368     // Output section VA is zero for -r, so r_offset is an offset within the
369     // section, but for --emit-relocs it is an virtual address.
370     P->r_offset = RelocatedSection->getOutputSection()->Addr +
371                   RelocatedSection->getOffset(Rel.r_offset);
372     P->setSymbolAndType(InX::SymTab->getSymbolIndex(&Body), Type,
373                         Config->IsMips64EL);
374
375     if (Body.Type == STT_SECTION) {
376       // We combine multiple section symbols into only one per
377       // section. This means we have to update the addend. That is
378       // trivial for Elf_Rela, but for Elf_Rel we have to write to the
379       // section data. We do that by adding to the Relocation vector.
380
381       // .eh_frame is horribly special and can reference discarded sections. To
382       // avoid having to parse and recreate .eh_frame, we just replace any
383       // relocation in it pointing to discarded sections with R_*_NONE, which
384       // hopefully creates a frame that is ignored at runtime.
385       SectionBase *Section = cast<DefinedRegular>(Body).Section;
386       if (Section == &InputSection::Discarded) {
387         P->setSymbolAndType(0, 0, false);
388         continue;
389       }
390
391       if (Config->IsRela) {
392         P->r_addend += Body.getVA() - Section->getOutputSection()->Addr;
393       } else if (Config->Relocatable) {
394         const uint8_t *BufLoc = RelocatedSection->Data.begin() + Rel.r_offset;
395         RelocatedSection->Relocations.push_back(
396             {R_ABS, Type, Rel.r_offset, Target->getImplicitAddend(BufLoc, Type),
397              &Body});
398       }
399     }
400
401   }
402 }
403
404 // The ARM and AArch64 ABI handle pc-relative relocations to undefined weak
405 // references specially. The general rule is that the value of the symbol in
406 // this context is the address of the place P. A further special case is that
407 // branch relocations to an undefined weak reference resolve to the next
408 // instruction.
409 static uint32_t getARMUndefinedRelativeWeakVA(uint32_t Type, uint32_t A,
410                                               uint32_t P) {
411   switch (Type) {
412   // Unresolved branch relocations to weak references resolve to next
413   // instruction, this will be either 2 or 4 bytes on from P.
414   case R_ARM_THM_JUMP11:
415     return P + 2 + A;
416   case R_ARM_CALL:
417   case R_ARM_JUMP24:
418   case R_ARM_PC24:
419   case R_ARM_PLT32:
420   case R_ARM_PREL31:
421   case R_ARM_THM_JUMP19:
422   case R_ARM_THM_JUMP24:
423     return P + 4 + A;
424   case R_ARM_THM_CALL:
425     // We don't want an interworking BLX to ARM
426     return P + 5 + A;
427   // Unresolved non branch pc-relative relocations
428   // R_ARM_TARGET2 which can be resolved relatively is not present as it never
429   // targets a weak-reference.
430   case R_ARM_MOVW_PREL_NC:
431   case R_ARM_MOVT_PREL:
432   case R_ARM_REL32:
433   case R_ARM_THM_MOVW_PREL_NC:
434   case R_ARM_THM_MOVT_PREL:
435     return P + A;
436   }
437   llvm_unreachable("ARM pc-relative relocation expected\n");
438 }
439
440 // The comment above getARMUndefinedRelativeWeakVA applies to this function.
441 static uint64_t getAArch64UndefinedRelativeWeakVA(uint64_t Type, uint64_t A,
442                                                   uint64_t P) {
443   switch (Type) {
444   // Unresolved branch relocations to weak references resolve to next
445   // instruction, this is 4 bytes on from P.
446   case R_AARCH64_CALL26:
447   case R_AARCH64_CONDBR19:
448   case R_AARCH64_JUMP26:
449   case R_AARCH64_TSTBR14:
450     return P + 4 + A;
451   // Unresolved non branch pc-relative relocations
452   case R_AARCH64_PREL16:
453   case R_AARCH64_PREL32:
454   case R_AARCH64_PREL64:
455   case R_AARCH64_ADR_PREL_LO21:
456     return P + A;
457   }
458   llvm_unreachable("AArch64 pc-relative relocation expected\n");
459 }
460
461 // ARM SBREL relocations are of the form S + A - B where B is the static base
462 // The ARM ABI defines base to be "addressing origin of the output segment
463 // defining the symbol S". We defined the "addressing origin"/static base to be
464 // the base of the PT_LOAD segment containing the Body.
465 // The procedure call standard only defines a Read Write Position Independent
466 // RWPI variant so in practice we should expect the static base to be the base
467 // of the RW segment.
468 static uint64_t getARMStaticBase(const SymbolBody &Body) {
469   OutputSection *OS = Body.getOutputSection();
470   if (!OS || !OS->FirstInPtLoad)
471     fatal("SBREL relocation to " + Body.getName() + " without static base");
472   return OS->FirstInPtLoad->Addr;
473 }
474
475 static uint64_t getRelocTargetVA(uint32_t Type, int64_t A, uint64_t P,
476                                  const SymbolBody &Body, RelExpr Expr) {
477   switch (Expr) {
478   case R_ABS:
479   case R_RELAX_GOT_PC_NOPIC:
480     return Body.getVA(A);
481   case R_ARM_SBREL:
482     return Body.getVA(A) - getARMStaticBase(Body);
483   case R_GOT:
484   case R_RELAX_TLS_GD_TO_IE_ABS:
485     return Body.getGotVA() + A;
486   case R_GOTONLY_PC:
487     return InX::Got->getVA() + A - P;
488   case R_GOTONLY_PC_FROM_END:
489     return InX::Got->getVA() + A - P + InX::Got->getSize();
490   case R_GOTREL:
491     return Body.getVA(A) - InX::Got->getVA();
492   case R_GOTREL_FROM_END:
493     return Body.getVA(A) - InX::Got->getVA() - InX::Got->getSize();
494   case R_GOT_FROM_END:
495   case R_RELAX_TLS_GD_TO_IE_END:
496     return Body.getGotOffset() + A - InX::Got->getSize();
497   case R_GOT_OFF:
498     return Body.getGotOffset() + A;
499   case R_GOT_PAGE_PC:
500   case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
501     return getAArch64Page(Body.getGotVA() + A) - getAArch64Page(P);
502   case R_GOT_PC:
503   case R_RELAX_TLS_GD_TO_IE:
504     return Body.getGotVA() + A - P;
505   case R_HINT:
506   case R_NONE:
507   case R_TLSDESC_CALL:
508     llvm_unreachable("cannot relocate hint relocs");
509   case R_MIPS_GOTREL:
510     return Body.getVA(A) - InX::MipsGot->getGp();
511   case R_MIPS_GOT_GP:
512     return InX::MipsGot->getGp() + A;
513   case R_MIPS_GOT_GP_PC: {
514     // R_MIPS_LO16 expression has R_MIPS_GOT_GP_PC type iif the target
515     // is _gp_disp symbol. In that case we should use the following
516     // formula for calculation "AHL + GP - P + 4". For details see p. 4-19 at
517     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
518     uint64_t V = InX::MipsGot->getGp() + A - P;
519     if (Type == R_MIPS_LO16)
520       V += 4;
521     return V;
522   }
523   case R_MIPS_GOT_LOCAL_PAGE:
524     // If relocation against MIPS local symbol requires GOT entry, this entry
525     // should be initialized by 'page address'. This address is high 16-bits
526     // of sum the symbol's value and the addend.
527     return InX::MipsGot->getVA() + InX::MipsGot->getPageEntryOffset(Body, A) -
528            InX::MipsGot->getGp();
529   case R_MIPS_GOT_OFF:
530   case R_MIPS_GOT_OFF32:
531     // In case of MIPS if a GOT relocation has non-zero addend this addend
532     // should be applied to the GOT entry content not to the GOT entry offset.
533     // That is why we use separate expression type.
534     return InX::MipsGot->getVA() + InX::MipsGot->getBodyEntryOffset(Body, A) -
535            InX::MipsGot->getGp();
536   case R_MIPS_TLSGD:
537     return InX::MipsGot->getVA() + InX::MipsGot->getTlsOffset() +
538            InX::MipsGot->getGlobalDynOffset(Body) - InX::MipsGot->getGp();
539   case R_MIPS_TLSLD:
540     return InX::MipsGot->getVA() + InX::MipsGot->getTlsOffset() +
541            InX::MipsGot->getTlsIndexOff() - InX::MipsGot->getGp();
542   case R_PAGE_PC:
543   case R_PLT_PAGE_PC: {
544     uint64_t Dest;
545     if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak())
546       Dest = getAArch64Page(A);
547     else
548       Dest = getAArch64Page(Body.getVA(A));
549     return Dest - getAArch64Page(P);
550   }
551   case R_PC: {
552     uint64_t Dest;
553     if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak()) {
554       // On ARM and AArch64 a branch to an undefined weak resolves to the
555       // next instruction, otherwise the place.
556       if (Config->EMachine == EM_ARM)
557         Dest = getARMUndefinedRelativeWeakVA(Type, A, P);
558       else if (Config->EMachine == EM_AARCH64)
559         Dest = getAArch64UndefinedRelativeWeakVA(Type, A, P);
560       else
561         Dest = Body.getVA(A);
562     } else {
563       Dest = Body.getVA(A);
564     }
565     return Dest - P;
566   }
567   case R_PLT:
568     return Body.getPltVA() + A;
569   case R_PLT_PC:
570   case R_PPC_PLT_OPD:
571     return Body.getPltVA() + A - P;
572   case R_PPC_OPD: {
573     uint64_t SymVA = Body.getVA(A);
574     // If we have an undefined weak symbol, we might get here with a symbol
575     // address of zero. That could overflow, but the code must be unreachable,
576     // so don't bother doing anything at all.
577     if (!SymVA)
578       return 0;
579     if (Out::Opd) {
580       // If this is a local call, and we currently have the address of a
581       // function-descriptor, get the underlying code address instead.
582       uint64_t OpdStart = Out::Opd->Addr;
583       uint64_t OpdEnd = OpdStart + Out::Opd->Size;
584       bool InOpd = OpdStart <= SymVA && SymVA < OpdEnd;
585       if (InOpd)
586         SymVA = read64be(&Out::OpdBuf[SymVA - OpdStart]);
587     }
588     return SymVA - P;
589   }
590   case R_PPC_TOC:
591     return getPPC64TocBase() + A;
592   case R_RELAX_GOT_PC:
593     return Body.getVA(A) - P;
594   case R_RELAX_TLS_GD_TO_LE:
595   case R_RELAX_TLS_IE_TO_LE:
596   case R_RELAX_TLS_LD_TO_LE:
597   case R_TLS:
598     // A weak undefined TLS symbol resolves to the base of the TLS
599     // block, i.e. gets a value of zero. If we pass --gc-sections to
600     // lld and .tbss is not referenced, it gets reclaimed and we don't
601     // create a TLS program header. Therefore, we resolve this
602     // statically to zero.
603     if (Body.isTls() && (Body.isLazy() || Body.isUndefined()) &&
604         Body.symbol()->isWeak())
605       return 0;
606     if (Target->TcbSize)
607       return Body.getVA(A) + alignTo(Target->TcbSize, Out::TlsPhdr->p_align);
608     return Body.getVA(A) - Out::TlsPhdr->p_memsz;
609   case R_RELAX_TLS_GD_TO_LE_NEG:
610   case R_NEG_TLS:
611     return Out::TlsPhdr->p_memsz - Body.getVA(A);
612   case R_SIZE:
613     return A; // Body.getSize was already folded into the addend.
614   case R_TLSDESC:
615     return InX::Got->getGlobalDynAddr(Body) + A;
616   case R_TLSDESC_PAGE:
617     return getAArch64Page(InX::Got->getGlobalDynAddr(Body) + A) -
618            getAArch64Page(P);
619   case R_TLSGD:
620     return InX::Got->getGlobalDynOffset(Body) + A - InX::Got->getSize();
621   case R_TLSGD_PC:
622     return InX::Got->getGlobalDynAddr(Body) + A - P;
623   case R_TLSLD:
624     return InX::Got->getTlsIndexOff() + A - InX::Got->getSize();
625   case R_TLSLD_PC:
626     return InX::Got->getTlsIndexVA() + A - P;
627   }
628   llvm_unreachable("Invalid expression");
629 }
630
631 // This function applies relocations to sections without SHF_ALLOC bit.
632 // Such sections are never mapped to memory at runtime. Debug sections are
633 // an example. Relocations in non-alloc sections are much easier to
634 // handle than in allocated sections because it will never need complex
635 // treatement such as GOT or PLT (because at runtime no one refers them).
636 // So, we handle relocations for non-alloc sections directly in this
637 // function as a performance optimization.
638 template <class ELFT, class RelTy>
639 void InputSection::relocateNonAlloc(uint8_t *Buf, ArrayRef<RelTy> Rels) {
640   for (const RelTy &Rel : Rels) {
641     uint32_t Type = Rel.getType(Config->IsMips64EL);
642     uint64_t Offset = getOffset(Rel.r_offset);
643     uint8_t *BufLoc = Buf + Offset;
644     int64_t Addend = getAddend<ELFT>(Rel);
645     if (!RelTy::IsRela)
646       Addend += Target->getImplicitAddend(BufLoc, Type);
647
648     SymbolBody &Sym = this->getFile<ELFT>()->getRelocTargetSym(Rel);
649     RelExpr Expr = Target->getRelExpr(Type, Sym, BufLoc);
650     if (Expr == R_NONE)
651       continue;
652     if (Expr != R_ABS) {
653       error(this->getLocation<ELFT>(Offset) + ": has non-ABS reloc");
654       return;
655     }
656
657     uint64_t AddrLoc = getParent()->Addr + Offset;
658     uint64_t SymVA = 0;
659     if (!Sym.isTls() || Out::TlsPhdr)
660       SymVA = SignExtend64<sizeof(typename ELFT::uint) * 8>(
661           getRelocTargetVA(Type, Addend, AddrLoc, Sym, R_ABS));
662     Target->relocateOne(BufLoc, Type, SymVA);
663   }
664 }
665
666 template <class ELFT> elf::ObjectFile<ELFT> *InputSectionBase::getFile() const {
667   return cast_or_null<elf::ObjectFile<ELFT>>(File);
668 }
669
670 template <class ELFT>
671 void InputSectionBase::relocate(uint8_t *Buf, uint8_t *BufEnd) {
672   if (Flags & SHF_ALLOC)
673     relocateAlloc(Buf, BufEnd);
674   else
675     relocateNonAlloc<ELFT>(Buf, BufEnd);
676 }
677
678 template <class ELFT>
679 void InputSectionBase::relocateNonAlloc(uint8_t *Buf, uint8_t *BufEnd) {
680   // scanReloc function in Writer.cpp constructs Relocations
681   // vector only for SHF_ALLOC'ed sections. For other sections,
682   // we handle relocations directly here.
683   auto *IS = cast<InputSection>(this);
684   assert(!(IS->Flags & SHF_ALLOC));
685   if (IS->AreRelocsRela)
686     IS->relocateNonAlloc<ELFT>(Buf, IS->template relas<ELFT>());
687   else
688     IS->relocateNonAlloc<ELFT>(Buf, IS->template rels<ELFT>());
689 }
690
691 void InputSectionBase::relocateAlloc(uint8_t *Buf, uint8_t *BufEnd) {
692   assert(Flags & SHF_ALLOC);
693   const unsigned Bits = Config->Wordsize * 8;
694   for (const Relocation &Rel : Relocations) {
695     uint64_t Offset = getOffset(Rel.Offset);
696     uint8_t *BufLoc = Buf + Offset;
697     uint32_t Type = Rel.Type;
698
699     uint64_t AddrLoc = getOutputSection()->Addr + Offset;
700     RelExpr Expr = Rel.Expr;
701     uint64_t TargetVA = SignExtend64(
702         getRelocTargetVA(Type, Rel.Addend, AddrLoc, *Rel.Sym, Expr), Bits);
703
704     switch (Expr) {
705     case R_RELAX_GOT_PC:
706     case R_RELAX_GOT_PC_NOPIC:
707       Target->relaxGot(BufLoc, TargetVA);
708       break;
709     case R_RELAX_TLS_IE_TO_LE:
710       Target->relaxTlsIeToLe(BufLoc, Type, TargetVA);
711       break;
712     case R_RELAX_TLS_LD_TO_LE:
713       Target->relaxTlsLdToLe(BufLoc, Type, TargetVA);
714       break;
715     case R_RELAX_TLS_GD_TO_LE:
716     case R_RELAX_TLS_GD_TO_LE_NEG:
717       Target->relaxTlsGdToLe(BufLoc, Type, TargetVA);
718       break;
719     case R_RELAX_TLS_GD_TO_IE:
720     case R_RELAX_TLS_GD_TO_IE_ABS:
721     case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
722     case R_RELAX_TLS_GD_TO_IE_END:
723       Target->relaxTlsGdToIe(BufLoc, Type, TargetVA);
724       break;
725     case R_PPC_PLT_OPD:
726       // Patch a nop (0x60000000) to a ld.
727       if (BufLoc + 8 <= BufEnd && read32be(BufLoc + 4) == 0x60000000)
728         write32be(BufLoc + 4, 0xe8410028); // ld %r2, 40(%r1)
729       LLVM_FALLTHROUGH;
730     default:
731       Target->relocateOne(BufLoc, Type, TargetVA);
732       break;
733     }
734   }
735 }
736
737 template <class ELFT> void InputSection::writeTo(uint8_t *Buf) {
738   if (this->Type == SHT_NOBITS)
739     return;
740
741   if (auto *S = dyn_cast<SyntheticSection>(this)) {
742     S->writeTo(Buf + OutSecOff);
743     return;
744   }
745
746   // If -r or --emit-relocs is given, then an InputSection
747   // may be a relocation section.
748   if (this->Type == SHT_RELA) {
749     copyRelocations<ELFT>(Buf + OutSecOff,
750                           this->template getDataAs<typename ELFT::Rela>());
751     return;
752   }
753   if (this->Type == SHT_REL) {
754     copyRelocations<ELFT>(Buf + OutSecOff,
755                           this->template getDataAs<typename ELFT::Rel>());
756     return;
757   }
758
759   // If -r is given, we may have a SHT_GROUP section.
760   if (this->Type == SHT_GROUP) {
761     copyShtGroup<ELFT>(Buf + OutSecOff);
762     return;
763   }
764
765   // Copy section contents from source object file to output file
766   // and then apply relocations.
767   memcpy(Buf + OutSecOff, Data.data(), Data.size());
768   uint8_t *BufEnd = Buf + OutSecOff + Data.size();
769   this->relocate<ELFT>(Buf, BufEnd);
770 }
771
772 void InputSection::replace(InputSection *Other) {
773   this->Alignment = std::max(this->Alignment, Other->Alignment);
774   Other->Repl = this->Repl;
775   Other->Live = false;
776 }
777
778 template <class ELFT>
779 EhInputSection::EhInputSection(elf::ObjectFile<ELFT> *F,
780                                const typename ELFT::Shdr *Header,
781                                StringRef Name)
782     : InputSectionBase(F, Header, Name, InputSectionBase::EHFrame) {
783   // Mark .eh_frame sections as live by default because there are
784   // usually no relocations that point to .eh_frames. Otherwise,
785   // the garbage collector would drop all .eh_frame sections.
786   this->Live = true;
787 }
788
789 SyntheticSection *EhInputSection::getParent() const {
790   return cast_or_null<SyntheticSection>(Parent);
791 }
792
793 bool EhInputSection::classof(const SectionBase *S) {
794   return S->kind() == InputSectionBase::EHFrame;
795 }
796
797 // Returns the index of the first relocation that points to a region between
798 // Begin and Begin+Size.
799 template <class IntTy, class RelTy>
800 static unsigned getReloc(IntTy Begin, IntTy Size, const ArrayRef<RelTy> &Rels,
801                          unsigned &RelocI) {
802   // Start search from RelocI for fast access. That works because the
803   // relocations are sorted in .eh_frame.
804   for (unsigned N = Rels.size(); RelocI < N; ++RelocI) {
805     const RelTy &Rel = Rels[RelocI];
806     if (Rel.r_offset < Begin)
807       continue;
808
809     if (Rel.r_offset < Begin + Size)
810       return RelocI;
811     return -1;
812   }
813   return -1;
814 }
815
816 // .eh_frame is a sequence of CIE or FDE records.
817 // This function splits an input section into records and returns them.
818 template <class ELFT> void EhInputSection::split() {
819   // Early exit if already split.
820   if (!this->Pieces.empty())
821     return;
822
823   if (this->NumRelocations) {
824     if (this->AreRelocsRela)
825       split<ELFT>(this->relas<ELFT>());
826     else
827       split<ELFT>(this->rels<ELFT>());
828     return;
829   }
830   split<ELFT>(makeArrayRef<typename ELFT::Rela>(nullptr, nullptr));
831 }
832
833 template <class ELFT, class RelTy>
834 void EhInputSection::split(ArrayRef<RelTy> Rels) {
835   ArrayRef<uint8_t> Data = this->Data;
836   unsigned RelI = 0;
837   for (size_t Off = 0, End = Data.size(); Off != End;) {
838     size_t Size = readEhRecordSize<ELFT>(this, Off);
839     this->Pieces.emplace_back(Off, this, Size, getReloc(Off, Size, Rels, RelI));
840     // The empty record is the end marker.
841     if (Size == 4)
842       break;
843     Off += Size;
844   }
845 }
846
847 static size_t findNull(ArrayRef<uint8_t> A, size_t EntSize) {
848   // Optimize the common case.
849   StringRef S((const char *)A.data(), A.size());
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 = this->Flags & SHF_ALLOC;
870   while (!Data.empty()) {
871     size_t End = findNull(Data, EntSize);
872     if (End == StringRef::npos)
873       fatal(toString(this) + ": string is not null terminated");
874     size_t Size = End + EntSize;
875     Pieces.emplace_back(Off, !IsAlloc);
876     Hashes.push_back(hash_value(toStringRef(Data.slice(0, Size))));
877     Data = Data.slice(Size);
878     Off += Size;
879   }
880 }
881
882 // Split non-SHF_STRINGS section. Such section is a sequence of
883 // fixed size records.
884 void MergeInputSection::splitNonStrings(ArrayRef<uint8_t> Data,
885                                         size_t EntSize) {
886   size_t Size = Data.size();
887   assert((Size % EntSize) == 0);
888   bool IsAlloc = this->Flags & SHF_ALLOC;
889   for (unsigned I = 0, N = Size; I != N; I += EntSize) {
890     Hashes.push_back(hash_value(toStringRef(Data.slice(I, EntSize))));
891     Pieces.emplace_back(I, !IsAlloc);
892   }
893 }
894
895 template <class ELFT>
896 MergeInputSection::MergeInputSection(elf::ObjectFile<ELFT> *F,
897                                      const typename ELFT::Shdr *Header,
898                                      StringRef Name)
899     : InputSectionBase(F, Header, Name, InputSectionBase::Merge) {}
900
901 // This function is called after we obtain a complete list of input sections
902 // that need to be linked. This is responsible to split section contents
903 // into small chunks for further processing.
904 //
905 // Note that this function is called from parallel_for_each. This must be
906 // thread-safe (i.e. no memory allocation from the pools).
907 void MergeInputSection::splitIntoPieces() {
908   ArrayRef<uint8_t> Data = this->Data;
909   uint64_t EntSize = this->Entsize;
910   if (this->Flags & SHF_STRINGS)
911     splitStrings(Data, EntSize);
912   else
913     splitNonStrings(Data, EntSize);
914
915   if (Config->GcSections && (this->Flags & SHF_ALLOC))
916     for (uint64_t Off : LiveOffsets)
917       this->getSectionPiece(Off)->Live = true;
918 }
919
920 bool MergeInputSection::classof(const SectionBase *S) {
921   return S->kind() == InputSectionBase::Merge;
922 }
923
924 // Do binary search to get a section piece at a given input offset.
925 SectionPiece *MergeInputSection::getSectionPiece(uint64_t Offset) {
926   auto *This = static_cast<const MergeInputSection *>(this);
927   return const_cast<SectionPiece *>(This->getSectionPiece(Offset));
928 }
929
930 template <class It, class T, class Compare>
931 static It fastUpperBound(It First, It Last, const T &Value, Compare Comp) {
932   size_t Size = std::distance(First, Last);
933   assert(Size != 0);
934   while (Size != 1) {
935     size_t H = Size / 2;
936     const It MI = First + H;
937     Size -= H;
938     First = Comp(Value, *MI) ? First : First + H;
939   }
940   return Comp(Value, *First) ? First : First + 1;
941 }
942
943 const SectionPiece *MergeInputSection::getSectionPiece(uint64_t Offset) const {
944   uint64_t Size = this->Data.size();
945   if (Offset >= Size)
946     fatal(toString(this) + ": entry is past the end of the section");
947
948   // Find the element this offset points to.
949   auto I = fastUpperBound(
950       Pieces.begin(), Pieces.end(), Offset,
951       [](const uint64_t &A, const SectionPiece &B) { return A < B.InputOff; });
952   --I;
953   return &*I;
954 }
955
956 // Returns the offset in an output section for a given input offset.
957 // Because contents of a mergeable section is not contiguous in output,
958 // it is not just an addition to a base output offset.
959 uint64_t MergeInputSection::getOffset(uint64_t Offset) const {
960   // Initialize OffsetMap lazily.
961   llvm::call_once(InitOffsetMap, [&] {
962     OffsetMap.reserve(Pieces.size());
963     for (const SectionPiece &Piece : Pieces)
964       OffsetMap[Piece.InputOff] = Piece.OutputOff;
965   });
966
967   // Find a string starting at a given offset.
968   auto It = OffsetMap.find(Offset);
969   if (It != OffsetMap.end())
970     return It->second;
971
972   if (!this->Live)
973     return 0;
974
975   // If Offset is not at beginning of a section piece, it is not in the map.
976   // In that case we need to search from the original section piece vector.
977   const SectionPiece &Piece = *this->getSectionPiece(Offset);
978   if (!Piece.Live)
979     return 0;
980
981   uint64_t Addend = Offset - Piece.InputOff;
982   return Piece.OutputOff + Addend;
983 }
984
985 template InputSection::InputSection(elf::ObjectFile<ELF32LE> *,
986                                     const ELF32LE::Shdr *, StringRef);
987 template InputSection::InputSection(elf::ObjectFile<ELF32BE> *,
988                                     const ELF32BE::Shdr *, StringRef);
989 template InputSection::InputSection(elf::ObjectFile<ELF64LE> *,
990                                     const ELF64LE::Shdr *, StringRef);
991 template InputSection::InputSection(elf::ObjectFile<ELF64BE> *,
992                                     const ELF64BE::Shdr *, StringRef);
993
994 template std::string InputSectionBase::getLocation<ELF32LE>(uint64_t);
995 template std::string InputSectionBase::getLocation<ELF32BE>(uint64_t);
996 template std::string InputSectionBase::getLocation<ELF64LE>(uint64_t);
997 template std::string InputSectionBase::getLocation<ELF64BE>(uint64_t);
998
999 template std::string InputSectionBase::getSrcMsg<ELF32LE>(uint64_t);
1000 template std::string InputSectionBase::getSrcMsg<ELF32BE>(uint64_t);
1001 template std::string InputSectionBase::getSrcMsg<ELF64LE>(uint64_t);
1002 template std::string InputSectionBase::getSrcMsg<ELF64BE>(uint64_t);
1003
1004 template std::string InputSectionBase::getObjMsg<ELF32LE>(uint64_t);
1005 template std::string InputSectionBase::getObjMsg<ELF32BE>(uint64_t);
1006 template std::string InputSectionBase::getObjMsg<ELF64LE>(uint64_t);
1007 template std::string InputSectionBase::getObjMsg<ELF64BE>(uint64_t);
1008
1009 template void InputSection::writeTo<ELF32LE>(uint8_t *);
1010 template void InputSection::writeTo<ELF32BE>(uint8_t *);
1011 template void InputSection::writeTo<ELF64LE>(uint8_t *);
1012 template void InputSection::writeTo<ELF64BE>(uint8_t *);
1013
1014 template elf::ObjectFile<ELF32LE> *InputSectionBase::getFile<ELF32LE>() const;
1015 template elf::ObjectFile<ELF32BE> *InputSectionBase::getFile<ELF32BE>() const;
1016 template elf::ObjectFile<ELF64LE> *InputSectionBase::getFile<ELF64LE>() const;
1017 template elf::ObjectFile<ELF64BE> *InputSectionBase::getFile<ELF64BE>() const;
1018
1019 template MergeInputSection::MergeInputSection(elf::ObjectFile<ELF32LE> *,
1020                                               const ELF32LE::Shdr *, StringRef);
1021 template MergeInputSection::MergeInputSection(elf::ObjectFile<ELF32BE> *,
1022                                               const ELF32BE::Shdr *, StringRef);
1023 template MergeInputSection::MergeInputSection(elf::ObjectFile<ELF64LE> *,
1024                                               const ELF64LE::Shdr *, StringRef);
1025 template MergeInputSection::MergeInputSection(elf::ObjectFile<ELF64BE> *,
1026                                               const ELF64BE::Shdr *, StringRef);
1027
1028 template EhInputSection::EhInputSection(elf::ObjectFile<ELF32LE> *,
1029                                         const ELF32LE::Shdr *, StringRef);
1030 template EhInputSection::EhInputSection(elf::ObjectFile<ELF32BE> *,
1031                                         const ELF32BE::Shdr *, StringRef);
1032 template EhInputSection::EhInputSection(elf::ObjectFile<ELF64LE> *,
1033                                         const ELF64LE::Shdr *, StringRef);
1034 template EhInputSection::EhInputSection(elf::ObjectFile<ELF64BE> *,
1035                                         const ELF64BE::Shdr *, StringRef);
1036
1037 template void EhInputSection::split<ELF32LE>();
1038 template void EhInputSection::split<ELF32BE>();
1039 template void EhInputSection::split<ELF64LE>();
1040 template void EhInputSection::split<ELF64BE>();