14288f9efSNick Lewycky //===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -----------------------===//
26c1ad483SMatt Fleming //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
66c1ad483SMatt Fleming //
76c1ad483SMatt Fleming //===----------------------------------------------------------------------===//
86c1ad483SMatt Fleming //
96c1ad483SMatt Fleming // This file implements ELF object file writer information.
106c1ad483SMatt Fleming //
116c1ad483SMatt Fleming //===----------------------------------------------------------------------===//
126c1ad483SMatt Fleming
13d3a6c897SEugene Zelenko #include "llvm/ADT/ArrayRef.h"
14d3a6c897SEugene Zelenko #include "llvm/ADT/DenseMap.h"
156bda14b3SChandler Carruth #include "llvm/ADT/STLExtras.h"
16d3a6c897SEugene Zelenko #include "llvm/ADT/SmallVector.h"
17d3a6c897SEugene Zelenko #include "llvm/ADT/StringRef.h"
18d3a6c897SEugene Zelenko #include "llvm/ADT/Twine.h"
19ef736a1cSserge-sans-paille #include "llvm/ADT/iterator.h"
20264b5d9eSZachary Turner #include "llvm/BinaryFormat/ELF.h"
21ceecfe5bSRafael Espindola #include "llvm/MC/MCAsmBackend.h"
228019bf81SDavid Blaikie #include "llvm/MC/MCAsmInfo.h"
236c1ad483SMatt Fleming #include "llvm/MC/MCAsmLayout.h"
2429abd977SRafael Espindola #include "llvm/MC/MCAssembler.h"
256c1ad483SMatt Fleming #include "llvm/MC/MCContext.h"
26d3a6c897SEugene Zelenko #include "llvm/MC/MCELFObjectWriter.h"
276c1ad483SMatt Fleming #include "llvm/MC/MCExpr.h"
28d3a6c897SEugene Zelenko #include "llvm/MC/MCFixup.h"
29ceecfe5bSRafael Espindola #include "llvm/MC/MCFixupKindInfo.h"
30d3a6c897SEugene Zelenko #include "llvm/MC/MCFragment.h"
316e80c280SCraig Topper #include "llvm/MC/MCObjectWriter.h"
32d3a6c897SEugene Zelenko #include "llvm/MC/MCSection.h"
336c1ad483SMatt Fleming #include "llvm/MC/MCSectionELF.h"
34d3a6c897SEugene Zelenko #include "llvm/MC/MCSymbol.h"
35a8695760SRafael Espindola #include "llvm/MC/MCSymbolELF.h"
36ef736a1cSserge-sans-paille #include "llvm/MC/MCTargetOptions.h"
376c1ad483SMatt Fleming #include "llvm/MC/MCValue.h"
3897de474aSRafael Espindola #include "llvm/MC/StringTableBuilder.h"
39af11cc7eSGuillaume Chatelet #include "llvm/Support/Alignment.h"
40d3a6c897SEugene Zelenko #include "llvm/Support/Casting.h"
418019bf81SDavid Blaikie #include "llvm/Support/Compression.h"
42ef736a1cSserge-sans-paille #include "llvm/Support/Endian.h"
43bcd7f777SSimon Pilgrim #include "llvm/Support/EndianStream.h"
44167ca4aeSGeorge Rimar #include "llvm/Support/Error.h"
45ed0881b2SChandler Carruth #include "llvm/Support/ErrorHandling.h"
46d3a6c897SEugene Zelenko #include "llvm/Support/Host.h"
473e227336SPeter Collingbourne #include "llvm/Support/LEB128.h"
48d3a6c897SEugene Zelenko #include "llvm/Support/MathExtras.h"
49d3a6c897SEugene Zelenko #include "llvm/Support/SMLoc.h"
50d3a6c897SEugene Zelenko #include "llvm/Support/raw_ostream.h"
51d3a6c897SEugene Zelenko #include <algorithm>
52d3a6c897SEugene Zelenko #include <cassert>
53d3a6c897SEugene Zelenko #include <cstddef>
54d3a6c897SEugene Zelenko #include <cstdint>
55d3a6c897SEugene Zelenko #include <map>
56d3a6c897SEugene Zelenko #include <memory>
57d3a6c897SEugene Zelenko #include <string>
58d3a6c897SEugene Zelenko #include <utility>
596c1ad483SMatt Fleming #include <vector>
60ecefe5a8SEugene Zelenko
616c1ad483SMatt Fleming using namespace llvm;
626c1ad483SMatt Fleming
63c09e7264SJason W Kim #undef DEBUG_TYPE
64c09e7264SJason W Kim #define DEBUG_TYPE "reloc-info"
65c09e7264SJason W Kim
6629abd977SRafael Espindola namespace {
67d3a6c897SEugene Zelenko
687975b99fSEugene Zelenko using SectionIndexMapTy = DenseMap<const MCSectionELF *, uint32_t>;
6910be0837SRafael Espindola
7091fd2778SRafael Espindola class ELFObjectWriter;
71a29fe579SPeter Collingbourne struct ELFWriter;
7291fd2778SRafael Espindola
isDwoSection(const MCSectionELF & Sec)7363062d9dSPeter Collingbourne bool isDwoSection(const MCSectionELF &Sec) {
747d1ff446SFangrui Song return Sec.getName().endswith(".dwo");
7563062d9dSPeter Collingbourne }
7663062d9dSPeter Collingbourne
7710be0837SRafael Espindola class SymbolTableWriter {
78a29fe579SPeter Collingbourne ELFWriter &EWriter;
7910be0837SRafael Espindola bool Is64Bit;
8010be0837SRafael Espindola
8191fd2778SRafael Espindola // indexes we are going to write to .symtab_shndx.
8291fd2778SRafael Espindola std::vector<uint32_t> ShndxIndexes;
8310be0837SRafael Espindola
8410be0837SRafael Espindola // The numbel of symbols written so far.
8510be0837SRafael Espindola unsigned NumWritten;
8610be0837SRafael Espindola
8710be0837SRafael Espindola void createSymtabShndx();
8810be0837SRafael Espindola
8991fd2778SRafael Espindola template <typename T> void write(T Value);
9010be0837SRafael Espindola
9110be0837SRafael Espindola public:
92a29fe579SPeter Collingbourne SymbolTableWriter(ELFWriter &EWriter, bool Is64Bit);
9310be0837SRafael Espindola
9410be0837SRafael Espindola void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
9510be0837SRafael Espindola uint8_t other, uint32_t shndx, bool Reserved);
9691fd2778SRafael Espindola
getShndxIndexes() const9791fd2778SRafael Espindola ArrayRef<uint32_t> getShndxIndexes() const { return ShndxIndexes; }
9810be0837SRafael Espindola };
9910be0837SRafael Espindola
100a29fe579SPeter Collingbourne struct ELFWriter {
101a29fe579SPeter Collingbourne ELFObjectWriter &OWriter;
102a29fe579SPeter Collingbourne support::endian::Writer W;
103a29fe579SPeter Collingbourne
10463062d9dSPeter Collingbourne enum DwoMode {
10563062d9dSPeter Collingbourne AllSections,
10663062d9dSPeter Collingbourne NonDwoOnly,
10763062d9dSPeter Collingbourne DwoOnly,
10863062d9dSPeter Collingbourne } Mode;
10963062d9dSPeter Collingbourne
110469f9dbdSDuncan P. N. Exon Smith static uint64_t SymbolValue(const MCSymbol &Sym, const MCAsmLayout &Layout);
11195fb9b93SRafael Espindola static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolELF &Symbol,
11229abd977SRafael Espindola bool Used, bool Renamed);
11329abd977SRafael Espindola
1146cd2180bSRafael Espindola /// Helper struct for containing some precomputed information on symbols.
11529abd977SRafael Espindola struct ELFSymbolData {
116a8695760SRafael Espindola const MCSymbolELF *Symbol;
11783e6e1e9SHans Wennborg StringRef Name;
11809294642SFangrui Song uint32_t SectionIndex;
11909294642SFangrui Song uint32_t Order;
12029abd977SRafael Espindola };
12129abd977SRafael Espindola
12229abd977SRafael Espindola /// @}
12329abd977SRafael Espindola /// @name Symbol Table Data
12429abd977SRafael Espindola /// @{
12529abd977SRafael Espindola
12621956e40SRafael Espindola StringTableBuilder StrTabBuilder{StringTableBuilder::ELF};
12729abd977SRafael Espindola
12829abd977SRafael Espindola /// @}
12929abd977SRafael Espindola
13029abd977SRafael Espindola // This holds the symbol table index of the last local symbol.
13129abd977SRafael Espindola unsigned LastLocalSymbolIndex;
13229abd977SRafael Espindola // This holds the .strtab section index.
13329abd977SRafael Espindola unsigned StringTableIndex;
13429abd977SRafael Espindola // This holds the .symtab section index.
13529abd977SRafael Espindola unsigned SymbolTableIndex;
13629abd977SRafael Espindola
13703d7abbbSRafael Espindola // Sections in the order they are to be output in the section table.
13808850b3aSRafael Espindola std::vector<const MCSectionELF *> SectionTable;
13908850b3aSRafael Espindola unsigned addToSectionTable(const MCSectionELF *Sec);
14029abd977SRafael Espindola
14129abd977SRafael Espindola // TargetObjectWriter wrappers.
142a29fe579SPeter Collingbourne bool is64Bit() const;
143ca3bdb57SFangrui Song bool usesRela(const MCSectionELF &Sec) const;
14429abd977SRafael Espindola
14553187f1eSFangrui Song uint64_t align(unsigned Alignment);
146b20fbb8bSRafael Espindola
1476977ff40SFangrui Song bool maybeWriteCompression(uint32_t ChType, uint64_t Size,
148e690137dSFangrui Song SmallVectorImpl<uint8_t> &CompressedContents,
149d63ec445SDavid Blaikie unsigned Alignment);
150c91e38c5SGeorge Rimar
15129abd977SRafael Espindola public:
ELFWriter__anon4df038aa0111::ELFWriter152a29fe579SPeter Collingbourne ELFWriter(ELFObjectWriter &OWriter, raw_pwrite_stream &OS,
15363062d9dSPeter Collingbourne bool IsLittleEndian, DwoMode Mode)
154a29fe579SPeter Collingbourne : OWriter(OWriter),
15563062d9dSPeter Collingbourne W(OS, IsLittleEndian ? support::little : support::big), Mode(Mode) {}
15629abd977SRafael Espindola
WriteWord__anon4df038aa0111::ELFWriter157f17b149dSPeter Collingbourne void WriteWord(uint64_t Word) {
15829abd977SRafael Espindola if (is64Bit())
159f17b149dSPeter Collingbourne W.write<uint64_t>(Word);
16029abd977SRafael Espindola else
161f17b149dSPeter Collingbourne W.write<uint32_t>(Word);
16229abd977SRafael Espindola }
16329abd977SRafael Espindola
write__anon4df038aa0111::ELFWriter16491fd2778SRafael Espindola template <typename T> void write(T Val) {
165f17b149dSPeter Collingbourne W.write(Val);
16691fd2778SRafael Espindola }
16791fd2778SRafael Espindola
1688c7829b8SRafael Espindola void writeHeader(const MCAssembler &Asm);
16929abd977SRafael Espindola
170e48421f6SRafael Espindola void writeSymbol(SymbolTableWriter &Writer, uint32_t StringIndex,
171e48421f6SRafael Espindola ELFSymbolData &MSD, const MCAsmLayout &Layout);
17229abd977SRafael Espindola
17391fd2778SRafael Espindola // Start and end offset of each section
1747975b99fSEugene Zelenko using SectionOffsetsTy =
1757975b99fSEugene Zelenko std::map<const MCSectionELF *, std::pair<uint64_t, uint64_t>>;
17691fd2778SRafael Espindola
17789feff3bSRafael Espindola // Map from a signature symbol to the group section index
1787975b99fSEugene Zelenko using RevGroupMapTy = DenseMap<const MCSymbol *, unsigned>;
17929abd977SRafael Espindola
180022bb768SRafael Espindola /// Compute the symbol table data
18129abd977SRafael Espindola ///
182073ee7d0SRafael Espindola /// \param Asm - The assembler.
183073ee7d0SRafael Espindola /// \param SectionIndexMap - Maps a section to its index.
184073ee7d0SRafael Espindola /// \param RevGroupMap - Maps a signature symbol to the group section.
185022bb768SRafael Espindola void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
18629abd977SRafael Espindola const SectionIndexMapTy &SectionIndexMap,
187aa486e9bSRafael Espindola const RevGroupMapTy &RevGroupMap,
188aa486e9bSRafael Espindola SectionOffsetsTy &SectionOffsets);
18929abd977SRafael Espindola
1903e227336SPeter Collingbourne void writeAddrsigSection();
1913e227336SPeter Collingbourne
1920a82ad79SRafael Espindola MCSectionELF *createRelocationSection(MCContext &Ctx,
193bda19809SRafael Espindola const MCSectionELF &Sec);
19429abd977SRafael Espindola
19557c80832SRafael Espindola void writeSectionHeader(const MCAsmLayout &Layout,
19629abd977SRafael Espindola const SectionIndexMapTy &SectionIndexMap,
197a8201697SRafael Espindola const SectionOffsetsTy &SectionOffsets);
19829abd977SRafael Espindola
199e15b1b76SRafael Espindola void writeSectionData(const MCAssembler &Asm, MCSection &Sec,
200868b3f47SRafael Espindola const MCAsmLayout &Layout);
201868b3f47SRafael Espindola
20229abd977SRafael Espindola void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
203868b3f47SRafael Espindola uint64_t Address, uint64_t Offset, uint64_t Size,
204868b3f47SRafael Espindola uint32_t Link, uint32_t Info, uint64_t Alignment,
205868b3f47SRafael Espindola uint64_t EntrySize);
20629abd977SRafael Espindola
20734948e5eSRafael Espindola void writeRelocations(const MCAssembler &Asm, const MCSectionELF &Sec);
20829abd977SRafael Espindola
209a29fe579SPeter Collingbourne uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout);
210e92c1bfaSRafael Espindola void writeSection(const SectionIndexMapTy &SectionIndexMap,
21128687587SRafael Espindola uint32_t GroupSymbolIndex, uint64_t Offset, uint64_t Size,
21229abd977SRafael Espindola const MCSectionELF &Section);
21329abd977SRafael Espindola };
214d3a6c897SEugene Zelenko
215a29fe579SPeter Collingbourne class ELFObjectWriter : public MCObjectWriter {
216a29fe579SPeter Collingbourne /// The target specific ELF writer instance.
217a29fe579SPeter Collingbourne std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
218a29fe579SPeter Collingbourne
219a29fe579SPeter Collingbourne DenseMap<const MCSectionELF *, std::vector<ELFRelocationEntry>> Relocations;
220a29fe579SPeter Collingbourne
221a29fe579SPeter Collingbourne DenseMap<const MCSymbolELF *, const MCSymbolELF *> Renames;
222a29fe579SPeter Collingbourne
22342e3f97aSFangrui Song bool SeenGnuAbi = false;
2243e227336SPeter Collingbourne
225a29fe579SPeter Collingbourne bool hasRelocationAddend() const;
226a29fe579SPeter Collingbourne
227a29fe579SPeter Collingbourne bool shouldRelocateWithSymbol(const MCAssembler &Asm,
228a29fe579SPeter Collingbourne const MCSymbolRefExpr *RefA,
229a29fe579SPeter Collingbourne const MCSymbolELF *Sym, uint64_t C,
230a29fe579SPeter Collingbourne unsigned Type) const;
231a29fe579SPeter Collingbourne
232a29fe579SPeter Collingbourne public:
ELFObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW)233f0226e62SPeter Collingbourne ELFObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW)
234f0226e62SPeter Collingbourne : TargetObjectWriter(std::move(MOTW)) {}
235a29fe579SPeter Collingbourne
reset()236a29fe579SPeter Collingbourne void reset() override {
23742e3f97aSFangrui Song SeenGnuAbi = false;
238a29fe579SPeter Collingbourne Relocations.clear();
239a29fe579SPeter Collingbourne Renames.clear();
240a29fe579SPeter Collingbourne MCObjectWriter::reset();
241a29fe579SPeter Collingbourne }
242a29fe579SPeter Collingbourne
243a29fe579SPeter Collingbourne bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
244a29fe579SPeter Collingbourne const MCSymbol &SymA,
245a29fe579SPeter Collingbourne const MCFragment &FB, bool InSet,
246a29fe579SPeter Collingbourne bool IsPCRel) const override;
247a29fe579SPeter Collingbourne
checkRelocation(MCContext & Ctx,SMLoc Loc,const MCSectionELF * From,const MCSectionELF * To)24863062d9dSPeter Collingbourne virtual bool checkRelocation(MCContext &Ctx, SMLoc Loc,
24963062d9dSPeter Collingbourne const MCSectionELF *From,
25063062d9dSPeter Collingbourne const MCSectionELF *To) {
25163062d9dSPeter Collingbourne return true;
25263062d9dSPeter Collingbourne }
25363062d9dSPeter Collingbourne
254a29fe579SPeter Collingbourne void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
255a29fe579SPeter Collingbourne const MCFragment *Fragment, const MCFixup &Fixup,
256a29fe579SPeter Collingbourne MCValue Target, uint64_t &FixedValue) override;
257a29fe579SPeter Collingbourne
258a29fe579SPeter Collingbourne void executePostLayoutBinding(MCAssembler &Asm,
259a29fe579SPeter Collingbourne const MCAsmLayout &Layout) override;
260a29fe579SPeter Collingbourne
markGnuAbi()26142e3f97aSFangrui Song void markGnuAbi() override { SeenGnuAbi = true; }
seenGnuAbi() const26242e3f97aSFangrui Song bool seenGnuAbi() const { return SeenGnuAbi; }
2633e227336SPeter Collingbourne
264a29fe579SPeter Collingbourne friend struct ELFWriter;
265a29fe579SPeter Collingbourne };
266a29fe579SPeter Collingbourne
267f0226e62SPeter Collingbourne class ELFSingleObjectWriter : public ELFObjectWriter {
268f0226e62SPeter Collingbourne raw_pwrite_stream &OS;
269f0226e62SPeter Collingbourne bool IsLittleEndian;
270f0226e62SPeter Collingbourne
271f0226e62SPeter Collingbourne public:
ELFSingleObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,raw_pwrite_stream & OS,bool IsLittleEndian)272f0226e62SPeter Collingbourne ELFSingleObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
273f0226e62SPeter Collingbourne raw_pwrite_stream &OS, bool IsLittleEndian)
274f0226e62SPeter Collingbourne : ELFObjectWriter(std::move(MOTW)), OS(OS),
275f0226e62SPeter Collingbourne IsLittleEndian(IsLittleEndian) {}
276f0226e62SPeter Collingbourne
writeObject(MCAssembler & Asm,const MCAsmLayout & Layout)277f0226e62SPeter Collingbourne uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override {
27863062d9dSPeter Collingbourne return ELFWriter(*this, OS, IsLittleEndian, ELFWriter::AllSections)
27963062d9dSPeter Collingbourne .writeObject(Asm, Layout);
28063062d9dSPeter Collingbourne }
28163062d9dSPeter Collingbourne
28263062d9dSPeter Collingbourne friend struct ELFWriter;
28363062d9dSPeter Collingbourne };
28463062d9dSPeter Collingbourne
28563062d9dSPeter Collingbourne class ELFDwoObjectWriter : public ELFObjectWriter {
28663062d9dSPeter Collingbourne raw_pwrite_stream &OS, &DwoOS;
28763062d9dSPeter Collingbourne bool IsLittleEndian;
28863062d9dSPeter Collingbourne
28963062d9dSPeter Collingbourne public:
ELFDwoObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,raw_pwrite_stream & OS,raw_pwrite_stream & DwoOS,bool IsLittleEndian)29063062d9dSPeter Collingbourne ELFDwoObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
29163062d9dSPeter Collingbourne raw_pwrite_stream &OS, raw_pwrite_stream &DwoOS,
29263062d9dSPeter Collingbourne bool IsLittleEndian)
29363062d9dSPeter Collingbourne : ELFObjectWriter(std::move(MOTW)), OS(OS), DwoOS(DwoOS),
29463062d9dSPeter Collingbourne IsLittleEndian(IsLittleEndian) {}
29563062d9dSPeter Collingbourne
checkRelocation(MCContext & Ctx,SMLoc Loc,const MCSectionELF * From,const MCSectionELF * To)296*3f3930a4SKazu Hirata bool checkRelocation(MCContext &Ctx, SMLoc Loc, const MCSectionELF *From,
29763062d9dSPeter Collingbourne const MCSectionELF *To) override {
29863062d9dSPeter Collingbourne if (isDwoSection(*From)) {
29963062d9dSPeter Collingbourne Ctx.reportError(Loc, "A dwo section may not contain relocations");
30063062d9dSPeter Collingbourne return false;
30163062d9dSPeter Collingbourne }
30263062d9dSPeter Collingbourne if (To && isDwoSection(*To)) {
30363062d9dSPeter Collingbourne Ctx.reportError(Loc, "A relocation may not refer to a dwo section");
30463062d9dSPeter Collingbourne return false;
30563062d9dSPeter Collingbourne }
30663062d9dSPeter Collingbourne return true;
30763062d9dSPeter Collingbourne }
30863062d9dSPeter Collingbourne
writeObject(MCAssembler & Asm,const MCAsmLayout & Layout)30963062d9dSPeter Collingbourne uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override {
31063062d9dSPeter Collingbourne uint64_t Size = ELFWriter(*this, OS, IsLittleEndian, ELFWriter::NonDwoOnly)
31163062d9dSPeter Collingbourne .writeObject(Asm, Layout);
31263062d9dSPeter Collingbourne Size += ELFWriter(*this, DwoOS, IsLittleEndian, ELFWriter::DwoOnly)
31363062d9dSPeter Collingbourne .writeObject(Asm, Layout);
31463062d9dSPeter Collingbourne return Size;
315f0226e62SPeter Collingbourne }
316f0226e62SPeter Collingbourne };
317f0226e62SPeter Collingbourne
318ecefe5a8SEugene Zelenko } // end anonymous namespace
31929abd977SRafael Espindola
align(unsigned Alignment)32053187f1eSFangrui Song uint64_t ELFWriter::align(unsigned Alignment) {
32153187f1eSFangrui Song uint64_t Offset = W.OS.tell(), NewOffset = alignTo(Offset, Alignment);
32253187f1eSFangrui Song W.OS.write_zeros(NewOffset - Offset);
32353187f1eSFangrui Song return NewOffset;
324b20fbb8bSRafael Espindola }
325b20fbb8bSRafael Espindola
addToSectionTable(const MCSectionELF * Sec)326a29fe579SPeter Collingbourne unsigned ELFWriter::addToSectionTable(const MCSectionELF *Sec) {
32703d7abbbSRafael Espindola SectionTable.push_back(Sec);
3287d1ff446SFangrui Song StrTabBuilder.add(Sec->getName());
32903d7abbbSRafael Espindola return SectionTable.size();
33003d7abbbSRafael Espindola }
33103d7abbbSRafael Espindola
createSymtabShndx()33210be0837SRafael Espindola void SymbolTableWriter::createSymtabShndx() {
33391fd2778SRafael Espindola if (!ShndxIndexes.empty())
33410be0837SRafael Espindola return;
33510be0837SRafael Espindola
33691fd2778SRafael Espindola ShndxIndexes.resize(NumWritten);
33710be0837SRafael Espindola }
33810be0837SRafael Espindola
write(T Value)33991fd2778SRafael Espindola template <typename T> void SymbolTableWriter::write(T Value) {
34091fd2778SRafael Espindola EWriter.write(Value);
34110be0837SRafael Espindola }
34210be0837SRafael Espindola
SymbolTableWriter(ELFWriter & EWriter,bool Is64Bit)343a29fe579SPeter Collingbourne SymbolTableWriter::SymbolTableWriter(ELFWriter &EWriter, bool Is64Bit)
34491fd2778SRafael Espindola : EWriter(EWriter), Is64Bit(Is64Bit), NumWritten(0) {}
34510be0837SRafael Espindola
writeSymbol(uint32_t name,uint8_t info,uint64_t value,uint64_t size,uint8_t other,uint32_t shndx,bool Reserved)34610be0837SRafael Espindola void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
34710be0837SRafael Espindola uint64_t size, uint8_t other,
34810be0837SRafael Espindola uint32_t shndx, bool Reserved) {
34910be0837SRafael Espindola bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
35010be0837SRafael Espindola
35110be0837SRafael Espindola if (LargeIndex)
35210be0837SRafael Espindola createSymtabShndx();
35310be0837SRafael Espindola
35491fd2778SRafael Espindola if (!ShndxIndexes.empty()) {
35510be0837SRafael Espindola if (LargeIndex)
35691fd2778SRafael Espindola ShndxIndexes.push_back(shndx);
35710be0837SRafael Espindola else
35891fd2778SRafael Espindola ShndxIndexes.push_back(0);
35910be0837SRafael Espindola }
36010be0837SRafael Espindola
36110be0837SRafael Espindola uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
36210be0837SRafael Espindola
36310be0837SRafael Espindola if (Is64Bit) {
36491fd2778SRafael Espindola write(name); // st_name
36591fd2778SRafael Espindola write(info); // st_info
36691fd2778SRafael Espindola write(other); // st_other
36791fd2778SRafael Espindola write(Index); // st_shndx
36891fd2778SRafael Espindola write(value); // st_value
36991fd2778SRafael Espindola write(size); // st_size
37010be0837SRafael Espindola } else {
37191fd2778SRafael Espindola write(name); // st_name
37291fd2778SRafael Espindola write(uint32_t(value)); // st_value
37391fd2778SRafael Espindola write(uint32_t(size)); // st_size
37491fd2778SRafael Espindola write(info); // st_info
37591fd2778SRafael Espindola write(other); // st_other
37691fd2778SRafael Espindola write(Index); // st_shndx
37710be0837SRafael Espindola }
37810be0837SRafael Espindola
37910be0837SRafael Espindola ++NumWritten;
38010be0837SRafael Espindola }
38110be0837SRafael Espindola
is64Bit() const382a29fe579SPeter Collingbourne bool ELFWriter::is64Bit() const {
383a29fe579SPeter Collingbourne return OWriter.TargetObjectWriter->is64Bit();
384a29fe579SPeter Collingbourne }
385a29fe579SPeter Collingbourne
usesRela(const MCSectionELF & Sec) const386ca3bdb57SFangrui Song bool ELFWriter::usesRela(const MCSectionELF &Sec) const {
387ca3bdb57SFangrui Song return OWriter.hasRelocationAddend() &&
388ca3bdb57SFangrui Song Sec.getType() != ELF::SHT_LLVM_CALL_GRAPH_PROFILE;
389a29fe579SPeter Collingbourne }
390a29fe579SPeter Collingbourne
3916c1ad483SMatt Fleming // Emit the ELF header.
writeHeader(const MCAssembler & Asm)392a29fe579SPeter Collingbourne void ELFWriter::writeHeader(const MCAssembler &Asm) {
3936c1ad483SMatt Fleming // ELF Header
3946c1ad483SMatt Fleming // ----------
3956c1ad483SMatt Fleming //
3966c1ad483SMatt Fleming // Note
3976c1ad483SMatt Fleming // ----
3986c1ad483SMatt Fleming // emitWord method behaves differently for ELF32 and ELF64, writing
3996c1ad483SMatt Fleming // 4 bytes in the former and 8 in the latter.
4006c1ad483SMatt Fleming
401f17b149dSPeter Collingbourne W.OS << ELF::ElfMagic; // e_ident[EI_MAG0] to e_ident[EI_MAG3]
4026c1ad483SMatt Fleming
403f17b149dSPeter Collingbourne W.OS << char(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
4046c1ad483SMatt Fleming
4056c1ad483SMatt Fleming // e_ident[EI_DATA]
406f17b149dSPeter Collingbourne W.OS << char(W.Endian == support::little ? ELF::ELFDATA2LSB
407f17b149dSPeter Collingbourne : ELF::ELFDATA2MSB);
4086c1ad483SMatt Fleming
409f17b149dSPeter Collingbourne W.OS << char(ELF::EV_CURRENT); // e_ident[EI_VERSION]
4103b727f55SRoman Divacky // e_ident[EI_OSABI]
41142e3f97aSFangrui Song uint8_t OSABI = OWriter.TargetObjectWriter->getOSABI();
41242e3f97aSFangrui Song W.OS << char(OSABI == ELF::ELFOSABI_NONE && OWriter.seenGnuAbi()
413ea548a4eSYang Fan ? int(ELF::ELFOSABI_GNU)
41442e3f97aSFangrui Song : OSABI);
415e0484eb2SKonstantin Zhuravlyov // e_ident[EI_ABIVERSION]
416e0484eb2SKonstantin Zhuravlyov W.OS << char(OWriter.TargetObjectWriter->getABIVersion());
4176c1ad483SMatt Fleming
418f17b149dSPeter Collingbourne W.OS.write_zeros(ELF::EI_NIDENT - ELF::EI_PAD);
4196c1ad483SMatt Fleming
420f17b149dSPeter Collingbourne W.write<uint16_t>(ELF::ET_REL); // e_type
4216c1ad483SMatt Fleming
422a29fe579SPeter Collingbourne W.write<uint16_t>(OWriter.TargetObjectWriter->getEMachine()); // e_machine = target
4236c1ad483SMatt Fleming
424f17b149dSPeter Collingbourne W.write<uint32_t>(ELF::EV_CURRENT); // e_version
4256c1ad483SMatt Fleming WriteWord(0); // e_entry, no entry point in .o file
4266c1ad483SMatt Fleming WriteWord(0); // e_phoff, no program header for .o
427642a2216SRafael Espindola WriteWord(0); // e_shoff = sec hdr table off in bytes
4286c1ad483SMatt Fleming
4294761fba8SJason W Kim // e_flags = whatever the target wants
430f17b149dSPeter Collingbourne W.write<uint32_t>(Asm.getELFHeaderEFlags());
4316c1ad483SMatt Fleming
4326c1ad483SMatt Fleming // e_ehsize = ELF header size
433f17b149dSPeter Collingbourne W.write<uint16_t>(is64Bit() ? sizeof(ELF::Elf64_Ehdr)
434f17b149dSPeter Collingbourne : sizeof(ELF::Elf32_Ehdr));
4356c1ad483SMatt Fleming
436f17b149dSPeter Collingbourne W.write<uint16_t>(0); // e_phentsize = prog header entry size
437f17b149dSPeter Collingbourne W.write<uint16_t>(0); // e_phnum = # prog header entries = 0
4386c1ad483SMatt Fleming
4396c1ad483SMatt Fleming // e_shentsize = Section header entry size
440f17b149dSPeter Collingbourne W.write<uint16_t>(is64Bit() ? sizeof(ELF::Elf64_Shdr)
441f17b149dSPeter Collingbourne : sizeof(ELF::Elf32_Shdr));
4426c1ad483SMatt Fleming
4436c1ad483SMatt Fleming // e_shnum = # of section header ents
444f17b149dSPeter Collingbourne W.write<uint16_t>(0);
4456c1ad483SMatt Fleming
44653187f1eSFangrui Song // e_shstrndx = Section # of '.strtab'
4475960cee1SRafael Espindola assert(StringTableIndex < ELF::SHN_LORESERVE);
448f17b149dSPeter Collingbourne W.write<uint16_t>(StringTableIndex);
4496c1ad483SMatt Fleming }
4506c1ad483SMatt Fleming
SymbolValue(const MCSymbol & Sym,const MCAsmLayout & Layout)451a29fe579SPeter Collingbourne uint64_t ELFWriter::SymbolValue(const MCSymbol &Sym,
45230a52decSJan Sjödin const MCAsmLayout &Layout) {
453e4c360a8SFangrui Song if (Sym.isCommon())
45414672508SRafael Espindola return Sym.getCommonAlignment();
4559735f4ffSRafael Espindola
456fee224f9SRafael Espindola uint64_t Res;
457469f9dbdSDuncan P. N. Exon Smith if (!Layout.getSymbolOffset(Sym, Res))
458553e5ebeSRafael Espindola return 0;
459553e5ebeSRafael Espindola
460469f9dbdSDuncan P. N. Exon Smith if (Layout.getAssembler().isThumbFunc(&Sym))
46166f96fe0SRafael Espindola Res |= 1;
462574bfa12SRafael Espindola
46366f96fe0SRafael Espindola return Res;
4649735f4ffSRafael Espindola }
4659735f4ffSRafael Espindola
mergeTypeForSet(uint8_t origType,uint8_t newType)4665a1c5499SRoman Divacky static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
4675a1c5499SRoman Divacky uint8_t Type = newType;
4685a1c5499SRoman Divacky
4695a1c5499SRoman Divacky // Propagation rules:
4705a1c5499SRoman Divacky // IFUNC > FUNC > OBJECT > NOTYPE
4715a1c5499SRoman Divacky // TLS_OBJECT > OBJECT > NOTYPE
4725a1c5499SRoman Divacky //
4735a1c5499SRoman Divacky // dont let the new type degrade the old type
4745a1c5499SRoman Divacky switch (origType) {
4755a1c5499SRoman Divacky default:
4765a1c5499SRoman Divacky break;
4775a1c5499SRoman Divacky case ELF::STT_GNU_IFUNC:
4785a1c5499SRoman Divacky if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
4795a1c5499SRoman Divacky Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
4805a1c5499SRoman Divacky Type = ELF::STT_GNU_IFUNC;
4815a1c5499SRoman Divacky break;
4825a1c5499SRoman Divacky case ELF::STT_FUNC:
4835a1c5499SRoman Divacky if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
4845a1c5499SRoman Divacky Type == ELF::STT_TLS)
4855a1c5499SRoman Divacky Type = ELF::STT_FUNC;
4865a1c5499SRoman Divacky break;
4875a1c5499SRoman Divacky case ELF::STT_OBJECT:
4885a1c5499SRoman Divacky if (Type == ELF::STT_NOTYPE)
4895a1c5499SRoman Divacky Type = ELF::STT_OBJECT;
4905a1c5499SRoman Divacky break;
4915a1c5499SRoman Divacky case ELF::STT_TLS:
4925a1c5499SRoman Divacky if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
4935a1c5499SRoman Divacky Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
4945a1c5499SRoman Divacky Type = ELF::STT_TLS;
4955a1c5499SRoman Divacky break;
4965a1c5499SRoman Divacky }
4975a1c5499SRoman Divacky
4985a1c5499SRoman Divacky return Type;
4995a1c5499SRoman Divacky }
5005a1c5499SRoman Divacky
isIFunc(const MCSymbolELF * Symbol)50172e99e63SFangrui Song static bool isIFunc(const MCSymbolELF *Symbol) {
50272e99e63SFangrui Song while (Symbol->getType() != ELF::STT_GNU_IFUNC) {
50372e99e63SFangrui Song const MCSymbolRefExpr *Value;
50472e99e63SFangrui Song if (!Symbol->isVariable() ||
50572e99e63SFangrui Song !(Value = dyn_cast<MCSymbolRefExpr>(Symbol->getVariableValue())) ||
50672e99e63SFangrui Song Value->getKind() != MCSymbolRefExpr::VK_None ||
50772e99e63SFangrui Song mergeTypeForSet(Symbol->getType(), ELF::STT_GNU_IFUNC) != ELF::STT_GNU_IFUNC)
50872e99e63SFangrui Song return false;
50972e99e63SFangrui Song Symbol = &cast<MCSymbolELF>(Value->getSymbol());
51072e99e63SFangrui Song }
51172e99e63SFangrui Song return true;
51272e99e63SFangrui Song }
51372e99e63SFangrui Song
writeSymbol(SymbolTableWriter & Writer,uint32_t StringIndex,ELFSymbolData & MSD,const MCAsmLayout & Layout)514a29fe579SPeter Collingbourne void ELFWriter::writeSymbol(SymbolTableWriter &Writer, uint32_t StringIndex,
515a29fe579SPeter Collingbourne ELFSymbolData &MSD, const MCAsmLayout &Layout) {
51695fb9b93SRafael Espindola const auto &Symbol = cast<MCSymbolELF>(*MSD.Symbol);
517a8695760SRafael Espindola const MCSymbolELF *Base =
518a8695760SRafael Espindola cast_or_null<MCSymbolELF>(Layout.getBaseSymbol(Symbol));
51985a8491aSRafael Espindola
52085a8491aSRafael Espindola // This has to be in sync with when computeSymbolTable uses SHN_ABS or
52185a8491aSRafael Espindola // SHN_COMMON.
5224d37b2a2SRafael Espindola bool IsReserved = !Base || Symbol.isCommon();
5233fe87a1eSRafael Espindola
5242f8d9d91SJack Carter // Binding and Type share the same byte as upper and lower nibbles
52595fb9b93SRafael Espindola uint8_t Binding = Symbol.getBinding();
52695fb9b93SRafael Espindola uint8_t Type = Symbol.getType();
52772e99e63SFangrui Song if (isIFunc(&Symbol))
52872e99e63SFangrui Song Type = ELF::STT_GNU_IFUNC;
529a6e3a599SRafael Espindola if (Base) {
53095fb9b93SRafael Espindola Type = mergeTypeForSet(Type, Base->getType());
531a6e3a599SRafael Espindola }
532f8794ff2SRafael Espindola uint8_t Info = (Binding << 4) | Type;
5332f8d9d91SJack Carter
534fc184734SJoerg Sonnenberger // Other and Visibility share the same byte with Visibility using the lower
5352f8d9d91SJack Carter // 2 bits
53695fb9b93SRafael Espindola uint8_t Visibility = Symbol.getVisibility();
5378c006ee3SRafael Espindola uint8_t Other = Symbol.getOther() | Visibility;
5385f2d6a5cSRafael Espindola
539469f9dbdSDuncan P. N. Exon Smith uint64_t Value = SymbolValue(*MSD.Symbol, Layout);
5406c1ad483SMatt Fleming uint64_t Size = 0;
5416c1ad483SMatt Fleming
5427c23cba6SRafael Espindola const MCExpr *ESize = MSD.Symbol->getSize();
543e07dfa53SFangrui Song if (!ESize && Base) {
544e07dfa53SFangrui Song // For expressions like .set y, x+1, if y's size is unset, inherit from x.
5457c23cba6SRafael Espindola ESize = Base->getSize();
546f0591c16SRafael Espindola
547e07dfa53SFangrui Song // For `.size x, 2; y = x; .size y, 1; z = y; z1 = z; .symver y, y@v1`, z,
548e07dfa53SFangrui Song // z1, and y@v1's st_size equals y's. However, `Base` is `x` which will give
549e07dfa53SFangrui Song // us 2. Follow the MCSymbolRefExpr assignment chain, which covers most
550e07dfa53SFangrui Song // needs. MCBinaryExpr is not handled.
551e07dfa53SFangrui Song const MCSymbolELF *Sym = &Symbol;
552e07dfa53SFangrui Song while (Sym->isVariable()) {
553e07dfa53SFangrui Song if (auto *Expr =
554e07dfa53SFangrui Song dyn_cast<MCSymbolRefExpr>(Sym->getVariableValue(false))) {
555e07dfa53SFangrui Song Sym = cast<MCSymbolELF>(&Expr->getSymbol());
556e07dfa53SFangrui Song if (!Sym->getSize())
557e07dfa53SFangrui Song continue;
558e07dfa53SFangrui Song ESize = Sym->getSize();
559e07dfa53SFangrui Song }
560e07dfa53SFangrui Song break;
561e07dfa53SFangrui Song }
562e07dfa53SFangrui Song }
563e07dfa53SFangrui Song
56473c0ae77SRafael Espindola if (ESize) {
56573c0ae77SRafael Espindola int64_t Res;
56694a88d71SRafael Espindola if (!ESize->evaluateKnownAbsolute(Res, Layout))
56773c0ae77SRafael Espindola report_fatal_error("Size expression must be absolute.");
56873c0ae77SRafael Espindola Size = Res;
5696c1ad483SMatt Fleming }
5706c1ad483SMatt Fleming
5716c1ad483SMatt Fleming // Write out the symbol table entry
572e48421f6SRafael Espindola Writer.writeSymbol(StringIndex, Info, Value, Size, Other, MSD.SectionIndex,
573e48421f6SRafael Espindola IsReserved);
5746c1ad483SMatt Fleming }
5756c1ad483SMatt Fleming
isInSymtab(const MCAsmLayout & Layout,const MCSymbolELF & Symbol,bool Used,bool Renamed)576a29fe579SPeter Collingbourne bool ELFWriter::isInSymtab(const MCAsmLayout &Layout, const MCSymbolELF &Symbol,
577a29fe579SPeter Collingbourne bool Used, bool Renamed) {
5787fadc0eaSRafael Espindola if (Symbol.isVariable()) {
5797fadc0eaSRafael Espindola const MCExpr *Expr = Symbol.getVariableValue();
58005e23350SNirav Dave // Target Expressions that are always inlined do not appear in the symtab
58105e23350SNirav Dave if (const auto *T = dyn_cast<MCTargetExpr>(Expr))
58205e23350SNirav Dave if (T->inlineAssignedExpr())
58305e23350SNirav Dave return false;
5847fadc0eaSRafael Espindola if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
5857fadc0eaSRafael Espindola if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
58616145978SRafael Espindola return false;
5877fadc0eaSRafael Espindola }
5887fadc0eaSRafael Espindola }
58916145978SRafael Espindola
590ee8d1515SRafael Espindola if (Used)
591ee8d1515SRafael Espindola return true;
592ee8d1515SRafael Espindola
593eb0c2c17SRafael Espindola if (Renamed)
594eb0c2c17SRafael Espindola return false;
595eb0c2c17SRafael Espindola
596ef1e863cSRafael Espindola if (Symbol.isVariable() && Symbol.isUndefined()) {
597ef1e863cSRafael Espindola // FIXME: this is here just to diagnose the case of a var = commmon_sym.
598ef1e863cSRafael Espindola Layout.getBaseSymbol(Symbol);
5999e18e962SRafael Espindola return false;
6003b5ee558SRafael Espindola }
6019e18e962SRafael Espindola
602ee8d1515SRafael Espindola if (Symbol.isTemporary())
603b1d07893SRafael Espindola return false;
604b1d07893SRafael Espindola
605a401eee2SRafael Espindola if (Symbol.getType() == ELF::STT_SECTION)
606a401eee2SRafael Espindola return false;
607a401eee2SRafael Espindola
608b1d07893SRafael Espindola return true;
609b1d07893SRafael Espindola }
610b1d07893SRafael Espindola
computeSymbolTable(MCAssembler & Asm,const MCAsmLayout & Layout,const SectionIndexMapTy & SectionIndexMap,const RevGroupMapTy & RevGroupMap,SectionOffsetsTy & SectionOffsets)611a29fe579SPeter Collingbourne void ELFWriter::computeSymbolTable(
612ea1b394bSRafael Espindola MCAssembler &Asm, const MCAsmLayout &Layout,
613aa486e9bSRafael Espindola const SectionIndexMapTy &SectionIndexMap, const RevGroupMapTy &RevGroupMap,
614aa486e9bSRafael Espindola SectionOffsetsTy &SectionOffsets) {
6155960cee1SRafael Espindola MCContext &Ctx = Asm.getContext();
616aa486e9bSRafael Espindola SymbolTableWriter Writer(*this, is64Bit());
617aa486e9bSRafael Espindola
6185960cee1SRafael Espindola // Symbol table
6195960cee1SRafael Espindola unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
6205960cee1SRafael Espindola MCSectionELF *SymtabSection =
62116af9739SPetr Hosek Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0, EntrySize);
62218f805a7SGuillaume Chatelet SymtabSection->setAlignment(is64Bit() ? Align(8) : Align(4));
6235960cee1SRafael Espindola SymbolTableIndex = addToSectionTable(SymtabSection);
6245960cee1SRafael Espindola
62553187f1eSFangrui Song uint64_t SecStart = align(SymtabSection->getAlignment());
626aa486e9bSRafael Espindola
627aa486e9bSRafael Espindola // The first entry is the undefined symbol entry.
628aa486e9bSRafael Espindola Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
629aa486e9bSRafael Espindola
630cfbd35c9SRafael Espindola std::vector<ELFSymbolData> LocalSymbolData;
631cfbd35c9SRafael Espindola std::vector<ELFSymbolData> ExternalSymbolData;
63209294642SFangrui Song MutableArrayRef<std::pair<std::string, size_t>> FileNames =
63309294642SFangrui Song Asm.getFileNames();
63409294642SFangrui Song for (const std::pair<std::string, size_t> &F : FileNames)
63509294642SFangrui Song StrTabBuilder.add(F.first);
636cfbd35c9SRafael Espindola
637bee6e9f8SRafael Espindola // Add the data for the symbols.
6385960cee1SRafael Espindola bool HasLargeSectionIndex = false;
63909294642SFangrui Song for (auto It : llvm::enumerate(Asm.symbols())) {
64009294642SFangrui Song const auto &Symbol = cast<MCSymbolELF>(It.value());
641ada43f63SRafael Espindola bool Used = Symbol.isUsedInReloc();
642212fdde2SRafael Espindola bool WeakrefUsed = Symbol.isWeakrefUsedInReloc();
6438c52a9b0SRafael Espindola bool isSignature = Symbol.isSignature();
6447d0ba346SRafael Espindola
645469f9dbdSDuncan P. N. Exon Smith if (!isInSymtab(Layout, Symbol, Used || WeakrefUsed || isSignature,
646a29fe579SPeter Collingbourne OWriter.Renames.count(&Symbol)))
6476c1ad483SMatt Fleming continue;
6486c1ad483SMatt Fleming
6499be59af3SOliver Stannard if (Symbol.isTemporary() && Symbol.isUndefined()) {
65002c13211SFangrui Song Ctx.reportError(SMLoc(), "Undefined temporary symbol " + Symbol.getName());
6519be59af3SOliver Stannard continue;
6529be59af3SOliver Stannard }
6536dff814cSRafael Espindola
6546c1ad483SMatt Fleming ELFSymbolData MSD;
655a8695760SRafael Espindola MSD.Symbol = cast<MCSymbolELF>(&Symbol);
65609294642SFangrui Song MSD.Order = It.index();
6576c1ad483SMatt Fleming
6588c52a9b0SRafael Espindola bool Local = Symbol.getBinding() == ELF::STB_LOCAL;
6596dff814cSRafael Espindola assert(Local || !Symbol.isTemporary());
6606dff814cSRafael Espindola
661f4b4430fSRafael Espindola if (Symbol.isAbsolute()) {
662022bb768SRafael Espindola MSD.SectionIndex = ELF::SHN_ABS;
66314672508SRafael Espindola } else if (Symbol.isCommon()) {
66408e8cb57SNicolai Haehnle if (Symbol.isTargetCommon()) {
66508e8cb57SNicolai Haehnle MSD.SectionIndex = Symbol.getIndex();
66608e8cb57SNicolai Haehnle } else {
667bee6e9f8SRafael Espindola assert(!Local);
668f0591c16SRafael Espindola MSD.SectionIndex = ELF::SHN_COMMON;
66908e8cb57SNicolai Haehnle }
670f4b4430fSRafael Espindola } else if (Symbol.isUndefined()) {
6715960cee1SRafael Espindola if (isSignature && !Used) {
67289feff3bSRafael Espindola MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
6735960cee1SRafael Espindola if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
6745960cee1SRafael Espindola HasLargeSectionIndex = true;
6755960cee1SRafael Espindola } else {
6766c1ad483SMatt Fleming MSD.SectionIndex = ELF::SHN_UNDEF;
6775960cee1SRafael Espindola }
6786c1ad483SMatt Fleming } else {
679d634003eSRafael Espindola const MCSectionELF &Section =
680f4b4430fSRafael Espindola static_cast<const MCSectionELF &>(Symbol.getSection());
68179ace92fSGeorge Rimar
68279ace92fSGeorge Rimar // We may end up with a situation when section symbol is technically
68379ace92fSGeorge Rimar // defined, but should not be. That happens because we explicitly
68479ace92fSGeorge Rimar // pre-create few .debug_* sections to have accessors.
68579ace92fSGeorge Rimar // And if these sections were not really defined in the code, but were
68679ace92fSGeorge Rimar // referenced, we simply error out.
68779ace92fSGeorge Rimar if (!Section.isRegistered()) {
68879ace92fSGeorge Rimar assert(static_cast<const MCSymbolELF &>(Symbol).getType() ==
68979ace92fSGeorge Rimar ELF::STT_SECTION);
69079ace92fSGeorge Rimar Ctx.reportError(SMLoc(),
69179ace92fSGeorge Rimar "Undefined section reference: " + Symbol.getName());
69279ace92fSGeorge Rimar continue;
69379ace92fSGeorge Rimar }
69479ace92fSGeorge Rimar
69563062d9dSPeter Collingbourne if (Mode == NonDwoOnly && isDwoSection(Section))
69663062d9dSPeter Collingbourne continue;
697d634003eSRafael Espindola MSD.SectionIndex = SectionIndexMap.lookup(&Section);
6986c1ad483SMatt Fleming assert(MSD.SectionIndex && "Invalid section index!");
6995960cee1SRafael Espindola if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
7005960cee1SRafael Espindola HasLargeSectionIndex = true;
701fbcf0db7SRafael Espindola }
702fbcf0db7SRafael Espindola
703eb0c2c17SRafael Espindola StringRef Name = Symbol.getName();
704b6613020SRafael Espindola
705b6613020SRafael Espindola // Sections have their own string table
706fc063e8fSRafael Espindola if (Symbol.getType() != ELF::STT_SECTION) {
707fc063e8fSRafael Espindola MSD.Name = Name;
708fc063e8fSRafael Espindola StrTabBuilder.add(Name);
709fc063e8fSRafael Espindola }
710eb0c2c17SRafael Espindola
71110d23875SRafael Espindola if (Local)
712bee6e9f8SRafael Espindola LocalSymbolData.push_back(MSD);
713bee6e9f8SRafael Espindola else
7146c1ad483SMatt Fleming ExternalSymbolData.push_back(MSD);
7156c1ad483SMatt Fleming }
7166c1ad483SMatt Fleming
7172cd19516SRafael Espindola // This holds the .symtab_shndx section index.
7182cd19516SRafael Espindola unsigned SymtabShndxSectionIndex = 0;
7192cd19516SRafael Espindola
7205960cee1SRafael Espindola if (HasLargeSectionIndex) {
7215960cee1SRafael Espindola MCSectionELF *SymtabShndxSection =
72216af9739SPetr Hosek Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0, 4);
7235960cee1SRafael Espindola SymtabShndxSectionIndex = addToSectionTable(SymtabShndxSection);
72418f805a7SGuillaume Chatelet SymtabShndxSection->setAlignment(Align(4));
7255960cee1SRafael Espindola }
7265960cee1SRafael Espindola
72721956e40SRafael Espindola StrTabBuilder.finalize();
72883e6e1e9SHans Wennborg
72909294642SFangrui Song // Make the first STT_FILE precede previous local symbols.
73009294642SFangrui Song unsigned Index = 1;
73109294642SFangrui Song auto FileNameIt = FileNames.begin();
73209294642SFangrui Song if (!FileNames.empty())
73309294642SFangrui Song FileNames[0].second = 0;
7340e3decfcSRafael Espindola
735aa486e9bSRafael Espindola for (ELFSymbolData &MSD : LocalSymbolData) {
73609294642SFangrui Song // Emit STT_FILE symbols before their associated local symbols.
73709294642SFangrui Song for (; FileNameIt != FileNames.end() && FileNameIt->second <= MSD.Order;
73809294642SFangrui Song ++FileNameIt) {
73909294642SFangrui Song Writer.writeSymbol(StrTabBuilder.getOffset(FileNameIt->first),
74009294642SFangrui Song ELF::STT_FILE | ELF::STB_LOCAL, 0, 0, ELF::STV_DEFAULT,
74109294642SFangrui Song ELF::SHN_ABS, true);
74209294642SFangrui Song ++Index;
74309294642SFangrui Song }
74409294642SFangrui Song
74541de8027SDaniel Jasper unsigned StringIndex = MSD.Symbol->getType() == ELF::STT_SECTION
74641de8027SDaniel Jasper ? 0
74741de8027SDaniel Jasper : StrTabBuilder.getOffset(MSD.Name);
748aa486e9bSRafael Espindola MSD.Symbol->setIndex(Index++);
749e48421f6SRafael Espindola writeSymbol(Writer, StringIndex, MSD, Layout);
750aa486e9bSRafael Espindola }
75109294642SFangrui Song for (; FileNameIt != FileNames.end(); ++FileNameIt) {
75209294642SFangrui Song Writer.writeSymbol(StrTabBuilder.getOffset(FileNameIt->first),
75309294642SFangrui Song ELF::STT_FILE | ELF::STB_LOCAL, 0, 0, ELF::STV_DEFAULT,
75409294642SFangrui Song ELF::SHN_ABS, true);
75509294642SFangrui Song ++Index;
75609294642SFangrui Song }
757aa486e9bSRafael Espindola
758aa486e9bSRafael Espindola // Write the symbol table entries.
7590cbea299SRafael Espindola LastLocalSymbolIndex = Index;
760aa486e9bSRafael Espindola
761dcda9979SRafael Espindola for (ELFSymbolData &MSD : ExternalSymbolData) {
762e48421f6SRafael Espindola unsigned StringIndex = StrTabBuilder.getOffset(MSD.Name);
7630cbea299SRafael Espindola MSD.Symbol->setIndex(Index++);
764e48421f6SRafael Espindola writeSymbol(Writer, StringIndex, MSD, Layout);
76595fb9b93SRafael Espindola assert(MSD.Symbol->getBinding() != ELF::STB_LOCAL);
766aa486e9bSRafael Espindola }
767aa486e9bSRafael Espindola
768f17b149dSPeter Collingbourne uint64_t SecEnd = W.OS.tell();
769aa486e9bSRafael Espindola SectionOffsets[SymtabSection] = std::make_pair(SecStart, SecEnd);
770aa486e9bSRafael Espindola
771aa486e9bSRafael Espindola ArrayRef<uint32_t> ShndxIndexes = Writer.getShndxIndexes();
772aa486e9bSRafael Espindola if (ShndxIndexes.empty()) {
773aa486e9bSRafael Espindola assert(SymtabShndxSectionIndex == 0);
774aa486e9bSRafael Espindola return;
775aa486e9bSRafael Espindola }
776aa486e9bSRafael Espindola assert(SymtabShndxSectionIndex != 0);
777aa486e9bSRafael Espindola
778f17b149dSPeter Collingbourne SecStart = W.OS.tell();
779aa486e9bSRafael Espindola const MCSectionELF *SymtabShndxSection =
780aa486e9bSRafael Espindola SectionTable[SymtabShndxSectionIndex - 1];
781aa486e9bSRafael Espindola for (uint32_t Index : ShndxIndexes)
782aa486e9bSRafael Espindola write(Index);
783f17b149dSPeter Collingbourne SecEnd = W.OS.tell();
784aa486e9bSRafael Espindola SectionOffsets[SymtabShndxSection] = std::make_pair(SecStart, SecEnd);
7856c1ad483SMatt Fleming }
7866c1ad483SMatt Fleming
writeAddrsigSection()7873e227336SPeter Collingbourne void ELFWriter::writeAddrsigSection() {
7883e227336SPeter Collingbourne for (const MCSymbol *Sym : OWriter.AddrsigSyms)
7893e227336SPeter Collingbourne encodeULEB128(Sym->getIndex(), W.OS);
7903e227336SPeter Collingbourne }
7913e227336SPeter Collingbourne
createRelocationSection(MCContext & Ctx,const MCSectionELF & Sec)792a29fe579SPeter Collingbourne MCSectionELF *ELFWriter::createRelocationSection(MCContext &Ctx,
79334948e5eSRafael Espindola const MCSectionELF &Sec) {
794a29fe579SPeter Collingbourne if (OWriter.Relocations[&Sec].empty())
795bda19809SRafael Espindola return nullptr;
7961557fd6dSRafael Espindola
7977d1ff446SFangrui Song const StringRef SectionName = Sec.getName();
798ca3bdb57SFangrui Song bool Rela = usesRela(Sec);
799ca3bdb57SFangrui Song std::string RelaSectionName = Rela ? ".rela" : ".rel";
8006c1ad483SMatt Fleming RelaSectionName += SectionName;
801fd054156SBenjamin Kramer
802fd054156SBenjamin Kramer unsigned EntrySize;
803ca3bdb57SFangrui Song if (Rela)
804fdaae0d1SRafael Espindola EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
805fd054156SBenjamin Kramer else
806fdaae0d1SRafael Espindola EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
8076c1ad483SMatt Fleming
808dfb7518dSFangrui Song unsigned Flags = ELF::SHF_INFO_LINK;
80934948e5eSRafael Espindola if (Sec.getFlags() & ELF::SHF_GROUP)
810a630fb0bSTim Northover Flags = ELF::SHF_GROUP;
811a630fb0bSTim Northover
8120709a7bdSRafael Espindola MCSectionELF *RelaSection = Ctx.createELFRelSection(
813ca3bdb57SFangrui Song RelaSectionName, Rela ? ELF::SHT_RELA : ELF::SHT_REL, Flags, EntrySize,
814ca3bdb57SFangrui Song Sec.getGroup(), &Sec);
81518f805a7SGuillaume Chatelet RelaSection->setAlignment(is64Bit() ? Align(8) : Align(4));
816bda19809SRafael Espindola return RelaSection;
8171557fd6dSRafael Espindola }
8186c1ad483SMatt Fleming
819c91e38c5SGeorge Rimar // Include the debug info compression header.
maybeWriteCompression(uint32_t ChType,uint64_t Size,SmallVectorImpl<uint8_t> & CompressedContents,unsigned Alignment)820a29fe579SPeter Collingbourne bool ELFWriter::maybeWriteCompression(
8216977ff40SFangrui Song uint32_t ChType, uint64_t Size,
8226977ff40SFangrui Song SmallVectorImpl<uint8_t> &CompressedContents, unsigned Alignment) {
823c91e38c5SGeorge Rimar uint64_t HdrSize =
824c91e38c5SGeorge Rimar is64Bit() ? sizeof(ELF::Elf32_Chdr) : sizeof(ELF::Elf64_Chdr);
825c91e38c5SGeorge Rimar if (Size <= HdrSize + CompressedContents.size())
826c91e38c5SGeorge Rimar return false;
827c91e38c5SGeorge Rimar // Platform specific header is followed by compressed data.
828c91e38c5SGeorge Rimar if (is64Bit()) {
829c91e38c5SGeorge Rimar // Write Elf64_Chdr header.
8306977ff40SFangrui Song write(static_cast<ELF::Elf64_Word>(ChType));
831c91e38c5SGeorge Rimar write(static_cast<ELF::Elf64_Word>(0)); // ch_reserved field.
832c91e38c5SGeorge Rimar write(static_cast<ELF::Elf64_Xword>(Size));
833c91e38c5SGeorge Rimar write(static_cast<ELF::Elf64_Xword>(Alignment));
834c91e38c5SGeorge Rimar } else {
835c91e38c5SGeorge Rimar // Write Elf32_Chdr header otherwise.
8366977ff40SFangrui Song write(static_cast<ELF::Elf32_Word>(ChType));
837c91e38c5SGeorge Rimar write(static_cast<ELF::Elf32_Word>(Size));
838c91e38c5SGeorge Rimar write(static_cast<ELF::Elf32_Word>(Alignment));
839c91e38c5SGeorge Rimar }
840c91e38c5SGeorge Rimar return true;
841c91e38c5SGeorge Rimar }
842c91e38c5SGeorge Rimar
writeSectionData(const MCAssembler & Asm,MCSection & Sec,const MCAsmLayout & Layout)843a29fe579SPeter Collingbourne void ELFWriter::writeSectionData(const MCAssembler &Asm, MCSection &Sec,
844868b3f47SRafael Espindola const MCAsmLayout &Layout) {
845e15b1b76SRafael Espindola MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
8467d1ff446SFangrui Song StringRef SectionName = Section.getName();
8478019bf81SDavid Blaikie
8481f62f57bSSaleem Abdulrasool auto &MC = Asm.getContext();
8491f62f57bSSaleem Abdulrasool const auto &MAI = MC.getAsmInfo();
8501f62f57bSSaleem Abdulrasool
851c91e38c5SGeorge Rimar bool CompressionEnabled =
8521f62f57bSSaleem Abdulrasool MAI->compressDebugSections() != DebugCompressionType::None;
853a7ac200fSFangrui Song if (!CompressionEnabled || !SectionName.startswith(".debug_")) {
854f17b149dSPeter Collingbourne Asm.writeSectionData(W.OS, &Section, Layout);
855868b3f47SRafael Espindola return;
8568019bf81SDavid Blaikie }
857868b3f47SRafael Espindola
8586977ff40SFangrui Song assert(MAI->compressDebugSections() == DebugCompressionType::Z &&
8596977ff40SFangrui Song "expected zlib style compression");
8601f62f57bSSaleem Abdulrasool
861abdb2d2aSDavid Majnemer SmallVector<char, 128> UncompressedData;
862abdb2d2aSDavid Majnemer raw_svector_ostream VecOS(UncompressedData);
863147db3e6SPeter Collingbourne Asm.writeSectionData(VecOS, &Section, Layout);
864868b3f47SRafael Espindola
8656977ff40SFangrui Song SmallVector<uint8_t, 128> Compressed;
8666977ff40SFangrui Song const uint32_t ChType = ELF::ELFCOMPRESS_ZLIB;
867ea61750cSCole Kissane compression::zlib::compress(
868e690137dSFangrui Song makeArrayRef(reinterpret_cast<uint8_t *>(UncompressedData.data()),
869e690137dSFangrui Song UncompressedData.size()),
8706977ff40SFangrui Song Compressed);
871868b3f47SRafael Espindola
8726977ff40SFangrui Song if (!maybeWriteCompression(ChType, UncompressedData.size(), Compressed,
873d63ec445SDavid Blaikie Sec.getAlignment())) {
874f17b149dSPeter Collingbourne W.OS << UncompressedData;
875868b3f47SRafael Espindola return;
876868b3f47SRafael Espindola }
877c91e38c5SGeorge Rimar
878c91e38c5SGeorge Rimar Section.setFlags(Section.getFlags() | ELF::SHF_COMPRESSED);
879b9ed9cb5SGeorge Rimar // Alignment field should reflect the requirements of
880b9ed9cb5SGeorge Rimar // the compressed section header.
88118f805a7SGuillaume Chatelet Section.setAlignment(is64Bit() ? Align(8) : Align(4));
8826977ff40SFangrui Song W.OS << toStringRef(Compressed);
8838019bf81SDavid Blaikie }
8848019bf81SDavid Blaikie
WriteSecHdrEntry(uint32_t Name,uint32_t Type,uint64_t Flags,uint64_t Address,uint64_t Offset,uint64_t Size,uint32_t Link,uint32_t Info,uint64_t Alignment,uint64_t EntrySize)885a29fe579SPeter Collingbourne void ELFWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
886a29fe579SPeter Collingbourne uint64_t Address, uint64_t Offset,
887a29fe579SPeter Collingbourne uint64_t Size, uint32_t Link, uint32_t Info,
888a29fe579SPeter Collingbourne uint64_t Alignment, uint64_t EntrySize) {
889f17b149dSPeter Collingbourne W.write<uint32_t>(Name); // sh_name: index into string table
890f17b149dSPeter Collingbourne W.write<uint32_t>(Type); // sh_type
8916c1ad483SMatt Fleming WriteWord(Flags); // sh_flags
8926c1ad483SMatt Fleming WriteWord(Address); // sh_addr
8936c1ad483SMatt Fleming WriteWord(Offset); // sh_offset
8946c1ad483SMatt Fleming WriteWord(Size); // sh_size
895f17b149dSPeter Collingbourne W.write<uint32_t>(Link); // sh_link
896f17b149dSPeter Collingbourne W.write<uint32_t>(Info); // sh_info
8976c1ad483SMatt Fleming WriteWord(Alignment); // sh_addralign
8986c1ad483SMatt Fleming WriteWord(EntrySize); // sh_entsize
8996c1ad483SMatt Fleming }
9006c1ad483SMatt Fleming
writeRelocations(const MCAssembler & Asm,const MCSectionELF & Sec)901a29fe579SPeter Collingbourne void ELFWriter::writeRelocations(const MCAssembler &Asm,
90234948e5eSRafael Espindola const MCSectionELF &Sec) {
903a29fe579SPeter Collingbourne std::vector<ELFRelocationEntry> &Relocs = OWriter.Relocations[&Sec];
90464ad2cf1SAkira Hatanaka
905f44db24eSRafael Espindola // We record relocations by pushing to the end of a vector. Reverse the vector
906f44db24eSRafael Espindola // to get the relocations in the order they were created.
907f44db24eSRafael Espindola // In most cases that is not important, but it can be for special sections
908f44db24eSRafael Espindola // (.eh_frame) or specific relocations (TLS optimizations on SystemZ).
909f44db24eSRafael Espindola std::reverse(Relocs.begin(), Relocs.end());
910d0e16522SRafael Espindola
911f44db24eSRafael Espindola // Sort the relocation entries. MIPS needs this.
912a29fe579SPeter Collingbourne OWriter.TargetObjectWriter->sortRelocs(Asm, Relocs);
9136c1ad483SMatt Fleming
914ca3bdb57SFangrui Song const bool Rela = usesRela(Sec);
9156c1ad483SMatt Fleming for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
9165904e12bSRafael Espindola const ELFRelocationEntry &Entry = Relocs[e - i - 1];
9175e9ed902SRafael Espindola unsigned Index = Entry.Symbol ? Entry.Symbol->getIndex() : 0;
9185904e12bSRafael Espindola
9195904e12bSRafael Espindola if (is64Bit()) {
920b8cbb267SRafael Espindola write(Entry.Offset);
921a29fe579SPeter Collingbourne if (OWriter.TargetObjectWriter->getEMachine() == ELF::EM_MIPS) {
922b8cbb267SRafael Espindola write(uint32_t(Index));
9235904e12bSRafael Espindola
924a29fe579SPeter Collingbourne write(OWriter.TargetObjectWriter->getRSsym(Entry.Type));
925a29fe579SPeter Collingbourne write(OWriter.TargetObjectWriter->getRType3(Entry.Type));
926a29fe579SPeter Collingbourne write(OWriter.TargetObjectWriter->getRType2(Entry.Type));
927a29fe579SPeter Collingbourne write(OWriter.TargetObjectWriter->getRType(Entry.Type));
9285904e12bSRafael Espindola } else {
929bce26a1eSRafael Espindola struct ELF::Elf64_Rela ERE64;
9305904e12bSRafael Espindola ERE64.setSymbolAndType(Index, Entry.Type);
931b8cbb267SRafael Espindola write(ERE64.r_info);
9328ad0c272SJack Carter }
933ca3bdb57SFangrui Song if (Rela)
934b8cbb267SRafael Espindola write(Entry.Addend);
9356c3c349bSBenjamin Kramer } else {
936b8cbb267SRafael Espindola write(uint32_t(Entry.Offset));
9376c3c349bSBenjamin Kramer
938bce26a1eSRafael Espindola struct ELF::Elf32_Rela ERE32;
9395904e12bSRafael Espindola ERE32.setSymbolAndType(Index, Entry.Type);
940b8cbb267SRafael Espindola write(ERE32.r_info);
9416c3c349bSBenjamin Kramer
942ca3bdb57SFangrui Song if (Rela)
943b8cbb267SRafael Espindola write(uint32_t(Entry.Addend));
944ede43b71SSimon Atanasyan
945a29fe579SPeter Collingbourne if (OWriter.TargetObjectWriter->getEMachine() == ELF::EM_MIPS) {
946a29fe579SPeter Collingbourne if (uint32_t RType =
947a29fe579SPeter Collingbourne OWriter.TargetObjectWriter->getRType2(Entry.Type)) {
948ede43b71SSimon Atanasyan write(uint32_t(Entry.Offset));
949ede43b71SSimon Atanasyan
950ede43b71SSimon Atanasyan ERE32.setSymbolAndType(0, RType);
951ede43b71SSimon Atanasyan write(ERE32.r_info);
952ede43b71SSimon Atanasyan write(uint32_t(0));
953ede43b71SSimon Atanasyan }
954a29fe579SPeter Collingbourne if (uint32_t RType =
955a29fe579SPeter Collingbourne OWriter.TargetObjectWriter->getRType3(Entry.Type)) {
956ede43b71SSimon Atanasyan write(uint32_t(Entry.Offset));
957ede43b71SSimon Atanasyan
958ede43b71SSimon Atanasyan ERE32.setSymbolAndType(0, RType);
959ede43b71SSimon Atanasyan write(ERE32.r_info);
960ede43b71SSimon Atanasyan write(uint32_t(0));
961ede43b71SSimon Atanasyan }
962ede43b71SSimon Atanasyan }
9636c3c349bSBenjamin Kramer }
9646c1ad483SMatt Fleming }
9656c1ad483SMatt Fleming }
9666c1ad483SMatt Fleming
writeSection(const SectionIndexMapTy & SectionIndexMap,uint32_t GroupSymbolIndex,uint64_t Offset,uint64_t Size,const MCSectionELF & Section)967a29fe579SPeter Collingbourne void ELFWriter::writeSection(const SectionIndexMapTy &SectionIndexMap,
968e92c1bfaSRafael Espindola uint32_t GroupSymbolIndex, uint64_t Offset,
969e92c1bfaSRafael Espindola uint64_t Size, const MCSectionELF &Section) {
9705a8d781cSRafael Espindola uint64_t sh_link = 0;
9715a8d781cSRafael Espindola uint64_t sh_info = 0;
9725a8d781cSRafael Espindola
9735a8d781cSRafael Espindola switch(Section.getType()) {
97486fe2febSRafael Espindola default:
97586fe2febSRafael Espindola // Nothing to do.
97686fe2febSRafael Espindola break;
97786fe2febSRafael Espindola
9785a8d781cSRafael Espindola case ELF::SHT_DYNAMIC:
97974ef480fSRafael Espindola llvm_unreachable("SHT_DYNAMIC in a relocatable object");
9805a8d781cSRafael Espindola
9815a8d781cSRafael Espindola case ELF::SHT_REL:
9825a8d781cSRafael Espindola case ELF::SHT_RELA: {
9833a7c0eb3SRafael Espindola sh_link = SymbolTableIndex;
9845a8d781cSRafael Espindola assert(sh_link && ".symtab not found");
985727362e8SFangrui Song const MCSection *InfoSection = Section.getLinkedToSection();
98643dcf4d3SEvgeniy Stepanov sh_info = SectionIndexMap.lookup(cast<MCSectionELF>(InfoSection));
9875a8d781cSRafael Espindola break;
9885a8d781cSRafael Espindola }
9895a8d781cSRafael Espindola
9905a8d781cSRafael Espindola case ELF::SHT_SYMTAB:
9915a8d781cSRafael Espindola sh_link = StringTableIndex;
9925a8d781cSRafael Espindola sh_info = LastLocalSymbolIndex;
9935a8d781cSRafael Espindola break;
9945a8d781cSRafael Espindola
9955a8d781cSRafael Espindola case ELF::SHT_SYMTAB_SHNDX:
996ae6eeaeaSMichael J. Spencer case ELF::SHT_LLVM_CALL_GRAPH_PROFILE:
9973e227336SPeter Collingbourne case ELF::SHT_LLVM_ADDRSIG:
9985a8d781cSRafael Espindola sh_link = SymbolTableIndex;
9995a8d781cSRafael Espindola break;
10005a8d781cSRafael Espindola
1001c6ac5f73SNick Lewycky case ELF::SHT_GROUP:
1002a3e9a229SRafael Espindola sh_link = SymbolTableIndex;
1003a3e9a229SRafael Espindola sh_info = GroupSymbolIndex;
1004a3e9a229SRafael Espindola break;
10055a8d781cSRafael Espindola }
10065a8d781cSRafael Espindola
100743dcf4d3SEvgeniy Stepanov if (Section.getFlags() & ELF::SHF_LINK_ORDER) {
100811bb7c22SFangrui Song // If the value in the associated metadata is not a definition, Sym will be
100911bb7c22SFangrui Song // undefined. Represent this with sh_link=0.
1010727362e8SFangrui Song const MCSymbol *Sym = Section.getLinkedToSymbol();
101111bb7c22SFangrui Song if (Sym && Sym->isInSection()) {
101243dcf4d3SEvgeniy Stepanov const MCSectionELF *Sec = cast<MCSectionELF>(&Sym->getSection());
101343dcf4d3SEvgeniy Stepanov sh_link = SectionIndexMap.lookup(Sec);
101443dcf4d3SEvgeniy Stepanov }
101511bb7c22SFangrui Song }
10164b724429SLogan Chien
10177d1ff446SFangrui Song WriteSecHdrEntry(StrTabBuilder.getOffset(Section.getName()),
101828687587SRafael Espindola Section.getType(), Section.getFlags(), 0, Offset, Size,
101928687587SRafael Espindola sh_link, sh_info, Section.getAlignment(),
102028687587SRafael Espindola Section.getEntrySize());
10215a8d781cSRafael Espindola }
10225a8d781cSRafael Espindola
writeSectionHeader(const MCAsmLayout & Layout,const SectionIndexMapTy & SectionIndexMap,const SectionOffsetsTy & SectionOffsets)1023a29fe579SPeter Collingbourne void ELFWriter::writeSectionHeader(
102457c80832SRafael Espindola const MCAsmLayout &Layout, const SectionIndexMapTy &SectionIndexMap,
1025a8201697SRafael Espindola const SectionOffsetsTy &SectionOffsets) {
1026b186391eSRafael Espindola const unsigned NumSections = SectionTable.size();
10271557fd6dSRafael Espindola
10286c1ad483SMatt Fleming // Null section first.
10293fe87a1eSRafael Espindola uint64_t FirstSectionSize =
1030bf0db6caSRafael Espindola (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
103188d1f632SRafael Espindola WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
10326c1ad483SMatt Fleming
103308850b3aSRafael Espindola for (const MCSectionELF *Section : SectionTable) {
1034a3e9a229SRafael Espindola uint32_t GroupSymbolIndex;
103503d7abbbSRafael Espindola unsigned Type = Section->getType();
103603d7abbbSRafael Espindola if (Type != ELF::SHT_GROUP)
1037a3e9a229SRafael Espindola GroupSymbolIndex = 0;
1038a3e9a229SRafael Espindola else
10395e9ed902SRafael Espindola GroupSymbolIndex = Section->getGroup()->getIndex();
10406c1ad483SMatt Fleming
1041bda19809SRafael Espindola const std::pair<uint64_t, uint64_t> &Offsets =
104203d7abbbSRafael Espindola SectionOffsets.find(Section)->second;
10431aa20fcbSRafael Espindola uint64_t Size;
10445a1e80bcSRafael Espindola if (Type == ELF::SHT_NOBITS)
10455a1e80bcSRafael Espindola Size = Layout.getSectionAddressSize(Section);
10465a1e80bcSRafael Espindola else
10471aa20fcbSRafael Espindola Size = Offsets.second - Offsets.first;
104860ebca9aSRafael Espindola
1049e92c1bfaSRafael Espindola writeSection(SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
105028687587SRafael Espindola *Section);
10516c1ad483SMatt Fleming }
10526c1ad483SMatt Fleming }
10536c1ad483SMatt Fleming
writeObject(MCAssembler & Asm,const MCAsmLayout & Layout)1054a29fe579SPeter Collingbourne uint64_t ELFWriter::writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) {
1055438390faSPeter Collingbourne uint64_t StartOffset = W.OS.tell();
1056438390faSPeter Collingbourne
1057bda19809SRafael Espindola MCContext &Ctx = Asm.getContext();
10585960cee1SRafael Espindola MCSectionELF *StrtabSection =
10595960cee1SRafael Espindola Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
10605960cee1SRafael Espindola StringTableIndex = addToSectionTable(StrtabSection);
1061bda19809SRafael Espindola
10621557fd6dSRafael Espindola RevGroupMapTy RevGroupMap;
10631557fd6dSRafael Espindola SectionIndexMapTy SectionIndexMap;
10641557fd6dSRafael Espindola
1065bda19809SRafael Espindola std::map<const MCSymbol *, std::vector<const MCSectionELF *>> GroupMembers;
10661557fd6dSRafael Espindola
10671557fd6dSRafael Espindola // Write out the ELF header ...
10688c7829b8SRafael Espindola writeHeader(Asm);
10691557fd6dSRafael Espindola
10707230f80eSRafael Espindola // ... then the sections ...
1071bda19809SRafael Espindola SectionOffsetsTy SectionOffsets;
10720a82ad79SRafael Espindola std::vector<MCSectionELF *> Groups;
10730a82ad79SRafael Espindola std::vector<MCSectionELF *> Relocations;
1074e15b1b76SRafael Espindola for (MCSection &Sec : Asm) {
1075e15b1b76SRafael Espindola MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
107663062d9dSPeter Collingbourne if (Mode == NonDwoOnly && isDwoSection(Section))
107763062d9dSPeter Collingbourne continue;
107863062d9dSPeter Collingbourne if (Mode == DwoOnly && !isDwoSection(Section))
107963062d9dSPeter Collingbourne continue;
1080bda19809SRafael Espindola
1081642a2216SRafael Espindola // Remember the offset into the file for this section.
108253187f1eSFangrui Song const uint64_t SecStart = align(Section.getAlignment());
1083b8cbb267SRafael Espindola
10840ccf9b71SRafael Espindola const MCSymbolELF *SignatureSymbol = Section.getGroup();
1085e15b1b76SRafael Espindola writeSectionData(Asm, Section, Layout);
1086b8cbb267SRafael Espindola
1087f17b149dSPeter Collingbourne uint64_t SecEnd = W.OS.tell();
1088bda19809SRafael Espindola SectionOffsets[&Section] = std::make_pair(SecStart, SecEnd);
1089bda19809SRafael Espindola
10900a82ad79SRafael Espindola MCSectionELF *RelSection = createRelocationSection(Ctx, Section);
1091bda19809SRafael Espindola
1092bda19809SRafael Espindola if (SignatureSymbol) {
1093bda19809SRafael Espindola unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
1094bda19809SRafael Espindola if (!GroupIdx) {
109516af9739SPetr Hosek MCSectionELF *Group =
109616af9739SPetr Hosek Ctx.createELFGroupSection(SignatureSymbol, Section.isComdat());
109703d7abbbSRafael Espindola GroupIdx = addToSectionTable(Group);
109818f805a7SGuillaume Chatelet Group->setAlignment(Align(4));
10990a82ad79SRafael Espindola Groups.push_back(Group);
1100bda19809SRafael Espindola }
11017830fc83SRafael Espindola std::vector<const MCSectionELF *> &Members =
11027830fc83SRafael Espindola GroupMembers[SignatureSymbol];
11037830fc83SRafael Espindola Members.push_back(&Section);
1104bda19809SRafael Espindola if (RelSection)
11057830fc83SRafael Espindola Members.push_back(RelSection);
1106bda19809SRafael Espindola }
1107bda19809SRafael Espindola
110803d7abbbSRafael Espindola SectionIndexMap[&Section] = addToSectionTable(&Section);
11090a82ad79SRafael Espindola if (RelSection) {
111003d7abbbSRafael Espindola SectionIndexMap[RelSection] = addToSectionTable(RelSection);
11110a82ad79SRafael Espindola Relocations.push_back(RelSection);
11120a82ad79SRafael Espindola }
1113fe83270eSEric Christopher
1114fe83270eSEric Christopher OWriter.TargetObjectWriter->addTargetSectionFlags(Ctx, Section);
1115bda19809SRafael Espindola }
1116bda19809SRafael Espindola
11170a82ad79SRafael Espindola for (MCSectionELF *Group : Groups) {
11180a82ad79SRafael Espindola // Remember the offset into the file for this section.
111953187f1eSFangrui Song const uint64_t SecStart = align(Group->getAlignment());
11200a82ad79SRafael Espindola
11210a82ad79SRafael Espindola const MCSymbol *SignatureSymbol = Group->getGroup();
11220a82ad79SRafael Espindola assert(SignatureSymbol);
11233ae27fcaSYang Fan write(uint32_t(Group->isComdat() ? unsigned(ELF::GRP_COMDAT) : 0));
11240a82ad79SRafael Espindola for (const MCSectionELF *Member : GroupMembers[SignatureSymbol]) {
11250a82ad79SRafael Espindola uint32_t SecIndex = SectionIndexMap.lookup(Member);
11260a82ad79SRafael Espindola write(SecIndex);
11270a82ad79SRafael Espindola }
11280a82ad79SRafael Espindola
1129f17b149dSPeter Collingbourne uint64_t SecEnd = W.OS.tell();
11300a82ad79SRafael Espindola SectionOffsets[Group] = std::make_pair(SecStart, SecEnd);
11310a82ad79SRafael Espindola }
11320a82ad79SRafael Espindola
113363062d9dSPeter Collingbourne if (Mode == DwoOnly) {
113463062d9dSPeter Collingbourne // dwo files don't have symbol tables or relocations, but they do have
113563062d9dSPeter Collingbourne // string tables.
113663062d9dSPeter Collingbourne StrTabBuilder.finalize();
113763062d9dSPeter Collingbourne } else {
11383e227336SPeter Collingbourne MCSectionELF *AddrsigSection;
11393e227336SPeter Collingbourne if (OWriter.EmitAddrsigSection) {
11403e227336SPeter Collingbourne AddrsigSection = Ctx.getELFSection(".llvm_addrsig", ELF::SHT_LLVM_ADDRSIG,
11413e227336SPeter Collingbourne ELF::SHF_EXCLUDE);
11423e227336SPeter Collingbourne addToSectionTable(AddrsigSection);
11433e227336SPeter Collingbourne }
11443e227336SPeter Collingbourne
1145bda19809SRafael Espindola // Compute symbol table information.
114663062d9dSPeter Collingbourne computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
114763062d9dSPeter Collingbourne SectionOffsets);
11480a82ad79SRafael Espindola
11490a82ad79SRafael Espindola for (MCSectionELF *RelSection : Relocations) {
11500a82ad79SRafael Espindola // Remember the offset into the file for this section.
115153187f1eSFangrui Song const uint64_t SecStart = align(RelSection->getAlignment());
11520a82ad79SRafael Espindola
115343dcf4d3SEvgeniy Stepanov writeRelocations(Asm,
1154727362e8SFangrui Song cast<MCSectionELF>(*RelSection->getLinkedToSection()));
11550a82ad79SRafael Espindola
1156f17b149dSPeter Collingbourne uint64_t SecEnd = W.OS.tell();
11570a82ad79SRafael Espindola SectionOffsets[RelSection] = std::make_pair(SecStart, SecEnd);
1158642a2216SRafael Espindola }
11593e227336SPeter Collingbourne
11603e227336SPeter Collingbourne if (OWriter.EmitAddrsigSection) {
11613e227336SPeter Collingbourne uint64_t SecStart = W.OS.tell();
11623e227336SPeter Collingbourne writeAddrsigSection();
11633e227336SPeter Collingbourne uint64_t SecEnd = W.OS.tell();
11643e227336SPeter Collingbourne SectionOffsets[AddrsigSection] = std::make_pair(SecStart, SecEnd);
11653e227336SPeter Collingbourne }
116663062d9dSPeter Collingbourne }
1167642a2216SRafael Espindola
116888d1f632SRafael Espindola {
1169f17b149dSPeter Collingbourne uint64_t SecStart = W.OS.tell();
117053187f1eSFangrui Song StrTabBuilder.write(W.OS);
117153187f1eSFangrui Song SectionOffsets[StrtabSection] = std::make_pair(SecStart, W.OS.tell());
117288abc39dSRafael Espindola }
117388abc39dSRafael Espindola
117453187f1eSFangrui Song const uint64_t SectionHeaderOffset = align(is64Bit() ? 8 : 4);
1175642a2216SRafael Espindola
11761557fd6dSRafael Espindola // ... then the section header table ...
117757c80832SRafael Espindola writeSectionHeader(Layout, SectionIndexMap, SectionOffsets);
1178642a2216SRafael Espindola
1179f17b149dSPeter Collingbourne uint16_t NumSections = support::endian::byte_swap<uint16_t>(
1180f17b149dSPeter Collingbourne (SectionTable.size() + 1 >= ELF::SHN_LORESERVE) ? (uint16_t)ELF::SHN_UNDEF
1181f17b149dSPeter Collingbourne : SectionTable.size() + 1,
1182f17b149dSPeter Collingbourne W.Endian);
11838c7829b8SRafael Espindola unsigned NumSectionsOffset;
11848c7829b8SRafael Espindola
1185f17b149dSPeter Collingbourne auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
1186642a2216SRafael Espindola if (is64Bit()) {
1187f17b149dSPeter Collingbourne uint64_t Val =
1188f17b149dSPeter Collingbourne support::endian::byte_swap<uint64_t>(SectionHeaderOffset, W.Endian);
1189f17b149dSPeter Collingbourne Stream.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1190642a2216SRafael Espindola offsetof(ELF::Elf64_Ehdr, e_shoff));
11918c7829b8SRafael Espindola NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum);
1192642a2216SRafael Espindola } else {
1193f17b149dSPeter Collingbourne uint32_t Val =
1194f17b149dSPeter Collingbourne support::endian::byte_swap<uint32_t>(SectionHeaderOffset, W.Endian);
1195f17b149dSPeter Collingbourne Stream.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1196642a2216SRafael Espindola offsetof(ELF::Elf32_Ehdr, e_shoff));
11978c7829b8SRafael Espindola NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum);
1198642a2216SRafael Espindola }
1199f17b149dSPeter Collingbourne Stream.pwrite(reinterpret_cast<char *>(&NumSections), sizeof(NumSections),
1200f17b149dSPeter Collingbourne NumSectionsOffset);
1201438390faSPeter Collingbourne
1202438390faSPeter Collingbourne return W.OS.tell() - StartOffset;
12031557fd6dSRafael Espindola }
12041557fd6dSRafael Espindola
hasRelocationAddend() const1205a29fe579SPeter Collingbourne bool ELFObjectWriter::hasRelocationAddend() const {
1206a29fe579SPeter Collingbourne return TargetObjectWriter->hasRelocationAddend();
1207a29fe579SPeter Collingbourne }
1208a29fe579SPeter Collingbourne
executePostLayoutBinding(MCAssembler & Asm,const MCAsmLayout & Layout)1209a29fe579SPeter Collingbourne void ELFObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
1210a29fe579SPeter Collingbourne const MCAsmLayout &Layout) {
1211a29fe579SPeter Collingbourne // The presence of symbol versions causes undefined symbols and
1212a29fe579SPeter Collingbourne // versions declared with @@@ to be renamed.
1213553d4d08SFangrui Song for (const MCAssembler::Symver &S : Asm.Symvers) {
1214553d4d08SFangrui Song StringRef AliasName = S.Name;
1215553d4d08SFangrui Song const auto &Symbol = cast<MCSymbolELF>(*S.Sym);
1216a29fe579SPeter Collingbourne size_t Pos = AliasName.find('@');
1217a29fe579SPeter Collingbourne assert(Pos != StringRef::npos);
1218a29fe579SPeter Collingbourne
1219a29fe579SPeter Collingbourne StringRef Prefix = AliasName.substr(0, Pos);
1220a29fe579SPeter Collingbourne StringRef Rest = AliasName.substr(Pos);
1221a29fe579SPeter Collingbourne StringRef Tail = Rest;
1222a29fe579SPeter Collingbourne if (Rest.startswith("@@@"))
1223a29fe579SPeter Collingbourne Tail = Rest.substr(Symbol.isUndefined() ? 2 : 1);
1224a29fe579SPeter Collingbourne
1225a29fe579SPeter Collingbourne auto *Alias =
1226a29fe579SPeter Collingbourne cast<MCSymbolELF>(Asm.getContext().getOrCreateSymbol(Prefix + Tail));
1227a29fe579SPeter Collingbourne Asm.registerSymbol(*Alias);
1228a29fe579SPeter Collingbourne const MCExpr *Value = MCSymbolRefExpr::create(&Symbol, Asm.getContext());
1229a29fe579SPeter Collingbourne Alias->setVariableValue(Value);
1230a29fe579SPeter Collingbourne
1231a29fe579SPeter Collingbourne // Aliases defined with .symvar copy the binding from the symbol they alias.
1232a29fe579SPeter Collingbourne // This is the first place we are able to copy this information.
1233a29fe579SPeter Collingbourne Alias->setBinding(Symbol.getBinding());
1234e6c17776SFangrui Song Alias->setVisibility(Symbol.getVisibility());
12359529c563SFangrui Song Alias->setOther(Symbol.getOther());
1236a29fe579SPeter Collingbourne
1237d96af2edSFangrui Song if (!Symbol.isUndefined() && S.KeepOriginalSym)
1238a29fe579SPeter Collingbourne continue;
1239a29fe579SPeter Collingbourne
1240a29fe579SPeter Collingbourne if (Symbol.isUndefined() && Rest.startswith("@@") &&
1241afe1e3e6SReid Kleckner !Rest.startswith("@@@")) {
1242553d4d08SFangrui Song Asm.getContext().reportError(S.Loc, "default version symbol " +
1243553d4d08SFangrui Song AliasName + " must be defined");
1244afe1e3e6SReid Kleckner continue;
1245afe1e3e6SReid Kleckner }
124630232770SManoj Gupta
124730232770SManoj Gupta if (Renames.count(&Symbol) && Renames[&Symbol] != Alias) {
1248553d4d08SFangrui Song Asm.getContext().reportError(S.Loc, Twine("multiple versions for ") +
124930232770SManoj Gupta Symbol.getName());
125030232770SManoj Gupta continue;
125130232770SManoj Gupta }
125230232770SManoj Gupta
125330232770SManoj Gupta Renames.insert(std::make_pair(&Symbol, Alias));
1254a29fe579SPeter Collingbourne }
12553e227336SPeter Collingbourne
12563e227336SPeter Collingbourne for (const MCSymbol *&Sym : AddrsigSyms) {
12573e227336SPeter Collingbourne if (const MCSymbol *R = Renames.lookup(cast<MCSymbolELF>(Sym)))
12583e227336SPeter Collingbourne Sym = R;
125969dd7cd4SPeter Collingbourne if (Sym->isInSection() && Sym->getName().startswith(".L"))
126069dd7cd4SPeter Collingbourne Sym = Sym->getSection().getBeginSymbol();
12613e227336SPeter Collingbourne Sym->setUsedInReloc();
12623e227336SPeter Collingbourne }
1263a29fe579SPeter Collingbourne }
1264a29fe579SPeter Collingbourne
1265a29fe579SPeter Collingbourne // It is always valid to create a relocation with a symbol. It is preferable
1266a29fe579SPeter Collingbourne // to use a relocation with a section if that is possible. Using the section
1267a29fe579SPeter Collingbourne // allows us to omit some local symbols from the symbol table.
shouldRelocateWithSymbol(const MCAssembler & Asm,const MCSymbolRefExpr * RefA,const MCSymbolELF * Sym,uint64_t C,unsigned Type) const1268a29fe579SPeter Collingbourne bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
1269a29fe579SPeter Collingbourne const MCSymbolRefExpr *RefA,
1270a29fe579SPeter Collingbourne const MCSymbolELF *Sym,
1271a29fe579SPeter Collingbourne uint64_t C,
1272a29fe579SPeter Collingbourne unsigned Type) const {
1273a29fe579SPeter Collingbourne // A PCRel relocation to an absolute value has no symbol (or section). We
1274a29fe579SPeter Collingbourne // represent that with a relocation to a null section.
1275a29fe579SPeter Collingbourne if (!RefA)
1276a29fe579SPeter Collingbourne return false;
1277a29fe579SPeter Collingbourne
1278a29fe579SPeter Collingbourne MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
1279a29fe579SPeter Collingbourne switch (Kind) {
1280a29fe579SPeter Collingbourne default:
1281a29fe579SPeter Collingbourne break;
1282a29fe579SPeter Collingbourne // The .odp creation emits a relocation against the symbol ".TOC." which
1283a29fe579SPeter Collingbourne // create a R_PPC64_TOC relocation. However the relocation symbol name
1284a29fe579SPeter Collingbourne // in final object creation should be NULL, since the symbol does not
1285a29fe579SPeter Collingbourne // really exist, it is just the reference to TOC base for the current
1286a29fe579SPeter Collingbourne // object file. Since the symbol is undefined, returning false results
1287a29fe579SPeter Collingbourne // in a relocation with a null section which is the desired result.
1288a29fe579SPeter Collingbourne case MCSymbolRefExpr::VK_PPC_TOCBASE:
1289a29fe579SPeter Collingbourne return false;
1290a29fe579SPeter Collingbourne
1291a29fe579SPeter Collingbourne // These VariantKind cause the relocation to refer to something other than
1292a29fe579SPeter Collingbourne // the symbol itself, like a linker generated table. Since the address of
1293a29fe579SPeter Collingbourne // symbol is not relevant, we cannot replace the symbol with the
1294a29fe579SPeter Collingbourne // section and patch the difference in the addend.
1295a29fe579SPeter Collingbourne case MCSymbolRefExpr::VK_GOT:
1296a29fe579SPeter Collingbourne case MCSymbolRefExpr::VK_PLT:
1297a29fe579SPeter Collingbourne case MCSymbolRefExpr::VK_GOTPCREL:
1298671f0930SMatt Morehouse case MCSymbolRefExpr::VK_GOTPCREL_NORELAX:
1299a29fe579SPeter Collingbourne case MCSymbolRefExpr::VK_PPC_GOT_LO:
1300a29fe579SPeter Collingbourne case MCSymbolRefExpr::VK_PPC_GOT_HI:
1301a29fe579SPeter Collingbourne case MCSymbolRefExpr::VK_PPC_GOT_HA:
1302a29fe579SPeter Collingbourne return true;
1303a29fe579SPeter Collingbourne }
1304a29fe579SPeter Collingbourne
1305a29fe579SPeter Collingbourne // An undefined symbol is not in any section, so the relocation has to point
1306a29fe579SPeter Collingbourne // to the symbol itself.
1307a29fe579SPeter Collingbourne assert(Sym && "Expected a symbol");
1308a29fe579SPeter Collingbourne if (Sym->isUndefined())
1309a29fe579SPeter Collingbourne return true;
1310a29fe579SPeter Collingbourne
1311a29fe579SPeter Collingbourne unsigned Binding = Sym->getBinding();
1312a29fe579SPeter Collingbourne switch(Binding) {
1313a29fe579SPeter Collingbourne default:
1314a29fe579SPeter Collingbourne llvm_unreachable("Invalid Binding");
1315a29fe579SPeter Collingbourne case ELF::STB_LOCAL:
1316a29fe579SPeter Collingbourne break;
1317a29fe579SPeter Collingbourne case ELF::STB_WEAK:
1318a29fe579SPeter Collingbourne // If the symbol is weak, it might be overridden by a symbol in another
1319a29fe579SPeter Collingbourne // file. The relocation has to point to the symbol so that the linker
1320a29fe579SPeter Collingbourne // can update it.
1321a29fe579SPeter Collingbourne return true;
1322a29fe579SPeter Collingbourne case ELF::STB_GLOBAL:
13236bdad85bSFangrui Song case ELF::STB_GNU_UNIQUE:
1324a29fe579SPeter Collingbourne // Global ELF symbols can be preempted by the dynamic linker. The relocation
1325a29fe579SPeter Collingbourne // has to point to the symbol for a reason analogous to the STB_WEAK case.
1326a29fe579SPeter Collingbourne return true;
1327a29fe579SPeter Collingbourne }
1328a29fe579SPeter Collingbourne
1329c841b9abSFangrui Song // Keep symbol type for a local ifunc because it may result in an IRELATIVE
1330c841b9abSFangrui Song // reloc that the dynamic loader will use to resolve the address at startup
1331c841b9abSFangrui Song // time.
1332c841b9abSFangrui Song if (Sym->getType() == ELF::STT_GNU_IFUNC)
1333c841b9abSFangrui Song return true;
1334c841b9abSFangrui Song
1335a29fe579SPeter Collingbourne // If a relocation points to a mergeable section, we have to be careful.
1336a29fe579SPeter Collingbourne // If the offset is zero, a relocation with the section will encode the
1337a29fe579SPeter Collingbourne // same information. With a non-zero offset, the situation is different.
1338a29fe579SPeter Collingbourne // For example, a relocation can point 42 bytes past the end of a string.
1339a29fe579SPeter Collingbourne // If we change such a relocation to use the section, the linker would think
1340a29fe579SPeter Collingbourne // that it pointed to another string and subtracting 42 at runtime will
1341a29fe579SPeter Collingbourne // produce the wrong value.
1342a29fe579SPeter Collingbourne if (Sym->isInSection()) {
1343a29fe579SPeter Collingbourne auto &Sec = cast<MCSectionELF>(Sym->getSection());
1344a29fe579SPeter Collingbourne unsigned Flags = Sec.getFlags();
1345a29fe579SPeter Collingbourne if (Flags & ELF::SHF_MERGE) {
1346a29fe579SPeter Collingbourne if (C != 0)
1347a29fe579SPeter Collingbourne return true;
1348382df1c6SMitch Phillips
134972e75ca3SFangrui Song // gold<2.34 incorrectly ignored the addend for R_386_GOTOFF (9)
135072e75ca3SFangrui Song // (http://sourceware.org/PR16794).
135172e75ca3SFangrui Song if (TargetObjectWriter->getEMachine() == ELF::EM_386 &&
135272e75ca3SFangrui Song Type == ELF::R_386_GOTOFF)
1353382df1c6SMitch Phillips return true;
13547e83a7f1SDimitry Andric
13557e83a7f1SDimitry Andric // ld.lld handles R_MIPS_HI16/R_MIPS_LO16 separately, not as a whole, so
13567e83a7f1SDimitry Andric // it doesn't know that an R_MIPS_HI16 with implicit addend 1 and an
13577e83a7f1SDimitry Andric // R_MIPS_LO16 with implicit addend -32768 represents 32768, which is in
13587e83a7f1SDimitry Andric // range of a MergeInputSection. We could introduce a new RelExpr member
13597e83a7f1SDimitry Andric // (like R_RISCV_PC_INDIRECT for R_RISCV_PCREL_HI20 / R_RISCV_PCREL_LO12)
13607e83a7f1SDimitry Andric // but the complexity is unnecessary given that GNU as keeps the original
13617e83a7f1SDimitry Andric // symbol for this case as well.
13627e83a7f1SDimitry Andric if (TargetObjectWriter->getEMachine() == ELF::EM_MIPS &&
13637e83a7f1SDimitry Andric !hasRelocationAddend())
13647e83a7f1SDimitry Andric return true;
1365a29fe579SPeter Collingbourne }
1366a29fe579SPeter Collingbourne
1367a29fe579SPeter Collingbourne // Most TLS relocations use a got, so they need the symbol. Even those that
1368a29fe579SPeter Collingbourne // are just an offset (@tpoff), require a symbol in gold versions before
1369a29fe579SPeter Collingbourne // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
1370a29fe579SPeter Collingbourne // http://sourceware.org/PR16773.
1371a29fe579SPeter Collingbourne if (Flags & ELF::SHF_TLS)
1372a29fe579SPeter Collingbourne return true;
1373a29fe579SPeter Collingbourne }
1374a29fe579SPeter Collingbourne
1375a29fe579SPeter Collingbourne // If the symbol is a thumb function the final relocation must set the lowest
1376a29fe579SPeter Collingbourne // bit. With a symbol that is done by just having the symbol have that bit
1377a29fe579SPeter Collingbourne // set, so we would lose the bit if we relocated with the section.
1378a29fe579SPeter Collingbourne // FIXME: We could use the section but add the bit to the relocation value.
1379a29fe579SPeter Collingbourne if (Asm.isThumbFunc(Sym))
1380a29fe579SPeter Collingbourne return true;
1381a29fe579SPeter Collingbourne
1382a29fe579SPeter Collingbourne if (TargetObjectWriter->needsRelocateWithSymbol(*Sym, Type))
1383a29fe579SPeter Collingbourne return true;
1384a29fe579SPeter Collingbourne return false;
1385a29fe579SPeter Collingbourne }
1386a29fe579SPeter Collingbourne
recordRelocation(MCAssembler & Asm,const MCAsmLayout & Layout,const MCFragment * Fragment,const MCFixup & Fixup,MCValue Target,uint64_t & FixedValue)1387a29fe579SPeter Collingbourne void ELFObjectWriter::recordRelocation(MCAssembler &Asm,
1388a29fe579SPeter Collingbourne const MCAsmLayout &Layout,
1389a29fe579SPeter Collingbourne const MCFragment *Fragment,
1390a29fe579SPeter Collingbourne const MCFixup &Fixup, MCValue Target,
1391a29fe579SPeter Collingbourne uint64_t &FixedValue) {
1392a29fe579SPeter Collingbourne MCAsmBackend &Backend = Asm.getBackend();
1393a29fe579SPeter Collingbourne bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
1394a29fe579SPeter Collingbourne MCFixupKindInfo::FKF_IsPCRel;
1395a29fe579SPeter Collingbourne const MCSectionELF &FixupSection = cast<MCSectionELF>(*Fragment->getParent());
1396a29fe579SPeter Collingbourne uint64_t C = Target.getConstant();
1397a29fe579SPeter Collingbourne uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
1398a29fe579SPeter Collingbourne MCContext &Ctx = Asm.getContext();
1399a29fe579SPeter Collingbourne
1400a29fe579SPeter Collingbourne if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
1401a29fe579SPeter Collingbourne const auto &SymB = cast<MCSymbolELF>(RefB->getSymbol());
1402a29fe579SPeter Collingbourne if (SymB.isUndefined()) {
1403a29fe579SPeter Collingbourne Ctx.reportError(Fixup.getLoc(),
1404a29fe579SPeter Collingbourne Twine("symbol '") + SymB.getName() +
1405a29fe579SPeter Collingbourne "' can not be undefined in a subtraction expression");
1406a29fe579SPeter Collingbourne return;
1407a29fe579SPeter Collingbourne }
1408a29fe579SPeter Collingbourne
1409a29fe579SPeter Collingbourne assert(!SymB.isAbsolute() && "Should have been folded");
1410a29fe579SPeter Collingbourne const MCSection &SecB = SymB.getSection();
1411a29fe579SPeter Collingbourne if (&SecB != &FixupSection) {
1412a29fe579SPeter Collingbourne Ctx.reportError(Fixup.getLoc(),
1413a29fe579SPeter Collingbourne "Cannot represent a difference across sections");
1414a29fe579SPeter Collingbourne return;
1415a29fe579SPeter Collingbourne }
1416a29fe579SPeter Collingbourne
1417b127771fSFangrui Song assert(!IsPCRel && "should have been folded");
1418a29fe579SPeter Collingbourne IsPCRel = true;
1419d9a071c5SFangrui Song C += FixupOffset - Layout.getSymbolOffset(SymB);
1420a29fe579SPeter Collingbourne }
1421a29fe579SPeter Collingbourne
1422a29fe579SPeter Collingbourne // We either rejected the fixup or folded B into C at this point.
1423a29fe579SPeter Collingbourne const MCSymbolRefExpr *RefA = Target.getSymA();
1424a29fe579SPeter Collingbourne const auto *SymA = RefA ? cast<MCSymbolELF>(&RefA->getSymbol()) : nullptr;
1425a29fe579SPeter Collingbourne
1426a29fe579SPeter Collingbourne bool ViaWeakRef = false;
1427a29fe579SPeter Collingbourne if (SymA && SymA->isVariable()) {
1428a29fe579SPeter Collingbourne const MCExpr *Expr = SymA->getVariableValue();
1429a29fe579SPeter Collingbourne if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr)) {
1430a29fe579SPeter Collingbourne if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) {
1431a29fe579SPeter Collingbourne SymA = cast<MCSymbolELF>(&Inner->getSymbol());
1432a29fe579SPeter Collingbourne ViaWeakRef = true;
1433a29fe579SPeter Collingbourne }
1434a29fe579SPeter Collingbourne }
1435a29fe579SPeter Collingbourne }
1436a29fe579SPeter Collingbourne
143763062d9dSPeter Collingbourne const MCSectionELF *SecA = (SymA && SymA->isInSection())
143863062d9dSPeter Collingbourne ? cast<MCSectionELF>(&SymA->getSection())
143963062d9dSPeter Collingbourne : nullptr;
144063062d9dSPeter Collingbourne if (!checkRelocation(Ctx, Fixup.getLoc(), &FixupSection, SecA))
144163062d9dSPeter Collingbourne return;
144263062d9dSPeter Collingbourne
1443d9a071c5SFangrui Song unsigned Type = TargetObjectWriter->getRelocType(Ctx, Target, Fixup, IsPCRel);
1444a224c519SAlexander Yermolovich const auto *Parent = cast<MCSectionELF>(Fragment->getParent());
1445a224c519SAlexander Yermolovich // Emiting relocation with sybmol for CG Profile to help with --cg-profile.
1446a224c519SAlexander Yermolovich bool RelocateWithSymbol =
1447a224c519SAlexander Yermolovich shouldRelocateWithSymbol(Asm, RefA, SymA, C, Type) ||
1448a224c519SAlexander Yermolovich (Parent->getType() == ELF::SHT_LLVM_CALL_GRAPH_PROFILE);
1449d9a071c5SFangrui Song uint64_t Addend = 0;
1450d9a071c5SFangrui Song
1451d9a071c5SFangrui Song FixedValue = !RelocateWithSymbol && SymA && !SymA->isUndefined()
1452d9a071c5SFangrui Song ? C + Layout.getSymbolOffset(*SymA)
1453d9a071c5SFangrui Song : C;
1454d9a071c5SFangrui Song if (hasRelocationAddend()) {
1455d9a071c5SFangrui Song Addend = FixedValue;
1456d9a071c5SFangrui Song FixedValue = 0;
1457d9a071c5SFangrui Song }
1458d9a071c5SFangrui Song
1459a29fe579SPeter Collingbourne if (!RelocateWithSymbol) {
1460a29fe579SPeter Collingbourne const auto *SectionSymbol =
1461a29fe579SPeter Collingbourne SecA ? cast<MCSymbolELF>(SecA->getBeginSymbol()) : nullptr;
1462a29fe579SPeter Collingbourne if (SectionSymbol)
1463a29fe579SPeter Collingbourne SectionSymbol->setUsedInReloc();
1464d9a071c5SFangrui Song ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend, SymA, C);
1465a29fe579SPeter Collingbourne Relocations[&FixupSection].push_back(Rec);
1466a29fe579SPeter Collingbourne return;
1467a29fe579SPeter Collingbourne }
1468a29fe579SPeter Collingbourne
1469d9a071c5SFangrui Song const MCSymbolELF *RenamedSymA = SymA;
1470a29fe579SPeter Collingbourne if (SymA) {
1471a29fe579SPeter Collingbourne if (const MCSymbolELF *R = Renames.lookup(SymA))
1472a29fe579SPeter Collingbourne RenamedSymA = R;
1473a29fe579SPeter Collingbourne
1474a29fe579SPeter Collingbourne if (ViaWeakRef)
1475a29fe579SPeter Collingbourne RenamedSymA->setIsWeakrefUsedInReloc();
1476a29fe579SPeter Collingbourne else
1477a29fe579SPeter Collingbourne RenamedSymA->setUsedInReloc();
1478a29fe579SPeter Collingbourne }
1479d9a071c5SFangrui Song ELFRelocationEntry Rec(FixupOffset, RenamedSymA, Type, Addend, SymA, C);
1480a29fe579SPeter Collingbourne Relocations[&FixupSection].push_back(Rec);
1481a29fe579SPeter Collingbourne }
1482a29fe579SPeter Collingbourne
isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler & Asm,const MCSymbol & SA,const MCFragment & FB,bool InSet,bool IsPCRel) const148336e60e91SJim Grosbach bool ELFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
148495fb9b93SRafael Espindola const MCAssembler &Asm, const MCSymbol &SA, const MCFragment &FB,
148535d6189fSRafael Espindola bool InSet, bool IsPCRel) const {
148695fb9b93SRafael Espindola const auto &SymA = cast<MCSymbolELF>(SA);
148735d6189fSRafael Espindola if (IsPCRel) {
148835d6189fSRafael Espindola assert(!InSet);
14890136f226SFangrui Song if (SymA.getBinding() != ELF::STB_LOCAL ||
14900136f226SFangrui Song SymA.getType() == ELF::STT_GNU_IFUNC)
1491d92d17bfSEli Friedman return false;
149235d6189fSRafael Espindola }
149336e60e91SJim Grosbach return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
149435d6189fSRafael Espindola InSet, IsPCRel);
1495d92d17bfSEli Friedman }
1496d92d17bfSEli Friedman
149760fbc7ccSLang Hames std::unique_ptr<MCObjectWriter>
createELFObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,raw_pwrite_stream & OS,bool IsLittleEndian)1498dcb312bdSLang Hames llvm::createELFObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
1499dcb312bdSLang Hames raw_pwrite_stream &OS, bool IsLittleEndian) {
15000eaee545SJonas Devlieghere return std::make_unique<ELFSingleObjectWriter>(std::move(MOTW), OS,
150160fbc7ccSLang Hames IsLittleEndian);
1502b264d338SRafael Espindola }
150363062d9dSPeter Collingbourne
150463062d9dSPeter Collingbourne std::unique_ptr<MCObjectWriter>
createELFDwoObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,raw_pwrite_stream & OS,raw_pwrite_stream & DwoOS,bool IsLittleEndian)150563062d9dSPeter Collingbourne llvm::createELFDwoObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
150663062d9dSPeter Collingbourne raw_pwrite_stream &OS, raw_pwrite_stream &DwoOS,
150763062d9dSPeter Collingbourne bool IsLittleEndian) {
15080eaee545SJonas Devlieghere return std::make_unique<ELFDwoObjectWriter>(std::move(MOTW), OS, DwoOS,
150963062d9dSPeter Collingbourne IsLittleEndian);
151063062d9dSPeter Collingbourne }
1511