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