1 //===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -----------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements ELF object file writer information.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/ADT/ArrayRef.h"
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/BinaryFormat/ELF.h"
21 #include "llvm/MC/MCAsmBackend.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/MC/MCAsmLayout.h"
24 #include "llvm/MC/MCAssembler.h"
25 #include "llvm/MC/MCContext.h"
26 #include "llvm/MC/MCELFObjectWriter.h"
27 #include "llvm/MC/MCExpr.h"
28 #include "llvm/MC/MCFixup.h"
29 #include "llvm/MC/MCFixupKindInfo.h"
30 #include "llvm/MC/MCFragment.h"
31 #include "llvm/MC/MCObjectFileInfo.h"
32 #include "llvm/MC/MCObjectWriter.h"
33 #include "llvm/MC/MCSection.h"
34 #include "llvm/MC/MCSectionELF.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/MC/MCSymbolELF.h"
37 #include "llvm/MC/MCValue.h"
38 #include "llvm/MC/StringTableBuilder.h"
39 #include "llvm/Support/Allocator.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/Compression.h"
42 #include "llvm/Support/Endian.h"
43 #include "llvm/Support/Error.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/Host.h"
46 #include "llvm/Support/LEB128.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Support/SMLoc.h"
49 #include "llvm/Support/StringSaver.h"
50 #include "llvm/Support/SwapByteOrder.h"
51 #include "llvm/Support/raw_ostream.h"
65 #define DEBUG_TYPE "reloc-info"
69 using SectionIndexMapTy
= DenseMap
<const MCSectionELF
*, uint32_t>;
71 class ELFObjectWriter
;
74 bool isDwoSection(const MCSectionELF
&Sec
) {
75 return Sec
.getSectionName().endswith(".dwo");
78 class SymbolTableWriter
{
82 // indexes we are going to write to .symtab_shndx.
83 std::vector
<uint32_t> ShndxIndexes
;
85 // The numbel of symbols written so far.
88 void createSymtabShndx();
90 template <typename T
> void write(T Value
);
93 SymbolTableWriter(ELFWriter
&EWriter
, bool Is64Bit
);
95 void writeSymbol(uint32_t name
, uint8_t info
, uint64_t value
, uint64_t size
,
96 uint8_t other
, uint32_t shndx
, bool Reserved
);
98 ArrayRef
<uint32_t> getShndxIndexes() const { return ShndxIndexes
; }
102 ELFObjectWriter
&OWriter
;
103 support::endian::Writer W
;
111 static uint64_t SymbolValue(const MCSymbol
&Sym
, const MCAsmLayout
&Layout
);
112 static bool isInSymtab(const MCAsmLayout
&Layout
, const MCSymbolELF
&Symbol
,
113 bool Used
, bool Renamed
);
115 /// Helper struct for containing some precomputed information on symbols.
116 struct ELFSymbolData
{
117 const MCSymbolELF
*Symbol
;
118 uint32_t SectionIndex
;
121 // Support lexicographic sorting.
122 bool operator<(const ELFSymbolData
&RHS
) const {
123 unsigned LHSType
= Symbol
->getType();
124 unsigned RHSType
= RHS
.Symbol
->getType();
125 if (LHSType
== ELF::STT_SECTION
&& RHSType
!= ELF::STT_SECTION
)
127 if (LHSType
!= ELF::STT_SECTION
&& RHSType
== ELF::STT_SECTION
)
129 if (LHSType
== ELF::STT_SECTION
&& RHSType
== ELF::STT_SECTION
)
130 return SectionIndex
< RHS
.SectionIndex
;
131 return Name
< RHS
.Name
;
136 /// @name Symbol Table Data
139 StringTableBuilder StrTabBuilder
{StringTableBuilder::ELF
};
143 // This holds the symbol table index of the last local symbol.
144 unsigned LastLocalSymbolIndex
;
145 // This holds the .strtab section index.
146 unsigned StringTableIndex
;
147 // This holds the .symtab section index.
148 unsigned SymbolTableIndex
;
150 // Sections in the order they are to be output in the section table.
151 std::vector
<const MCSectionELF
*> SectionTable
;
152 unsigned addToSectionTable(const MCSectionELF
*Sec
);
154 // TargetObjectWriter wrappers.
155 bool is64Bit() const;
156 bool hasRelocationAddend() const;
158 void align(unsigned Alignment
);
160 bool maybeWriteCompression(uint64_t Size
,
161 SmallVectorImpl
<char> &CompressedContents
,
162 bool ZLibStyle
, unsigned Alignment
);
165 ELFWriter(ELFObjectWriter
&OWriter
, raw_pwrite_stream
&OS
,
166 bool IsLittleEndian
, DwoMode Mode
)
168 W(OS
, IsLittleEndian
? support::little
: support::big
), Mode(Mode
) {}
170 void WriteWord(uint64_t Word
) {
172 W
.write
<uint64_t>(Word
);
174 W
.write
<uint32_t>(Word
);
177 template <typename T
> void write(T Val
) {
181 void writeHeader(const MCAssembler
&Asm
);
183 void writeSymbol(SymbolTableWriter
&Writer
, uint32_t StringIndex
,
184 ELFSymbolData
&MSD
, const MCAsmLayout
&Layout
);
186 // Start and end offset of each section
187 using SectionOffsetsTy
=
188 std::map
<const MCSectionELF
*, std::pair
<uint64_t, uint64_t>>;
190 // Map from a signature symbol to the group section index
191 using RevGroupMapTy
= DenseMap
<const MCSymbol
*, unsigned>;
193 /// Compute the symbol table data
195 /// \param Asm - The assembler.
196 /// \param SectionIndexMap - Maps a section to its index.
197 /// \param RevGroupMap - Maps a signature symbol to the group section.
198 void computeSymbolTable(MCAssembler
&Asm
, const MCAsmLayout
&Layout
,
199 const SectionIndexMapTy
&SectionIndexMap
,
200 const RevGroupMapTy
&RevGroupMap
,
201 SectionOffsetsTy
&SectionOffsets
);
203 void writeAddrsigSection();
205 MCSectionELF
*createRelocationSection(MCContext
&Ctx
,
206 const MCSectionELF
&Sec
);
208 const MCSectionELF
*createStringTable(MCContext
&Ctx
);
210 void writeSectionHeader(const MCAsmLayout
&Layout
,
211 const SectionIndexMapTy
&SectionIndexMap
,
212 const SectionOffsetsTy
&SectionOffsets
);
214 void writeSectionData(const MCAssembler
&Asm
, MCSection
&Sec
,
215 const MCAsmLayout
&Layout
);
217 void WriteSecHdrEntry(uint32_t Name
, uint32_t Type
, uint64_t Flags
,
218 uint64_t Address
, uint64_t Offset
, uint64_t Size
,
219 uint32_t Link
, uint32_t Info
, uint64_t Alignment
,
222 void writeRelocations(const MCAssembler
&Asm
, const MCSectionELF
&Sec
);
224 uint64_t writeObject(MCAssembler
&Asm
, const MCAsmLayout
&Layout
);
225 void writeSection(const SectionIndexMapTy
&SectionIndexMap
,
226 uint32_t GroupSymbolIndex
, uint64_t Offset
, uint64_t Size
,
227 const MCSectionELF
&Section
);
230 class ELFObjectWriter
: public MCObjectWriter
{
231 /// The target specific ELF writer instance.
232 std::unique_ptr
<MCELFObjectTargetWriter
> TargetObjectWriter
;
234 DenseMap
<const MCSectionELF
*, std::vector
<ELFRelocationEntry
>> Relocations
;
236 DenseMap
<const MCSymbolELF
*, const MCSymbolELF
*> Renames
;
238 bool EmitAddrsigSection
= false;
239 std::vector
<const MCSymbol
*> AddrsigSyms
;
241 bool hasRelocationAddend() const;
243 bool shouldRelocateWithSymbol(const MCAssembler
&Asm
,
244 const MCSymbolRefExpr
*RefA
,
245 const MCSymbolELF
*Sym
, uint64_t C
,
246 unsigned Type
) const;
249 ELFObjectWriter(std::unique_ptr
<MCELFObjectTargetWriter
> MOTW
)
250 : TargetObjectWriter(std::move(MOTW
)) {}
252 void reset() override
{
255 MCObjectWriter::reset();
258 bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler
&Asm
,
259 const MCSymbol
&SymA
,
260 const MCFragment
&FB
, bool InSet
,
261 bool IsPCRel
) const override
;
263 virtual bool checkRelocation(MCContext
&Ctx
, SMLoc Loc
,
264 const MCSectionELF
*From
,
265 const MCSectionELF
*To
) {
269 void recordRelocation(MCAssembler
&Asm
, const MCAsmLayout
&Layout
,
270 const MCFragment
*Fragment
, const MCFixup
&Fixup
,
271 MCValue Target
, uint64_t &FixedValue
) override
;
273 void executePostLayoutBinding(MCAssembler
&Asm
,
274 const MCAsmLayout
&Layout
) override
;
276 void emitAddrsigSection() override
{ EmitAddrsigSection
= true; }
277 void addAddrsigSymbol(const MCSymbol
*Sym
) override
{
278 AddrsigSyms
.push_back(Sym
);
281 friend struct ELFWriter
;
284 class ELFSingleObjectWriter
: public ELFObjectWriter
{
285 raw_pwrite_stream
&OS
;
289 ELFSingleObjectWriter(std::unique_ptr
<MCELFObjectTargetWriter
> MOTW
,
290 raw_pwrite_stream
&OS
, bool IsLittleEndian
)
291 : ELFObjectWriter(std::move(MOTW
)), OS(OS
),
292 IsLittleEndian(IsLittleEndian
) {}
294 uint64_t writeObject(MCAssembler
&Asm
, const MCAsmLayout
&Layout
) override
{
295 return ELFWriter(*this, OS
, IsLittleEndian
, ELFWriter::AllSections
)
296 .writeObject(Asm
, Layout
);
299 friend struct ELFWriter
;
302 class ELFDwoObjectWriter
: public ELFObjectWriter
{
303 raw_pwrite_stream
&OS
, &DwoOS
;
307 ELFDwoObjectWriter(std::unique_ptr
<MCELFObjectTargetWriter
> MOTW
,
308 raw_pwrite_stream
&OS
, raw_pwrite_stream
&DwoOS
,
310 : ELFObjectWriter(std::move(MOTW
)), OS(OS
), DwoOS(DwoOS
),
311 IsLittleEndian(IsLittleEndian
) {}
313 virtual bool checkRelocation(MCContext
&Ctx
, SMLoc Loc
,
314 const MCSectionELF
*From
,
315 const MCSectionELF
*To
) override
{
316 if (isDwoSection(*From
)) {
317 Ctx
.reportError(Loc
, "A dwo section may not contain relocations");
320 if (To
&& isDwoSection(*To
)) {
321 Ctx
.reportError(Loc
, "A relocation may not refer to a dwo section");
327 uint64_t writeObject(MCAssembler
&Asm
, const MCAsmLayout
&Layout
) override
{
328 uint64_t Size
= ELFWriter(*this, OS
, IsLittleEndian
, ELFWriter::NonDwoOnly
)
329 .writeObject(Asm
, Layout
);
330 Size
+= ELFWriter(*this, DwoOS
, IsLittleEndian
, ELFWriter::DwoOnly
)
331 .writeObject(Asm
, Layout
);
336 } // end anonymous namespace
338 void ELFWriter::align(unsigned Alignment
) {
339 uint64_t Padding
= OffsetToAlignment(W
.OS
.tell(), Alignment
);
340 W
.OS
.write_zeros(Padding
);
343 unsigned ELFWriter::addToSectionTable(const MCSectionELF
*Sec
) {
344 SectionTable
.push_back(Sec
);
345 StrTabBuilder
.add(Sec
->getSectionName());
346 return SectionTable
.size();
349 void SymbolTableWriter::createSymtabShndx() {
350 if (!ShndxIndexes
.empty())
353 ShndxIndexes
.resize(NumWritten
);
356 template <typename T
> void SymbolTableWriter::write(T Value
) {
357 EWriter
.write(Value
);
360 SymbolTableWriter::SymbolTableWriter(ELFWriter
&EWriter
, bool Is64Bit
)
361 : EWriter(EWriter
), Is64Bit(Is64Bit
), NumWritten(0) {}
363 void SymbolTableWriter::writeSymbol(uint32_t name
, uint8_t info
, uint64_t value
,
364 uint64_t size
, uint8_t other
,
365 uint32_t shndx
, bool Reserved
) {
366 bool LargeIndex
= shndx
>= ELF::SHN_LORESERVE
&& !Reserved
;
371 if (!ShndxIndexes
.empty()) {
373 ShndxIndexes
.push_back(shndx
);
375 ShndxIndexes
.push_back(0);
378 uint16_t Index
= LargeIndex
? uint16_t(ELF::SHN_XINDEX
) : shndx
;
381 write(name
); // st_name
382 write(info
); // st_info
383 write(other
); // st_other
384 write(Index
); // st_shndx
385 write(value
); // st_value
386 write(size
); // st_size
388 write(name
); // st_name
389 write(uint32_t(value
)); // st_value
390 write(uint32_t(size
)); // st_size
391 write(info
); // st_info
392 write(other
); // st_other
393 write(Index
); // st_shndx
399 bool ELFWriter::is64Bit() const {
400 return OWriter
.TargetObjectWriter
->is64Bit();
403 bool ELFWriter::hasRelocationAddend() const {
404 return OWriter
.hasRelocationAddend();
407 // Emit the ELF header.
408 void ELFWriter::writeHeader(const MCAssembler
&Asm
) {
414 // emitWord method behaves differently for ELF32 and ELF64, writing
415 // 4 bytes in the former and 8 in the latter.
417 W
.OS
<< ELF::ElfMagic
; // e_ident[EI_MAG0] to e_ident[EI_MAG3]
419 W
.OS
<< char(is64Bit() ? ELF::ELFCLASS64
: ELF::ELFCLASS32
); // e_ident[EI_CLASS]
422 W
.OS
<< char(W
.Endian
== support::little
? ELF::ELFDATA2LSB
425 W
.OS
<< char(ELF::EV_CURRENT
); // e_ident[EI_VERSION]
427 W
.OS
<< char(OWriter
.TargetObjectWriter
->getOSABI());
428 // e_ident[EI_ABIVERSION]
429 W
.OS
<< char(OWriter
.TargetObjectWriter
->getABIVersion());
431 W
.OS
.write_zeros(ELF::EI_NIDENT
- ELF::EI_PAD
);
433 W
.write
<uint16_t>(ELF::ET_REL
); // e_type
435 W
.write
<uint16_t>(OWriter
.TargetObjectWriter
->getEMachine()); // e_machine = target
437 W
.write
<uint32_t>(ELF::EV_CURRENT
); // e_version
438 WriteWord(0); // e_entry, no entry point in .o file
439 WriteWord(0); // e_phoff, no program header for .o
440 WriteWord(0); // e_shoff = sec hdr table off in bytes
442 // e_flags = whatever the target wants
443 W
.write
<uint32_t>(Asm
.getELFHeaderEFlags());
445 // e_ehsize = ELF header size
446 W
.write
<uint16_t>(is64Bit() ? sizeof(ELF::Elf64_Ehdr
)
447 : sizeof(ELF::Elf32_Ehdr
));
449 W
.write
<uint16_t>(0); // e_phentsize = prog header entry size
450 W
.write
<uint16_t>(0); // e_phnum = # prog header entries = 0
452 // e_shentsize = Section header entry size
453 W
.write
<uint16_t>(is64Bit() ? sizeof(ELF::Elf64_Shdr
)
454 : sizeof(ELF::Elf32_Shdr
));
456 // e_shnum = # of section header ents
457 W
.write
<uint16_t>(0);
459 // e_shstrndx = Section # of '.shstrtab'
460 assert(StringTableIndex
< ELF::SHN_LORESERVE
);
461 W
.write
<uint16_t>(StringTableIndex
);
464 uint64_t ELFWriter::SymbolValue(const MCSymbol
&Sym
,
465 const MCAsmLayout
&Layout
) {
466 if (Sym
.isCommon() && Sym
.isExternal())
467 return Sym
.getCommonAlignment();
470 if (!Layout
.getSymbolOffset(Sym
, Res
))
473 if (Layout
.getAssembler().isThumbFunc(&Sym
))
479 static uint8_t mergeTypeForSet(uint8_t origType
, uint8_t newType
) {
480 uint8_t Type
= newType
;
482 // Propagation rules:
483 // IFUNC > FUNC > OBJECT > NOTYPE
484 // TLS_OBJECT > OBJECT > NOTYPE
486 // dont let the new type degrade the old type
490 case ELF::STT_GNU_IFUNC
:
491 if (Type
== ELF::STT_FUNC
|| Type
== ELF::STT_OBJECT
||
492 Type
== ELF::STT_NOTYPE
|| Type
== ELF::STT_TLS
)
493 Type
= ELF::STT_GNU_IFUNC
;
496 if (Type
== ELF::STT_OBJECT
|| Type
== ELF::STT_NOTYPE
||
497 Type
== ELF::STT_TLS
)
498 Type
= ELF::STT_FUNC
;
500 case ELF::STT_OBJECT
:
501 if (Type
== ELF::STT_NOTYPE
)
502 Type
= ELF::STT_OBJECT
;
505 if (Type
== ELF::STT_OBJECT
|| Type
== ELF::STT_NOTYPE
||
506 Type
== ELF::STT_GNU_IFUNC
|| Type
== ELF::STT_FUNC
)
514 void ELFWriter::writeSymbol(SymbolTableWriter
&Writer
, uint32_t StringIndex
,
515 ELFSymbolData
&MSD
, const MCAsmLayout
&Layout
) {
516 const auto &Symbol
= cast
<MCSymbolELF
>(*MSD
.Symbol
);
517 const MCSymbolELF
*Base
=
518 cast_or_null
<MCSymbolELF
>(Layout
.getBaseSymbol(Symbol
));
520 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
522 bool IsReserved
= !Base
|| Symbol
.isCommon();
524 // Binding and Type share the same byte as upper and lower nibbles
525 uint8_t Binding
= Symbol
.getBinding();
526 uint8_t Type
= Symbol
.getType();
528 Type
= mergeTypeForSet(Type
, Base
->getType());
530 uint8_t Info
= (Binding
<< 4) | Type
;
532 // Other and Visibility share the same byte with Visibility using the lower
534 uint8_t Visibility
= Symbol
.getVisibility();
535 uint8_t Other
= Symbol
.getOther() | Visibility
;
537 uint64_t Value
= SymbolValue(*MSD
.Symbol
, Layout
);
540 const MCExpr
*ESize
= MSD
.Symbol
->getSize();
542 ESize
= Base
->getSize();
546 if (!ESize
->evaluateKnownAbsolute(Res
, Layout
))
547 report_fatal_error("Size expression must be absolute.");
551 // Write out the symbol table entry
552 Writer
.writeSymbol(StringIndex
, Info
, Value
, Size
, Other
, MSD
.SectionIndex
,
556 // True if the assembler knows nothing about the final value of the symbol.
557 // This doesn't cover the comdat issues, since in those cases the assembler
558 // can at least know that all symbols in the section will move together.
559 static bool isWeak(const MCSymbolELF
&Sym
) {
560 if (Sym
.getType() == ELF::STT_GNU_IFUNC
)
563 switch (Sym
.getBinding()) {
565 llvm_unreachable("Unknown binding");
568 case ELF::STB_GLOBAL
:
571 case ELF::STB_GNU_UNIQUE
:
576 bool ELFWriter::isInSymtab(const MCAsmLayout
&Layout
, const MCSymbolELF
&Symbol
,
577 bool Used
, bool Renamed
) {
578 if (Symbol
.isVariable()) {
579 const MCExpr
*Expr
= Symbol
.getVariableValue();
580 if (const MCSymbolRefExpr
*Ref
= dyn_cast
<MCSymbolRefExpr
>(Expr
)) {
581 if (Ref
->getKind() == MCSymbolRefExpr::VK_WEAKREF
)
592 if (Symbol
.isVariable() && Symbol
.isUndefined()) {
593 // FIXME: this is here just to diagnose the case of a var = commmon_sym.
594 Layout
.getBaseSymbol(Symbol
);
598 if (Symbol
.isUndefined() && !Symbol
.isBindingSet())
601 if (Symbol
.isTemporary())
604 if (Symbol
.getType() == ELF::STT_SECTION
)
610 void ELFWriter::computeSymbolTable(
611 MCAssembler
&Asm
, const MCAsmLayout
&Layout
,
612 const SectionIndexMapTy
&SectionIndexMap
, const RevGroupMapTy
&RevGroupMap
,
613 SectionOffsetsTy
&SectionOffsets
) {
614 MCContext
&Ctx
= Asm
.getContext();
615 SymbolTableWriter
Writer(*this, is64Bit());
618 unsigned EntrySize
= is64Bit() ? ELF::SYMENTRY_SIZE64
: ELF::SYMENTRY_SIZE32
;
619 MCSectionELF
*SymtabSection
=
620 Ctx
.getELFSection(".symtab", ELF::SHT_SYMTAB
, 0, EntrySize
, "");
621 SymtabSection
->setAlignment(is64Bit() ? 8 : 4);
622 SymbolTableIndex
= addToSectionTable(SymtabSection
);
624 align(SymtabSection
->getAlignment());
625 uint64_t SecStart
= W
.OS
.tell();
627 // The first entry is the undefined symbol entry.
628 Writer
.writeSymbol(0, 0, 0, 0, 0, 0, false);
630 std::vector
<ELFSymbolData
> LocalSymbolData
;
631 std::vector
<ELFSymbolData
> ExternalSymbolData
;
633 // Add the data for the symbols.
634 bool HasLargeSectionIndex
= false;
635 for (const MCSymbol
&S
: Asm
.symbols()) {
636 const auto &Symbol
= cast
<MCSymbolELF
>(S
);
637 bool Used
= Symbol
.isUsedInReloc();
638 bool WeakrefUsed
= Symbol
.isWeakrefUsedInReloc();
639 bool isSignature
= Symbol
.isSignature();
641 if (!isInSymtab(Layout
, Symbol
, Used
|| WeakrefUsed
|| isSignature
,
642 OWriter
.Renames
.count(&Symbol
)))
645 if (Symbol
.isTemporary() && Symbol
.isUndefined()) {
646 Ctx
.reportError(SMLoc(), "Undefined temporary symbol");
651 MSD
.Symbol
= cast
<MCSymbolELF
>(&Symbol
);
653 bool Local
= Symbol
.getBinding() == ELF::STB_LOCAL
;
654 assert(Local
|| !Symbol
.isTemporary());
656 if (Symbol
.isAbsolute()) {
657 MSD
.SectionIndex
= ELF::SHN_ABS
;
658 } else if (Symbol
.isCommon()) {
660 MSD
.SectionIndex
= ELF::SHN_COMMON
;
661 } else if (Symbol
.isUndefined()) {
662 if (isSignature
&& !Used
) {
663 MSD
.SectionIndex
= RevGroupMap
.lookup(&Symbol
);
664 if (MSD
.SectionIndex
>= ELF::SHN_LORESERVE
)
665 HasLargeSectionIndex
= true;
667 MSD
.SectionIndex
= ELF::SHN_UNDEF
;
670 const MCSectionELF
&Section
=
671 static_cast<const MCSectionELF
&>(Symbol
.getSection());
673 // We may end up with a situation when section symbol is technically
674 // defined, but should not be. That happens because we explicitly
675 // pre-create few .debug_* sections to have accessors.
676 // And if these sections were not really defined in the code, but were
677 // referenced, we simply error out.
678 if (!Section
.isRegistered()) {
679 assert(static_cast<const MCSymbolELF
&>(Symbol
).getType() ==
681 Ctx
.reportError(SMLoc(),
682 "Undefined section reference: " + Symbol
.getName());
686 if (Mode
== NonDwoOnly
&& isDwoSection(Section
))
688 MSD
.SectionIndex
= SectionIndexMap
.lookup(&Section
);
689 assert(MSD
.SectionIndex
&& "Invalid section index!");
690 if (MSD
.SectionIndex
>= ELF::SHN_LORESERVE
)
691 HasLargeSectionIndex
= true;
694 StringRef Name
= Symbol
.getName();
696 // Sections have their own string table
697 if (Symbol
.getType() != ELF::STT_SECTION
) {
699 StrTabBuilder
.add(Name
);
703 LocalSymbolData
.push_back(MSD
);
705 ExternalSymbolData
.push_back(MSD
);
708 // This holds the .symtab_shndx section index.
709 unsigned SymtabShndxSectionIndex
= 0;
711 if (HasLargeSectionIndex
) {
712 MCSectionELF
*SymtabShndxSection
=
713 Ctx
.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX
, 0, 4, "");
714 SymtabShndxSectionIndex
= addToSectionTable(SymtabShndxSection
);
715 SymtabShndxSection
->setAlignment(4);
718 ArrayRef
<std::string
> FileNames
= Asm
.getFileNames();
719 for (const std::string
&Name
: FileNames
)
720 StrTabBuilder
.add(Name
);
722 StrTabBuilder
.finalize();
724 // File symbols are emitted first and handled separately from normal symbols,
725 // i.e. a non-STT_FILE symbol with the same name may appear.
726 for (const std::string
&Name
: FileNames
)
727 Writer
.writeSymbol(StrTabBuilder
.getOffset(Name
),
728 ELF::STT_FILE
| ELF::STB_LOCAL
, 0, 0, ELF::STV_DEFAULT
,
731 // Symbols are required to be in lexicographic order.
732 array_pod_sort(LocalSymbolData
.begin(), LocalSymbolData
.end());
733 array_pod_sort(ExternalSymbolData
.begin(), ExternalSymbolData
.end());
735 // Set the symbol indices. Local symbols must come before all other
736 // symbols with non-local bindings.
737 unsigned Index
= FileNames
.size() + 1;
739 for (ELFSymbolData
&MSD
: LocalSymbolData
) {
740 unsigned StringIndex
= MSD
.Symbol
->getType() == ELF::STT_SECTION
742 : StrTabBuilder
.getOffset(MSD
.Name
);
743 MSD
.Symbol
->setIndex(Index
++);
744 writeSymbol(Writer
, StringIndex
, MSD
, Layout
);
747 // Write the symbol table entries.
748 LastLocalSymbolIndex
= Index
;
750 for (ELFSymbolData
&MSD
: ExternalSymbolData
) {
751 unsigned StringIndex
= StrTabBuilder
.getOffset(MSD
.Name
);
752 MSD
.Symbol
->setIndex(Index
++);
753 writeSymbol(Writer
, StringIndex
, MSD
, Layout
);
754 assert(MSD
.Symbol
->getBinding() != ELF::STB_LOCAL
);
757 uint64_t SecEnd
= W
.OS
.tell();
758 SectionOffsets
[SymtabSection
] = std::make_pair(SecStart
, SecEnd
);
760 ArrayRef
<uint32_t> ShndxIndexes
= Writer
.getShndxIndexes();
761 if (ShndxIndexes
.empty()) {
762 assert(SymtabShndxSectionIndex
== 0);
765 assert(SymtabShndxSectionIndex
!= 0);
767 SecStart
= W
.OS
.tell();
768 const MCSectionELF
*SymtabShndxSection
=
769 SectionTable
[SymtabShndxSectionIndex
- 1];
770 for (uint32_t Index
: ShndxIndexes
)
772 SecEnd
= W
.OS
.tell();
773 SectionOffsets
[SymtabShndxSection
] = std::make_pair(SecStart
, SecEnd
);
776 void ELFWriter::writeAddrsigSection() {
777 for (const MCSymbol
*Sym
: OWriter
.AddrsigSyms
)
778 encodeULEB128(Sym
->getIndex(), W
.OS
);
781 MCSectionELF
*ELFWriter::createRelocationSection(MCContext
&Ctx
,
782 const MCSectionELF
&Sec
) {
783 if (OWriter
.Relocations
[&Sec
].empty())
786 const StringRef SectionName
= Sec
.getSectionName();
787 std::string RelaSectionName
= hasRelocationAddend() ? ".rela" : ".rel";
788 RelaSectionName
+= SectionName
;
791 if (hasRelocationAddend())
792 EntrySize
= is64Bit() ? sizeof(ELF::Elf64_Rela
) : sizeof(ELF::Elf32_Rela
);
794 EntrySize
= is64Bit() ? sizeof(ELF::Elf64_Rel
) : sizeof(ELF::Elf32_Rel
);
797 if (Sec
.getFlags() & ELF::SHF_GROUP
)
798 Flags
= ELF::SHF_GROUP
;
800 MCSectionELF
*RelaSection
= Ctx
.createELFRelSection(
801 RelaSectionName
, hasRelocationAddend() ? ELF::SHT_RELA
: ELF::SHT_REL
,
802 Flags
, EntrySize
, Sec
.getGroup(), &Sec
);
803 RelaSection
->setAlignment(is64Bit() ? 8 : 4);
807 // Include the debug info compression header.
808 bool ELFWriter::maybeWriteCompression(
809 uint64_t Size
, SmallVectorImpl
<char> &CompressedContents
, bool ZLibStyle
,
810 unsigned Alignment
) {
813 is64Bit() ? sizeof(ELF::Elf32_Chdr
) : sizeof(ELF::Elf64_Chdr
);
814 if (Size
<= HdrSize
+ CompressedContents
.size())
816 // Platform specific header is followed by compressed data.
818 // Write Elf64_Chdr header.
819 write(static_cast<ELF::Elf64_Word
>(ELF::ELFCOMPRESS_ZLIB
));
820 write(static_cast<ELF::Elf64_Word
>(0)); // ch_reserved field.
821 write(static_cast<ELF::Elf64_Xword
>(Size
));
822 write(static_cast<ELF::Elf64_Xword
>(Alignment
));
824 // Write Elf32_Chdr header otherwise.
825 write(static_cast<ELF::Elf32_Word
>(ELF::ELFCOMPRESS_ZLIB
));
826 write(static_cast<ELF::Elf32_Word
>(Size
));
827 write(static_cast<ELF::Elf32_Word
>(Alignment
));
832 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
833 // useful for consumers to preallocate a buffer to decompress into.
834 const StringRef Magic
= "ZLIB";
835 if (Size
<= Magic
.size() + sizeof(Size
) + CompressedContents
.size())
838 support::endian::write(W
.OS
, Size
, support::big
);
842 void ELFWriter::writeSectionData(const MCAssembler
&Asm
, MCSection
&Sec
,
843 const MCAsmLayout
&Layout
) {
844 MCSectionELF
&Section
= static_cast<MCSectionELF
&>(Sec
);
845 StringRef SectionName
= Section
.getSectionName();
847 auto &MC
= Asm
.getContext();
848 const auto &MAI
= MC
.getAsmInfo();
850 // Compressing debug_frame requires handling alignment fragments which is
851 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
852 // for writing to arbitrary buffers) for little benefit.
853 bool CompressionEnabled
=
854 MAI
->compressDebugSections() != DebugCompressionType::None
;
855 if (!CompressionEnabled
|| !SectionName
.startswith(".debug_") ||
856 SectionName
== ".debug_frame") {
857 Asm
.writeSectionData(W
.OS
, &Section
, Layout
);
861 assert((MAI
->compressDebugSections() == DebugCompressionType::Z
||
862 MAI
->compressDebugSections() == DebugCompressionType::GNU
) &&
863 "expected zlib or zlib-gnu style compression");
865 SmallVector
<char, 128> UncompressedData
;
866 raw_svector_ostream
VecOS(UncompressedData
);
867 Asm
.writeSectionData(VecOS
, &Section
, Layout
);
869 SmallVector
<char, 128> CompressedContents
;
870 if (Error E
= zlib::compress(
871 StringRef(UncompressedData
.data(), UncompressedData
.size()),
872 CompressedContents
)) {
873 consumeError(std::move(E
));
874 W
.OS
<< UncompressedData
;
878 bool ZlibStyle
= MAI
->compressDebugSections() == DebugCompressionType::Z
;
879 if (!maybeWriteCompression(UncompressedData
.size(), CompressedContents
,
880 ZlibStyle
, Sec
.getAlignment())) {
881 W
.OS
<< UncompressedData
;
886 // Set the compressed flag. That is zlib style.
887 Section
.setFlags(Section
.getFlags() | ELF::SHF_COMPRESSED
);
889 // Add "z" prefix to section name. This is zlib-gnu style.
890 MC
.renameELFSection(&Section
, (".z" + SectionName
.drop_front(1)).str());
891 W
.OS
<< CompressedContents
;
894 void ELFWriter::WriteSecHdrEntry(uint32_t Name
, uint32_t Type
, uint64_t Flags
,
895 uint64_t Address
, uint64_t Offset
,
896 uint64_t Size
, uint32_t Link
, uint32_t Info
,
897 uint64_t Alignment
, uint64_t EntrySize
) {
898 W
.write
<uint32_t>(Name
); // sh_name: index into string table
899 W
.write
<uint32_t>(Type
); // sh_type
900 WriteWord(Flags
); // sh_flags
901 WriteWord(Address
); // sh_addr
902 WriteWord(Offset
); // sh_offset
903 WriteWord(Size
); // sh_size
904 W
.write
<uint32_t>(Link
); // sh_link
905 W
.write
<uint32_t>(Info
); // sh_info
906 WriteWord(Alignment
); // sh_addralign
907 WriteWord(EntrySize
); // sh_entsize
910 void ELFWriter::writeRelocations(const MCAssembler
&Asm
,
911 const MCSectionELF
&Sec
) {
912 std::vector
<ELFRelocationEntry
> &Relocs
= OWriter
.Relocations
[&Sec
];
914 // We record relocations by pushing to the end of a vector. Reverse the vector
915 // to get the relocations in the order they were created.
916 // In most cases that is not important, but it can be for special sections
917 // (.eh_frame) or specific relocations (TLS optimizations on SystemZ).
918 std::reverse(Relocs
.begin(), Relocs
.end());
920 // Sort the relocation entries. MIPS needs this.
921 OWriter
.TargetObjectWriter
->sortRelocs(Asm
, Relocs
);
923 for (unsigned i
= 0, e
= Relocs
.size(); i
!= e
; ++i
) {
924 const ELFRelocationEntry
&Entry
= Relocs
[e
- i
- 1];
925 unsigned Index
= Entry
.Symbol
? Entry
.Symbol
->getIndex() : 0;
929 if (OWriter
.TargetObjectWriter
->getEMachine() == ELF::EM_MIPS
) {
930 write(uint32_t(Index
));
932 write(OWriter
.TargetObjectWriter
->getRSsym(Entry
.Type
));
933 write(OWriter
.TargetObjectWriter
->getRType3(Entry
.Type
));
934 write(OWriter
.TargetObjectWriter
->getRType2(Entry
.Type
));
935 write(OWriter
.TargetObjectWriter
->getRType(Entry
.Type
));
937 struct ELF::Elf64_Rela ERE64
;
938 ERE64
.setSymbolAndType(Index
, Entry
.Type
);
941 if (hasRelocationAddend())
944 write(uint32_t(Entry
.Offset
));
946 struct ELF::Elf32_Rela ERE32
;
947 ERE32
.setSymbolAndType(Index
, Entry
.Type
);
950 if (hasRelocationAddend())
951 write(uint32_t(Entry
.Addend
));
953 if (OWriter
.TargetObjectWriter
->getEMachine() == ELF::EM_MIPS
) {
955 OWriter
.TargetObjectWriter
->getRType2(Entry
.Type
)) {
956 write(uint32_t(Entry
.Offset
));
958 ERE32
.setSymbolAndType(0, RType
);
963 OWriter
.TargetObjectWriter
->getRType3(Entry
.Type
)) {
964 write(uint32_t(Entry
.Offset
));
966 ERE32
.setSymbolAndType(0, RType
);
975 const MCSectionELF
*ELFWriter::createStringTable(MCContext
&Ctx
) {
976 const MCSectionELF
*StrtabSection
= SectionTable
[StringTableIndex
- 1];
977 StrTabBuilder
.write(W
.OS
);
978 return StrtabSection
;
981 void ELFWriter::writeSection(const SectionIndexMapTy
&SectionIndexMap
,
982 uint32_t GroupSymbolIndex
, uint64_t Offset
,
983 uint64_t Size
, const MCSectionELF
&Section
) {
984 uint64_t sh_link
= 0;
985 uint64_t sh_info
= 0;
987 switch(Section
.getType()) {
992 case ELF::SHT_DYNAMIC
:
993 llvm_unreachable("SHT_DYNAMIC in a relocatable object");
996 case ELF::SHT_RELA
: {
997 sh_link
= SymbolTableIndex
;
998 assert(sh_link
&& ".symtab not found");
999 const MCSection
*InfoSection
= Section
.getAssociatedSection();
1000 sh_info
= SectionIndexMap
.lookup(cast
<MCSectionELF
>(InfoSection
));
1004 case ELF::SHT_SYMTAB
:
1005 sh_link
= StringTableIndex
;
1006 sh_info
= LastLocalSymbolIndex
;
1009 case ELF::SHT_SYMTAB_SHNDX
:
1010 case ELF::SHT_LLVM_CALL_GRAPH_PROFILE
:
1011 case ELF::SHT_LLVM_ADDRSIG
:
1012 sh_link
= SymbolTableIndex
;
1015 case ELF::SHT_GROUP
:
1016 sh_link
= SymbolTableIndex
;
1017 sh_info
= GroupSymbolIndex
;
1021 if (Section
.getFlags() & ELF::SHF_LINK_ORDER
) {
1022 const MCSymbol
*Sym
= Section
.getAssociatedSymbol();
1023 const MCSectionELF
*Sec
= cast
<MCSectionELF
>(&Sym
->getSection());
1024 sh_link
= SectionIndexMap
.lookup(Sec
);
1027 WriteSecHdrEntry(StrTabBuilder
.getOffset(Section
.getSectionName()),
1028 Section
.getType(), Section
.getFlags(), 0, Offset
, Size
,
1029 sh_link
, sh_info
, Section
.getAlignment(),
1030 Section
.getEntrySize());
1033 void ELFWriter::writeSectionHeader(
1034 const MCAsmLayout
&Layout
, const SectionIndexMapTy
&SectionIndexMap
,
1035 const SectionOffsetsTy
&SectionOffsets
) {
1036 const unsigned NumSections
= SectionTable
.size();
1038 // Null section first.
1039 uint64_t FirstSectionSize
=
1040 (NumSections
+ 1) >= ELF::SHN_LORESERVE
? NumSections
+ 1 : 0;
1041 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize
, 0, 0, 0, 0);
1043 for (const MCSectionELF
*Section
: SectionTable
) {
1044 uint32_t GroupSymbolIndex
;
1045 unsigned Type
= Section
->getType();
1046 if (Type
!= ELF::SHT_GROUP
)
1047 GroupSymbolIndex
= 0;
1049 GroupSymbolIndex
= Section
->getGroup()->getIndex();
1051 const std::pair
<uint64_t, uint64_t> &Offsets
=
1052 SectionOffsets
.find(Section
)->second
;
1054 if (Type
== ELF::SHT_NOBITS
)
1055 Size
= Layout
.getSectionAddressSize(Section
);
1057 Size
= Offsets
.second
- Offsets
.first
;
1059 writeSection(SectionIndexMap
, GroupSymbolIndex
, Offsets
.first
, Size
,
1064 uint64_t ELFWriter::writeObject(MCAssembler
&Asm
, const MCAsmLayout
&Layout
) {
1065 uint64_t StartOffset
= W
.OS
.tell();
1067 MCContext
&Ctx
= Asm
.getContext();
1068 MCSectionELF
*StrtabSection
=
1069 Ctx
.getELFSection(".strtab", ELF::SHT_STRTAB
, 0);
1070 StringTableIndex
= addToSectionTable(StrtabSection
);
1072 RevGroupMapTy RevGroupMap
;
1073 SectionIndexMapTy SectionIndexMap
;
1075 std::map
<const MCSymbol
*, std::vector
<const MCSectionELF
*>> GroupMembers
;
1077 // Write out the ELF header ...
1080 // ... then the sections ...
1081 SectionOffsetsTy SectionOffsets
;
1082 std::vector
<MCSectionELF
*> Groups
;
1083 std::vector
<MCSectionELF
*> Relocations
;
1084 for (MCSection
&Sec
: Asm
) {
1085 MCSectionELF
&Section
= static_cast<MCSectionELF
&>(Sec
);
1086 if (Mode
== NonDwoOnly
&& isDwoSection(Section
))
1088 if (Mode
== DwoOnly
&& !isDwoSection(Section
))
1091 align(Section
.getAlignment());
1093 // Remember the offset into the file for this section.
1094 uint64_t SecStart
= W
.OS
.tell();
1096 const MCSymbolELF
*SignatureSymbol
= Section
.getGroup();
1097 writeSectionData(Asm
, Section
, Layout
);
1099 uint64_t SecEnd
= W
.OS
.tell();
1100 SectionOffsets
[&Section
] = std::make_pair(SecStart
, SecEnd
);
1102 MCSectionELF
*RelSection
= createRelocationSection(Ctx
, Section
);
1104 if (SignatureSymbol
) {
1105 Asm
.registerSymbol(*SignatureSymbol
);
1106 unsigned &GroupIdx
= RevGroupMap
[SignatureSymbol
];
1108 MCSectionELF
*Group
= Ctx
.createELFGroupSection(SignatureSymbol
);
1109 GroupIdx
= addToSectionTable(Group
);
1110 Group
->setAlignment(4);
1111 Groups
.push_back(Group
);
1113 std::vector
<const MCSectionELF
*> &Members
=
1114 GroupMembers
[SignatureSymbol
];
1115 Members
.push_back(&Section
);
1117 Members
.push_back(RelSection
);
1120 SectionIndexMap
[&Section
] = addToSectionTable(&Section
);
1122 SectionIndexMap
[RelSection
] = addToSectionTable(RelSection
);
1123 Relocations
.push_back(RelSection
);
1126 OWriter
.TargetObjectWriter
->addTargetSectionFlags(Ctx
, Section
);
1129 MCSectionELF
*CGProfileSection
= nullptr;
1130 if (!Asm
.CGProfile
.empty()) {
1131 CGProfileSection
= Ctx
.getELFSection(".llvm.call-graph-profile",
1132 ELF::SHT_LLVM_CALL_GRAPH_PROFILE
,
1133 ELF::SHF_EXCLUDE
, 16, "");
1134 SectionIndexMap
[CGProfileSection
] = addToSectionTable(CGProfileSection
);
1137 for (MCSectionELF
*Group
: Groups
) {
1138 align(Group
->getAlignment());
1140 // Remember the offset into the file for this section.
1141 uint64_t SecStart
= W
.OS
.tell();
1143 const MCSymbol
*SignatureSymbol
= Group
->getGroup();
1144 assert(SignatureSymbol
);
1145 write(uint32_t(ELF::GRP_COMDAT
));
1146 for (const MCSectionELF
*Member
: GroupMembers
[SignatureSymbol
]) {
1147 uint32_t SecIndex
= SectionIndexMap
.lookup(Member
);
1151 uint64_t SecEnd
= W
.OS
.tell();
1152 SectionOffsets
[Group
] = std::make_pair(SecStart
, SecEnd
);
1155 if (Mode
== DwoOnly
) {
1156 // dwo files don't have symbol tables or relocations, but they do have
1158 StrTabBuilder
.finalize();
1160 MCSectionELF
*AddrsigSection
;
1161 if (OWriter
.EmitAddrsigSection
) {
1162 AddrsigSection
= Ctx
.getELFSection(".llvm_addrsig", ELF::SHT_LLVM_ADDRSIG
,
1164 addToSectionTable(AddrsigSection
);
1167 // Compute symbol table information.
1168 computeSymbolTable(Asm
, Layout
, SectionIndexMap
, RevGroupMap
,
1171 for (MCSectionELF
*RelSection
: Relocations
) {
1172 align(RelSection
->getAlignment());
1174 // Remember the offset into the file for this section.
1175 uint64_t SecStart
= W
.OS
.tell();
1177 writeRelocations(Asm
,
1178 cast
<MCSectionELF
>(*RelSection
->getAssociatedSection()));
1180 uint64_t SecEnd
= W
.OS
.tell();
1181 SectionOffsets
[RelSection
] = std::make_pair(SecStart
, SecEnd
);
1184 if (OWriter
.EmitAddrsigSection
) {
1185 uint64_t SecStart
= W
.OS
.tell();
1186 writeAddrsigSection();
1187 uint64_t SecEnd
= W
.OS
.tell();
1188 SectionOffsets
[AddrsigSection
] = std::make_pair(SecStart
, SecEnd
);
1192 if (CGProfileSection
) {
1193 uint64_t SecStart
= W
.OS
.tell();
1194 for (const MCAssembler::CGProfileEntry
&CGPE
: Asm
.CGProfile
) {
1195 W
.write
<uint32_t>(CGPE
.From
->getSymbol().getIndex());
1196 W
.write
<uint32_t>(CGPE
.To
->getSymbol().getIndex());
1197 W
.write
<uint64_t>(CGPE
.Count
);
1199 uint64_t SecEnd
= W
.OS
.tell();
1200 SectionOffsets
[CGProfileSection
] = std::make_pair(SecStart
, SecEnd
);
1204 uint64_t SecStart
= W
.OS
.tell();
1205 const MCSectionELF
*Sec
= createStringTable(Ctx
);
1206 uint64_t SecEnd
= W
.OS
.tell();
1207 SectionOffsets
[Sec
] = std::make_pair(SecStart
, SecEnd
);
1210 uint64_t NaturalAlignment
= is64Bit() ? 8 : 4;
1211 align(NaturalAlignment
);
1213 const uint64_t SectionHeaderOffset
= W
.OS
.tell();
1215 // ... then the section header table ...
1216 writeSectionHeader(Layout
, SectionIndexMap
, SectionOffsets
);
1218 uint16_t NumSections
= support::endian::byte_swap
<uint16_t>(
1219 (SectionTable
.size() + 1 >= ELF::SHN_LORESERVE
) ? (uint16_t)ELF::SHN_UNDEF
1220 : SectionTable
.size() + 1,
1222 unsigned NumSectionsOffset
;
1224 auto &Stream
= static_cast<raw_pwrite_stream
&>(W
.OS
);
1227 support::endian::byte_swap
<uint64_t>(SectionHeaderOffset
, W
.Endian
);
1228 Stream
.pwrite(reinterpret_cast<char *>(&Val
), sizeof(Val
),
1229 offsetof(ELF::Elf64_Ehdr
, e_shoff
));
1230 NumSectionsOffset
= offsetof(ELF::Elf64_Ehdr
, e_shnum
);
1233 support::endian::byte_swap
<uint32_t>(SectionHeaderOffset
, W
.Endian
);
1234 Stream
.pwrite(reinterpret_cast<char *>(&Val
), sizeof(Val
),
1235 offsetof(ELF::Elf32_Ehdr
, e_shoff
));
1236 NumSectionsOffset
= offsetof(ELF::Elf32_Ehdr
, e_shnum
);
1238 Stream
.pwrite(reinterpret_cast<char *>(&NumSections
), sizeof(NumSections
),
1241 return W
.OS
.tell() - StartOffset
;
1244 bool ELFObjectWriter::hasRelocationAddend() const {
1245 return TargetObjectWriter
->hasRelocationAddend();
1248 void ELFObjectWriter::executePostLayoutBinding(MCAssembler
&Asm
,
1249 const MCAsmLayout
&Layout
) {
1250 // The presence of symbol versions causes undefined symbols and
1251 // versions declared with @@@ to be renamed.
1252 for (const std::pair
<StringRef
, const MCSymbol
*> &P
: Asm
.Symvers
) {
1253 StringRef AliasName
= P
.first
;
1254 const auto &Symbol
= cast
<MCSymbolELF
>(*P
.second
);
1255 size_t Pos
= AliasName
.find('@');
1256 assert(Pos
!= StringRef::npos
);
1258 StringRef Prefix
= AliasName
.substr(0, Pos
);
1259 StringRef Rest
= AliasName
.substr(Pos
);
1260 StringRef Tail
= Rest
;
1261 if (Rest
.startswith("@@@"))
1262 Tail
= Rest
.substr(Symbol
.isUndefined() ? 2 : 1);
1265 cast
<MCSymbolELF
>(Asm
.getContext().getOrCreateSymbol(Prefix
+ Tail
));
1266 Asm
.registerSymbol(*Alias
);
1267 const MCExpr
*Value
= MCSymbolRefExpr::create(&Symbol
, Asm
.getContext());
1268 Alias
->setVariableValue(Value
);
1270 // Aliases defined with .symvar copy the binding from the symbol they alias.
1271 // This is the first place we are able to copy this information.
1272 Alias
->setExternal(Symbol
.isExternal());
1273 Alias
->setBinding(Symbol
.getBinding());
1275 if (!Symbol
.isUndefined() && !Rest
.startswith("@@@"))
1278 // FIXME: Get source locations for these errors or diagnose them earlier.
1279 if (Symbol
.isUndefined() && Rest
.startswith("@@") &&
1280 !Rest
.startswith("@@@")) {
1281 Asm
.getContext().reportError(SMLoc(), "versioned symbol " + AliasName
+
1282 " must be defined");
1286 if (Renames
.count(&Symbol
) && Renames
[&Symbol
] != Alias
) {
1287 Asm
.getContext().reportError(
1288 SMLoc(), llvm::Twine("multiple symbol versions defined for ") +
1293 Renames
.insert(std::make_pair(&Symbol
, Alias
));
1296 for (const MCSymbol
*&Sym
: AddrsigSyms
) {
1297 if (const MCSymbol
*R
= Renames
.lookup(cast
<MCSymbolELF
>(Sym
)))
1299 if (Sym
->isInSection() && Sym
->getName().startswith(".L"))
1300 Sym
= Sym
->getSection().getBeginSymbol();
1301 Sym
->setUsedInReloc();
1305 // It is always valid to create a relocation with a symbol. It is preferable
1306 // to use a relocation with a section if that is possible. Using the section
1307 // allows us to omit some local symbols from the symbol table.
1308 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler
&Asm
,
1309 const MCSymbolRefExpr
*RefA
,
1310 const MCSymbolELF
*Sym
,
1312 unsigned Type
) const {
1313 // A PCRel relocation to an absolute value has no symbol (or section). We
1314 // represent that with a relocation to a null section.
1318 MCSymbolRefExpr::VariantKind Kind
= RefA
->getKind();
1322 // The .odp creation emits a relocation against the symbol ".TOC." which
1323 // create a R_PPC64_TOC relocation. However the relocation symbol name
1324 // in final object creation should be NULL, since the symbol does not
1325 // really exist, it is just the reference to TOC base for the current
1326 // object file. Since the symbol is undefined, returning false results
1327 // in a relocation with a null section which is the desired result.
1328 case MCSymbolRefExpr::VK_PPC_TOCBASE
:
1331 // These VariantKind cause the relocation to refer to something other than
1332 // the symbol itself, like a linker generated table. Since the address of
1333 // symbol is not relevant, we cannot replace the symbol with the
1334 // section and patch the difference in the addend.
1335 case MCSymbolRefExpr::VK_GOT
:
1336 case MCSymbolRefExpr::VK_PLT
:
1337 case MCSymbolRefExpr::VK_GOTPCREL
:
1338 case MCSymbolRefExpr::VK_PPC_GOT_LO
:
1339 case MCSymbolRefExpr::VK_PPC_GOT_HI
:
1340 case MCSymbolRefExpr::VK_PPC_GOT_HA
:
1344 // An undefined symbol is not in any section, so the relocation has to point
1345 // to the symbol itself.
1346 assert(Sym
&& "Expected a symbol");
1347 if (Sym
->isUndefined())
1350 unsigned Binding
= Sym
->getBinding();
1353 llvm_unreachable("Invalid Binding");
1354 case ELF::STB_LOCAL
:
1357 // If the symbol is weak, it might be overridden by a symbol in another
1358 // file. The relocation has to point to the symbol so that the linker
1361 case ELF::STB_GLOBAL
:
1362 // Global ELF symbols can be preempted by the dynamic linker. The relocation
1363 // has to point to the symbol for a reason analogous to the STB_WEAK case.
1367 // If a relocation points to a mergeable section, we have to be careful.
1368 // If the offset is zero, a relocation with the section will encode the
1369 // same information. With a non-zero offset, the situation is different.
1370 // For example, a relocation can point 42 bytes past the end of a string.
1371 // If we change such a relocation to use the section, the linker would think
1372 // that it pointed to another string and subtracting 42 at runtime will
1373 // produce the wrong value.
1374 if (Sym
->isInSection()) {
1375 auto &Sec
= cast
<MCSectionELF
>(Sym
->getSection());
1376 unsigned Flags
= Sec
.getFlags();
1377 if (Flags
& ELF::SHF_MERGE
) {
1381 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
1382 // only handle section relocations to mergeable sections if using RELA.
1383 if (!hasRelocationAddend())
1387 // Most TLS relocations use a got, so they need the symbol. Even those that
1388 // are just an offset (@tpoff), require a symbol in gold versions before
1389 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
1390 // http://sourceware.org/PR16773.
1391 if (Flags
& ELF::SHF_TLS
)
1395 // If the symbol is a thumb function the final relocation must set the lowest
1396 // bit. With a symbol that is done by just having the symbol have that bit
1397 // set, so we would lose the bit if we relocated with the section.
1398 // FIXME: We could use the section but add the bit to the relocation value.
1399 if (Asm
.isThumbFunc(Sym
))
1402 if (TargetObjectWriter
->needsRelocateWithSymbol(*Sym
, Type
))
1407 void ELFObjectWriter::recordRelocation(MCAssembler
&Asm
,
1408 const MCAsmLayout
&Layout
,
1409 const MCFragment
*Fragment
,
1410 const MCFixup
&Fixup
, MCValue Target
,
1411 uint64_t &FixedValue
) {
1412 MCAsmBackend
&Backend
= Asm
.getBackend();
1413 bool IsPCRel
= Backend
.getFixupKindInfo(Fixup
.getKind()).Flags
&
1414 MCFixupKindInfo::FKF_IsPCRel
;
1415 const MCSectionELF
&FixupSection
= cast
<MCSectionELF
>(*Fragment
->getParent());
1416 uint64_t C
= Target
.getConstant();
1417 uint64_t FixupOffset
= Layout
.getFragmentOffset(Fragment
) + Fixup
.getOffset();
1418 MCContext
&Ctx
= Asm
.getContext();
1420 if (const MCSymbolRefExpr
*RefB
= Target
.getSymB()) {
1421 // Let A, B and C being the components of Target and R be the location of
1422 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
1423 // If it is pcrel, we want to compute (A - B + C - R).
1425 // In general, ELF has no relocations for -B. It can only represent (A + C)
1426 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
1427 // replace B to implement it: (A - R - K + C)
1431 "No relocation available to represent this relative expression");
1435 const auto &SymB
= cast
<MCSymbolELF
>(RefB
->getSymbol());
1437 if (SymB
.isUndefined()) {
1438 Ctx
.reportError(Fixup
.getLoc(),
1439 Twine("symbol '") + SymB
.getName() +
1440 "' can not be undefined in a subtraction expression");
1444 assert(!SymB
.isAbsolute() && "Should have been folded");
1445 const MCSection
&SecB
= SymB
.getSection();
1446 if (&SecB
!= &FixupSection
) {
1447 Ctx
.reportError(Fixup
.getLoc(),
1448 "Cannot represent a difference across sections");
1452 uint64_t SymBOffset
= Layout
.getSymbolOffset(SymB
);
1453 uint64_t K
= SymBOffset
- FixupOffset
;
1458 // We either rejected the fixup or folded B into C at this point.
1459 const MCSymbolRefExpr
*RefA
= Target
.getSymA();
1460 const auto *SymA
= RefA
? cast
<MCSymbolELF
>(&RefA
->getSymbol()) : nullptr;
1462 bool ViaWeakRef
= false;
1463 if (SymA
&& SymA
->isVariable()) {
1464 const MCExpr
*Expr
= SymA
->getVariableValue();
1465 if (const auto *Inner
= dyn_cast
<MCSymbolRefExpr
>(Expr
)) {
1466 if (Inner
->getKind() == MCSymbolRefExpr::VK_WEAKREF
) {
1467 SymA
= cast
<MCSymbolELF
>(&Inner
->getSymbol());
1473 unsigned Type
= TargetObjectWriter
->getRelocType(Ctx
, Target
, Fixup
, IsPCRel
);
1474 uint64_t OriginalC
= C
;
1475 bool RelocateWithSymbol
= shouldRelocateWithSymbol(Asm
, RefA
, SymA
, C
, Type
);
1476 if (!RelocateWithSymbol
&& SymA
&& !SymA
->isUndefined())
1477 C
+= Layout
.getSymbolOffset(*SymA
);
1479 uint64_t Addend
= 0;
1480 if (hasRelocationAddend()) {
1487 const MCSectionELF
*SecA
= (SymA
&& SymA
->isInSection())
1488 ? cast
<MCSectionELF
>(&SymA
->getSection())
1490 if (!checkRelocation(Ctx
, Fixup
.getLoc(), &FixupSection
, SecA
))
1493 if (!RelocateWithSymbol
) {
1494 const auto *SectionSymbol
=
1495 SecA
? cast
<MCSymbolELF
>(SecA
->getBeginSymbol()) : nullptr;
1497 SectionSymbol
->setUsedInReloc();
1498 ELFRelocationEntry
Rec(FixupOffset
, SectionSymbol
, Type
, Addend
, SymA
,
1500 Relocations
[&FixupSection
].push_back(Rec
);
1504 const auto *RenamedSymA
= SymA
;
1506 if (const MCSymbolELF
*R
= Renames
.lookup(SymA
))
1510 RenamedSymA
->setIsWeakrefUsedInReloc();
1512 RenamedSymA
->setUsedInReloc();
1514 ELFRelocationEntry
Rec(FixupOffset
, RenamedSymA
, Type
, Addend
, SymA
,
1516 Relocations
[&FixupSection
].push_back(Rec
);
1519 bool ELFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
1520 const MCAssembler
&Asm
, const MCSymbol
&SA
, const MCFragment
&FB
,
1521 bool InSet
, bool IsPCRel
) const {
1522 const auto &SymA
= cast
<MCSymbolELF
>(SA
);
1528 return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm
, SymA
, FB
,
1532 std::unique_ptr
<MCObjectWriter
>
1533 llvm::createELFObjectWriter(std::unique_ptr
<MCELFObjectTargetWriter
> MOTW
,
1534 raw_pwrite_stream
&OS
, bool IsLittleEndian
) {
1535 return llvm::make_unique
<ELFSingleObjectWriter
>(std::move(MOTW
), OS
,
1539 std::unique_ptr
<MCObjectWriter
>
1540 llvm::createELFDwoObjectWriter(std::unique_ptr
<MCELFObjectTargetWriter
> MOTW
,
1541 raw_pwrite_stream
&OS
, raw_pwrite_stream
&DwoOS
,
1542 bool IsLittleEndian
) {
1543 return llvm::make_unique
<ELFDwoObjectWriter
>(std::move(MOTW
), OS
, DwoOS
,