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/Support/Compression.h"
23 #include "llvm/Support/Endian.h"
27 using namespace llvm::ELF;
28 using namespace llvm::object;
29 using namespace llvm::support;
30 using namespace llvm::support::endian;
33 using namespace lld::elf;
35 // Returns a string to construct an error message.
37 std::string lld::toString(const InputSectionBase<ELFT> *Sec) {
38 return (Sec->getFile()->getName() + ":(" + Sec->Name + ")").str();
42 static ArrayRef<uint8_t> getSectionContents(elf::ObjectFile<ELFT> *File,
43 const typename ELFT::Shdr *Hdr) {
44 if (!File || Hdr->sh_type == SHT_NOBITS)
45 return makeArrayRef<uint8_t>(nullptr, Hdr->sh_size);
46 return check(File->getObj().getSectionContents(Hdr));
50 InputSectionBase<ELFT>::InputSectionBase(elf::ObjectFile<ELFT> *File,
51 uintX_t Flags, uint32_t Type,
52 uintX_t Entsize, uint32_t Link,
53 uint32_t Info, uintX_t Addralign,
54 ArrayRef<uint8_t> Data, StringRef Name,
56 : InputSectionData(SectionKind, Name, Data,
57 !Config->GcSections || !(Flags & SHF_ALLOC)),
58 File(File), Flags(Flags), Entsize(Entsize), Type(Type), Link(Link),
59 Info(Info), Repl(this) {
61 AreRelocsRela = false;
63 // The ELF spec states that a value of 0 means the section has
64 // no alignment constraits.
65 uint64_t V = std::max<uint64_t>(Addralign, 1);
66 if (!isPowerOf2_64(V))
67 fatal(toString(File) + ": section sh_addralign is not a power of 2");
69 // We reject object files having insanely large alignments even though
70 // they are allowed by the spec. I think 4GB is a reasonable limitation.
71 // We might want to relax this in the future.
73 fatal(toString(File) + ": section sh_addralign is too large");
76 // If it is not a mergeable section, overwrite the flag so that the flag
77 // is consistent with the class. This inconsistency could occur when
78 // string merging is disabled using -O0 flag.
79 if (!Config->Relocatable && !isa<MergeInputSection<ELFT>>(this))
80 this->Flags &= ~(SHF_MERGE | SHF_STRINGS);
84 InputSectionBase<ELFT>::InputSectionBase(elf::ObjectFile<ELFT> *File,
85 const Elf_Shdr *Hdr, StringRef Name,
87 : InputSectionBase(File, Hdr->sh_flags & ~SHF_INFO_LINK, Hdr->sh_type,
88 Hdr->sh_entsize, Hdr->sh_link, Hdr->sh_info,
89 Hdr->sh_addralign, getSectionContents(File, Hdr), Name,
91 this->Offset = Hdr->sh_offset;
94 template <class ELFT> size_t InputSectionBase<ELFT>::getSize() const {
95 if (auto *S = dyn_cast<SyntheticSection<ELFT>>(this))
98 if (auto *D = dyn_cast<InputSection<ELFT>>(this))
99 if (D->getThunksSize() > 0)
100 return D->getThunkOff() + D->getThunksSize();
105 // Returns a string for an error message.
106 template <class SectionT> static std::string getName(SectionT *Sec) {
107 return (Sec->getFile()->getName() + ":(" + Sec->Name + ")").str();
110 template <class ELFT>
111 typename ELFT::uint InputSectionBase<ELFT>::getOffset(uintX_t Offset) const {
114 return cast<InputSection<ELFT>>(this)->OutSecOff + Offset;
116 // For synthetic sections we treat offset -1 as the end of the section.
117 // The same approach is used for synthetic symbols (DefinedSynthetic).
118 return cast<InputSection<ELFT>>(this)->OutSecOff +
119 (Offset == uintX_t(-1) ? getSize() : Offset);
121 // The file crtbeginT.o has relocations pointing to the start of an empty
122 // .eh_frame that is known to be the first in the link. It does that to
123 // identify the start of the output .eh_frame.
126 return cast<MergeInputSection<ELFT>>(this)->getOffset(Offset);
128 llvm_unreachable("invalid section kind");
131 template <class ELFT> bool InputSectionBase<ELFT>::isCompressed() const {
132 return (Flags & SHF_COMPRESSED) || Name.startswith(".zdebug");
135 // Returns compressed data and its size when uncompressed.
136 template <class ELFT>
137 std::pair<ArrayRef<uint8_t>, uint64_t>
138 InputSectionBase<ELFT>::getElfCompressedData(ArrayRef<uint8_t> Data) {
139 // Compressed section with Elf_Chdr is the ELF standard.
140 if (Data.size() < sizeof(Elf_Chdr))
141 fatal(toString(this) + ": corrupted compressed section");
142 auto *Hdr = reinterpret_cast<const Elf_Chdr *>(Data.data());
143 if (Hdr->ch_type != ELFCOMPRESS_ZLIB)
144 fatal(toString(this) + ": unsupported compression type");
145 return {Data.slice(sizeof(*Hdr)), Hdr->ch_size};
148 // Returns compressed data and its size when uncompressed.
149 template <class ELFT>
150 std::pair<ArrayRef<uint8_t>, uint64_t>
151 InputSectionBase<ELFT>::getRawCompressedData(ArrayRef<uint8_t> Data) {
152 // Compressed sections without Elf_Chdr header contain this header
153 // instead. This is a GNU extension.
155 char Magic[4]; // Should be "ZLIB"
156 char Size[8]; // Uncompressed size in big-endian
159 if (Data.size() < sizeof(ZlibHeader))
160 fatal(toString(this) + ": corrupted compressed section");
161 auto *Hdr = reinterpret_cast<const ZlibHeader *>(Data.data());
162 if (memcmp(Hdr->Magic, "ZLIB", 4))
163 fatal(toString(this) + ": broken ZLIB-compressed section");
164 return {Data.slice(sizeof(*Hdr)), read64be(Hdr->Size)};
167 // Uncompress section contents. Note that this function is called
168 // from parallel_for_each, so it must be thread-safe.
169 template <class ELFT> void InputSectionBase<ELFT>::uncompress() {
170 if (!zlib::isAvailable())
171 fatal(toString(this) +
172 ": build lld with zlib to enable compressed sections support");
174 // This section is compressed. Here we decompress it. Ideally, all
175 // compressed sections have SHF_COMPRESSED bit and their contents
176 // start with headers of Elf_Chdr type. However, sections whose
177 // names start with ".zdebug_" don't have the bit and contains a raw
178 // ZLIB-compressed data (which is a bad thing because section names
179 // shouldn't be significant in ELF.) We need to be able to read both.
180 ArrayRef<uint8_t> Buf; // Compressed data
181 size_t Size; // Uncompressed size
182 if (Flags & SHF_COMPRESSED)
183 std::tie(Buf, Size) = getElfCompressedData(Data);
185 std::tie(Buf, Size) = getRawCompressedData(Data);
190 static std::mutex Mu;
191 std::lock_guard<std::mutex> Lock(Mu);
192 OutputBuf = BAlloc.Allocate<char>(Size);
194 if (zlib::uncompress(toStringRef(Buf), OutputBuf, Size) != zlib::StatusOK)
195 fatal(toString(this) + ": error while uncompressing section");
196 Data = ArrayRef<uint8_t>((uint8_t *)OutputBuf, Size);
199 template <class ELFT>
201 InputSectionBase<ELFT>::getOffset(const DefinedRegular<ELFT> &Sym) const {
202 return getOffset(Sym.Value);
205 template <class ELFT>
206 InputSectionBase<ELFT> *InputSectionBase<ELFT>::getLinkOrderDep() const {
207 if ((Flags & SHF_LINK_ORDER) && Link != 0)
208 return getFile()->getSections()[Link];
212 // Returns a source location string. Used to construct an error message.
213 template <class ELFT>
214 std::string InputSectionBase<ELFT>::getLocation(typename ELFT::uint Offset) {
215 // First check if we can get desired values from debugging information.
216 std::string LineInfo = File->getLineInfo(this, Offset);
217 if (!LineInfo.empty())
220 // File->SourceFile contains STT_FILE symbol that contains a
221 // source file name. If it's missing, we use an object file name.
222 std::string SrcFile = File->SourceFile;
224 SrcFile = toString(File);
226 // Find a function symbol that encloses a given location.
227 for (SymbolBody *B : File->getSymbols())
228 if (auto *D = dyn_cast<DefinedRegular<ELFT>>(B))
229 if (D->Section == this && D->Type == STT_FUNC)
230 if (D->Value <= Offset && Offset < D->Value + D->Size)
231 return SrcFile + ":(function " + toString(*D) + ")";
233 // If there's no symbol, print out the offset in the section.
234 return (SrcFile + ":(" + Name + "+0x" + utohexstr(Offset) + ")").str();
237 template <class ELFT>
238 InputSection<ELFT>::InputSection() : InputSectionBase<ELFT>() {}
240 template <class ELFT>
241 InputSection<ELFT>::InputSection(uintX_t Flags, uint32_t Type,
242 uintX_t Addralign, ArrayRef<uint8_t> Data,
243 StringRef Name, Kind K)
244 : InputSectionBase<ELFT>(nullptr, Flags, Type,
245 /*Entsize*/ 0, /*Link*/ 0, /*Info*/ 0, Addralign,
248 template <class ELFT>
249 InputSection<ELFT>::InputSection(elf::ObjectFile<ELFT> *F,
250 const Elf_Shdr *Header, StringRef Name)
251 : InputSectionBase<ELFT>(F, Header, Name, Base::Regular) {}
253 template <class ELFT>
254 bool InputSection<ELFT>::classof(const InputSectionData *S) {
255 return S->kind() == Base::Regular || S->kind() == Base::Synthetic;
258 template <class ELFT>
259 InputSectionBase<ELFT> *InputSection<ELFT>::getRelocatedSection() {
260 assert(this->Type == SHT_RELA || this->Type == SHT_REL);
261 ArrayRef<InputSectionBase<ELFT> *> Sections = this->File->getSections();
262 return Sections[this->Info];
265 template <class ELFT> void InputSection<ELFT>::addThunk(const Thunk<ELFT> *T) {
269 template <class ELFT> uint64_t InputSection<ELFT>::getThunkOff() const {
270 return this->Data.size();
273 template <class ELFT> uint64_t InputSection<ELFT>::getThunksSize() const {
275 for (const Thunk<ELFT> *T : Thunks)
280 // This is used for -r. We can't use memcpy to copy relocations because we need
281 // to update symbol table offset and section index for each relocation. So we
282 // copy relocations one by one.
283 template <class ELFT>
284 template <class RelTy>
285 void InputSection<ELFT>::copyRelocations(uint8_t *Buf, ArrayRef<RelTy> Rels) {
286 InputSectionBase<ELFT> *RelocatedSection = getRelocatedSection();
288 for (const RelTy &Rel : Rels) {
289 uint32_t Type = Rel.getType(Config->Mips64EL);
290 SymbolBody &Body = this->File->getRelocTargetSym(Rel);
292 Elf_Rela *P = reinterpret_cast<Elf_Rela *>(Buf);
293 Buf += sizeof(RelTy);
296 P->r_addend = getAddend<ELFT>(Rel);
297 P->r_offset = RelocatedSection->getOffset(Rel.r_offset);
298 P->setSymbolAndType(Body.DynsymIndex, Type, Config->Mips64EL);
302 static uint32_t getARMUndefinedRelativeWeakVA(uint32_t Type, uint32_t A,
305 case R_ARM_THM_JUMP11:
312 case R_ARM_THM_JUMP19:
313 case R_ARM_THM_JUMP24:
316 // We don't want an interworking BLX to ARM
323 static uint64_t getAArch64UndefinedRelativeWeakVA(uint64_t Type, uint64_t A,
326 case R_AARCH64_CALL26:
327 case R_AARCH64_CONDBR19:
328 case R_AARCH64_JUMP26:
329 case R_AARCH64_TSTBR14:
336 template <class ELFT>
337 static typename ELFT::uint
338 getRelocTargetVA(uint32_t Type, typename ELFT::uint A, typename ELFT::uint P,
339 const SymbolBody &Body, RelExpr Expr) {
343 llvm_unreachable("cannot relocate hint relocs");
345 return In<ELFT>::Got->getTlsIndexOff() + A - In<ELFT>::Got->getSize();
347 return In<ELFT>::Got->getTlsIndexVA() + A - P;
349 return Body.getThunkVA<ELFT>() + A;
352 return Body.getThunkVA<ELFT>() + A - P;
354 return getPPC64TocBase() + A;
356 return In<ELFT>::Got->getGlobalDynOffset(Body) + A -
357 In<ELFT>::Got->getSize();
359 return In<ELFT>::Got->getGlobalDynAddr(Body) + A - P;
361 return In<ELFT>::Got->getGlobalDynAddr(Body) + A;
363 return getAArch64Page(In<ELFT>::Got->getGlobalDynAddr(Body) + A) -
366 return Body.getPltVA<ELFT>() + A;
369 return Body.getPltVA<ELFT>() + A - P;
371 return Body.getSize<ELFT>() + A;
373 return Body.getVA<ELFT>(A) - In<ELFT>::Got->getVA();
374 case R_GOTREL_FROM_END:
375 return Body.getVA<ELFT>(A) - In<ELFT>::Got->getVA() -
376 In<ELFT>::Got->getSize();
377 case R_RELAX_TLS_GD_TO_IE_END:
379 return Body.getGotOffset<ELFT>() + A - In<ELFT>::Got->getSize();
380 case R_RELAX_TLS_GD_TO_IE_ABS:
382 return Body.getGotVA<ELFT>() + A;
383 case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
385 return getAArch64Page(Body.getGotVA<ELFT>() + A) - getAArch64Page(P);
386 case R_RELAX_TLS_GD_TO_IE:
388 return Body.getGotVA<ELFT>() + A - P;
390 return In<ELFT>::Got->getVA() + A - P;
391 case R_GOTONLY_PC_FROM_END:
392 return In<ELFT>::Got->getVA() + A - P + In<ELFT>::Got->getSize();
393 case R_RELAX_TLS_LD_TO_LE:
394 case R_RELAX_TLS_IE_TO_LE:
395 case R_RELAX_TLS_GD_TO_LE:
397 // A weak undefined TLS symbol resolves to the base of the TLS
398 // block, i.e. gets a value of zero. If we pass --gc-sections to
399 // lld and .tbss is not referenced, it gets reclaimed and we don't
400 // create a TLS program header. Therefore, we resolve this
401 // statically to zero.
402 if (Body.isTls() && (Body.isLazy() || Body.isUndefined()) &&
403 Body.symbol()->isWeak())
406 return Body.getVA<ELFT>(A) +
407 alignTo(Target->TcbSize, Out<ELFT>::TlsPhdr->p_align);
408 return Body.getVA<ELFT>(A) - Out<ELFT>::TlsPhdr->p_memsz;
409 case R_RELAX_TLS_GD_TO_LE_NEG:
411 return Out<ELF32LE>::TlsPhdr->p_memsz - Body.getVA<ELFT>(A);
413 case R_RELAX_GOT_PC_NOPIC:
414 return Body.getVA<ELFT>(A);
416 return Body.getGotOffset<ELFT>() + A;
417 case R_MIPS_GOT_LOCAL_PAGE:
418 // If relocation against MIPS local symbol requires GOT entry, this entry
419 // should be initialized by 'page address'. This address is high 16-bits
420 // of sum the symbol's value and the addend.
421 return In<ELFT>::MipsGot->getVA() +
422 In<ELFT>::MipsGot->getPageEntryOffset(Body, A) -
423 In<ELFT>::MipsGot->getGp();
425 case R_MIPS_GOT_OFF32:
426 // In case of MIPS if a GOT relocation has non-zero addend this addend
427 // should be applied to the GOT entry content not to the GOT entry offset.
428 // That is why we use separate expression type.
429 return In<ELFT>::MipsGot->getVA() +
430 In<ELFT>::MipsGot->getBodyEntryOffset(Body, A) -
431 In<ELFT>::MipsGot->getGp();
433 return Body.getVA<ELFT>(A) - In<ELFT>::MipsGot->getGp();
435 return In<ELFT>::MipsGot->getVA() + In<ELFT>::MipsGot->getTlsOffset() +
436 In<ELFT>::MipsGot->getGlobalDynOffset(Body) -
437 In<ELFT>::MipsGot->getGp();
439 return In<ELFT>::MipsGot->getVA() + In<ELFT>::MipsGot->getTlsOffset() +
440 In<ELFT>::MipsGot->getTlsIndexOff() - In<ELFT>::MipsGot->getGp();
442 uint64_t SymVA = Body.getVA<ELFT>(A);
443 // If we have an undefined weak symbol, we might get here with a symbol
444 // address of zero. That could overflow, but the code must be unreachable,
445 // so don't bother doing anything at all.
448 if (Out<ELF64BE>::Opd) {
449 // If this is a local call, and we currently have the address of a
450 // function-descriptor, get the underlying code address instead.
451 uint64_t OpdStart = Out<ELF64BE>::Opd->Addr;
452 uint64_t OpdEnd = OpdStart + Out<ELF64BE>::Opd->Size;
453 bool InOpd = OpdStart <= SymVA && SymVA < OpdEnd;
455 SymVA = read64be(&Out<ELF64BE>::OpdBuf[SymVA - OpdStart]);
460 if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak()) {
461 // On ARM and AArch64 a branch to an undefined weak resolves to the
462 // next instruction, otherwise the place.
463 if (Config->EMachine == EM_ARM)
464 return getARMUndefinedRelativeWeakVA(Type, A, P);
465 if (Config->EMachine == EM_AARCH64)
466 return getAArch64UndefinedRelativeWeakVA(Type, A, P);
469 return Body.getVA<ELFT>(A) - P;
472 if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak())
473 return getAArch64Page(A);
474 return getAArch64Page(Body.getVA<ELFT>(A)) - getAArch64Page(P);
476 llvm_unreachable("Invalid expression");
479 // This function applies relocations to sections without SHF_ALLOC bit.
480 // Such sections are never mapped to memory at runtime. Debug sections are
481 // an example. Relocations in non-alloc sections are much easier to
482 // handle than in allocated sections because it will never need complex
483 // treatement such as GOT or PLT (because at runtime no one refers them).
484 // So, we handle relocations for non-alloc sections directly in this
485 // function as a performance optimization.
486 template <class ELFT>
487 template <class RelTy>
488 void InputSection<ELFT>::relocateNonAlloc(uint8_t *Buf, ArrayRef<RelTy> Rels) {
489 for (const RelTy &Rel : Rels) {
490 uint32_t Type = Rel.getType(Config->Mips64EL);
491 uintX_t Offset = this->getOffset(Rel.r_offset);
492 uint8_t *BufLoc = Buf + Offset;
493 uintX_t Addend = getAddend<ELFT>(Rel);
495 Addend += Target->getImplicitAddend(BufLoc, Type);
497 SymbolBody &Sym = this->File->getRelocTargetSym(Rel);
498 if (Target->getRelExpr(Type, Sym) != R_ABS) {
499 error(this->getLocation(Offset) + ": has non-ABS reloc");
503 uintX_t AddrLoc = this->OutSec->Addr + Offset;
505 if (!Sym.isTls() || Out<ELFT>::TlsPhdr)
506 SymVA = SignExtend64<sizeof(uintX_t) * 8>(
507 getRelocTargetVA<ELFT>(Type, Addend, AddrLoc, Sym, R_ABS));
508 Target->relocateOne(BufLoc, Type, SymVA);
512 template <class ELFT>
513 void InputSectionBase<ELFT>::relocate(uint8_t *Buf, uint8_t *BufEnd) {
514 // scanReloc function in Writer.cpp constructs Relocations
515 // vector only for SHF_ALLOC'ed sections. For other sections,
516 // we handle relocations directly here.
517 auto *IS = dyn_cast<InputSection<ELFT>>(this);
518 if (IS && !(IS->Flags & SHF_ALLOC)) {
519 if (IS->AreRelocsRela)
520 IS->relocateNonAlloc(Buf, IS->relas());
522 IS->relocateNonAlloc(Buf, IS->rels());
526 const unsigned Bits = sizeof(uintX_t) * 8;
527 for (const Relocation &Rel : Relocations) {
528 uintX_t Offset = getOffset(Rel.Offset);
529 uint8_t *BufLoc = Buf + Offset;
530 uint32_t Type = Rel.Type;
531 uintX_t A = Rel.Addend;
533 uintX_t AddrLoc = OutSec->Addr + Offset;
534 RelExpr Expr = Rel.Expr;
535 uint64_t TargetVA = SignExtend64<Bits>(
536 getRelocTargetVA<ELFT>(Type, A, AddrLoc, *Rel.Sym, Expr));
540 case R_RELAX_GOT_PC_NOPIC:
541 Target->relaxGot(BufLoc, TargetVA);
543 case R_RELAX_TLS_IE_TO_LE:
544 Target->relaxTlsIeToLe(BufLoc, Type, TargetVA);
546 case R_RELAX_TLS_LD_TO_LE:
547 Target->relaxTlsLdToLe(BufLoc, Type, TargetVA);
549 case R_RELAX_TLS_GD_TO_LE:
550 case R_RELAX_TLS_GD_TO_LE_NEG:
551 Target->relaxTlsGdToLe(BufLoc, Type, TargetVA);
553 case R_RELAX_TLS_GD_TO_IE:
554 case R_RELAX_TLS_GD_TO_IE_ABS:
555 case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
556 case R_RELAX_TLS_GD_TO_IE_END:
557 Target->relaxTlsGdToIe(BufLoc, Type, TargetVA);
560 // Patch a nop (0x60000000) to a ld.
561 if (BufLoc + 8 <= BufEnd && read32be(BufLoc + 4) == 0x60000000)
562 write32be(BufLoc + 4, 0xe8410028); // ld %r2, 40(%r1)
565 Target->relocateOne(BufLoc, Type, TargetVA);
571 template <class ELFT> void InputSection<ELFT>::writeTo(uint8_t *Buf) {
572 if (this->Type == SHT_NOBITS)
575 if (auto *S = dyn_cast<SyntheticSection<ELFT>>(this)) {
576 S->writeTo(Buf + OutSecOff);
580 // If -r is given, then an InputSection may be a relocation section.
581 if (this->Type == SHT_RELA) {
582 copyRelocations(Buf + OutSecOff, this->template getDataAs<Elf_Rela>());
585 if (this->Type == SHT_REL) {
586 copyRelocations(Buf + OutSecOff, this->template getDataAs<Elf_Rel>());
590 // Copy section contents from source object file to output file.
591 ArrayRef<uint8_t> Data = this->Data;
592 memcpy(Buf + OutSecOff, Data.data(), Data.size());
594 // Iterate over all relocation sections that apply to this section.
595 uint8_t *BufEnd = Buf + OutSecOff + Data.size();
596 this->relocate(Buf, BufEnd);
598 // The section might have a data/code generated by the linker and need
599 // to be written after the section. Usually these are thunks - small piece
600 // of code used to jump between "incompatible" functions like PIC and non-PIC
601 // or if the jump target too far and its address does not fit to the short
603 if (!Thunks.empty()) {
604 Buf += OutSecOff + getThunkOff();
605 for (const Thunk<ELFT> *T : Thunks) {
612 template <class ELFT>
613 void InputSection<ELFT>::replace(InputSection<ELFT> *Other) {
614 this->Alignment = std::max(this->Alignment, Other->Alignment);
615 Other->Repl = this->Repl;
619 template <class ELFT>
620 EhInputSection<ELFT>::EhInputSection(elf::ObjectFile<ELFT> *F,
621 const Elf_Shdr *Header, StringRef Name)
622 : InputSectionBase<ELFT>(F, Header, Name, InputSectionBase<ELFT>::EHFrame) {
623 // Mark .eh_frame sections as live by default because there are
624 // usually no relocations that point to .eh_frames. Otherwise,
625 // the garbage collector would drop all .eh_frame sections.
629 template <class ELFT>
630 bool EhInputSection<ELFT>::classof(const InputSectionData *S) {
631 return S->kind() == InputSectionBase<ELFT>::EHFrame;
634 // Returns the index of the first relocation that points to a region between
635 // Begin and Begin+Size.
636 template <class IntTy, class RelTy>
637 static unsigned getReloc(IntTy Begin, IntTy Size, const ArrayRef<RelTy> &Rels,
639 // Start search from RelocI for fast access. That works because the
640 // relocations are sorted in .eh_frame.
641 for (unsigned N = Rels.size(); RelocI < N; ++RelocI) {
642 const RelTy &Rel = Rels[RelocI];
643 if (Rel.r_offset < Begin)
646 if (Rel.r_offset < Begin + Size)
653 // .eh_frame is a sequence of CIE or FDE records.
654 // This function splits an input section into records and returns them.
655 template <class ELFT> void EhInputSection<ELFT>::split() {
656 // Early exit if already split.
657 if (!this->Pieces.empty())
660 if (this->NumRelocations) {
661 if (this->AreRelocsRela)
662 split(this->relas());
667 split(makeArrayRef<typename ELFT::Rela>(nullptr, nullptr));
670 template <class ELFT>
671 template <class RelTy>
672 void EhInputSection<ELFT>::split(ArrayRef<RelTy> Rels) {
673 ArrayRef<uint8_t> Data = this->Data;
675 for (size_t Off = 0, End = Data.size(); Off != End;) {
676 size_t Size = readEhRecordSize<ELFT>(this, Off);
677 this->Pieces.emplace_back(Off, this, Size, getReloc(Off, Size, Rels, RelI));
678 // The empty record is the end marker.
685 static size_t findNull(ArrayRef<uint8_t> A, size_t EntSize) {
686 // Optimize the common case.
687 StringRef S((const char *)A.data(), A.size());
691 for (unsigned I = 0, N = S.size(); I != N; I += EntSize) {
692 const char *B = S.begin() + I;
693 if (std::all_of(B, B + EntSize, [](char C) { return C == 0; }))
696 return StringRef::npos;
699 // Split SHF_STRINGS section. Such section is a sequence of
700 // null-terminated strings.
701 template <class ELFT>
702 void MergeInputSection<ELFT>::splitStrings(ArrayRef<uint8_t> Data,
705 bool IsAlloc = this->Flags & SHF_ALLOC;
706 while (!Data.empty()) {
707 size_t End = findNull(Data, EntSize);
708 if (End == StringRef::npos)
709 fatal(toString(this) + ": string is not null terminated");
710 size_t Size = End + EntSize;
711 Pieces.emplace_back(Off, !IsAlloc);
712 Hashes.push_back(hash_value(toStringRef(Data.slice(0, Size))));
713 Data = Data.slice(Size);
718 // Split non-SHF_STRINGS section. Such section is a sequence of
719 // fixed size records.
720 template <class ELFT>
721 void MergeInputSection<ELFT>::splitNonStrings(ArrayRef<uint8_t> Data,
723 size_t Size = Data.size();
724 assert((Size % EntSize) == 0);
725 bool IsAlloc = this->Flags & SHF_ALLOC;
726 for (unsigned I = 0, N = Size; I != N; I += EntSize) {
727 Hashes.push_back(hash_value(toStringRef(Data.slice(I, EntSize))));
728 Pieces.emplace_back(I, !IsAlloc);
732 template <class ELFT>
733 MergeInputSection<ELFT>::MergeInputSection(elf::ObjectFile<ELFT> *F,
734 const Elf_Shdr *Header,
736 : InputSectionBase<ELFT>(F, Header, Name, InputSectionBase<ELFT>::Merge) {}
738 // This function is called after we obtain a complete list of input sections
739 // that need to be linked. This is responsible to split section contents
740 // into small chunks for further processing.
742 // Note that this function is called from parallel_for_each. This must be
743 // thread-safe (i.e. no memory allocation from the pools).
744 template <class ELFT> void MergeInputSection<ELFT>::splitIntoPieces() {
745 ArrayRef<uint8_t> Data = this->Data;
746 uintX_t EntSize = this->Entsize;
747 if (this->Flags & SHF_STRINGS)
748 splitStrings(Data, EntSize);
750 splitNonStrings(Data, EntSize);
752 if (Config->GcSections && (this->Flags & SHF_ALLOC))
753 for (uintX_t Off : LiveOffsets)
754 this->getSectionPiece(Off)->Live = true;
757 template <class ELFT>
758 bool MergeInputSection<ELFT>::classof(const InputSectionData *S) {
759 return S->kind() == InputSectionBase<ELFT>::Merge;
762 // Do binary search to get a section piece at a given input offset.
763 template <class ELFT>
764 SectionPiece *MergeInputSection<ELFT>::getSectionPiece(uintX_t Offset) {
765 auto *This = static_cast<const MergeInputSection<ELFT> *>(this);
766 return const_cast<SectionPiece *>(This->getSectionPiece(Offset));
769 template <class It, class T, class Compare>
770 static It fastUpperBound(It First, It Last, const T &Value, Compare Comp) {
771 size_t Size = std::distance(First, Last);
775 const It MI = First + H;
777 First = Comp(Value, *MI) ? First : First + H;
779 return Comp(Value, *First) ? First : First + 1;
782 template <class ELFT>
784 MergeInputSection<ELFT>::getSectionPiece(uintX_t Offset) const {
785 uintX_t Size = this->Data.size();
787 fatal(toString(this) + ": entry is past the end of the section");
789 // Find the element this offset points to.
790 auto I = fastUpperBound(
791 Pieces.begin(), Pieces.end(), Offset,
792 [](const uintX_t &A, const SectionPiece &B) { return A < B.InputOff; });
797 // Returns the offset in an output section for a given input offset.
798 // Because contents of a mergeable section is not contiguous in output,
799 // it is not just an addition to a base output offset.
800 template <class ELFT>
801 typename ELFT::uint MergeInputSection<ELFT>::getOffset(uintX_t Offset) const {
802 // Initialize OffsetMap lazily.
803 std::call_once(InitOffsetMap, [&] {
804 OffsetMap.reserve(Pieces.size());
805 for (const SectionPiece &Piece : Pieces)
806 OffsetMap[Piece.InputOff] = Piece.OutputOff;
809 // Find a string starting at a given offset.
810 auto It = OffsetMap.find(Offset);
811 if (It != OffsetMap.end())
817 // If Offset is not at beginning of a section piece, it is not in the map.
818 // In that case we need to search from the original section piece vector.
819 const SectionPiece &Piece = *this->getSectionPiece(Offset);
823 uintX_t Addend = Offset - Piece.InputOff;
824 return Piece.OutputOff + Addend;
827 template class elf::InputSectionBase<ELF32LE>;
828 template class elf::InputSectionBase<ELF32BE>;
829 template class elf::InputSectionBase<ELF64LE>;
830 template class elf::InputSectionBase<ELF64BE>;
832 template class elf::InputSection<ELF32LE>;
833 template class elf::InputSection<ELF32BE>;
834 template class elf::InputSection<ELF64LE>;
835 template class elf::InputSection<ELF64BE>;
837 template class elf::EhInputSection<ELF32LE>;
838 template class elf::EhInputSection<ELF32BE>;
839 template class elf::EhInputSection<ELF64LE>;
840 template class elf::EhInputSection<ELF64BE>;
842 template class elf::MergeInputSection<ELF32LE>;
843 template class elf::MergeInputSection<ELF32BE>;
844 template class elf::MergeInputSection<ELF64LE>;
845 template class elf::MergeInputSection<ELF64BE>;
847 template std::string lld::toString(const InputSectionBase<ELF32LE> *);
848 template std::string lld::toString(const InputSectionBase<ELF32BE> *);
849 template std::string lld::toString(const InputSectionBase<ELF64LE> *);
850 template std::string lld::toString(const InputSectionBase<ELF64BE> *);