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>();
279 std::string Filename = File ? File->getName() : "(internal)";
282 if (!File->ArchiveName.empty())
283 Archive = (" in archive " + File->ArchiveName).str();
285 // Find a symbol that encloses a given location.
286 for (SymbolBody *B : getFile<ELFT>()->getSymbols())
287 if (auto *D = dyn_cast<DefinedRegular>(B))
288 if (D->Section == this && D->Value <= Off && Off < D->Value + D->Size)
289 return Filename + ":(" + toString(*D) + ")" + Archive;
291 // If there's no symbol, print out the offset in the section.
292 return (Filename + ":(" + Name + "+0x" + utohexstr(Off) + ")" + Archive)
296 InputSectionBase InputSectionBase::Discarded;
298 InputSection::InputSection(uint64_t Flags, uint32_t Type, uint32_t Alignment,
299 ArrayRef<uint8_t> Data, StringRef Name, Kind K)
300 : InputSectionBase(nullptr, Flags, Type,
301 /*Entsize*/ 0, /*Link*/ 0, /*Info*/ 0, Alignment, Data,
304 template <class ELFT>
305 InputSection::InputSection(elf::ObjectFile<ELFT> *F,
306 const typename ELFT::Shdr *Header, StringRef Name)
307 : InputSectionBase(F, Header, Name, InputSectionBase::Regular) {}
309 bool InputSection::classof(const SectionBase *S) {
310 return S->kind() == SectionBase::Regular ||
311 S->kind() == SectionBase::Synthetic;
314 bool InputSectionBase::classof(const SectionBase *S) {
315 return S->kind() != Output;
318 OutputSection *InputSection::getParent() const {
319 return cast_or_null<OutputSection>(Parent);
322 // Copy SHT_GROUP section contents. Used only for the -r option.
323 template <class ELFT> void InputSection::copyShtGroup(uint8_t *Buf) {
324 // ELFT::Word is the 32-bit integral type in the target endianness.
325 typedef typename ELFT::Word u32;
326 ArrayRef<u32> From = getDataAs<u32>();
327 auto *To = reinterpret_cast<u32 *>(Buf);
329 // The first entry is not a section number but a flag.
332 // Adjust section numbers because section numbers in an input object
333 // files are different in the output.
334 ArrayRef<InputSectionBase *> Sections = this->File->getSections();
335 for (uint32_t Idx : From.slice(1))
336 *To++ = Sections[Idx]->getOutputSection()->SectionIndex;
339 InputSectionBase *InputSection::getRelocatedSection() {
340 assert(this->Type == SHT_RELA || this->Type == SHT_REL);
341 ArrayRef<InputSectionBase *> Sections = this->File->getSections();
342 return Sections[this->Info];
345 // This is used for -r and --emit-relocs. We can't use memcpy to copy
346 // relocations because we need to update symbol table offset and section index
347 // for each relocation. So we copy relocations one by one.
348 template <class ELFT, class RelTy>
349 void InputSection::copyRelocations(uint8_t *Buf, ArrayRef<RelTy> Rels) {
350 InputSectionBase *RelocatedSection = getRelocatedSection();
352 // Loop is slow and have complexity O(N*M), where N - amount of
353 // relocations and M - amount of symbols in symbol table.
354 // That happens because getSymbolIndex(...) call below performs
355 // simple linear search.
356 for (const RelTy &Rel : Rels) {
357 uint32_t Type = Rel.getType(Config->IsMips64EL);
358 SymbolBody &Body = this->getFile<ELFT>()->getRelocTargetSym(Rel);
360 auto *P = reinterpret_cast<typename ELFT::Rela *>(Buf);
361 Buf += sizeof(RelTy);
364 P->r_addend = getAddend<ELFT>(Rel);
366 // Output section VA is zero for -r, so r_offset is an offset within the
367 // section, but for --emit-relocs it is an virtual address.
368 P->r_offset = RelocatedSection->getOutputSection()->Addr +
369 RelocatedSection->getOffset(Rel.r_offset);
370 P->setSymbolAndType(InX::SymTab->getSymbolIndex(&Body), Type,
373 if (Body.Type == STT_SECTION) {
374 // We combine multiple section symbols into only one per
375 // section. This means we have to update the addend. That is
376 // trivial for Elf_Rela, but for Elf_Rel we have to write to the
377 // section data. We do that by adding to the Relocation vector.
379 // .eh_frame is horribly special and can reference discarded sections. To
380 // avoid having to parse and recreate .eh_frame, we just replace any
381 // relocation in it pointing to discarded sections with R_*_NONE, which
382 // hopefully creates a frame that is ignored at runtime.
383 SectionBase *Section = cast<DefinedRegular>(Body).Section;
384 if (Section == &InputSection::Discarded) {
385 P->setSymbolAndType(0, 0, false);
389 if (Config->IsRela) {
390 P->r_addend += Body.getVA() - Section->getOutputSection()->Addr;
391 } else if (Config->Relocatable) {
392 const uint8_t *BufLoc = RelocatedSection->Data.begin() + Rel.r_offset;
393 RelocatedSection->Relocations.push_back(
394 {R_ABS, Type, Rel.r_offset, Target->getImplicitAddend(BufLoc, Type),
402 // The ARM and AArch64 ABI handle pc-relative relocations to undefined weak
403 // references specially. The general rule is that the value of the symbol in
404 // this context is the address of the place P. A further special case is that
405 // branch relocations to an undefined weak reference resolve to the next
407 static uint32_t getARMUndefinedRelativeWeakVA(uint32_t Type, uint32_t A,
410 // Unresolved branch relocations to weak references resolve to next
411 // instruction, this will be either 2 or 4 bytes on from P.
412 case R_ARM_THM_JUMP11:
419 case R_ARM_THM_JUMP19:
420 case R_ARM_THM_JUMP24:
423 // We don't want an interworking BLX to ARM
425 // Unresolved non branch pc-relative relocations
426 // R_ARM_TARGET2 which can be resolved relatively is not present as it never
427 // targets a weak-reference.
428 case R_ARM_MOVW_PREL_NC:
429 case R_ARM_MOVT_PREL:
431 case R_ARM_THM_MOVW_PREL_NC:
432 case R_ARM_THM_MOVT_PREL:
435 llvm_unreachable("ARM pc-relative relocation expected\n");
438 // The comment above getARMUndefinedRelativeWeakVA applies to this function.
439 static uint64_t getAArch64UndefinedRelativeWeakVA(uint64_t Type, uint64_t A,
442 // Unresolved branch relocations to weak references resolve to next
443 // instruction, this is 4 bytes on from P.
444 case R_AARCH64_CALL26:
445 case R_AARCH64_CONDBR19:
446 case R_AARCH64_JUMP26:
447 case R_AARCH64_TSTBR14:
449 // Unresolved non branch pc-relative relocations
450 case R_AARCH64_PREL16:
451 case R_AARCH64_PREL32:
452 case R_AARCH64_PREL64:
453 case R_AARCH64_ADR_PREL_LO21:
456 llvm_unreachable("AArch64 pc-relative relocation expected\n");
459 // ARM SBREL relocations are of the form S + A - B where B is the static base
460 // The ARM ABI defines base to be "addressing origin of the output segment
461 // defining the symbol S". We defined the "addressing origin"/static base to be
462 // the base of the PT_LOAD segment containing the Body.
463 // The procedure call standard only defines a Read Write Position Independent
464 // RWPI variant so in practice we should expect the static base to be the base
465 // of the RW segment.
466 static uint64_t getARMStaticBase(const SymbolBody &Body) {
467 OutputSection *OS = Body.getOutputSection();
468 if (!OS || !OS->FirstInPtLoad)
469 fatal("SBREL relocation to " + Body.getName() + " without static base\n");
470 return OS->FirstInPtLoad->Addr;
473 static uint64_t getRelocTargetVA(uint32_t Type, int64_t A, uint64_t P,
474 const SymbolBody &Body, RelExpr Expr) {
477 case R_RELAX_GOT_PC_NOPIC:
478 return Body.getVA(A);
480 return Body.getVA(A) - getARMStaticBase(Body);
482 case R_RELAX_TLS_GD_TO_IE_ABS:
483 return Body.getGotVA() + A;
485 return InX::Got->getVA() + A - P;
486 case R_GOTONLY_PC_FROM_END:
487 return InX::Got->getVA() + A - P + InX::Got->getSize();
489 return Body.getVA(A) - InX::Got->getVA();
490 case R_GOTREL_FROM_END:
491 return Body.getVA(A) - InX::Got->getVA() - InX::Got->getSize();
493 case R_RELAX_TLS_GD_TO_IE_END:
494 return Body.getGotOffset() + A - InX::Got->getSize();
496 return Body.getGotOffset() + A;
498 case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
499 return getAArch64Page(Body.getGotVA() + A) - getAArch64Page(P);
501 case R_RELAX_TLS_GD_TO_IE:
502 return Body.getGotVA() + A - P;
506 llvm_unreachable("cannot relocate hint relocs");
508 return Body.getVA(A) - InX::MipsGot->getGp();
510 return InX::MipsGot->getGp() + A;
511 case R_MIPS_GOT_GP_PC: {
512 // R_MIPS_LO16 expression has R_MIPS_GOT_GP_PC type iif the target
513 // is _gp_disp symbol. In that case we should use the following
514 // formula for calculation "AHL + GP - P + 4". For details see p. 4-19 at
515 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
516 uint64_t V = InX::MipsGot->getGp() + A - P;
517 if (Type == R_MIPS_LO16)
521 case R_MIPS_GOT_LOCAL_PAGE:
522 // If relocation against MIPS local symbol requires GOT entry, this entry
523 // should be initialized by 'page address'. This address is high 16-bits
524 // of sum the symbol's value and the addend.
525 return InX::MipsGot->getVA() + InX::MipsGot->getPageEntryOffset(Body, A) -
526 InX::MipsGot->getGp();
528 case R_MIPS_GOT_OFF32:
529 // In case of MIPS if a GOT relocation has non-zero addend this addend
530 // should be applied to the GOT entry content not to the GOT entry offset.
531 // That is why we use separate expression type.
532 return InX::MipsGot->getVA() + InX::MipsGot->getBodyEntryOffset(Body, A) -
533 InX::MipsGot->getGp();
535 return InX::MipsGot->getVA() + InX::MipsGot->getTlsOffset() +
536 InX::MipsGot->getGlobalDynOffset(Body) - InX::MipsGot->getGp();
538 return InX::MipsGot->getVA() + InX::MipsGot->getTlsOffset() +
539 InX::MipsGot->getTlsIndexOff() - InX::MipsGot->getGp();
541 case R_PLT_PAGE_PC: {
543 if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak())
544 Dest = getAArch64Page(A);
546 Dest = getAArch64Page(Body.getVA(A));
547 return Dest - getAArch64Page(P);
551 if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak()) {
552 // On ARM and AArch64 a branch to an undefined weak resolves to the
553 // next instruction, otherwise the place.
554 if (Config->EMachine == EM_ARM)
555 Dest = getARMUndefinedRelativeWeakVA(Type, A, P);
556 else if (Config->EMachine == EM_AARCH64)
557 Dest = getAArch64UndefinedRelativeWeakVA(Type, A, P);
559 Dest = Body.getVA(A);
561 Dest = Body.getVA(A);
566 return Body.getPltVA() + A;
569 return Body.getPltVA() + A - P;
571 uint64_t SymVA = Body.getVA(A);
572 // If we have an undefined weak symbol, we might get here with a symbol
573 // address of zero. That could overflow, but the code must be unreachable,
574 // so don't bother doing anything at all.
578 // If this is a local call, and we currently have the address of a
579 // function-descriptor, get the underlying code address instead.
580 uint64_t OpdStart = Out::Opd->Addr;
581 uint64_t OpdEnd = OpdStart + Out::Opd->Size;
582 bool InOpd = OpdStart <= SymVA && SymVA < OpdEnd;
584 SymVA = read64be(&Out::OpdBuf[SymVA - OpdStart]);
589 return getPPC64TocBase() + A;
591 return Body.getVA(A) - P;
592 case R_RELAX_TLS_GD_TO_LE:
593 case R_RELAX_TLS_IE_TO_LE:
594 case R_RELAX_TLS_LD_TO_LE:
596 // A weak undefined TLS symbol resolves to the base of the TLS
597 // block, i.e. gets a value of zero. If we pass --gc-sections to
598 // lld and .tbss is not referenced, it gets reclaimed and we don't
599 // create a TLS program header. Therefore, we resolve this
600 // statically to zero.
601 if (Body.isTls() && (Body.isLazy() || Body.isUndefined()) &&
602 Body.symbol()->isWeak())
605 return Body.getVA(A) + alignTo(Target->TcbSize, Out::TlsPhdr->p_align);
606 return Body.getVA(A) - Out::TlsPhdr->p_memsz;
607 case R_RELAX_TLS_GD_TO_LE_NEG:
609 return Out::TlsPhdr->p_memsz - Body.getVA(A);
611 return A; // Body.getSize was already folded into the addend.
613 return InX::Got->getGlobalDynAddr(Body) + A;
615 return getAArch64Page(InX::Got->getGlobalDynAddr(Body) + A) -
618 return InX::Got->getGlobalDynOffset(Body) + A - InX::Got->getSize();
620 return InX::Got->getGlobalDynAddr(Body) + A - P;
622 return InX::Got->getTlsIndexOff() + A - InX::Got->getSize();
624 return InX::Got->getTlsIndexVA() + A - P;
626 llvm_unreachable("Invalid expression");
629 // This function applies relocations to sections without SHF_ALLOC bit.
630 // Such sections are never mapped to memory at runtime. Debug sections are
631 // an example. Relocations in non-alloc sections are much easier to
632 // handle than in allocated sections because it will never need complex
633 // treatement such as GOT or PLT (because at runtime no one refers them).
634 // So, we handle relocations for non-alloc sections directly in this
635 // function as a performance optimization.
636 template <class ELFT, class RelTy>
637 void InputSection::relocateNonAlloc(uint8_t *Buf, ArrayRef<RelTy> Rels) {
638 for (const RelTy &Rel : Rels) {
639 uint32_t Type = Rel.getType(Config->IsMips64EL);
640 uint64_t Offset = getOffset(Rel.r_offset);
641 uint8_t *BufLoc = Buf + Offset;
642 int64_t Addend = getAddend<ELFT>(Rel);
644 Addend += Target->getImplicitAddend(BufLoc, Type);
646 SymbolBody &Sym = this->getFile<ELFT>()->getRelocTargetSym(Rel);
647 RelExpr Expr = Target->getRelExpr(Type, Sym, BufLoc);
651 error(this->getLocation<ELFT>(Offset) + ": has non-ABS reloc");
655 uint64_t AddrLoc = getParent()->Addr + Offset;
657 if (!Sym.isTls() || Out::TlsPhdr)
658 SymVA = SignExtend64<sizeof(typename ELFT::uint) * 8>(
659 getRelocTargetVA(Type, Addend, AddrLoc, Sym, R_ABS));
660 Target->relocateOne(BufLoc, Type, SymVA);
664 template <class ELFT> elf::ObjectFile<ELFT> *InputSectionBase::getFile() const {
665 return cast_or_null<elf::ObjectFile<ELFT>>(File);
668 template <class ELFT>
669 void InputSectionBase::relocate(uint8_t *Buf, uint8_t *BufEnd) {
670 if (Flags & SHF_ALLOC)
671 relocateAlloc(Buf, BufEnd);
673 relocateNonAlloc<ELFT>(Buf, BufEnd);
676 template <class ELFT>
677 void InputSectionBase::relocateNonAlloc(uint8_t *Buf, uint8_t *BufEnd) {
678 // scanReloc function in Writer.cpp constructs Relocations
679 // vector only for SHF_ALLOC'ed sections. For other sections,
680 // we handle relocations directly here.
681 auto *IS = cast<InputSection>(this);
682 assert(!(IS->Flags & SHF_ALLOC));
683 if (IS->AreRelocsRela)
684 IS->relocateNonAlloc<ELFT>(Buf, IS->template relas<ELFT>());
686 IS->relocateNonAlloc<ELFT>(Buf, IS->template rels<ELFT>());
689 void InputSectionBase::relocateAlloc(uint8_t *Buf, uint8_t *BufEnd) {
690 assert(Flags & SHF_ALLOC);
691 const unsigned Bits = Config->Wordsize * 8;
692 for (const Relocation &Rel : Relocations) {
693 uint64_t Offset = getOffset(Rel.Offset);
694 uint8_t *BufLoc = Buf + Offset;
695 uint32_t Type = Rel.Type;
697 uint64_t AddrLoc = getOutputSection()->Addr + Offset;
698 RelExpr Expr = Rel.Expr;
699 uint64_t TargetVA = SignExtend64(
700 getRelocTargetVA(Type, Rel.Addend, AddrLoc, *Rel.Sym, Expr), Bits);
704 case R_RELAX_GOT_PC_NOPIC:
705 Target->relaxGot(BufLoc, TargetVA);
707 case R_RELAX_TLS_IE_TO_LE:
708 Target->relaxTlsIeToLe(BufLoc, Type, TargetVA);
710 case R_RELAX_TLS_LD_TO_LE:
711 Target->relaxTlsLdToLe(BufLoc, Type, TargetVA);
713 case R_RELAX_TLS_GD_TO_LE:
714 case R_RELAX_TLS_GD_TO_LE_NEG:
715 Target->relaxTlsGdToLe(BufLoc, Type, TargetVA);
717 case R_RELAX_TLS_GD_TO_IE:
718 case R_RELAX_TLS_GD_TO_IE_ABS:
719 case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
720 case R_RELAX_TLS_GD_TO_IE_END:
721 Target->relaxTlsGdToIe(BufLoc, Type, TargetVA);
724 // Patch a nop (0x60000000) to a ld.
725 if (BufLoc + 8 <= BufEnd && read32be(BufLoc + 4) == 0x60000000)
726 write32be(BufLoc + 4, 0xe8410028); // ld %r2, 40(%r1)
729 Target->relocateOne(BufLoc, Type, TargetVA);
735 template <class ELFT> void InputSection::writeTo(uint8_t *Buf) {
736 if (this->Type == SHT_NOBITS)
739 if (auto *S = dyn_cast<SyntheticSection>(this)) {
740 S->writeTo(Buf + OutSecOff);
744 // If -r or --emit-relocs is given, then an InputSection
745 // may be a relocation section.
746 if (this->Type == SHT_RELA) {
747 copyRelocations<ELFT>(Buf + OutSecOff,
748 this->template getDataAs<typename ELFT::Rela>());
751 if (this->Type == SHT_REL) {
752 copyRelocations<ELFT>(Buf + OutSecOff,
753 this->template getDataAs<typename ELFT::Rel>());
757 // If -r is given, we may have a SHT_GROUP section.
758 if (this->Type == SHT_GROUP) {
759 copyShtGroup<ELFT>(Buf + OutSecOff);
763 // Copy section contents from source object file to output file
764 // and then apply relocations.
765 memcpy(Buf + OutSecOff, Data.data(), Data.size());
766 uint8_t *BufEnd = Buf + OutSecOff + Data.size();
767 this->relocate<ELFT>(Buf, BufEnd);
770 void InputSection::replace(InputSection *Other) {
771 this->Alignment = std::max(this->Alignment, Other->Alignment);
772 Other->Repl = this->Repl;
776 template <class ELFT>
777 EhInputSection::EhInputSection(elf::ObjectFile<ELFT> *F,
778 const typename ELFT::Shdr *Header,
780 : InputSectionBase(F, Header, Name, InputSectionBase::EHFrame) {
781 // Mark .eh_frame sections as live by default because there are
782 // usually no relocations that point to .eh_frames. Otherwise,
783 // the garbage collector would drop all .eh_frame sections.
787 SyntheticSection *EhInputSection::getParent() const {
788 return cast_or_null<SyntheticSection>(Parent);
791 bool EhInputSection::classof(const SectionBase *S) {
792 return S->kind() == InputSectionBase::EHFrame;
795 // Returns the index of the first relocation that points to a region between
796 // Begin and Begin+Size.
797 template <class IntTy, class RelTy>
798 static unsigned getReloc(IntTy Begin, IntTy Size, const ArrayRef<RelTy> &Rels,
800 // Start search from RelocI for fast access. That works because the
801 // relocations are sorted in .eh_frame.
802 for (unsigned N = Rels.size(); RelocI < N; ++RelocI) {
803 const RelTy &Rel = Rels[RelocI];
804 if (Rel.r_offset < Begin)
807 if (Rel.r_offset < Begin + Size)
814 // .eh_frame is a sequence of CIE or FDE records.
815 // This function splits an input section into records and returns them.
816 template <class ELFT> void EhInputSection::split() {
817 // Early exit if already split.
818 if (!this->Pieces.empty())
821 if (this->NumRelocations) {
822 if (this->AreRelocsRela)
823 split<ELFT>(this->relas<ELFT>());
825 split<ELFT>(this->rels<ELFT>());
828 split<ELFT>(makeArrayRef<typename ELFT::Rela>(nullptr, nullptr));
831 template <class ELFT, class RelTy>
832 void EhInputSection::split(ArrayRef<RelTy> Rels) {
833 ArrayRef<uint8_t> Data = this->Data;
835 for (size_t Off = 0, End = Data.size(); Off != End;) {
836 size_t Size = readEhRecordSize<ELFT>(this, Off);
837 this->Pieces.emplace_back(Off, this, Size, getReloc(Off, Size, Rels, RelI));
838 // The empty record is the end marker.
845 static size_t findNull(ArrayRef<uint8_t> A, size_t EntSize) {
846 // Optimize the common case.
847 StringRef S((const char *)A.data(), A.size());
851 for (unsigned I = 0, N = S.size(); I != N; I += EntSize) {
852 const char *B = S.begin() + I;
853 if (std::all_of(B, B + EntSize, [](char C) { return C == 0; }))
856 return StringRef::npos;
859 SyntheticSection *MergeInputSection::getParent() const {
860 return cast_or_null<SyntheticSection>(Parent);
863 // Split SHF_STRINGS section. Such section is a sequence of
864 // null-terminated strings.
865 void MergeInputSection::splitStrings(ArrayRef<uint8_t> Data, size_t EntSize) {
867 bool IsAlloc = this->Flags & SHF_ALLOC;
868 while (!Data.empty()) {
869 size_t End = findNull(Data, EntSize);
870 if (End == StringRef::npos)
871 fatal(toString(this) + ": string is not null terminated");
872 size_t Size = End + EntSize;
873 Pieces.emplace_back(Off, !IsAlloc);
874 Hashes.push_back(hash_value(toStringRef(Data.slice(0, Size))));
875 Data = Data.slice(Size);
880 // Split non-SHF_STRINGS section. Such section is a sequence of
881 // fixed size records.
882 void MergeInputSection::splitNonStrings(ArrayRef<uint8_t> Data,
884 size_t Size = Data.size();
885 assert((Size % EntSize) == 0);
886 bool IsAlloc = this->Flags & SHF_ALLOC;
887 for (unsigned I = 0, N = Size; I != N; I += EntSize) {
888 Hashes.push_back(hash_value(toStringRef(Data.slice(I, EntSize))));
889 Pieces.emplace_back(I, !IsAlloc);
893 template <class ELFT>
894 MergeInputSection::MergeInputSection(elf::ObjectFile<ELFT> *F,
895 const typename ELFT::Shdr *Header,
897 : InputSectionBase(F, Header, Name, InputSectionBase::Merge) {}
899 // This function is called after we obtain a complete list of input sections
900 // that need to be linked. This is responsible to split section contents
901 // into small chunks for further processing.
903 // Note that this function is called from parallel_for_each. This must be
904 // thread-safe (i.e. no memory allocation from the pools).
905 void MergeInputSection::splitIntoPieces() {
906 ArrayRef<uint8_t> Data = this->Data;
907 uint64_t EntSize = this->Entsize;
908 if (this->Flags & SHF_STRINGS)
909 splitStrings(Data, EntSize);
911 splitNonStrings(Data, EntSize);
913 if (Config->GcSections && (this->Flags & SHF_ALLOC))
914 for (uint64_t Off : LiveOffsets)
915 this->getSectionPiece(Off)->Live = true;
918 bool MergeInputSection::classof(const SectionBase *S) {
919 return S->kind() == InputSectionBase::Merge;
922 // Do binary search to get a section piece at a given input offset.
923 SectionPiece *MergeInputSection::getSectionPiece(uint64_t Offset) {
924 auto *This = static_cast<const MergeInputSection *>(this);
925 return const_cast<SectionPiece *>(This->getSectionPiece(Offset));
928 template <class It, class T, class Compare>
929 static It fastUpperBound(It First, It Last, const T &Value, Compare Comp) {
930 size_t Size = std::distance(First, Last);
934 const It MI = First + H;
936 First = Comp(Value, *MI) ? First : First + H;
938 return Comp(Value, *First) ? First : First + 1;
941 const SectionPiece *MergeInputSection::getSectionPiece(uint64_t Offset) const {
942 uint64_t Size = this->Data.size();
944 fatal(toString(this) + ": entry is past the end of the section");
946 // Find the element this offset points to.
947 auto I = fastUpperBound(
948 Pieces.begin(), Pieces.end(), Offset,
949 [](const uint64_t &A, const SectionPiece &B) { return A < B.InputOff; });
954 // Returns the offset in an output section for a given input offset.
955 // Because contents of a mergeable section is not contiguous in output,
956 // it is not just an addition to a base output offset.
957 uint64_t MergeInputSection::getOffset(uint64_t Offset) const {
958 // Initialize OffsetMap lazily.
959 llvm::call_once(InitOffsetMap, [&] {
960 OffsetMap.reserve(Pieces.size());
961 for (const SectionPiece &Piece : Pieces)
962 OffsetMap[Piece.InputOff] = Piece.OutputOff;
965 // Find a string starting at a given offset.
966 auto It = OffsetMap.find(Offset);
967 if (It != OffsetMap.end())
973 // If Offset is not at beginning of a section piece, it is not in the map.
974 // In that case we need to search from the original section piece vector.
975 const SectionPiece &Piece = *this->getSectionPiece(Offset);
979 uint64_t Addend = Offset - Piece.InputOff;
980 return Piece.OutputOff + Addend;
983 template InputSection::InputSection(elf::ObjectFile<ELF32LE> *,
984 const ELF32LE::Shdr *, StringRef);
985 template InputSection::InputSection(elf::ObjectFile<ELF32BE> *,
986 const ELF32BE::Shdr *, StringRef);
987 template InputSection::InputSection(elf::ObjectFile<ELF64LE> *,
988 const ELF64LE::Shdr *, StringRef);
989 template InputSection::InputSection(elf::ObjectFile<ELF64BE> *,
990 const ELF64BE::Shdr *, StringRef);
992 template std::string InputSectionBase::getLocation<ELF32LE>(uint64_t);
993 template std::string InputSectionBase::getLocation<ELF32BE>(uint64_t);
994 template std::string InputSectionBase::getLocation<ELF64LE>(uint64_t);
995 template std::string InputSectionBase::getLocation<ELF64BE>(uint64_t);
997 template std::string InputSectionBase::getSrcMsg<ELF32LE>(uint64_t);
998 template std::string InputSectionBase::getSrcMsg<ELF32BE>(uint64_t);
999 template std::string InputSectionBase::getSrcMsg<ELF64LE>(uint64_t);
1000 template std::string InputSectionBase::getSrcMsg<ELF64BE>(uint64_t);
1002 template std::string InputSectionBase::getObjMsg<ELF32LE>(uint64_t);
1003 template std::string InputSectionBase::getObjMsg<ELF32BE>(uint64_t);
1004 template std::string InputSectionBase::getObjMsg<ELF64LE>(uint64_t);
1005 template std::string InputSectionBase::getObjMsg<ELF64BE>(uint64_t);
1007 template void InputSection::writeTo<ELF32LE>(uint8_t *);
1008 template void InputSection::writeTo<ELF32BE>(uint8_t *);
1009 template void InputSection::writeTo<ELF64LE>(uint8_t *);
1010 template void InputSection::writeTo<ELF64BE>(uint8_t *);
1012 template elf::ObjectFile<ELF32LE> *InputSectionBase::getFile<ELF32LE>() const;
1013 template elf::ObjectFile<ELF32BE> *InputSectionBase::getFile<ELF32BE>() const;
1014 template elf::ObjectFile<ELF64LE> *InputSectionBase::getFile<ELF64LE>() const;
1015 template elf::ObjectFile<ELF64BE> *InputSectionBase::getFile<ELF64BE>() const;
1017 template MergeInputSection::MergeInputSection(elf::ObjectFile<ELF32LE> *,
1018 const ELF32LE::Shdr *, StringRef);
1019 template MergeInputSection::MergeInputSection(elf::ObjectFile<ELF32BE> *,
1020 const ELF32BE::Shdr *, StringRef);
1021 template MergeInputSection::MergeInputSection(elf::ObjectFile<ELF64LE> *,
1022 const ELF64LE::Shdr *, StringRef);
1023 template MergeInputSection::MergeInputSection(elf::ObjectFile<ELF64BE> *,
1024 const ELF64BE::Shdr *, StringRef);
1026 template EhInputSection::EhInputSection(elf::ObjectFile<ELF32LE> *,
1027 const ELF32LE::Shdr *, StringRef);
1028 template EhInputSection::EhInputSection(elf::ObjectFile<ELF32BE> *,
1029 const ELF32BE::Shdr *, StringRef);
1030 template EhInputSection::EhInputSection(elf::ObjectFile<ELF64LE> *,
1031 const ELF64LE::Shdr *, StringRef);
1032 template EhInputSection::EhInputSection(elf::ObjectFile<ELF64BE> *,
1033 const ELF64BE::Shdr *, StringRef);
1035 template void EhInputSection::split<ELF32LE>();
1036 template void EhInputSection::split<ELF32BE>();
1037 template void EhInputSection::split<ELF64LE>();
1038 template void EhInputSection::split<ELF64BE>();