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/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"
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;
38 using namespace lld::elf;
40 std::vector<InputSectionBase *> elf::InputSections;
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();
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));
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,
62 File(File), Data(Data), Repl(this) {
63 Live = !Config->GcSections || !(Flags & SHF_ALLOC);
66 AreRelocsRela = false;
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");
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;
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.
92 // .section .init_array.100, "aw"
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;
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");
119 size_t InputSectionBase::getSize() const {
120 if (auto *S = dyn_cast<SyntheticSection>(this))
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;
132 uint64_t SectionBase::getOffset(uint64_t Offset) const {
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;
140 return cast<InputSection>(this)->OutSecOff + Offset;
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);
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.
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);
157 llvm_unreachable("invalid section kind");
160 OutputSection *SectionBase::getOutputSection() {
162 if (auto *IS = dyn_cast<InputSection>(this))
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();
169 return cast<OutputSection>(this);
170 return Sec ? Sec->getParent() : nullptr;
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));
179 size_t Size = Dec.getDecompressedSize();
182 static std::mutex Mu;
183 std::lock_guard<std::mutex> Lock(Mu);
184 OutputBuf = BAlloc.Allocate<char>(Size);
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;
194 uint64_t SectionBase::getOffset(const DefinedRegular &Sym) const {
195 return getOffset(Sym.Value);
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))
204 "Merge and .eh_frame sections are not supported with SHF_LINK_ORDER " +
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) + ")")
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())
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;
227 SrcFile = toString(File);
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) + ")";
236 // If there's no symbol, print out the offset in the section.
237 return (SrcFile + ":(" + Name + "+0x" + utohexstr(Offset) + ")").str();
240 // Returns a source location string. This function is intended to be
241 // used for constructing an error message. The returned message looks
244 // foo.c:42 (/home/alice/possibly/very/long/path/foo.c:42)
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>();
253 Optional<DILineInfo> Info = File->getDILineInfo(this, Offset);
255 // File->SourceFile contains STT_FILE symbol, and that is a last resort.
257 return File->SourceFile;
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 + ")";
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:
271 // path/to/foo.o:(function bar)
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>();
280 return ("(internal):(" + Name + "+0x" + utohexstr(Off) + ")").str();
281 std::string Filename = File->getName();
284 if (!File->ArchiveName.empty())
285 Archive = (" in archive " + File->ArchiveName).str();
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;
293 // If there's no symbol, print out the offset in the section.
294 return (Filename + ":(" + Name + "+0x" + utohexstr(Off) + ")" + Archive)
298 InputSectionBase InputSectionBase::Discarded;
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,
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) {}
311 bool InputSection::classof(const SectionBase *S) {
312 return S->kind() == SectionBase::Regular ||
313 S->kind() == SectionBase::Synthetic;
316 bool InputSectionBase::classof(const SectionBase *S) {
317 return S->kind() != Output;
320 OutputSection *InputSection::getParent() const {
321 return cast_or_null<OutputSection>(Parent);
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);
331 // The first entry is not a section number but a flag.
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;
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];
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();
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);
362 auto *P = reinterpret_cast<typename ELFT::Rela *>(Buf);
363 Buf += sizeof(RelTy);
366 P->r_addend = getAddend<ELFT>(Rel);
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,
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.
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);
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),
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
409 static uint32_t getARMUndefinedRelativeWeakVA(uint32_t Type, uint32_t A,
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:
421 case R_ARM_THM_JUMP19:
422 case R_ARM_THM_JUMP24:
425 // We don't want an interworking BLX to ARM
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:
433 case R_ARM_THM_MOVW_PREL_NC:
434 case R_ARM_THM_MOVT_PREL:
437 llvm_unreachable("ARM pc-relative relocation expected\n");
440 // The comment above getARMUndefinedRelativeWeakVA applies to this function.
441 static uint64_t getAArch64UndefinedRelativeWeakVA(uint64_t Type, uint64_t A,
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:
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:
458 llvm_unreachable("AArch64 pc-relative relocation expected\n");
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;
475 static uint64_t getRelocTargetVA(uint32_t Type, int64_t A, uint64_t P,
476 const SymbolBody &Body, RelExpr Expr) {
479 case R_RELAX_GOT_PC_NOPIC:
480 return Body.getVA(A);
482 return Body.getVA(A) - getARMStaticBase(Body);
484 case R_RELAX_TLS_GD_TO_IE_ABS:
485 return Body.getGotVA() + A;
487 return InX::Got->getVA() + A - P;
488 case R_GOTONLY_PC_FROM_END:
489 return InX::Got->getVA() + A - P + InX::Got->getSize();
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();
495 case R_RELAX_TLS_GD_TO_IE_END:
496 return Body.getGotOffset() + A - InX::Got->getSize();
498 return Body.getGotOffset() + A;
500 case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
501 return getAArch64Page(Body.getGotVA() + A) - getAArch64Page(P);
503 case R_RELAX_TLS_GD_TO_IE:
504 return Body.getGotVA() + A - P;
508 llvm_unreachable("cannot relocate hint relocs");
510 return Body.getVA(A) - InX::MipsGot->getGp();
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)
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();
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();
537 return InX::MipsGot->getVA() + InX::MipsGot->getTlsOffset() +
538 InX::MipsGot->getGlobalDynOffset(Body) - InX::MipsGot->getGp();
540 return InX::MipsGot->getVA() + InX::MipsGot->getTlsOffset() +
541 InX::MipsGot->getTlsIndexOff() - InX::MipsGot->getGp();
543 case R_PLT_PAGE_PC: {
545 if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak())
546 Dest = getAArch64Page(A);
548 Dest = getAArch64Page(Body.getVA(A));
549 return Dest - getAArch64Page(P);
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);
561 Dest = Body.getVA(A);
563 Dest = Body.getVA(A);
568 return Body.getPltVA() + A;
571 return Body.getPltVA() + A - P;
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.
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;
586 SymVA = read64be(&Out::OpdBuf[SymVA - OpdStart]);
591 return getPPC64TocBase() + A;
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:
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())
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:
611 return Out::TlsPhdr->p_memsz - Body.getVA(A);
613 return A; // Body.getSize was already folded into the addend.
615 return InX::Got->getGlobalDynAddr(Body) + A;
617 return getAArch64Page(InX::Got->getGlobalDynAddr(Body) + A) -
620 return InX::Got->getGlobalDynOffset(Body) + A - InX::Got->getSize();
622 return InX::Got->getGlobalDynAddr(Body) + A - P;
624 return InX::Got->getTlsIndexOff() + A - InX::Got->getSize();
626 return InX::Got->getTlsIndexVA() + A - P;
628 llvm_unreachable("Invalid expression");
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);
646 Addend += Target->getImplicitAddend(BufLoc, Type);
648 SymbolBody &Sym = this->getFile<ELFT>()->getRelocTargetSym(Rel);
649 RelExpr Expr = Target->getRelExpr(Type, Sym, BufLoc);
653 error(this->getLocation<ELFT>(Offset) + ": has non-ABS reloc");
657 uint64_t AddrLoc = getParent()->Addr + Offset;
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);
666 template <class ELFT> elf::ObjectFile<ELFT> *InputSectionBase::getFile() const {
667 return cast_or_null<elf::ObjectFile<ELFT>>(File);
670 template <class ELFT>
671 void InputSectionBase::relocate(uint8_t *Buf, uint8_t *BufEnd) {
672 if (Flags & SHF_ALLOC)
673 relocateAlloc(Buf, BufEnd);
675 relocateNonAlloc<ELFT>(Buf, BufEnd);
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>());
688 IS->relocateNonAlloc<ELFT>(Buf, IS->template rels<ELFT>());
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;
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);
706 case R_RELAX_GOT_PC_NOPIC:
707 Target->relaxGot(BufLoc, TargetVA);
709 case R_RELAX_TLS_IE_TO_LE:
710 Target->relaxTlsIeToLe(BufLoc, Type, TargetVA);
712 case R_RELAX_TLS_LD_TO_LE:
713 Target->relaxTlsLdToLe(BufLoc, Type, TargetVA);
715 case R_RELAX_TLS_GD_TO_LE:
716 case R_RELAX_TLS_GD_TO_LE_NEG:
717 Target->relaxTlsGdToLe(BufLoc, Type, TargetVA);
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);
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)
731 Target->relocateOne(BufLoc, Type, TargetVA);
737 template <class ELFT> void InputSection::writeTo(uint8_t *Buf) {
738 if (this->Type == SHT_NOBITS)
741 if (auto *S = dyn_cast<SyntheticSection>(this)) {
742 S->writeTo(Buf + OutSecOff);
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>());
753 if (this->Type == SHT_REL) {
754 copyRelocations<ELFT>(Buf + OutSecOff,
755 this->template getDataAs<typename ELFT::Rel>());
759 // If -r is given, we may have a SHT_GROUP section.
760 if (this->Type == SHT_GROUP) {
761 copyShtGroup<ELFT>(Buf + OutSecOff);
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);
772 void InputSection::replace(InputSection *Other) {
773 this->Alignment = std::max(this->Alignment, Other->Alignment);
774 Other->Repl = this->Repl;
778 template <class ELFT>
779 EhInputSection::EhInputSection(elf::ObjectFile<ELFT> *F,
780 const typename ELFT::Shdr *Header,
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.
789 SyntheticSection *EhInputSection::getParent() const {
790 return cast_or_null<SyntheticSection>(Parent);
793 bool EhInputSection::classof(const SectionBase *S) {
794 return S->kind() == InputSectionBase::EHFrame;
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,
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)
809 if (Rel.r_offset < Begin + Size)
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())
823 if (this->NumRelocations) {
824 if (this->AreRelocsRela)
825 split<ELFT>(this->relas<ELFT>());
827 split<ELFT>(this->rels<ELFT>());
830 split<ELFT>(makeArrayRef<typename ELFT::Rela>(nullptr, nullptr));
833 template <class ELFT, class RelTy>
834 void EhInputSection::split(ArrayRef<RelTy> Rels) {
835 ArrayRef<uint8_t> Data = this->Data;
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.
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());
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; }))
858 return StringRef::npos;
861 SyntheticSection *MergeInputSection::getParent() const {
862 return cast_or_null<SyntheticSection>(Parent);
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) {
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);
882 // Split non-SHF_STRINGS section. Such section is a sequence of
883 // fixed size records.
884 void MergeInputSection::splitNonStrings(ArrayRef<uint8_t> Data,
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);
895 template <class ELFT>
896 MergeInputSection::MergeInputSection(elf::ObjectFile<ELFT> *F,
897 const typename ELFT::Shdr *Header,
899 : InputSectionBase(F, Header, Name, InputSectionBase::Merge) {}
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.
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);
913 splitNonStrings(Data, EntSize);
915 if (Config->GcSections && (this->Flags & SHF_ALLOC))
916 for (uint64_t Off : LiveOffsets)
917 this->getSectionPiece(Off)->Live = true;
920 bool MergeInputSection::classof(const SectionBase *S) {
921 return S->kind() == InputSectionBase::Merge;
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));
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);
936 const It MI = First + H;
938 First = Comp(Value, *MI) ? First : First + H;
940 return Comp(Value, *First) ? First : First + 1;
943 const SectionPiece *MergeInputSection::getSectionPiece(uint64_t Offset) const {
944 uint64_t Size = this->Data.size();
946 fatal(toString(this) + ": entry is past the end of the section");
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; });
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;
967 // Find a string starting at a given offset.
968 auto It = OffsetMap.find(Offset);
969 if (It != OffsetMap.end())
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);
981 uint64_t Addend = Offset - Piece.InputOff;
982 return Piece.OutputOff + Addend;
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);
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);
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);
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);
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 *);
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;
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);
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);
1037 template void EhInputSection::split<ELF32LE>();
1038 template void EhInputSection::split<ELF32BE>();
1039 template void EhInputSection::split<ELF64LE>();
1040 template void EhInputSection::split<ELF64BE>();