1 //===- InputSection.cpp ---------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "InputSection.h"
14 #include "InputFiles.h"
15 #include "LinkerScript.h"
17 #include "OutputSections.h"
18 #include "Relocations.h"
19 #include "SyntheticSections.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 "llvm/Support/Threading.h"
30 using namespace llvm::ELF;
31 using namespace llvm::object;
32 using namespace llvm::support;
33 using namespace llvm::support::endian;
34 using namespace llvm::sys;
37 using namespace lld::elf;
39 std::vector<InputSectionBase *> elf::InputSections;
41 // Returns a string to construct an error message.
42 std::string lld::toString(const InputSectionBase *Sec) {
43 return (toString(Sec->File) + ":(" + Sec->Name + ")").str();
47 static ArrayRef<uint8_t> getSectionContents(elf::ObjectFile<ELFT> *File,
48 const typename ELFT::Shdr *Hdr) {
49 if (!File || Hdr->sh_type == SHT_NOBITS)
50 return makeArrayRef<uint8_t>(nullptr, Hdr->sh_size);
51 return check(File->getObj().getSectionContents(Hdr));
54 InputSectionBase::InputSectionBase(InputFile *File, uint64_t Flags,
55 uint32_t Type, uint64_t Entsize,
56 uint32_t Link, uint32_t Info,
57 uint32_t Alignment, ArrayRef<uint8_t> Data,
58 StringRef Name, Kind SectionKind)
59 : SectionBase(SectionKind, Name, Flags, Entsize, Alignment, Type, Info,
61 File(File), Data(Data), Repl(this) {
62 Live = !Config->GcSections || !(Flags & SHF_ALLOC);
65 AreRelocsRela = false;
67 // The ELF spec states that a value of 0 means the section has
68 // no alignment constraits.
69 uint32_t V = std::max<uint64_t>(Alignment, 1);
70 if (!isPowerOf2_64(V))
71 fatal(toString(File) + ": section sh_addralign is not a power of 2");
75 // GNU assembler 2.24 and LLVM 4.0.0's MC (the newest release as of
76 // March 2017) fail to infer section types for sections starting with
77 // ".init_array." or ".fini_array.". They set SHT_PROGBITS instead of
78 // SHF_INIT_ARRAY. As a result, the following assembler directive
79 // creates ".init_array.100" with SHT_PROGBITS, for example.
81 // .section .init_array.100, "aw"
83 // This function forces SHT_{INIT,FINI}_ARRAY so that we can handle
84 // incorrect inputs as if they were correct from the beginning.
85 static uint64_t getType(uint64_t Type, StringRef Name) {
86 if (Type == SHT_PROGBITS && Name.startswith(".init_array."))
87 return SHT_INIT_ARRAY;
88 if (Type == SHT_PROGBITS && Name.startswith(".fini_array."))
89 return SHT_FINI_ARRAY;
94 InputSectionBase::InputSectionBase(elf::ObjectFile<ELFT> *File,
95 const typename ELFT::Shdr *Hdr,
96 StringRef Name, Kind SectionKind)
97 : InputSectionBase(File, Hdr->sh_flags & ~SHF_INFO_LINK,
98 getType(Hdr->sh_type, Name), Hdr->sh_entsize,
99 Hdr->sh_link, Hdr->sh_info, Hdr->sh_addralign,
100 getSectionContents(File, Hdr), Name, SectionKind) {
101 // We reject object files having insanely large alignments even though
102 // they are allowed by the spec. I think 4GB is a reasonable limitation.
103 // We might want to relax this in the future.
104 if (Hdr->sh_addralign > UINT32_MAX)
105 fatal(toString(File) + ": section sh_addralign is too large");
108 size_t InputSectionBase::getSize() const {
109 if (auto *S = dyn_cast<SyntheticSection>(this))
115 uint64_t InputSectionBase::getOffsetInFile() const {
116 const uint8_t *FileStart = (const uint8_t *)File->MB.getBufferStart();
117 const uint8_t *SecStart = Data.begin();
118 return SecStart - FileStart;
121 uint64_t SectionBase::getOffset(uint64_t Offset) const {
124 auto *OS = cast<OutputSection>(this);
125 // For output sections we treat offset -1 as the end of the section.
126 return Offset == uint64_t(-1) ? OS->Size : Offset;
129 return cast<InputSection>(this)->OutSecOff + Offset;
131 auto *IS = cast<InputSection>(this);
132 // For synthetic sections we treat offset -1 as the end of the section.
133 return IS->OutSecOff + (Offset == uint64_t(-1) ? IS->getSize() : Offset);
136 // The file crtbeginT.o has relocations pointing to the start of an empty
137 // .eh_frame that is known to be the first in the link. It does that to
138 // identify the start of the output .eh_frame.
141 const MergeInputSection *MS = cast<MergeInputSection>(this);
143 return MS->MergeSec->OutSecOff + MS->getOffset(Offset);
144 return MS->getOffset(Offset);
146 llvm_unreachable("invalid section kind");
149 OutputSection *SectionBase::getOutputSection() {
150 if (auto *IS = dyn_cast<InputSection>(this))
152 if (auto *MS = dyn_cast<MergeInputSection>(this))
153 return MS->MergeSec ? MS->MergeSec->OutSec : nullptr;
154 if (auto *EH = dyn_cast<EhInputSection>(this))
155 return EH->EHSec->OutSec;
156 return cast<OutputSection>(this);
159 // Uncompress section contents. Note that this function is called
160 // from parallel_for_each, so it must be thread-safe.
161 void InputSectionBase::uncompress() {
162 Decompressor Dec = check(Decompressor::create(Name, toStringRef(Data),
163 Config->IsLE, Config->Is64));
165 size_t Size = Dec.getDecompressedSize();
168 static std::mutex Mu;
169 std::lock_guard<std::mutex> Lock(Mu);
170 OutputBuf = BAlloc.Allocate<char>(Size);
173 if (Error E = Dec.decompress({OutputBuf, Size}))
174 fatal(toString(this) +
175 ": decompress failed: " + llvm::toString(std::move(E)));
176 this->Data = ArrayRef<uint8_t>((uint8_t *)OutputBuf, Size);
177 this->Flags &= ~(uint64_t)SHF_COMPRESSED;
180 uint64_t SectionBase::getOffset(const DefinedRegular &Sym) const {
181 return getOffset(Sym.Value);
184 InputSectionBase *InputSectionBase::getLinkOrderDep() const {
185 if ((Flags & SHF_LINK_ORDER) && Link != 0)
186 return File->getSections()[Link];
190 // Returns a source location string. Used to construct an error message.
191 template <class ELFT>
192 std::string InputSectionBase::getLocation(uint64_t Offset) {
193 // We don't have file for synthetic sections.
194 if (getFile<ELFT>() == nullptr)
195 return (Config->OutputFile + ":(" + Name + "+0x" + utohexstr(Offset) + ")")
198 // First check if we can get desired values from debugging information.
199 std::string LineInfo = getFile<ELFT>()->getLineInfo(this, Offset);
200 if (!LineInfo.empty())
203 // File->SourceFile contains STT_FILE symbol that contains a
204 // source file name. If it's missing, we use an object file name.
205 std::string SrcFile = getFile<ELFT>()->SourceFile;
207 SrcFile = toString(File);
209 // Find a function symbol that encloses a given location.
210 for (SymbolBody *B : getFile<ELFT>()->getSymbols())
211 if (auto *D = dyn_cast<DefinedRegular>(B))
212 if (D->Section == this && D->Type == STT_FUNC)
213 if (D->Value <= Offset && Offset < D->Value + D->Size)
214 return SrcFile + ":(function " + toString(*D) + ")";
216 // If there's no symbol, print out the offset in the section.
217 return (SrcFile + ":(" + Name + "+0x" + utohexstr(Offset) + ")").str();
220 // Returns a source location string. This function is intended to be
221 // used for constructing an error message. The returned message looks
224 // foo.c:42 (/home/alice/possibly/very/long/path/foo.c:42)
226 // Returns an empty string if there's no way to get line info.
227 template <class ELFT> std::string InputSectionBase::getSrcMsg(uint64_t Offset) {
228 // Synthetic sections don't have input files.
229 elf::ObjectFile<ELFT> *File = getFile<ELFT>();
233 Optional<DILineInfo> Info = File->getDILineInfo(this, Offset);
235 // File->SourceFile contains STT_FILE symbol, and that is a last resort.
237 return File->SourceFile;
239 std::string Path = Info->FileName;
240 std::string Filename = path::filename(Path);
241 std::string Lineno = ":" + std::to_string(Info->Line);
242 if (Filename == Path)
243 return Filename + Lineno;
244 return Filename + Lineno + " (" + Path + Lineno + ")";
247 // Returns a filename string along with an optional section name. This
248 // function is intended to be used for constructing an error
249 // message. The returned message looks like this:
251 // path/to/foo.o:(function bar)
255 // path/to/foo.o:(function bar) in archive path/to/bar.a
256 template <class ELFT> std::string InputSectionBase::getObjMsg(uint64_t Off) {
257 // Synthetic sections don't have input files.
258 elf::ObjectFile<ELFT> *File = getFile<ELFT>();
259 std::string Filename = File ? File->getName() : "(internal)";
262 if (!File->ArchiveName.empty())
263 Archive = (" in archive " + File->ArchiveName).str();
265 // Find a symbol that encloses a given location.
266 for (SymbolBody *B : getFile<ELFT>()->getSymbols())
267 if (auto *D = dyn_cast<DefinedRegular>(B))
268 if (D->Section == this && D->Value <= Off && Off < D->Value + D->Size)
269 return Filename + ":(" + toString(*D) + ")" + Archive;
271 // If there's no symbol, print out the offset in the section.
272 return (Filename + ":(" + Name + "+0x" + utohexstr(Off) + ")" + Archive)
276 InputSectionBase InputSectionBase::Discarded;
278 InputSection::InputSection(uint64_t Flags, uint32_t Type, uint32_t Alignment,
279 ArrayRef<uint8_t> Data, StringRef Name, Kind K)
280 : InputSectionBase(nullptr, Flags, Type,
281 /*Entsize*/ 0, /*Link*/ 0, /*Info*/ 0, Alignment, Data,
284 template <class ELFT>
285 InputSection::InputSection(elf::ObjectFile<ELFT> *F,
286 const typename ELFT::Shdr *Header, StringRef Name)
287 : InputSectionBase(F, Header, Name, InputSectionBase::Regular) {}
289 bool InputSection::classof(const SectionBase *S) {
290 return S->kind() == SectionBase::Regular ||
291 S->kind() == SectionBase::Synthetic;
294 bool InputSectionBase::classof(const SectionBase *S) {
295 return S->kind() != Output;
298 void InputSection::copyShtGroup(uint8_t *Buf) {
299 assert(this->Type == SHT_GROUP);
301 ArrayRef<uint32_t> From = getDataAs<uint32_t>();
302 uint32_t *To = reinterpret_cast<uint32_t *>(Buf);
304 // First entry is a flag word, we leave it unchanged.
307 // Here we adjust indices of sections that belong to group as it
308 // might change during linking.
309 ArrayRef<InputSectionBase *> Sections = this->File->getSections();
310 for (uint32_t Val : From.slice(1)) {
311 uint32_t Index = read32(&Val, Config->Endianness);
312 write32(To++, Sections[Index]->OutSec->SectionIndex, Config->Endianness);
316 InputSectionBase *InputSection::getRelocatedSection() {
317 assert(this->Type == SHT_RELA || this->Type == SHT_REL);
318 ArrayRef<InputSectionBase *> Sections = this->File->getSections();
319 return Sections[this->Info];
322 // This is used for -r and --emit-relocs. We can't use memcpy to copy
323 // relocations because we need to update symbol table offset and section index
324 // for each relocation. So we copy relocations one by one.
325 template <class ELFT, class RelTy>
326 void InputSection::copyRelocations(uint8_t *Buf, ArrayRef<RelTy> Rels) {
327 InputSectionBase *RelocatedSection = getRelocatedSection();
329 // Loop is slow and have complexity O(N*M), where N - amount of
330 // relocations and M - amount of symbols in symbol table.
331 // That happens because getSymbolIndex(...) call below performs
332 // simple linear search.
333 for (const RelTy &Rel : Rels) {
334 uint32_t Type = Rel.getType(Config->IsMips64EL);
335 SymbolBody &Body = this->getFile<ELFT>()->getRelocTargetSym(Rel);
337 auto *P = reinterpret_cast<typename ELFT::Rela *>(Buf);
338 Buf += sizeof(RelTy);
341 P->r_addend = getAddend<ELFT>(Rel);
343 // Output section VA is zero for -r, so r_offset is an offset within the
344 // section, but for --emit-relocs it is an virtual address.
345 P->r_offset = RelocatedSection->OutSec->Addr +
346 RelocatedSection->getOffset(Rel.r_offset);
347 P->setSymbolAndType(InX::SymTab->getSymbolIndex(&Body), Type,
350 if (Body.Type == STT_SECTION) {
351 // We combine multiple section symbols into only one per
352 // section. This means we have to update the addend. That is
353 // trivial for Elf_Rela, but for Elf_Rel we have to write to the
354 // section data. We do that by adding to the Relocation vector.
356 // .eh_frame is horribly special and can reference discarded sections. To
357 // avoid having to parse and recreate .eh_frame, we just replace any
358 // relocation in it pointing to discarded sections with R_*_NONE, which
359 // hopefully creates a frame that is ignored at runtime.
360 SectionBase *Section = cast<DefinedRegular>(Body).Section;
361 if (Section == &InputSection::Discarded) {
362 P->setSymbolAndType(0, 0, false);
366 if (Config->IsRela) {
367 P->r_addend += Body.getVA() - Section->getOutputSection()->Addr;
368 } else if (Config->Relocatable) {
369 const uint8_t *BufLoc = RelocatedSection->Data.begin() + Rel.r_offset;
370 RelocatedSection->Relocations.push_back(
371 {R_ABS, Type, Rel.r_offset, Target->getImplicitAddend(BufLoc, Type),
379 static uint32_t getARMUndefinedRelativeWeakVA(uint32_t Type, uint32_t A,
382 case R_ARM_THM_JUMP11:
389 case R_ARM_THM_JUMP19:
390 case R_ARM_THM_JUMP24:
393 // We don't want an interworking BLX to ARM
400 static uint64_t getAArch64UndefinedRelativeWeakVA(uint64_t Type, uint64_t A,
403 case R_AARCH64_CALL26:
404 case R_AARCH64_CONDBR19:
405 case R_AARCH64_JUMP26:
406 case R_AARCH64_TSTBR14:
413 // ARM SBREL relocations are of the form S + A - B where B is the static base
414 // The ARM ABI defines base to be "addressing origin of the output segment
415 // defining the symbol S". We defined the "addressing origin"/static base to be
416 // the base of the PT_LOAD segment containing the Body.
417 // The procedure call standard only defines a Read Write Position Independent
418 // RWPI variant so in practice we should expect the static base to be the base
419 // of the RW segment.
420 static uint64_t getARMStaticBase(const SymbolBody &Body) {
421 OutputSection *OS = Body.getOutputSection();
422 if (!OS || !OS->FirstInPtLoad)
423 fatal("SBREL relocation to " + Body.getName() + " without static base\n");
424 return OS->FirstInPtLoad->Addr;
427 static uint64_t getRelocTargetVA(uint32_t Type, int64_t A, uint64_t P,
428 const SymbolBody &Body, RelExpr Expr) {
431 case R_RELAX_GOT_PC_NOPIC:
432 return Body.getVA(A);
434 return Body.getVA(A) - getARMStaticBase(Body);
436 case R_RELAX_TLS_GD_TO_IE_ABS:
437 return Body.getGotVA() + A;
439 return InX::Got->getVA() + A - P;
440 case R_GOTONLY_PC_FROM_END:
441 return InX::Got->getVA() + A - P + InX::Got->getSize();
443 return Body.getVA(A) - InX::Got->getVA();
444 case R_GOTREL_FROM_END:
445 return Body.getVA(A) - InX::Got->getVA() - InX::Got->getSize();
447 case R_RELAX_TLS_GD_TO_IE_END:
448 return Body.getGotOffset() + A - InX::Got->getSize();
450 return Body.getGotOffset() + A;
452 case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
453 return getAArch64Page(Body.getGotVA() + A) - getAArch64Page(P);
455 case R_RELAX_TLS_GD_TO_IE:
456 return Body.getGotVA() + A - P;
460 llvm_unreachable("cannot relocate hint relocs");
462 return Body.getVA(A) - InX::MipsGot->getGp();
464 return InX::MipsGot->getGp() + A;
465 case R_MIPS_GOT_GP_PC: {
466 // R_MIPS_LO16 expression has R_MIPS_GOT_GP_PC type iif the target
467 // is _gp_disp symbol. In that case we should use the following
468 // formula for calculation "AHL + GP - P + 4". For details see p. 4-19 at
469 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
470 uint64_t V = InX::MipsGot->getGp() + A - P;
471 if (Type == R_MIPS_LO16)
475 case R_MIPS_GOT_LOCAL_PAGE:
476 // If relocation against MIPS local symbol requires GOT entry, this entry
477 // should be initialized by 'page address'. This address is high 16-bits
478 // of sum the symbol's value and the addend.
479 return InX::MipsGot->getVA() + InX::MipsGot->getPageEntryOffset(Body, A) -
480 InX::MipsGot->getGp();
482 case R_MIPS_GOT_OFF32:
483 // In case of MIPS if a GOT relocation has non-zero addend this addend
484 // should be applied to the GOT entry content not to the GOT entry offset.
485 // That is why we use separate expression type.
486 return InX::MipsGot->getVA() + InX::MipsGot->getBodyEntryOffset(Body, A) -
487 InX::MipsGot->getGp();
489 return InX::MipsGot->getVA() + InX::MipsGot->getTlsOffset() +
490 InX::MipsGot->getGlobalDynOffset(Body) - InX::MipsGot->getGp();
492 return InX::MipsGot->getVA() + InX::MipsGot->getTlsOffset() +
493 InX::MipsGot->getTlsIndexOff() - InX::MipsGot->getGp();
496 if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak())
497 return getAArch64Page(A);
498 return getAArch64Page(Body.getVA(A)) - getAArch64Page(P);
500 if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak()) {
501 // On ARM and AArch64 a branch to an undefined weak resolves to the
502 // next instruction, otherwise the place.
503 if (Config->EMachine == EM_ARM)
504 return getARMUndefinedRelativeWeakVA(Type, A, P);
505 if (Config->EMachine == EM_AARCH64)
506 return getAArch64UndefinedRelativeWeakVA(Type, A, P);
508 return Body.getVA(A) - P;
510 return Body.getPltVA() + A;
513 return Body.getPltVA() + A - P;
515 uint64_t SymVA = Body.getVA(A);
516 // If we have an undefined weak symbol, we might get here with a symbol
517 // address of zero. That could overflow, but the code must be unreachable,
518 // so don't bother doing anything at all.
522 // If this is a local call, and we currently have the address of a
523 // function-descriptor, get the underlying code address instead.
524 uint64_t OpdStart = Out::Opd->Addr;
525 uint64_t OpdEnd = OpdStart + Out::Opd->Size;
526 bool InOpd = OpdStart <= SymVA && SymVA < OpdEnd;
528 SymVA = read64be(&Out::OpdBuf[SymVA - OpdStart]);
533 return getPPC64TocBase() + A;
535 return Body.getVA(A) - P;
536 case R_RELAX_TLS_GD_TO_LE:
537 case R_RELAX_TLS_IE_TO_LE:
538 case R_RELAX_TLS_LD_TO_LE:
540 // A weak undefined TLS symbol resolves to the base of the TLS
541 // block, i.e. gets a value of zero. If we pass --gc-sections to
542 // lld and .tbss is not referenced, it gets reclaimed and we don't
543 // create a TLS program header. Therefore, we resolve this
544 // statically to zero.
545 if (Body.isTls() && (Body.isLazy() || Body.isUndefined()) &&
546 Body.symbol()->isWeak())
549 return Body.getVA(A) + alignTo(Target->TcbSize, Out::TlsPhdr->p_align);
550 return Body.getVA(A) - Out::TlsPhdr->p_memsz;
551 case R_RELAX_TLS_GD_TO_LE_NEG:
553 return Out::TlsPhdr->p_memsz - Body.getVA(A);
555 return A; // Body.getSize was already folded into the addend.
557 return InX::Got->getGlobalDynAddr(Body) + A;
559 return getAArch64Page(InX::Got->getGlobalDynAddr(Body) + A) -
562 return InX::Got->getGlobalDynOffset(Body) + A - InX::Got->getSize();
564 return InX::Got->getGlobalDynAddr(Body) + A - P;
566 return InX::Got->getTlsIndexOff() + A - InX::Got->getSize();
568 return InX::Got->getTlsIndexVA() + A - P;
570 llvm_unreachable("Invalid expression");
573 // This function applies relocations to sections without SHF_ALLOC bit.
574 // Such sections are never mapped to memory at runtime. Debug sections are
575 // an example. Relocations in non-alloc sections are much easier to
576 // handle than in allocated sections because it will never need complex
577 // treatement such as GOT or PLT (because at runtime no one refers them).
578 // So, we handle relocations for non-alloc sections directly in this
579 // function as a performance optimization.
580 template <class ELFT, class RelTy>
581 void InputSection::relocateNonAlloc(uint8_t *Buf, ArrayRef<RelTy> Rels) {
582 for (const RelTy &Rel : Rels) {
583 uint32_t Type = Rel.getType(Config->IsMips64EL);
584 uint64_t Offset = getOffset(Rel.r_offset);
585 uint8_t *BufLoc = Buf + Offset;
586 int64_t Addend = getAddend<ELFT>(Rel);
588 Addend += Target->getImplicitAddend(BufLoc, Type);
590 SymbolBody &Sym = this->getFile<ELFT>()->getRelocTargetSym(Rel);
591 RelExpr Expr = Target->getRelExpr(Type, Sym, BufLoc);
595 error(this->getLocation<ELFT>(Offset) + ": has non-ABS reloc");
599 uint64_t AddrLoc = this->OutSec->Addr + Offset;
601 if (!Sym.isTls() || Out::TlsPhdr)
602 SymVA = SignExtend64<sizeof(typename ELFT::uint) * 8>(
603 getRelocTargetVA(Type, Addend, AddrLoc, Sym, R_ABS));
604 Target->relocateOne(BufLoc, Type, SymVA);
608 template <class ELFT> elf::ObjectFile<ELFT> *InputSectionBase::getFile() const {
609 return cast_or_null<elf::ObjectFile<ELFT>>(File);
612 template <class ELFT>
613 void InputSectionBase::relocate(uint8_t *Buf, uint8_t *BufEnd) {
614 if (Flags & SHF_ALLOC)
615 relocateAlloc(Buf, BufEnd);
617 relocateNonAlloc<ELFT>(Buf, BufEnd);
620 template <class ELFT>
621 void InputSectionBase::relocateNonAlloc(uint8_t *Buf, uint8_t *BufEnd) {
622 // scanReloc function in Writer.cpp constructs Relocations
623 // vector only for SHF_ALLOC'ed sections. For other sections,
624 // we handle relocations directly here.
625 auto *IS = cast<InputSection>(this);
626 assert(!(IS->Flags & SHF_ALLOC));
627 if (IS->AreRelocsRela)
628 IS->relocateNonAlloc<ELFT>(Buf, IS->template relas<ELFT>());
630 IS->relocateNonAlloc<ELFT>(Buf, IS->template rels<ELFT>());
633 void InputSectionBase::relocateAlloc(uint8_t *Buf, uint8_t *BufEnd) {
634 assert(Flags & SHF_ALLOC);
635 const unsigned Bits = Config->Wordsize * 8;
636 for (const Relocation &Rel : Relocations) {
637 uint64_t Offset = getOffset(Rel.Offset);
638 uint8_t *BufLoc = Buf + Offset;
639 uint32_t Type = Rel.Type;
641 uint64_t AddrLoc = getOutputSection()->Addr + Offset;
642 RelExpr Expr = Rel.Expr;
643 uint64_t TargetVA = SignExtend64(
644 getRelocTargetVA(Type, Rel.Addend, AddrLoc, *Rel.Sym, Expr), Bits);
648 case R_RELAX_GOT_PC_NOPIC:
649 Target->relaxGot(BufLoc, TargetVA);
651 case R_RELAX_TLS_IE_TO_LE:
652 Target->relaxTlsIeToLe(BufLoc, Type, TargetVA);
654 case R_RELAX_TLS_LD_TO_LE:
655 Target->relaxTlsLdToLe(BufLoc, Type, TargetVA);
657 case R_RELAX_TLS_GD_TO_LE:
658 case R_RELAX_TLS_GD_TO_LE_NEG:
659 Target->relaxTlsGdToLe(BufLoc, Type, TargetVA);
661 case R_RELAX_TLS_GD_TO_IE:
662 case R_RELAX_TLS_GD_TO_IE_ABS:
663 case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
664 case R_RELAX_TLS_GD_TO_IE_END:
665 Target->relaxTlsGdToIe(BufLoc, Type, TargetVA);
668 // Patch a nop (0x60000000) to a ld.
669 if (BufLoc + 8 <= BufEnd && read32be(BufLoc + 4) == 0x60000000)
670 write32be(BufLoc + 4, 0xe8410028); // ld %r2, 40(%r1)
673 Target->relocateOne(BufLoc, Type, TargetVA);
679 template <class ELFT> void InputSection::writeTo(uint8_t *Buf) {
680 if (this->Type == SHT_NOBITS)
683 if (auto *S = dyn_cast<SyntheticSection>(this)) {
684 S->writeTo(Buf + OutSecOff);
688 // If -r or --emit-relocs is given, then an InputSection
689 // may be a relocation section.
690 if (this->Type == SHT_RELA) {
691 copyRelocations<ELFT>(Buf + OutSecOff,
692 this->template getDataAs<typename ELFT::Rela>());
695 if (this->Type == SHT_REL) {
696 copyRelocations<ELFT>(Buf + OutSecOff,
697 this->template getDataAs<typename ELFT::Rel>());
701 // If -r is given, linker should keep SHT_GROUP sections. We should fixup
702 // them, see copyShtGroup().
703 if (this->Type == SHT_GROUP) {
704 copyShtGroup(Buf + OutSecOff);
708 // Copy section contents from source object file to output file
709 // and then apply relocations.
710 memcpy(Buf + OutSecOff, Data.data(), Data.size());
711 uint8_t *BufEnd = Buf + OutSecOff + Data.size();
712 this->relocate<ELFT>(Buf, BufEnd);
715 void InputSection::replace(InputSection *Other) {
716 this->Alignment = std::max(this->Alignment, Other->Alignment);
717 Other->Repl = this->Repl;
721 template <class ELFT>
722 EhInputSection::EhInputSection(elf::ObjectFile<ELFT> *F,
723 const typename ELFT::Shdr *Header,
725 : InputSectionBase(F, Header, Name, InputSectionBase::EHFrame) {
726 // Mark .eh_frame sections as live by default because there are
727 // usually no relocations that point to .eh_frames. Otherwise,
728 // the garbage collector would drop all .eh_frame sections.
732 bool EhInputSection::classof(const SectionBase *S) {
733 return S->kind() == InputSectionBase::EHFrame;
736 // Returns the index of the first relocation that points to a region between
737 // Begin and Begin+Size.
738 template <class IntTy, class RelTy>
739 static unsigned getReloc(IntTy Begin, IntTy Size, const ArrayRef<RelTy> &Rels,
741 // Start search from RelocI for fast access. That works because the
742 // relocations are sorted in .eh_frame.
743 for (unsigned N = Rels.size(); RelocI < N; ++RelocI) {
744 const RelTy &Rel = Rels[RelocI];
745 if (Rel.r_offset < Begin)
748 if (Rel.r_offset < Begin + Size)
755 // .eh_frame is a sequence of CIE or FDE records.
756 // This function splits an input section into records and returns them.
757 template <class ELFT> void EhInputSection::split() {
758 // Early exit if already split.
759 if (!this->Pieces.empty())
762 if (this->NumRelocations) {
763 if (this->AreRelocsRela)
764 split<ELFT>(this->relas<ELFT>());
766 split<ELFT>(this->rels<ELFT>());
769 split<ELFT>(makeArrayRef<typename ELFT::Rela>(nullptr, nullptr));
772 template <class ELFT, class RelTy>
773 void EhInputSection::split(ArrayRef<RelTy> Rels) {
774 ArrayRef<uint8_t> Data = this->Data;
776 for (size_t Off = 0, End = Data.size(); Off != End;) {
777 size_t Size = readEhRecordSize<ELFT>(this, Off);
778 this->Pieces.emplace_back(Off, this, Size, getReloc(Off, Size, Rels, RelI));
779 // The empty record is the end marker.
786 static size_t findNull(ArrayRef<uint8_t> A, size_t EntSize) {
787 // Optimize the common case.
788 StringRef S((const char *)A.data(), A.size());
792 for (unsigned I = 0, N = S.size(); I != N; I += EntSize) {
793 const char *B = S.begin() + I;
794 if (std::all_of(B, B + EntSize, [](char C) { return C == 0; }))
797 return StringRef::npos;
800 // Split SHF_STRINGS section. Such section is a sequence of
801 // null-terminated strings.
802 void MergeInputSection::splitStrings(ArrayRef<uint8_t> Data, size_t EntSize) {
804 bool IsAlloc = this->Flags & SHF_ALLOC;
805 while (!Data.empty()) {
806 size_t End = findNull(Data, EntSize);
807 if (End == StringRef::npos)
808 fatal(toString(this) + ": string is not null terminated");
809 size_t Size = End + EntSize;
810 Pieces.emplace_back(Off, !IsAlloc);
811 Hashes.push_back(hash_value(toStringRef(Data.slice(0, Size))));
812 Data = Data.slice(Size);
817 // Split non-SHF_STRINGS section. Such section is a sequence of
818 // fixed size records.
819 void MergeInputSection::splitNonStrings(ArrayRef<uint8_t> Data,
821 size_t Size = Data.size();
822 assert((Size % EntSize) == 0);
823 bool IsAlloc = this->Flags & SHF_ALLOC;
824 for (unsigned I = 0, N = Size; I != N; I += EntSize) {
825 Hashes.push_back(hash_value(toStringRef(Data.slice(I, EntSize))));
826 Pieces.emplace_back(I, !IsAlloc);
830 template <class ELFT>
831 MergeInputSection::MergeInputSection(elf::ObjectFile<ELFT> *F,
832 const typename ELFT::Shdr *Header,
834 : InputSectionBase(F, Header, Name, InputSectionBase::Merge) {}
836 // This function is called after we obtain a complete list of input sections
837 // that need to be linked. This is responsible to split section contents
838 // into small chunks for further processing.
840 // Note that this function is called from parallel_for_each. This must be
841 // thread-safe (i.e. no memory allocation from the pools).
842 void MergeInputSection::splitIntoPieces() {
843 ArrayRef<uint8_t> Data = this->Data;
844 uint64_t EntSize = this->Entsize;
845 if (this->Flags & SHF_STRINGS)
846 splitStrings(Data, EntSize);
848 splitNonStrings(Data, EntSize);
850 if (Config->GcSections && (this->Flags & SHF_ALLOC))
851 for (uint64_t Off : LiveOffsets)
852 this->getSectionPiece(Off)->Live = true;
855 bool MergeInputSection::classof(const SectionBase *S) {
856 return S->kind() == InputSectionBase::Merge;
859 // Do binary search to get a section piece at a given input offset.
860 SectionPiece *MergeInputSection::getSectionPiece(uint64_t Offset) {
861 auto *This = static_cast<const MergeInputSection *>(this);
862 return const_cast<SectionPiece *>(This->getSectionPiece(Offset));
865 template <class It, class T, class Compare>
866 static It fastUpperBound(It First, It Last, const T &Value, Compare Comp) {
867 size_t Size = std::distance(First, Last);
871 const It MI = First + H;
873 First = Comp(Value, *MI) ? First : First + H;
875 return Comp(Value, *First) ? First : First + 1;
878 const SectionPiece *MergeInputSection::getSectionPiece(uint64_t Offset) const {
879 uint64_t Size = this->Data.size();
881 fatal(toString(this) + ": entry is past the end of the section");
883 // Find the element this offset points to.
884 auto I = fastUpperBound(
885 Pieces.begin(), Pieces.end(), Offset,
886 [](const uint64_t &A, const SectionPiece &B) { return A < B.InputOff; });
891 // Returns the offset in an output section for a given input offset.
892 // Because contents of a mergeable section is not contiguous in output,
893 // it is not just an addition to a base output offset.
894 uint64_t MergeInputSection::getOffset(uint64_t Offset) const {
895 // Initialize OffsetMap lazily.
896 llvm::call_once(InitOffsetMap, [&] {
897 OffsetMap.reserve(Pieces.size());
898 for (const SectionPiece &Piece : Pieces)
899 OffsetMap[Piece.InputOff] = Piece.OutputOff;
902 // Find a string starting at a given offset.
903 auto It = OffsetMap.find(Offset);
904 if (It != OffsetMap.end())
910 // If Offset is not at beginning of a section piece, it is not in the map.
911 // In that case we need to search from the original section piece vector.
912 const SectionPiece &Piece = *this->getSectionPiece(Offset);
916 uint64_t Addend = Offset - Piece.InputOff;
917 return Piece.OutputOff + Addend;
920 template InputSection::InputSection(elf::ObjectFile<ELF32LE> *,
921 const ELF32LE::Shdr *, StringRef);
922 template InputSection::InputSection(elf::ObjectFile<ELF32BE> *,
923 const ELF32BE::Shdr *, StringRef);
924 template InputSection::InputSection(elf::ObjectFile<ELF64LE> *,
925 const ELF64LE::Shdr *, StringRef);
926 template InputSection::InputSection(elf::ObjectFile<ELF64BE> *,
927 const ELF64BE::Shdr *, StringRef);
929 template std::string InputSectionBase::getLocation<ELF32LE>(uint64_t);
930 template std::string InputSectionBase::getLocation<ELF32BE>(uint64_t);
931 template std::string InputSectionBase::getLocation<ELF64LE>(uint64_t);
932 template std::string InputSectionBase::getLocation<ELF64BE>(uint64_t);
934 template std::string InputSectionBase::getSrcMsg<ELF32LE>(uint64_t);
935 template std::string InputSectionBase::getSrcMsg<ELF32BE>(uint64_t);
936 template std::string InputSectionBase::getSrcMsg<ELF64LE>(uint64_t);
937 template std::string InputSectionBase::getSrcMsg<ELF64BE>(uint64_t);
939 template std::string InputSectionBase::getObjMsg<ELF32LE>(uint64_t);
940 template std::string InputSectionBase::getObjMsg<ELF32BE>(uint64_t);
941 template std::string InputSectionBase::getObjMsg<ELF64LE>(uint64_t);
942 template std::string InputSectionBase::getObjMsg<ELF64BE>(uint64_t);
944 template void InputSection::writeTo<ELF32LE>(uint8_t *);
945 template void InputSection::writeTo<ELF32BE>(uint8_t *);
946 template void InputSection::writeTo<ELF64LE>(uint8_t *);
947 template void InputSection::writeTo<ELF64BE>(uint8_t *);
949 template elf::ObjectFile<ELF32LE> *InputSectionBase::getFile<ELF32LE>() const;
950 template elf::ObjectFile<ELF32BE> *InputSectionBase::getFile<ELF32BE>() const;
951 template elf::ObjectFile<ELF64LE> *InputSectionBase::getFile<ELF64LE>() const;
952 template elf::ObjectFile<ELF64BE> *InputSectionBase::getFile<ELF64BE>() const;
954 template MergeInputSection::MergeInputSection(elf::ObjectFile<ELF32LE> *,
955 const ELF32LE::Shdr *, StringRef);
956 template MergeInputSection::MergeInputSection(elf::ObjectFile<ELF32BE> *,
957 const ELF32BE::Shdr *, StringRef);
958 template MergeInputSection::MergeInputSection(elf::ObjectFile<ELF64LE> *,
959 const ELF64LE::Shdr *, StringRef);
960 template MergeInputSection::MergeInputSection(elf::ObjectFile<ELF64BE> *,
961 const ELF64BE::Shdr *, StringRef);
963 template EhInputSection::EhInputSection(elf::ObjectFile<ELF32LE> *,
964 const ELF32LE::Shdr *, StringRef);
965 template EhInputSection::EhInputSection(elf::ObjectFile<ELF32BE> *,
966 const ELF32BE::Shdr *, StringRef);
967 template EhInputSection::EhInputSection(elf::ObjectFile<ELF64LE> *,
968 const ELF64LE::Shdr *, StringRef);
969 template EhInputSection::EhInputSection(elf::ObjectFile<ELF64BE> *,
970 const ELF64BE::Shdr *, StringRef);
972 template void EhInputSection::split<ELF32LE>();
973 template void EhInputSection::split<ELF32BE>();
974 template void EhInputSection::split<ELF64LE>();
975 template void EhInputSection::split<ELF64BE>();