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"
28 using namespace llvm::ELF;
29 using namespace llvm::object;
30 using namespace llvm::support;
31 using namespace llvm::support::endian;
34 using namespace lld::elf;
36 // Returns a string to construct an error message.
38 std::string lld::toString(const InputSectionBase<ELFT> *Sec) {
39 // File can be absent if section is synthetic.
40 std::string FileName =
41 Sec->getFile() ? Sec->getFile()->getName() : "<internal>";
42 return (FileName + ":(" + Sec->Name + ")").str();
46 static ArrayRef<uint8_t> getSectionContents(elf::ObjectFile<ELFT> *File,
47 const typename ELFT::Shdr *Hdr) {
48 if (!File || Hdr->sh_type == SHT_NOBITS)
49 return makeArrayRef<uint8_t>(nullptr, Hdr->sh_size);
50 return check(File->getObj().getSectionContents(Hdr));
54 InputSectionBase<ELFT>::InputSectionBase(elf::ObjectFile<ELFT> *File,
55 uintX_t Flags, uint32_t Type,
56 uintX_t Entsize, uint32_t Link,
57 uint32_t Info, uintX_t Addralign,
58 ArrayRef<uint8_t> Data, StringRef Name,
60 : InputSectionData(SectionKind, Name, Data,
61 !Config->GcSections || !(Flags & SHF_ALLOC)),
62 File(File), Flags(Flags), Entsize(Entsize), Type(Type), Link(Link),
63 Info(Info), Repl(this) {
65 AreRelocsRela = false;
67 // The ELF spec states that a value of 0 means the section has
68 // no alignment constraits.
69 uint64_t V = std::max<uint64_t>(Addralign, 1);
70 if (!isPowerOf2_64(V))
71 fatal(toString(File) + ": section sh_addralign is not a power of 2");
73 // We reject object files having insanely large alignments even though
74 // they are allowed by the spec. I think 4GB is a reasonable limitation.
75 // We might want to relax this in the future.
77 fatal(toString(File) + ": section sh_addralign is too large");
80 // If it is not a mergeable section, overwrite the flag so that the flag
81 // is consistent with the class. This inconsistency could occur when
82 // string merging is disabled using -O0 flag.
83 if (!Config->Relocatable && !isa<MergeInputSection<ELFT>>(this))
84 this->Flags &= ~(SHF_MERGE | SHF_STRINGS);
88 InputSectionBase<ELFT>::InputSectionBase(elf::ObjectFile<ELFT> *File,
89 const Elf_Shdr *Hdr, StringRef Name,
91 : InputSectionBase(File, Hdr->sh_flags & ~SHF_INFO_LINK, Hdr->sh_type,
92 Hdr->sh_entsize, Hdr->sh_link, Hdr->sh_info,
93 Hdr->sh_addralign, getSectionContents(File, Hdr), Name,
95 this->Offset = Hdr->sh_offset;
98 template <class ELFT> size_t InputSectionBase<ELFT>::getSize() const {
99 if (auto *S = dyn_cast<SyntheticSection<ELFT>>(this))
102 if (auto *D = dyn_cast<InputSection<ELFT>>(this))
103 if (D->getThunksSize() > 0)
104 return D->getThunkOff() + D->getThunksSize();
109 template <class ELFT>
110 typename ELFT::uint InputSectionBase<ELFT>::getOffset(uintX_t Offset) const {
113 return cast<InputSection<ELFT>>(this)->OutSecOff + Offset;
115 // For synthetic sections we treat offset -1 as the end of the section.
116 // The same approach is used for synthetic symbols (DefinedSynthetic).
117 return cast<InputSection<ELFT>>(this)->OutSecOff +
118 (Offset == uintX_t(-1) ? getSize() : Offset);
120 // The file crtbeginT.o has relocations pointing to the start of an empty
121 // .eh_frame that is known to be the first in the link. It does that to
122 // identify the start of the output .eh_frame.
125 return cast<MergeInputSection<ELFT>>(this)->getOffset(Offset);
127 llvm_unreachable("invalid section kind");
130 // Uncompress section contents. Note that this function is called
131 // from parallel_for_each, so it must be thread-safe.
132 template <class ELFT> void InputSectionBase<ELFT>::uncompress() {
133 Decompressor Decompressor = check(Decompressor::create(
134 Name, toStringRef(Data), ELFT::TargetEndianness == llvm::support::little,
137 size_t Size = Decompressor.getDecompressedSize();
140 static std::mutex Mu;
141 std::lock_guard<std::mutex> Lock(Mu);
142 OutputBuf = BAlloc.Allocate<char>(Size);
145 if (Error E = Decompressor.decompress({OutputBuf, Size}))
146 fatal(E, toString(this));
147 Data = ArrayRef<uint8_t>((uint8_t *)OutputBuf, Size);
150 template <class ELFT>
152 InputSectionBase<ELFT>::getOffset(const DefinedRegular<ELFT> &Sym) const {
153 return getOffset(Sym.Value);
156 template <class ELFT>
157 InputSectionBase<ELFT> *InputSectionBase<ELFT>::getLinkOrderDep() const {
158 if ((Flags & SHF_LINK_ORDER) && Link != 0)
159 return getFile()->getSections()[Link];
163 // Returns a source location string. Used to construct an error message.
164 template <class ELFT>
165 std::string InputSectionBase<ELFT>::getLocation(typename ELFT::uint Offset) {
166 // First check if we can get desired values from debugging information.
167 std::string LineInfo = File->getLineInfo(this, Offset);
168 if (!LineInfo.empty())
171 // File->SourceFile contains STT_FILE symbol that contains a
172 // source file name. If it's missing, we use an object file name.
173 std::string SrcFile = File->SourceFile;
175 SrcFile = toString(File);
177 // Find a function symbol that encloses a given location.
178 for (SymbolBody *B : File->getSymbols())
179 if (auto *D = dyn_cast<DefinedRegular<ELFT>>(B))
180 if (D->Section == this && D->Type == STT_FUNC)
181 if (D->Value <= Offset && Offset < D->Value + D->Size)
182 return SrcFile + ":(function " + toString(*D) + ")";
184 // If there's no symbol, print out the offset in the section.
185 return (SrcFile + ":(" + Name + "+0x" + utohexstr(Offset) + ")").str();
188 template <class ELFT>
189 InputSection<ELFT>::InputSection() : InputSectionBase<ELFT>() {}
191 template <class ELFT>
192 InputSection<ELFT>::InputSection(uintX_t Flags, uint32_t Type,
193 uintX_t Addralign, ArrayRef<uint8_t> Data,
194 StringRef Name, Kind K)
195 : InputSectionBase<ELFT>(nullptr, Flags, Type,
196 /*Entsize*/ 0, /*Link*/ 0, /*Info*/ 0, Addralign,
199 template <class ELFT>
200 InputSection<ELFT>::InputSection(elf::ObjectFile<ELFT> *F,
201 const Elf_Shdr *Header, StringRef Name)
202 : InputSectionBase<ELFT>(F, Header, Name, Base::Regular) {}
204 template <class ELFT>
205 bool InputSection<ELFT>::classof(const InputSectionData *S) {
206 return S->kind() == Base::Regular || S->kind() == Base::Synthetic;
209 template <class ELFT>
210 InputSectionBase<ELFT> *InputSection<ELFT>::getRelocatedSection() {
211 assert(this->Type == SHT_RELA || this->Type == SHT_REL);
212 ArrayRef<InputSectionBase<ELFT> *> Sections = this->File->getSections();
213 return Sections[this->Info];
216 template <class ELFT> void InputSection<ELFT>::addThunk(const Thunk<ELFT> *T) {
220 template <class ELFT> uint64_t InputSection<ELFT>::getThunkOff() const {
221 return this->Data.size();
224 template <class ELFT> uint64_t InputSection<ELFT>::getThunksSize() const {
226 for (const Thunk<ELFT> *T : Thunks)
231 // This is used for -r. We can't use memcpy to copy relocations because we need
232 // to update symbol table offset and section index for each relocation. So we
233 // copy relocations one by one.
234 template <class ELFT>
235 template <class RelTy>
236 void InputSection<ELFT>::copyRelocations(uint8_t *Buf, ArrayRef<RelTy> Rels) {
237 InputSectionBase<ELFT> *RelocatedSection = getRelocatedSection();
239 for (const RelTy &Rel : Rels) {
240 uint32_t Type = Rel.getType(Config->Mips64EL);
241 SymbolBody &Body = this->File->getRelocTargetSym(Rel);
243 Elf_Rela *P = reinterpret_cast<Elf_Rela *>(Buf);
244 Buf += sizeof(RelTy);
247 P->r_addend = getAddend<ELFT>(Rel);
248 P->r_offset = RelocatedSection->getOffset(Rel.r_offset);
249 P->setSymbolAndType(In<ELFT>::SymTab->getSymbolIndex(&Body), Type,
254 static uint32_t getARMUndefinedRelativeWeakVA(uint32_t Type, uint32_t A,
257 case R_ARM_THM_JUMP11:
264 case R_ARM_THM_JUMP19:
265 case R_ARM_THM_JUMP24:
268 // We don't want an interworking BLX to ARM
275 static uint64_t getAArch64UndefinedRelativeWeakVA(uint64_t Type, uint64_t A,
278 case R_AARCH64_CALL26:
279 case R_AARCH64_CONDBR19:
280 case R_AARCH64_JUMP26:
281 case R_AARCH64_TSTBR14:
288 template <class ELFT>
289 static typename ELFT::uint
290 getRelocTargetVA(uint32_t Type, typename ELFT::uint A, typename ELFT::uint P,
291 const SymbolBody &Body, RelExpr Expr) {
295 llvm_unreachable("cannot relocate hint relocs");
297 return In<ELFT>::Got->getTlsIndexOff() + A - In<ELFT>::Got->getSize();
299 return In<ELFT>::Got->getTlsIndexVA() + A - P;
301 return Body.getThunkVA<ELFT>() + A;
304 return Body.getThunkVA<ELFT>() + A - P;
306 return getPPC64TocBase() + A;
308 return In<ELFT>::Got->getGlobalDynOffset(Body) + A -
309 In<ELFT>::Got->getSize();
311 return In<ELFT>::Got->getGlobalDynAddr(Body) + A - P;
313 return In<ELFT>::Got->getGlobalDynAddr(Body) + A;
315 return getAArch64Page(In<ELFT>::Got->getGlobalDynAddr(Body) + A) -
318 return Body.getPltVA<ELFT>() + A;
321 return Body.getPltVA<ELFT>() + A - P;
323 return Body.getSize<ELFT>() + A;
325 return Body.getVA<ELFT>(A) - In<ELFT>::Got->getVA();
326 case R_GOTREL_FROM_END:
327 return Body.getVA<ELFT>(A) - In<ELFT>::Got->getVA() -
328 In<ELFT>::Got->getSize();
329 case R_RELAX_TLS_GD_TO_IE_END:
331 return Body.getGotOffset<ELFT>() + A - In<ELFT>::Got->getSize();
332 case R_RELAX_TLS_GD_TO_IE_ABS:
334 return Body.getGotVA<ELFT>() + A;
335 case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
337 return getAArch64Page(Body.getGotVA<ELFT>() + A) - getAArch64Page(P);
338 case R_RELAX_TLS_GD_TO_IE:
340 return Body.getGotVA<ELFT>() + A - P;
342 return In<ELFT>::Got->getVA() + A - P;
343 case R_GOTONLY_PC_FROM_END:
344 return In<ELFT>::Got->getVA() + A - P + In<ELFT>::Got->getSize();
345 case R_RELAX_TLS_LD_TO_LE:
346 case R_RELAX_TLS_IE_TO_LE:
347 case R_RELAX_TLS_GD_TO_LE:
349 // A weak undefined TLS symbol resolves to the base of the TLS
350 // block, i.e. gets a value of zero. If we pass --gc-sections to
351 // lld and .tbss is not referenced, it gets reclaimed and we don't
352 // create a TLS program header. Therefore, we resolve this
353 // statically to zero.
354 if (Body.isTls() && (Body.isLazy() || Body.isUndefined()) &&
355 Body.symbol()->isWeak())
358 return Body.getVA<ELFT>(A) +
359 alignTo(Target->TcbSize, Out<ELFT>::TlsPhdr->p_align);
360 return Body.getVA<ELFT>(A) - Out<ELFT>::TlsPhdr->p_memsz;
361 case R_RELAX_TLS_GD_TO_LE_NEG:
363 return Out<ELF32LE>::TlsPhdr->p_memsz - Body.getVA<ELFT>(A);
365 case R_RELAX_GOT_PC_NOPIC:
366 return Body.getVA<ELFT>(A);
368 return Body.getGotOffset<ELFT>() + A;
369 case R_MIPS_GOT_LOCAL_PAGE:
370 // If relocation against MIPS local symbol requires GOT entry, this entry
371 // should be initialized by 'page address'. This address is high 16-bits
372 // of sum the symbol's value and the addend.
373 return In<ELFT>::MipsGot->getVA() +
374 In<ELFT>::MipsGot->getPageEntryOffset(Body, A) -
375 In<ELFT>::MipsGot->getGp();
377 case R_MIPS_GOT_OFF32:
378 // In case of MIPS if a GOT relocation has non-zero addend this addend
379 // should be applied to the GOT entry content not to the GOT entry offset.
380 // That is why we use separate expression type.
381 return In<ELFT>::MipsGot->getVA() +
382 In<ELFT>::MipsGot->getBodyEntryOffset(Body, A) -
383 In<ELFT>::MipsGot->getGp();
385 return Body.getVA<ELFT>(A) - In<ELFT>::MipsGot->getGp();
387 return In<ELFT>::MipsGot->getVA() + In<ELFT>::MipsGot->getTlsOffset() +
388 In<ELFT>::MipsGot->getGlobalDynOffset(Body) -
389 In<ELFT>::MipsGot->getGp();
391 return In<ELFT>::MipsGot->getVA() + In<ELFT>::MipsGot->getTlsOffset() +
392 In<ELFT>::MipsGot->getTlsIndexOff() - In<ELFT>::MipsGot->getGp();
394 uint64_t SymVA = Body.getVA<ELFT>(A);
395 // If we have an undefined weak symbol, we might get here with a symbol
396 // address of zero. That could overflow, but the code must be unreachable,
397 // so don't bother doing anything at all.
400 if (Out<ELF64BE>::Opd) {
401 // If this is a local call, and we currently have the address of a
402 // function-descriptor, get the underlying code address instead.
403 uint64_t OpdStart = Out<ELF64BE>::Opd->Addr;
404 uint64_t OpdEnd = OpdStart + Out<ELF64BE>::Opd->Size;
405 bool InOpd = OpdStart <= SymVA && SymVA < OpdEnd;
407 SymVA = read64be(&Out<ELF64BE>::OpdBuf[SymVA - OpdStart]);
412 if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak()) {
413 // On ARM and AArch64 a branch to an undefined weak resolves to the
414 // next instruction, otherwise the place.
415 if (Config->EMachine == EM_ARM)
416 return getARMUndefinedRelativeWeakVA(Type, A, P);
417 if (Config->EMachine == EM_AARCH64)
418 return getAArch64UndefinedRelativeWeakVA(Type, A, P);
421 return Body.getVA<ELFT>(A) - P;
424 if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak())
425 return getAArch64Page(A);
426 return getAArch64Page(Body.getVA<ELFT>(A)) - getAArch64Page(P);
428 llvm_unreachable("Invalid expression");
431 // This function applies relocations to sections without SHF_ALLOC bit.
432 // Such sections are never mapped to memory at runtime. Debug sections are
433 // an example. Relocations in non-alloc sections are much easier to
434 // handle than in allocated sections because it will never need complex
435 // treatement such as GOT or PLT (because at runtime no one refers them).
436 // So, we handle relocations for non-alloc sections directly in this
437 // function as a performance optimization.
438 template <class ELFT>
439 template <class RelTy>
440 void InputSection<ELFT>::relocateNonAlloc(uint8_t *Buf, ArrayRef<RelTy> Rels) {
441 for (const RelTy &Rel : Rels) {
442 uint32_t Type = Rel.getType(Config->Mips64EL);
443 uintX_t Offset = this->getOffset(Rel.r_offset);
444 uint8_t *BufLoc = Buf + Offset;
445 uintX_t Addend = getAddend<ELFT>(Rel);
447 Addend += Target->getImplicitAddend(BufLoc, Type);
449 SymbolBody &Sym = this->File->getRelocTargetSym(Rel);
450 if (Target->getRelExpr(Type, Sym) != R_ABS) {
451 error(this->getLocation(Offset) + ": has non-ABS reloc");
455 uintX_t AddrLoc = this->OutSec->Addr + Offset;
457 if (!Sym.isTls() || Out<ELFT>::TlsPhdr)
458 SymVA = SignExtend64<sizeof(uintX_t) * 8>(
459 getRelocTargetVA<ELFT>(Type, Addend, AddrLoc, Sym, R_ABS));
460 Target->relocateOne(BufLoc, Type, SymVA);
464 template <class ELFT>
465 void InputSectionBase<ELFT>::relocate(uint8_t *Buf, uint8_t *BufEnd) {
466 // scanReloc function in Writer.cpp constructs Relocations
467 // vector only for SHF_ALLOC'ed sections. For other sections,
468 // we handle relocations directly here.
469 auto *IS = dyn_cast<InputSection<ELFT>>(this);
470 if (IS && !(IS->Flags & SHF_ALLOC)) {
471 if (IS->AreRelocsRela)
472 IS->relocateNonAlloc(Buf, IS->relas());
474 IS->relocateNonAlloc(Buf, IS->rels());
478 const unsigned Bits = sizeof(uintX_t) * 8;
479 for (const Relocation &Rel : Relocations) {
480 uintX_t Offset = getOffset(Rel.Offset);
481 uint8_t *BufLoc = Buf + Offset;
482 uint32_t Type = Rel.Type;
483 uintX_t A = Rel.Addend;
485 uintX_t AddrLoc = OutSec->Addr + Offset;
486 RelExpr Expr = Rel.Expr;
487 uint64_t TargetVA = SignExtend64<Bits>(
488 getRelocTargetVA<ELFT>(Type, A, AddrLoc, *Rel.Sym, Expr));
492 case R_RELAX_GOT_PC_NOPIC:
493 Target->relaxGot(BufLoc, TargetVA);
495 case R_RELAX_TLS_IE_TO_LE:
496 Target->relaxTlsIeToLe(BufLoc, Type, TargetVA);
498 case R_RELAX_TLS_LD_TO_LE:
499 Target->relaxTlsLdToLe(BufLoc, Type, TargetVA);
501 case R_RELAX_TLS_GD_TO_LE:
502 case R_RELAX_TLS_GD_TO_LE_NEG:
503 Target->relaxTlsGdToLe(BufLoc, Type, TargetVA);
505 case R_RELAX_TLS_GD_TO_IE:
506 case R_RELAX_TLS_GD_TO_IE_ABS:
507 case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
508 case R_RELAX_TLS_GD_TO_IE_END:
509 Target->relaxTlsGdToIe(BufLoc, Type, TargetVA);
512 // Patch a nop (0x60000000) to a ld.
513 if (BufLoc + 8 <= BufEnd && read32be(BufLoc + 4) == 0x60000000)
514 write32be(BufLoc + 4, 0xe8410028); // ld %r2, 40(%r1)
517 Target->relocateOne(BufLoc, Type, TargetVA);
523 template <class ELFT> void InputSection<ELFT>::writeTo(uint8_t *Buf) {
524 if (this->Type == SHT_NOBITS)
527 if (auto *S = dyn_cast<SyntheticSection<ELFT>>(this)) {
528 S->writeTo(Buf + OutSecOff);
532 // If -r is given, then an InputSection may be a relocation section.
533 if (this->Type == SHT_RELA) {
534 copyRelocations(Buf + OutSecOff, this->template getDataAs<Elf_Rela>());
537 if (this->Type == SHT_REL) {
538 copyRelocations(Buf + OutSecOff, this->template getDataAs<Elf_Rel>());
542 // Copy section contents from source object file to output file.
543 ArrayRef<uint8_t> Data = this->Data;
544 memcpy(Buf + OutSecOff, Data.data(), Data.size());
546 // Iterate over all relocation sections that apply to this section.
547 uint8_t *BufEnd = Buf + OutSecOff + Data.size();
548 this->relocate(Buf, BufEnd);
550 // The section might have a data/code generated by the linker and need
551 // to be written after the section. Usually these are thunks - small piece
552 // of code used to jump between "incompatible" functions like PIC and non-PIC
553 // or if the jump target too far and its address does not fit to the short
555 if (!Thunks.empty()) {
556 Buf += OutSecOff + getThunkOff();
557 for (const Thunk<ELFT> *T : Thunks) {
564 template <class ELFT>
565 void InputSection<ELFT>::replace(InputSection<ELFT> *Other) {
566 this->Alignment = std::max(this->Alignment, Other->Alignment);
567 Other->Repl = this->Repl;
571 template <class ELFT>
572 EhInputSection<ELFT>::EhInputSection(elf::ObjectFile<ELFT> *F,
573 const Elf_Shdr *Header, StringRef Name)
574 : InputSectionBase<ELFT>(F, Header, Name, InputSectionBase<ELFT>::EHFrame) {
575 // Mark .eh_frame sections as live by default because there are
576 // usually no relocations that point to .eh_frames. Otherwise,
577 // the garbage collector would drop all .eh_frame sections.
581 template <class ELFT>
582 bool EhInputSection<ELFT>::classof(const InputSectionData *S) {
583 return S->kind() == InputSectionBase<ELFT>::EHFrame;
586 // Returns the index of the first relocation that points to a region between
587 // Begin and Begin+Size.
588 template <class IntTy, class RelTy>
589 static unsigned getReloc(IntTy Begin, IntTy Size, const ArrayRef<RelTy> &Rels,
591 // Start search from RelocI for fast access. That works because the
592 // relocations are sorted in .eh_frame.
593 for (unsigned N = Rels.size(); RelocI < N; ++RelocI) {
594 const RelTy &Rel = Rels[RelocI];
595 if (Rel.r_offset < Begin)
598 if (Rel.r_offset < Begin + Size)
605 // .eh_frame is a sequence of CIE or FDE records.
606 // This function splits an input section into records and returns them.
607 template <class ELFT> void EhInputSection<ELFT>::split() {
608 // Early exit if already split.
609 if (!this->Pieces.empty())
612 if (this->NumRelocations) {
613 if (this->AreRelocsRela)
614 split(this->relas());
619 split(makeArrayRef<typename ELFT::Rela>(nullptr, nullptr));
622 template <class ELFT>
623 template <class RelTy>
624 void EhInputSection<ELFT>::split(ArrayRef<RelTy> Rels) {
625 ArrayRef<uint8_t> Data = this->Data;
627 for (size_t Off = 0, End = Data.size(); Off != End;) {
628 size_t Size = readEhRecordSize<ELFT>(this, Off);
629 this->Pieces.emplace_back(Off, this, Size, getReloc(Off, Size, Rels, RelI));
630 // The empty record is the end marker.
637 static size_t findNull(ArrayRef<uint8_t> A, size_t EntSize) {
638 // Optimize the common case.
639 StringRef S((const char *)A.data(), A.size());
643 for (unsigned I = 0, N = S.size(); I != N; I += EntSize) {
644 const char *B = S.begin() + I;
645 if (std::all_of(B, B + EntSize, [](char C) { return C == 0; }))
648 return StringRef::npos;
651 // Split SHF_STRINGS section. Such section is a sequence of
652 // null-terminated strings.
653 template <class ELFT>
654 void MergeInputSection<ELFT>::splitStrings(ArrayRef<uint8_t> Data,
657 bool IsAlloc = this->Flags & SHF_ALLOC;
658 while (!Data.empty()) {
659 size_t End = findNull(Data, EntSize);
660 if (End == StringRef::npos)
661 fatal(toString(this) + ": string is not null terminated");
662 size_t Size = End + EntSize;
663 Pieces.emplace_back(Off, !IsAlloc);
664 Hashes.push_back(hash_value(toStringRef(Data.slice(0, Size))));
665 Data = Data.slice(Size);
670 // Split non-SHF_STRINGS section. Such section is a sequence of
671 // fixed size records.
672 template <class ELFT>
673 void MergeInputSection<ELFT>::splitNonStrings(ArrayRef<uint8_t> Data,
675 size_t Size = Data.size();
676 assert((Size % EntSize) == 0);
677 bool IsAlloc = this->Flags & SHF_ALLOC;
678 for (unsigned I = 0, N = Size; I != N; I += EntSize) {
679 Hashes.push_back(hash_value(toStringRef(Data.slice(I, EntSize))));
680 Pieces.emplace_back(I, !IsAlloc);
684 template <class ELFT>
685 MergeInputSection<ELFT>::MergeInputSection(elf::ObjectFile<ELFT> *F,
686 const Elf_Shdr *Header,
688 : InputSectionBase<ELFT>(F, Header, Name, InputSectionBase<ELFT>::Merge) {}
690 // This function is called after we obtain a complete list of input sections
691 // that need to be linked. This is responsible to split section contents
692 // into small chunks for further processing.
694 // Note that this function is called from parallel_for_each. This must be
695 // thread-safe (i.e. no memory allocation from the pools).
696 template <class ELFT> void MergeInputSection<ELFT>::splitIntoPieces() {
697 ArrayRef<uint8_t> Data = this->Data;
698 uintX_t EntSize = this->Entsize;
699 if (this->Flags & SHF_STRINGS)
700 splitStrings(Data, EntSize);
702 splitNonStrings(Data, EntSize);
704 if (Config->GcSections && (this->Flags & SHF_ALLOC))
705 for (uintX_t Off : LiveOffsets)
706 this->getSectionPiece(Off)->Live = true;
709 template <class ELFT>
710 bool MergeInputSection<ELFT>::classof(const InputSectionData *S) {
711 return S->kind() == InputSectionBase<ELFT>::Merge;
714 // Do binary search to get a section piece at a given input offset.
715 template <class ELFT>
716 SectionPiece *MergeInputSection<ELFT>::getSectionPiece(uintX_t Offset) {
717 auto *This = static_cast<const MergeInputSection<ELFT> *>(this);
718 return const_cast<SectionPiece *>(This->getSectionPiece(Offset));
721 template <class It, class T, class Compare>
722 static It fastUpperBound(It First, It Last, const T &Value, Compare Comp) {
723 size_t Size = std::distance(First, Last);
727 const It MI = First + H;
729 First = Comp(Value, *MI) ? First : First + H;
731 return Comp(Value, *First) ? First : First + 1;
734 template <class ELFT>
736 MergeInputSection<ELFT>::getSectionPiece(uintX_t Offset) const {
737 uintX_t Size = this->Data.size();
739 fatal(toString(this) + ": entry is past the end of the section");
741 // Find the element this offset points to.
742 auto I = fastUpperBound(
743 Pieces.begin(), Pieces.end(), Offset,
744 [](const uintX_t &A, const SectionPiece &B) { return A < B.InputOff; });
749 // Returns the offset in an output section for a given input offset.
750 // Because contents of a mergeable section is not contiguous in output,
751 // it is not just an addition to a base output offset.
752 template <class ELFT>
753 typename ELFT::uint MergeInputSection<ELFT>::getOffset(uintX_t Offset) const {
754 // Initialize OffsetMap lazily.
755 std::call_once(InitOffsetMap, [&] {
756 OffsetMap.reserve(Pieces.size());
757 for (const SectionPiece &Piece : Pieces)
758 OffsetMap[Piece.InputOff] = Piece.OutputOff;
761 // Find a string starting at a given offset.
762 auto It = OffsetMap.find(Offset);
763 if (It != OffsetMap.end())
769 // If Offset is not at beginning of a section piece, it is not in the map.
770 // In that case we need to search from the original section piece vector.
771 const SectionPiece &Piece = *this->getSectionPiece(Offset);
775 uintX_t Addend = Offset - Piece.InputOff;
776 return Piece.OutputOff + Addend;
779 template class elf::InputSectionBase<ELF32LE>;
780 template class elf::InputSectionBase<ELF32BE>;
781 template class elf::InputSectionBase<ELF64LE>;
782 template class elf::InputSectionBase<ELF64BE>;
784 template class elf::InputSection<ELF32LE>;
785 template class elf::InputSection<ELF32BE>;
786 template class elf::InputSection<ELF64LE>;
787 template class elf::InputSection<ELF64BE>;
789 template class elf::EhInputSection<ELF32LE>;
790 template class elf::EhInputSection<ELF32BE>;
791 template class elf::EhInputSection<ELF64LE>;
792 template class elf::EhInputSection<ELF64BE>;
794 template class elf::MergeInputSection<ELF32LE>;
795 template class elf::MergeInputSection<ELF32BE>;
796 template class elf::MergeInputSection<ELF64LE>;
797 template class elf::MergeInputSection<ELF64BE>;
799 template std::string lld::toString(const InputSectionBase<ELF32LE> *);
800 template std::string lld::toString(const InputSectionBase<ELF32BE> *);
801 template std::string lld::toString(const InputSectionBase<ELF64LE> *);
802 template std::string lld::toString(const InputSectionBase<ELF64BE> *);