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"
13 #include "InputFiles.h"
14 #include "LinkerScript.h"
15 #include "OutputSections.h"
16 #include "Relocations.h"
18 #include "SyntheticSections.h"
21 #include "lld/Common/ErrorHandler.h"
22 #include "lld/Common/Memory.h"
23 #include "llvm/Object/Decompressor.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/Compression.h"
26 #include "llvm/Support/Endian.h"
27 #include "llvm/Support/Threading.h"
28 #include "llvm/Support/xxhash.h"
32 using namespace llvm::ELF;
33 using namespace llvm::object;
34 using namespace llvm::support;
35 using namespace llvm::support::endian;
36 using namespace llvm::sys;
39 using namespace lld::elf;
41 std::vector<InputSectionBase *> elf::InputSections;
43 // Returns a string to construct an error message.
44 std::string lld::toString(const InputSectionBase *Sec) {
45 return (toString(Sec->File) + ":(" + Sec->Name + ")").str();
48 DenseMap<SectionBase *, int> elf::buildSectionOrder() {
49 DenseMap<SectionBase *, int> SectionOrder;
50 if (Config->SymbolOrderingFile.empty())
53 // Build a map from symbols to their priorities. Symbols that didn't
54 // appear in the symbol ordering file have the lowest priority 0.
55 // All explicitly mentioned symbols have negative (higher) priorities.
56 DenseMap<StringRef, int> SymbolOrder;
57 int Priority = -Config->SymbolOrderingFile.size();
58 for (StringRef S : Config->SymbolOrderingFile)
59 SymbolOrder.insert({S, Priority++});
61 // Build a map from sections to their priorities.
62 for (InputFile *File : ObjectFiles) {
63 for (Symbol *Sym : File->getSymbols()) {
64 auto *D = dyn_cast<Defined>(Sym);
65 if (!D || !D->Section)
67 int &Priority = SectionOrder[D->Section];
68 Priority = std::min(Priority, SymbolOrder.lookup(D->getName()));
75 static ArrayRef<uint8_t> getSectionContents(ObjFile<ELFT> &File,
76 const typename ELFT::Shdr &Hdr) {
77 if (Hdr.sh_type == SHT_NOBITS)
78 return makeArrayRef<uint8_t>(nullptr, Hdr.sh_size);
79 return check(File.getObj().getSectionContents(&Hdr));
82 InputSectionBase::InputSectionBase(InputFile *File, uint64_t Flags,
83 uint32_t Type, uint64_t Entsize,
84 uint32_t Link, uint32_t Info,
85 uint32_t Alignment, ArrayRef<uint8_t> Data,
86 StringRef Name, Kind SectionKind)
87 : SectionBase(SectionKind, Name, Flags, Entsize, Alignment, Type, Info,
89 File(File), Data(Data) {
90 // In order to reduce memory allocation, we assume that mergeable
91 // sections are smaller than 4 GiB, which is not an unreasonable
92 // assumption as of 2017.
93 if (SectionKind == SectionBase::Merge && Data.size() > UINT32_MAX)
94 error(toString(this) + ": section too large");
97 AreRelocsRela = false;
99 // The ELF spec states that a value of 0 means the section has
100 // no alignment constraits.
101 uint32_t V = std::max<uint64_t>(Alignment, 1);
102 if (!isPowerOf2_64(V))
103 fatal(toString(File) + ": section sh_addralign is not a power of 2");
107 // Drop SHF_GROUP bit unless we are producing a re-linkable object file.
108 // SHF_GROUP is a marker that a section belongs to some comdat group.
109 // That flag doesn't make sense in an executable.
110 static uint64_t getFlags(uint64_t Flags) {
111 Flags &= ~(uint64_t)SHF_INFO_LINK;
112 if (!Config->Relocatable)
113 Flags &= ~(uint64_t)SHF_GROUP;
117 // GNU assembler 2.24 and LLVM 4.0.0's MC (the newest release as of
118 // March 2017) fail to infer section types for sections starting with
119 // ".init_array." or ".fini_array.". They set SHT_PROGBITS instead of
120 // SHF_INIT_ARRAY. As a result, the following assembler directive
121 // creates ".init_array.100" with SHT_PROGBITS, for example.
123 // .section .init_array.100, "aw"
125 // This function forces SHT_{INIT,FINI}_ARRAY so that we can handle
126 // incorrect inputs as if they were correct from the beginning.
127 static uint64_t getType(uint64_t Type, StringRef Name) {
128 if (Type == SHT_PROGBITS && Name.startswith(".init_array."))
129 return SHT_INIT_ARRAY;
130 if (Type == SHT_PROGBITS && Name.startswith(".fini_array."))
131 return SHT_FINI_ARRAY;
135 template <class ELFT>
136 InputSectionBase::InputSectionBase(ObjFile<ELFT> &File,
137 const typename ELFT::Shdr &Hdr,
138 StringRef Name, Kind SectionKind)
139 : InputSectionBase(&File, getFlags(Hdr.sh_flags),
140 getType(Hdr.sh_type, Name), Hdr.sh_entsize, Hdr.sh_link,
141 Hdr.sh_info, Hdr.sh_addralign,
142 getSectionContents(File, Hdr), Name, SectionKind) {
143 // We reject object files having insanely large alignments even though
144 // they are allowed by the spec. I think 4GB is a reasonable limitation.
145 // We might want to relax this in the future.
146 if (Hdr.sh_addralign > UINT32_MAX)
147 fatal(toString(&File) + ": section sh_addralign is too large");
150 size_t InputSectionBase::getSize() const {
151 if (auto *S = dyn_cast<SyntheticSection>(this))
157 uint64_t InputSectionBase::getOffsetInFile() const {
158 const uint8_t *FileStart = (const uint8_t *)File->MB.getBufferStart();
159 const uint8_t *SecStart = Data.begin();
160 return SecStart - FileStart;
163 uint64_t SectionBase::getOffset(uint64_t Offset) const {
166 auto *OS = cast<OutputSection>(this);
167 // For output sections we treat offset -1 as the end of the section.
168 return Offset == uint64_t(-1) ? OS->Size : Offset;
171 return cast<InputSection>(this)->OutSecOff + Offset;
173 auto *IS = cast<InputSection>(this);
174 // For synthetic sections we treat offset -1 as the end of the section.
175 return IS->OutSecOff + (Offset == uint64_t(-1) ? IS->getSize() : Offset);
178 // The file crtbeginT.o has relocations pointing to the start of an empty
179 // .eh_frame that is known to be the first in the link. It does that to
180 // identify the start of the output .eh_frame.
183 const MergeInputSection *MS = cast<MergeInputSection>(this);
184 if (InputSection *IS = MS->getParent())
185 return IS->OutSecOff + MS->getOffset(Offset);
186 return MS->getOffset(Offset);
188 llvm_unreachable("invalid section kind");
191 OutputSection *SectionBase::getOutputSection() {
193 if (auto *IS = dyn_cast<InputSection>(this))
194 return IS->getParent();
195 else if (auto *MS = dyn_cast<MergeInputSection>(this))
196 Sec = MS->getParent();
197 else if (auto *EH = dyn_cast<EhInputSection>(this))
198 Sec = EH->getParent();
200 return cast<OutputSection>(this);
201 return Sec ? Sec->getParent() : nullptr;
204 // Uncompress section contents if required. Note that this function
205 // is called from parallelForEach, so it must be thread-safe.
206 void InputSectionBase::maybeUncompress() {
207 if (UncompressBuf || !Decompressor::isCompressedELFSection(Flags, Name))
210 Decompressor Dec = check(Decompressor::create(Name, toStringRef(Data),
211 Config->IsLE, Config->Is64));
213 size_t Size = Dec.getDecompressedSize();
214 UncompressBuf.reset(new char[Size]());
215 if (Error E = Dec.decompress({UncompressBuf.get(), Size}))
216 fatal(toString(this) +
217 ": decompress failed: " + llvm::toString(std::move(E)));
219 Data = makeArrayRef((uint8_t *)UncompressBuf.get(), Size);
220 Flags &= ~(uint64_t)SHF_COMPRESSED;
223 InputSection *InputSectionBase::getLinkOrderDep() const {
224 if ((Flags & SHF_LINK_ORDER) && Link != 0) {
225 InputSectionBase *L = File->getSections()[Link];
226 if (auto *IS = dyn_cast<InputSection>(L))
228 error("a section with SHF_LINK_ORDER should not refer a non-regular "
235 // Returns a source location string. Used to construct an error message.
236 template <class ELFT>
237 std::string InputSectionBase::getLocation(uint64_t Offset) {
238 // We don't have file for synthetic sections.
239 if (getFile<ELFT>() == nullptr)
240 return (Config->OutputFile + ":(" + Name + "+0x" + utohexstr(Offset) + ")")
243 // First check if we can get desired values from debugging information.
244 std::string LineInfo = getFile<ELFT>()->getLineInfo(this, Offset);
245 if (!LineInfo.empty())
248 // File->SourceFile contains STT_FILE symbol that contains a
249 // source file name. If it's missing, we use an object file name.
250 std::string SrcFile = getFile<ELFT>()->SourceFile;
252 SrcFile = toString(File);
254 // Find a function symbol that encloses a given location.
255 for (Symbol *B : File->getSymbols())
256 if (auto *D = dyn_cast<Defined>(B))
257 if (D->Section == this && D->Type == STT_FUNC)
258 if (D->Value <= Offset && Offset < D->Value + D->Size)
259 return SrcFile + ":(function " + toString(*D) + ")";
261 // If there's no symbol, print out the offset in the section.
262 return (SrcFile + ":(" + Name + "+0x" + utohexstr(Offset) + ")").str();
265 // This function is intended to be used for constructing an error message.
266 // The returned message looks like this:
268 // foo.c:42 (/home/alice/possibly/very/long/path/foo.c:42)
270 // Returns an empty string if there's no way to get line info.
271 std::string InputSectionBase::getSrcMsg(const Symbol &Sym, uint64_t Offset) {
272 // Synthetic sections don't have input files.
275 return File->getSrcMsg(Sym, *this, Offset);
278 // Returns a filename string along with an optional section name. This
279 // function is intended to be used for constructing an error
280 // message. The returned message looks like this:
282 // path/to/foo.o:(function bar)
286 // path/to/foo.o:(function bar) in archive path/to/bar.a
287 std::string InputSectionBase::getObjMsg(uint64_t Off) {
288 // Synthetic sections don't have input files.
290 return ("<internal>:(" + Name + "+0x" + utohexstr(Off) + ")").str();
291 std::string Filename = File->getName();
294 if (!File->ArchiveName.empty())
295 Archive = (" in archive " + File->ArchiveName).str();
297 // Find a symbol that encloses a given location.
298 for (Symbol *B : File->getSymbols())
299 if (auto *D = dyn_cast<Defined>(B))
300 if (D->Section == this && D->Value <= Off && Off < D->Value + D->Size)
301 return Filename + ":(" + toString(*D) + ")" + Archive;
303 // If there's no symbol, print out the offset in the section.
304 return (Filename + ":(" + Name + "+0x" + utohexstr(Off) + ")" + Archive)
308 InputSection InputSection::Discarded(nullptr, 0, 0, 0, ArrayRef<uint8_t>(), "");
310 InputSection::InputSection(InputFile *F, uint64_t Flags, uint32_t Type,
311 uint32_t Alignment, ArrayRef<uint8_t> Data,
312 StringRef Name, Kind K)
313 : InputSectionBase(F, Flags, Type,
314 /*Entsize*/ 0, /*Link*/ 0, /*Info*/ 0, Alignment, Data,
317 template <class ELFT>
318 InputSection::InputSection(ObjFile<ELFT> &F, const typename ELFT::Shdr &Header,
320 : InputSectionBase(F, Header, Name, InputSectionBase::Regular) {}
322 bool InputSection::classof(const SectionBase *S) {
323 return S->kind() == SectionBase::Regular ||
324 S->kind() == SectionBase::Synthetic;
327 OutputSection *InputSection::getParent() const {
328 return cast_or_null<OutputSection>(Parent);
331 // Copy SHT_GROUP section contents. Used only for the -r option.
332 template <class ELFT> void InputSection::copyShtGroup(uint8_t *Buf) {
333 // ELFT::Word is the 32-bit integral type in the target endianness.
334 typedef typename ELFT::Word u32;
335 ArrayRef<u32> From = getDataAs<u32>();
336 auto *To = reinterpret_cast<u32 *>(Buf);
338 // The first entry is not a section number but a flag.
341 // Adjust section numbers because section numbers in an input object
342 // files are different in the output.
343 ArrayRef<InputSectionBase *> Sections = File->getSections();
344 for (uint32_t Idx : From.slice(1))
345 *To++ = Sections[Idx]->getOutputSection()->SectionIndex;
348 InputSectionBase *InputSection::getRelocatedSection() {
349 assert(Type == SHT_RELA || Type == SHT_REL);
350 ArrayRef<InputSectionBase *> Sections = File->getSections();
351 return Sections[Info];
354 // This is used for -r and --emit-relocs. We can't use memcpy to copy
355 // relocations because we need to update symbol table offset and section index
356 // for each relocation. So we copy relocations one by one.
357 template <class ELFT, class RelTy>
358 void InputSection::copyRelocations(uint8_t *Buf, ArrayRef<RelTy> Rels) {
359 InputSectionBase *Sec = getRelocatedSection();
361 for (const RelTy &Rel : Rels) {
362 RelType Type = Rel.getType(Config->IsMips64EL);
363 Symbol &Sym = getFile<ELFT>()->getRelocTargetSym(Rel);
365 auto *P = reinterpret_cast<typename ELFT::Rela *>(Buf);
366 Buf += sizeof(RelTy);
369 P->r_addend = getAddend<ELFT>(Rel);
371 // Output section VA is zero for -r, so r_offset is an offset within the
372 // section, but for --emit-relocs it is an virtual address.
373 P->r_offset = Sec->getOutputSection()->Addr + Sec->getOffset(Rel.r_offset);
374 P->setSymbolAndType(InX::SymTab->getSymbolIndex(&Sym), Type,
377 if (Sym.Type == STT_SECTION) {
378 // We combine multiple section symbols into only one per
379 // section. This means we have to update the addend. That is
380 // trivial for Elf_Rela, but for Elf_Rel we have to write to the
381 // section data. We do that by adding to the Relocation vector.
383 // .eh_frame is horribly special and can reference discarded sections. To
384 // avoid having to parse and recreate .eh_frame, we just replace any
385 // relocation in it pointing to discarded sections with R_*_NONE, which
386 // hopefully creates a frame that is ignored at runtime.
387 auto *D = dyn_cast<Defined>(&Sym);
389 error("STT_SECTION symbol should be defined");
392 SectionBase *Section = D->Section;
393 if (Section == &InputSection::Discarded) {
394 P->setSymbolAndType(0, 0, false);
398 if (Config->IsRela) {
400 Sym.getVA(getAddend<ELFT>(Rel)) - Section->getOutputSection()->Addr;
401 } else if (Config->Relocatable) {
402 const uint8_t *BufLoc = Sec->Data.begin() + Rel.r_offset;
403 Sec->Relocations.push_back({R_ABS, Type, Rel.r_offset,
404 Target->getImplicitAddend(BufLoc, Type),
412 // The ARM and AArch64 ABI handle pc-relative relocations to undefined weak
413 // references specially. The general rule is that the value of the symbol in
414 // this context is the address of the place P. A further special case is that
415 // branch relocations to an undefined weak reference resolve to the next
417 static uint32_t getARMUndefinedRelativeWeakVA(RelType Type, uint32_t A,
420 // Unresolved branch relocations to weak references resolve to next
421 // instruction, this will be either 2 or 4 bytes on from P.
422 case R_ARM_THM_JUMP11:
429 case R_ARM_THM_JUMP19:
430 case R_ARM_THM_JUMP24:
433 // We don't want an interworking BLX to ARM
435 // Unresolved non branch pc-relative relocations
436 // R_ARM_TARGET2 which can be resolved relatively is not present as it never
437 // targets a weak-reference.
438 case R_ARM_MOVW_PREL_NC:
439 case R_ARM_MOVT_PREL:
441 case R_ARM_THM_MOVW_PREL_NC:
442 case R_ARM_THM_MOVT_PREL:
445 llvm_unreachable("ARM pc-relative relocation expected\n");
448 // The comment above getARMUndefinedRelativeWeakVA applies to this function.
449 static uint64_t getAArch64UndefinedRelativeWeakVA(uint64_t Type, uint64_t A,
452 // Unresolved branch relocations to weak references resolve to next
453 // instruction, this is 4 bytes on from P.
454 case R_AARCH64_CALL26:
455 case R_AARCH64_CONDBR19:
456 case R_AARCH64_JUMP26:
457 case R_AARCH64_TSTBR14:
459 // Unresolved non branch pc-relative relocations
460 case R_AARCH64_PREL16:
461 case R_AARCH64_PREL32:
462 case R_AARCH64_PREL64:
463 case R_AARCH64_ADR_PREL_LO21:
464 case R_AARCH64_LD_PREL_LO19:
467 llvm_unreachable("AArch64 pc-relative relocation expected\n");
470 // ARM SBREL relocations are of the form S + A - B where B is the static base
471 // The ARM ABI defines base to be "addressing origin of the output segment
472 // defining the symbol S". We defined the "addressing origin"/static base to be
473 // the base of the PT_LOAD segment containing the Sym.
474 // The procedure call standard only defines a Read Write Position Independent
475 // RWPI variant so in practice we should expect the static base to be the base
476 // of the RW segment.
477 static uint64_t getARMStaticBase(const Symbol &Sym) {
478 OutputSection *OS = Sym.getOutputSection();
479 if (!OS || !OS->PtLoad || !OS->PtLoad->FirstSec)
480 fatal("SBREL relocation to " + Sym.getName() + " without static base");
481 return OS->PtLoad->FirstSec->Addr;
484 static uint64_t getRelocTargetVA(RelType Type, int64_t A, uint64_t P,
485 const Symbol &Sym, RelExpr Expr) {
490 case R_RELAX_GOT_PC_NOPIC:
493 return Sym.getVA(A) - getARMStaticBase(Sym);
495 case R_RELAX_TLS_GD_TO_IE_ABS:
496 return Sym.getGotVA() + A;
498 return InX::Got->getVA() + A - P;
499 case R_GOTONLY_PC_FROM_END:
500 return InX::Got->getVA() + A - P + InX::Got->getSize();
502 return Sym.getVA(A) - InX::Got->getVA();
503 case R_GOTREL_FROM_END:
504 return Sym.getVA(A) - InX::Got->getVA() - InX::Got->getSize();
506 case R_RELAX_TLS_GD_TO_IE_END:
507 return Sym.getGotOffset() + A - InX::Got->getSize();
509 return Sym.getGotOffset() + A;
511 case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
512 return getAArch64Page(Sym.getGotVA() + A) - getAArch64Page(P);
514 case R_RELAX_TLS_GD_TO_IE:
515 return Sym.getGotVA() + A - P;
519 llvm_unreachable("cannot relocate hint relocs");
521 return Sym.getVA(A) - InX::MipsGot->getGp();
523 return InX::MipsGot->getGp() + A;
524 case R_MIPS_GOT_GP_PC: {
525 // R_MIPS_LO16 expression has R_MIPS_GOT_GP_PC type iif the target
526 // is _gp_disp symbol. In that case we should use the following
527 // formula for calculation "AHL + GP - P + 4". For details see p. 4-19 at
528 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
529 // microMIPS variants of these relocations use slightly different
530 // expressions: AHL + GP - P + 3 for %lo() and AHL + GP - P - 1 for %hi()
531 // to correctly handle less-sugnificant bit of the microMIPS symbol.
532 uint64_t V = InX::MipsGot->getGp() + A - P;
533 if (Type == R_MIPS_LO16 || Type == R_MICROMIPS_LO16)
535 if (Type == R_MICROMIPS_LO16 || Type == R_MICROMIPS_HI16)
539 case R_MIPS_GOT_LOCAL_PAGE:
540 // If relocation against MIPS local symbol requires GOT entry, this entry
541 // should be initialized by 'page address'. This address is high 16-bits
542 // of sum the symbol's value and the addend.
543 return InX::MipsGot->getVA() + InX::MipsGot->getPageEntryOffset(Sym, A) -
544 InX::MipsGot->getGp();
546 case R_MIPS_GOT_OFF32:
547 // In case of MIPS if a GOT relocation has non-zero addend this addend
548 // should be applied to the GOT entry content not to the GOT entry offset.
549 // That is why we use separate expression type.
550 return InX::MipsGot->getVA() + InX::MipsGot->getSymEntryOffset(Sym, A) -
551 InX::MipsGot->getGp();
553 return InX::MipsGot->getVA() + InX::MipsGot->getTlsOffset() +
554 InX::MipsGot->getGlobalDynOffset(Sym) - InX::MipsGot->getGp();
556 return InX::MipsGot->getVA() + InX::MipsGot->getTlsOffset() +
557 InX::MipsGot->getTlsIndexOff() - InX::MipsGot->getGp();
559 case R_PLT_PAGE_PC: {
561 if (Sym.isUndefWeak())
562 Dest = getAArch64Page(A);
564 Dest = getAArch64Page(Sym.getVA(A));
565 return Dest - getAArch64Page(P);
569 if (Sym.isUndefWeak()) {
570 // On ARM and AArch64 a branch to an undefined weak resolves to the
571 // next instruction, otherwise the place.
572 if (Config->EMachine == EM_ARM)
573 Dest = getARMUndefinedRelativeWeakVA(Type, A, P);
574 else if (Config->EMachine == EM_AARCH64)
575 Dest = getAArch64UndefinedRelativeWeakVA(Type, A, P);
584 return Sym.getPltVA() + A;
587 return Sym.getPltVA() + A - P;
589 uint64_t SymVA = Sym.getVA(A);
590 // If we have an undefined weak symbol, we might get here with a symbol
591 // address of zero. That could overflow, but the code must be unreachable,
592 // so don't bother doing anything at all.
596 // If this is a local call, and we currently have the address of a
597 // function-descriptor, get the underlying code address instead.
598 uint64_t OpdStart = Out::Opd->Addr;
599 uint64_t OpdEnd = OpdStart + Out::Opd->Size;
600 bool InOpd = OpdStart <= SymVA && SymVA < OpdEnd;
602 SymVA = read64be(&Out::OpdBuf[SymVA - OpdStart]);
607 return getPPC64TocBase() + A;
609 return Sym.getVA(A) - P;
610 case R_RELAX_TLS_GD_TO_LE:
611 case R_RELAX_TLS_IE_TO_LE:
612 case R_RELAX_TLS_LD_TO_LE:
614 // A weak undefined TLS symbol resolves to the base of the TLS
615 // block, i.e. gets a value of zero. If we pass --gc-sections to
616 // lld and .tbss is not referenced, it gets reclaimed and we don't
617 // create a TLS program header. Therefore, we resolve this
618 // statically to zero.
619 if (Sym.isTls() && Sym.isUndefWeak())
622 return Sym.getVA(A) + alignTo(Target->TcbSize, Out::TlsPhdr->p_align);
623 return Sym.getVA(A) - Out::TlsPhdr->p_memsz;
624 case R_RELAX_TLS_GD_TO_LE_NEG:
626 return Out::TlsPhdr->p_memsz - Sym.getVA(A);
628 return A; // Sym.getSize was already folded into the addend.
630 return InX::Got->getGlobalDynAddr(Sym) + A;
632 return getAArch64Page(InX::Got->getGlobalDynAddr(Sym) + A) -
635 return InX::Got->getGlobalDynOffset(Sym) + A - InX::Got->getSize();
637 return InX::Got->getGlobalDynAddr(Sym) + A - P;
639 return InX::Got->getTlsIndexOff() + A - InX::Got->getSize();
641 return InX::Got->getTlsIndexVA() + A - P;
643 llvm_unreachable("Invalid expression");
646 // This function applies relocations to sections without SHF_ALLOC bit.
647 // Such sections are never mapped to memory at runtime. Debug sections are
648 // an example. Relocations in non-alloc sections are much easier to
649 // handle than in allocated sections because it will never need complex
650 // treatement such as GOT or PLT (because at runtime no one refers them).
651 // So, we handle relocations for non-alloc sections directly in this
652 // function as a performance optimization.
653 template <class ELFT, class RelTy>
654 void InputSection::relocateNonAlloc(uint8_t *Buf, ArrayRef<RelTy> Rels) {
655 const unsigned Bits = sizeof(typename ELFT::uint) * 8;
657 for (const RelTy &Rel : Rels) {
658 RelType Type = Rel.getType(Config->IsMips64EL);
659 uint64_t Offset = getOffset(Rel.r_offset);
660 uint8_t *BufLoc = Buf + Offset;
661 int64_t Addend = getAddend<ELFT>(Rel);
663 Addend += Target->getImplicitAddend(BufLoc, Type);
665 Symbol &Sym = getFile<ELFT>()->getRelocTargetSym(Rel);
666 RelExpr Expr = Target->getRelExpr(Type, Sym, BufLoc);
670 // GCC 8.0 or earlier have a bug that it emits R_386_GOTPC relocations
671 // against _GLOBAL_OFFSET_TABLE for .debug_info. The bug seems to have
672 // been fixed in 2017: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82630,
673 // but we need to keep this bug-compatible code for a while.
674 if (Config->EMachine == EM_386 && Type == R_386_GOTPC)
677 error(getLocation<ELFT>(Offset) + ": has non-ABS relocation " +
678 toString(Type) + " against symbol '" + toString(Sym) + "'");
682 if (Sym.isTls() && !Out::TlsPhdr)
683 Target->relocateOne(BufLoc, Type, 0);
685 Target->relocateOne(BufLoc, Type, SignExtend64<Bits>(Sym.getVA(Addend)));
689 // This is used when '-r' is given.
690 // For REL targets, InputSection::copyRelocations() may store artificial
691 // relocations aimed to update addends. They are handled in relocateAlloc()
692 // for allocatable sections, and this function does the same for
693 // non-allocatable sections, such as sections with debug information.
694 static void relocateNonAllocForRelocatable(InputSection *Sec, uint8_t *Buf) {
695 const unsigned Bits = Config->Is64 ? 64 : 32;
697 for (const Relocation &Rel : Sec->Relocations) {
698 // InputSection::copyRelocations() adds only R_ABS relocations.
699 assert(Rel.Expr == R_ABS);
700 uint8_t *BufLoc = Buf + Rel.Offset + Sec->OutSecOff;
701 uint64_t TargetVA = SignExtend64(Rel.Sym->getVA(Rel.Addend), Bits);
702 Target->relocateOne(BufLoc, Rel.Type, TargetVA);
706 template <class ELFT>
707 void InputSectionBase::relocate(uint8_t *Buf, uint8_t *BufEnd) {
708 if (Flags & SHF_ALLOC) {
709 relocateAlloc(Buf, BufEnd);
713 auto *Sec = cast<InputSection>(this);
714 if (Config->Relocatable)
715 relocateNonAllocForRelocatable(Sec, Buf);
716 else if (Sec->AreRelocsRela)
717 Sec->relocateNonAlloc<ELFT>(Buf, Sec->template relas<ELFT>());
719 Sec->relocateNonAlloc<ELFT>(Buf, Sec->template rels<ELFT>());
722 void InputSectionBase::relocateAlloc(uint8_t *Buf, uint8_t *BufEnd) {
723 assert(Flags & SHF_ALLOC);
724 const unsigned Bits = Config->Wordsize * 8;
726 for (const Relocation &Rel : Relocations) {
727 uint64_t Offset = getOffset(Rel.Offset);
728 uint8_t *BufLoc = Buf + Offset;
729 RelType Type = Rel.Type;
731 uint64_t AddrLoc = getOutputSection()->Addr + Offset;
732 RelExpr Expr = Rel.Expr;
733 uint64_t TargetVA = SignExtend64(
734 getRelocTargetVA(Type, Rel.Addend, AddrLoc, *Rel.Sym, Expr), Bits);
738 case R_RELAX_GOT_PC_NOPIC:
739 Target->relaxGot(BufLoc, TargetVA);
741 case R_RELAX_TLS_IE_TO_LE:
742 Target->relaxTlsIeToLe(BufLoc, Type, TargetVA);
744 case R_RELAX_TLS_LD_TO_LE:
745 Target->relaxTlsLdToLe(BufLoc, Type, TargetVA);
747 case R_RELAX_TLS_GD_TO_LE:
748 case R_RELAX_TLS_GD_TO_LE_NEG:
749 Target->relaxTlsGdToLe(BufLoc, Type, TargetVA);
751 case R_RELAX_TLS_GD_TO_IE:
752 case R_RELAX_TLS_GD_TO_IE_ABS:
753 case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
754 case R_RELAX_TLS_GD_TO_IE_END:
755 Target->relaxTlsGdToIe(BufLoc, Type, TargetVA);
758 // Patch a nop (0x60000000) to a ld.
759 if (BufLoc + 8 <= BufEnd && read32be(BufLoc + 4) == 0x60000000)
760 write32be(BufLoc + 4, 0xe8410028); // ld %r2, 40(%r1)
763 Target->relocateOne(BufLoc, Type, TargetVA);
769 template <class ELFT> void InputSection::writeTo(uint8_t *Buf) {
770 if (Type == SHT_NOBITS)
773 if (auto *S = dyn_cast<SyntheticSection>(this)) {
774 S->writeTo(Buf + OutSecOff);
778 // If -r or --emit-relocs is given, then an InputSection
779 // may be a relocation section.
780 if (Type == SHT_RELA) {
781 copyRelocations<ELFT>(Buf + OutSecOff, getDataAs<typename ELFT::Rela>());
784 if (Type == SHT_REL) {
785 copyRelocations<ELFT>(Buf + OutSecOff, getDataAs<typename ELFT::Rel>());
789 // If -r is given, we may have a SHT_GROUP section.
790 if (Type == SHT_GROUP) {
791 copyShtGroup<ELFT>(Buf + OutSecOff);
795 // Copy section contents from source object file to output file
796 // and then apply relocations.
797 memcpy(Buf + OutSecOff, Data.data(), Data.size());
798 uint8_t *BufEnd = Buf + OutSecOff + Data.size();
799 relocate<ELFT>(Buf, BufEnd);
802 void InputSection::replace(InputSection *Other) {
803 Alignment = std::max(Alignment, Other->Alignment);
808 template <class ELFT>
809 EhInputSection::EhInputSection(ObjFile<ELFT> &F,
810 const typename ELFT::Shdr &Header,
812 : InputSectionBase(F, Header, Name, InputSectionBase::EHFrame) {}
814 SyntheticSection *EhInputSection::getParent() const {
815 return cast_or_null<SyntheticSection>(Parent);
818 // Returns the index of the first relocation that points to a region between
819 // Begin and Begin+Size.
820 template <class IntTy, class RelTy>
821 static unsigned getReloc(IntTy Begin, IntTy Size, const ArrayRef<RelTy> &Rels,
823 // Start search from RelocI for fast access. That works because the
824 // relocations are sorted in .eh_frame.
825 for (unsigned N = Rels.size(); RelocI < N; ++RelocI) {
826 const RelTy &Rel = Rels[RelocI];
827 if (Rel.r_offset < Begin)
830 if (Rel.r_offset < Begin + Size)
837 // .eh_frame is a sequence of CIE or FDE records.
838 // This function splits an input section into records and returns them.
839 template <class ELFT> void EhInputSection::split() {
840 // Early exit if already split.
845 split<ELFT>(relas<ELFT>());
847 split<ELFT>(rels<ELFT>());
850 template <class ELFT, class RelTy>
851 void EhInputSection::split(ArrayRef<RelTy> Rels) {
853 for (size_t Off = 0, End = Data.size(); Off != End;) {
854 size_t Size = readEhRecordSize(this, Off);
855 Pieces.emplace_back(Off, this, Size, getReloc(Off, Size, Rels, RelI));
856 // The empty record is the end marker.
863 static size_t findNull(StringRef S, size_t EntSize) {
864 // Optimize the common case.
868 for (unsigned I = 0, N = S.size(); I != N; I += EntSize) {
869 const char *B = S.begin() + I;
870 if (std::all_of(B, B + EntSize, [](char C) { return C == 0; }))
873 return StringRef::npos;
876 SyntheticSection *MergeInputSection::getParent() const {
877 return cast_or_null<SyntheticSection>(Parent);
880 // Split SHF_STRINGS section. Such section is a sequence of
881 // null-terminated strings.
882 void MergeInputSection::splitStrings(ArrayRef<uint8_t> Data, size_t EntSize) {
884 bool IsAlloc = Flags & SHF_ALLOC;
885 StringRef S = toStringRef(Data);
888 size_t End = findNull(S, EntSize);
889 if (End == StringRef::npos)
890 fatal(toString(this) + ": string is not null terminated");
891 size_t Size = End + EntSize;
893 Pieces.emplace_back(Off, xxHash64(S.substr(0, Size)), !IsAlloc);
899 // Split non-SHF_STRINGS section. Such section is a sequence of
900 // fixed size records.
901 void MergeInputSection::splitNonStrings(ArrayRef<uint8_t> Data,
903 size_t Size = Data.size();
904 assert((Size % EntSize) == 0);
905 bool IsAlloc = Flags & SHF_ALLOC;
907 for (size_t I = 0; I != Size; I += EntSize)
908 Pieces.emplace_back(I, xxHash64(toStringRef(Data.slice(I, EntSize))),
912 template <class ELFT>
913 MergeInputSection::MergeInputSection(ObjFile<ELFT> &F,
914 const typename ELFT::Shdr &Header,
916 : InputSectionBase(F, Header, Name, InputSectionBase::Merge) {}
918 MergeInputSection::MergeInputSection(uint64_t Flags, uint32_t Type,
919 uint64_t Entsize, ArrayRef<uint8_t> Data,
921 : InputSectionBase(nullptr, Flags, Type, Entsize, /*Link*/ 0, /*Info*/ 0,
922 /*Alignment*/ Entsize, Data, Name, SectionBase::Merge) {}
924 // This function is called after we obtain a complete list of input sections
925 // that need to be linked. This is responsible to split section contents
926 // into small chunks for further processing.
928 // Note that this function is called from parallelForEach. This must be
929 // thread-safe (i.e. no memory allocation from the pools).
930 void MergeInputSection::splitIntoPieces() {
931 assert(Pieces.empty());
933 if (Flags & SHF_STRINGS)
934 splitStrings(Data, Entsize);
936 splitNonStrings(Data, Entsize);
938 if (Config->GcSections && (Flags & SHF_ALLOC))
939 for (uint64_t Off : LiveOffsets)
940 getSectionPiece(Off)->Live = true;
943 // Do binary search to get a section piece at a given input offset.
944 SectionPiece *MergeInputSection::getSectionPiece(uint64_t Offset) {
945 auto *This = static_cast<const MergeInputSection *>(this);
946 return const_cast<SectionPiece *>(This->getSectionPiece(Offset));
949 template <class It, class T, class Compare>
950 static It fastUpperBound(It First, It Last, const T &Value, Compare Comp) {
951 size_t Size = std::distance(First, Last);
955 const It MI = First + H;
957 First = Comp(Value, *MI) ? First : First + H;
959 return Comp(Value, *First) ? First : First + 1;
962 const SectionPiece *MergeInputSection::getSectionPiece(uint64_t Offset) const {
963 if (Data.size() <= Offset)
964 fatal(toString(this) + ": entry is past the end of the section");
966 // Find the element this offset points to.
967 auto I = fastUpperBound(
968 Pieces.begin(), Pieces.end(), Offset,
969 [](const uint64_t &A, const SectionPiece &B) { return A < B.InputOff; });
974 // Returns the offset in an output section for a given input offset.
975 // Because contents of a mergeable section is not contiguous in output,
976 // it is not just an addition to a base output offset.
977 uint64_t MergeInputSection::getOffset(uint64_t Offset) const {
981 // Initialize OffsetMap lazily.
982 llvm::call_once(InitOffsetMap, [&] {
983 OffsetMap.reserve(Pieces.size());
984 for (size_t I = 0; I < Pieces.size(); ++I)
985 OffsetMap[Pieces[I].InputOff] = I;
988 // Find a string starting at a given offset.
989 auto It = OffsetMap.find(Offset);
990 if (It != OffsetMap.end())
991 return Pieces[It->second].OutputOff;
993 // If Offset is not at beginning of a section piece, it is not in the map.
994 // In that case we need to search from the original section piece vector.
995 const SectionPiece &Piece = *getSectionPiece(Offset);
999 uint64_t Addend = Offset - Piece.InputOff;
1000 return Piece.OutputOff + Addend;
1003 template InputSection::InputSection(ObjFile<ELF32LE> &, const ELF32LE::Shdr &,
1005 template InputSection::InputSection(ObjFile<ELF32BE> &, const ELF32BE::Shdr &,
1007 template InputSection::InputSection(ObjFile<ELF64LE> &, const ELF64LE::Shdr &,
1009 template InputSection::InputSection(ObjFile<ELF64BE> &, const ELF64BE::Shdr &,
1012 template std::string InputSectionBase::getLocation<ELF32LE>(uint64_t);
1013 template std::string InputSectionBase::getLocation<ELF32BE>(uint64_t);
1014 template std::string InputSectionBase::getLocation<ELF64LE>(uint64_t);
1015 template std::string InputSectionBase::getLocation<ELF64BE>(uint64_t);
1017 template void InputSection::writeTo<ELF32LE>(uint8_t *);
1018 template void InputSection::writeTo<ELF32BE>(uint8_t *);
1019 template void InputSection::writeTo<ELF64LE>(uint8_t *);
1020 template void InputSection::writeTo<ELF64BE>(uint8_t *);
1022 template MergeInputSection::MergeInputSection(ObjFile<ELF32LE> &,
1023 const ELF32LE::Shdr &, StringRef);
1024 template MergeInputSection::MergeInputSection(ObjFile<ELF32BE> &,
1025 const ELF32BE::Shdr &, StringRef);
1026 template MergeInputSection::MergeInputSection(ObjFile<ELF64LE> &,
1027 const ELF64LE::Shdr &, StringRef);
1028 template MergeInputSection::MergeInputSection(ObjFile<ELF64BE> &,
1029 const ELF64BE::Shdr &, StringRef);
1031 template EhInputSection::EhInputSection(ObjFile<ELF32LE> &,
1032 const ELF32LE::Shdr &, StringRef);
1033 template EhInputSection::EhInputSection(ObjFile<ELF32BE> &,
1034 const ELF32BE::Shdr &, StringRef);
1035 template EhInputSection::EhInputSection(ObjFile<ELF64LE> &,
1036 const ELF64LE::Shdr &, StringRef);
1037 template EhInputSection::EhInputSection(ObjFile<ELF64BE> &,
1038 const ELF64BE::Shdr &, StringRef);
1040 template void EhInputSection::split<ELF32LE>();
1041 template void EhInputSection::split<ELF32BE>();
1042 template void EhInputSection::split<ELF64LE>();
1043 template void EhInputSection::split<ELF64BE>();