blob: a8f88ce49e29d92b9b73c420160a7faf617d3596 [file] [log] [blame]
Nick Lewycky4288f9e2013-03-09 09:32:16 +00001//===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -----------------------===//
Matt Fleming6c1ad482010-08-16 18:57:57 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements ELF object file writer information.
11//
12//===----------------------------------------------------------------------===//
13
Eugene Zelenkod3a6c892017-02-11 00:27:28 +000014#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/DenseMap.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000016#include "llvm/ADT/STLExtras.h"
Rafael Espindola29abd972011-12-22 03:38:00 +000017#include "llvm/ADT/SmallString.h"
Eugene Zelenkod3a6c892017-02-11 00:27:28 +000018#include "llvm/ADT/SmallVector.h"
Eugene Zelenkod3a6c892017-02-11 00:27:28 +000019#include "llvm/ADT/StringRef.h"
20#include "llvm/ADT/Twine.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000021#include "llvm/BinaryFormat/ELF.h"
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +000022#include "llvm/MC/MCAsmBackend.h"
David Blaikie8019bf82014-04-10 21:53:53 +000023#include "llvm/MC/MCAsmInfo.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000024#include "llvm/MC/MCAsmLayout.h"
Rafael Espindola29abd972011-12-22 03:38:00 +000025#include "llvm/MC/MCAssembler.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000026#include "llvm/MC/MCContext.h"
Eugene Zelenkod3a6c892017-02-11 00:27:28 +000027#include "llvm/MC/MCELFObjectWriter.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000028#include "llvm/MC/MCExpr.h"
Eugene Zelenkod3a6c892017-02-11 00:27:28 +000029#include "llvm/MC/MCFixup.h"
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +000030#include "llvm/MC/MCFixupKindInfo.h"
Eugene Zelenkod3a6c892017-02-11 00:27:28 +000031#include "llvm/MC/MCFragment.h"
Craig Topper6e80c282012-03-26 06:58:25 +000032#include "llvm/MC/MCObjectWriter.h"
Eugene Zelenkod3a6c892017-02-11 00:27:28 +000033#include "llvm/MC/MCSection.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000034#include "llvm/MC/MCSectionELF.h"
Eugene Zelenkod3a6c892017-02-11 00:27:28 +000035#include "llvm/MC/MCSymbol.h"
Rafael Espindolaa8695762015-06-02 00:25:12 +000036#include "llvm/MC/MCSymbolELF.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000037#include "llvm/MC/MCValue.h"
Rafael Espindola97de4742014-07-03 02:01:39 +000038#include "llvm/MC/StringTableBuilder.h"
Eugene Zelenkod3a6c892017-02-11 00:27:28 +000039#include "llvm/Support/Allocator.h"
40#include "llvm/Support/Casting.h"
David Blaikie8019bf82014-04-10 21:53:53 +000041#include "llvm/Support/Compression.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000042#include "llvm/Support/Endian.h"
George Rimar167ca4a2017-01-17 15:45:07 +000043#include "llvm/Support/Error.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000044#include "llvm/Support/ErrorHandling.h"
Eugene Zelenkod3a6c892017-02-11 00:27:28 +000045#include "llvm/Support/Host.h"
46#include "llvm/Support/MathExtras.h"
47#include "llvm/Support/SMLoc.h"
Rafael Espindolafc063e82015-10-22 18:32:06 +000048#include "llvm/Support/StringSaver.h"
Eugene Zelenkod3a6c892017-02-11 00:27:28 +000049#include "llvm/Support/SwapByteOrder.h"
50#include "llvm/Support/raw_ostream.h"
51#include <algorithm>
52#include <cassert>
53#include <cstddef>
54#include <cstdint>
55#include <map>
56#include <memory>
57#include <string>
58#include <utility>
Matt Fleming6c1ad482010-08-16 18:57:57 +000059#include <vector>
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +000060
Matt Fleming6c1ad482010-08-16 18:57:57 +000061using namespace llvm;
62
Jason W Kimc09e7262011-05-11 22:53:06 +000063#undef DEBUG_TYPE
64#define DEBUG_TYPE "reloc-info"
65
Rafael Espindola29abd972011-12-22 03:38:00 +000066namespace {
Eugene Zelenkod3a6c892017-02-11 00:27:28 +000067
Eugene Zelenko7975b992017-04-26 22:31:39 +000068using SectionIndexMapTy = DenseMap<const MCSectionELF *, uint32_t>;
Rafael Espindola10be0832014-03-25 23:44:25 +000069
Rafael Espindola91fd2772015-04-29 21:09:32 +000070class ELFObjectWriter;
Peter Collingbournea29fe572018-05-21 19:18:28 +000071struct ELFWriter;
Rafael Espindola91fd2772015-04-29 21:09:32 +000072
Rafael Espindola10be0832014-03-25 23:44:25 +000073class SymbolTableWriter {
Peter Collingbournea29fe572018-05-21 19:18:28 +000074 ELFWriter &EWriter;
Rafael Espindola10be0832014-03-25 23:44:25 +000075 bool Is64Bit;
Rafael Espindola10be0832014-03-25 23:44:25 +000076
Rafael Espindola91fd2772015-04-29 21:09:32 +000077 // indexes we are going to write to .symtab_shndx.
78 std::vector<uint32_t> ShndxIndexes;
Rafael Espindola10be0832014-03-25 23:44:25 +000079
80 // The numbel of symbols written so far.
81 unsigned NumWritten;
82
83 void createSymtabShndx();
84
Rafael Espindola91fd2772015-04-29 21:09:32 +000085 template <typename T> void write(T Value);
Rafael Espindola10be0832014-03-25 23:44:25 +000086
87public:
Peter Collingbournea29fe572018-05-21 19:18:28 +000088 SymbolTableWriter(ELFWriter &EWriter, bool Is64Bit);
Rafael Espindola10be0832014-03-25 23:44:25 +000089
90 void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
91 uint8_t other, uint32_t shndx, bool Reserved);
Rafael Espindola91fd2772015-04-29 21:09:32 +000092
93 ArrayRef<uint32_t> getShndxIndexes() const { return ShndxIndexes; }
Rafael Espindola10be0832014-03-25 23:44:25 +000094};
95
Peter Collingbournea29fe572018-05-21 19:18:28 +000096struct ELFWriter {
97 ELFObjectWriter &OWriter;
98 support::endian::Writer W;
99
David Blaikiea0fa2622016-04-12 21:45:53 +0000100 static uint64_t SymbolValue(const MCSymbol &Sym, const MCAsmLayout &Layout);
101 static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolELF &Symbol,
102 bool Used, bool Renamed);
Rafael Espindola29abd972011-12-22 03:38:00 +0000103
David Blaikiea0fa2622016-04-12 21:45:53 +0000104 /// Helper struct for containing some precomputed information on symbols.
105 struct ELFSymbolData {
106 const MCSymbolELF *Symbol;
107 uint32_t SectionIndex;
108 StringRef Name;
Rafael Espindola29abd972011-12-22 03:38:00 +0000109
David Blaikiea0fa2622016-04-12 21:45:53 +0000110 // Support lexicographic sorting.
111 bool operator<(const ELFSymbolData &RHS) const {
112 unsigned LHSType = Symbol->getType();
113 unsigned RHSType = RHS.Symbol->getType();
114 if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
115 return false;
116 if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
117 return true;
118 if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
119 return SectionIndex < RHS.SectionIndex;
120 return Name < RHS.Name;
Rafael Espindola29abd972011-12-22 03:38:00 +0000121 }
Rafael Espindola29abd972011-12-22 03:38:00 +0000122 };
David Blaikiea0fa2622016-04-12 21:45:53 +0000123
David Blaikiea0fa2622016-04-12 21:45:53 +0000124 /// @}
125 /// @name Symbol Table Data
126 /// @{
127
David Blaikiea0fa2622016-04-12 21:45:53 +0000128 StringTableBuilder StrTabBuilder{StringTableBuilder::ELF};
129
130 /// @}
131
132 // This holds the symbol table index of the last local symbol.
133 unsigned LastLocalSymbolIndex;
134 // This holds the .strtab section index.
135 unsigned StringTableIndex;
136 // This holds the .symtab section index.
137 unsigned SymbolTableIndex;
138
139 // Sections in the order they are to be output in the section table.
140 std::vector<const MCSectionELF *> SectionTable;
141 unsigned addToSectionTable(const MCSectionELF *Sec);
142
143 // TargetObjectWriter wrappers.
Peter Collingbournea29fe572018-05-21 19:18:28 +0000144 bool is64Bit() const;
145 bool hasRelocationAddend() const;
David Blaikiea0fa2622016-04-12 21:45:53 +0000146
147 void align(unsigned Alignment);
148
George Rimarc91e38c2016-05-27 12:27:32 +0000149 bool maybeWriteCompression(uint64_t Size,
150 SmallVectorImpl<char> &CompressedContents,
151 bool ZLibStyle, unsigned Alignment);
152
David Blaikiea0fa2622016-04-12 21:45:53 +0000153public:
Peter Collingbournea29fe572018-05-21 19:18:28 +0000154 ELFWriter(ELFObjectWriter &OWriter, raw_pwrite_stream &OS,
155 bool IsLittleEndian)
156 : OWriter(OWriter),
Peter Collingbournef17b1492018-05-21 18:17:42 +0000157 W(OS, IsLittleEndian ? support::little : support::big) {}
David Blaikiea0fa2622016-04-12 21:45:53 +0000158
Peter Collingbournef17b1492018-05-21 18:17:42 +0000159 void WriteWord(uint64_t Word) {
David Blaikiea0fa2622016-04-12 21:45:53 +0000160 if (is64Bit())
Peter Collingbournef17b1492018-05-21 18:17:42 +0000161 W.write<uint64_t>(Word);
David Blaikiea0fa2622016-04-12 21:45:53 +0000162 else
Peter Collingbournef17b1492018-05-21 18:17:42 +0000163 W.write<uint32_t>(Word);
David Blaikiea0fa2622016-04-12 21:45:53 +0000164 }
165
166 template <typename T> void write(T Val) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000167 W.write(Val);
David Blaikiea0fa2622016-04-12 21:45:53 +0000168 }
169
170 void writeHeader(const MCAssembler &Asm);
171
172 void writeSymbol(SymbolTableWriter &Writer, uint32_t StringIndex,
173 ELFSymbolData &MSD, const MCAsmLayout &Layout);
174
175 // Start and end offset of each section
Eugene Zelenko7975b992017-04-26 22:31:39 +0000176 using SectionOffsetsTy =
177 std::map<const MCSectionELF *, std::pair<uint64_t, uint64_t>>;
David Blaikiea0fa2622016-04-12 21:45:53 +0000178
David Blaikiea0fa2622016-04-12 21:45:53 +0000179 // Map from a signature symbol to the group section index
Eugene Zelenko7975b992017-04-26 22:31:39 +0000180 using RevGroupMapTy = DenseMap<const MCSymbol *, unsigned>;
David Blaikiea0fa2622016-04-12 21:45:53 +0000181
182 /// Compute the symbol table data
183 ///
184 /// \param Asm - The assembler.
185 /// \param SectionIndexMap - Maps a section to its index.
186 /// \param RevGroupMap - Maps a signature symbol to the group section.
187 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
188 const SectionIndexMapTy &SectionIndexMap,
189 const RevGroupMapTy &RevGroupMap,
190 SectionOffsetsTy &SectionOffsets);
191
192 MCSectionELF *createRelocationSection(MCContext &Ctx,
193 const MCSectionELF &Sec);
194
195 const MCSectionELF *createStringTable(MCContext &Ctx);
196
David Blaikiea0fa2622016-04-12 21:45:53 +0000197 void writeSectionHeader(const MCAsmLayout &Layout,
198 const SectionIndexMapTy &SectionIndexMap,
199 const SectionOffsetsTy &SectionOffsets);
200
201 void writeSectionData(const MCAssembler &Asm, MCSection &Sec,
202 const MCAsmLayout &Layout);
203
204 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
205 uint64_t Address, uint64_t Offset, uint64_t Size,
206 uint32_t Link, uint32_t Info, uint64_t Alignment,
207 uint64_t EntrySize);
208
209 void writeRelocations(const MCAssembler &Asm, const MCSectionELF &Sec);
210
Peter Collingbournea29fe572018-05-21 19:18:28 +0000211 uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout);
David Blaikiea0fa2622016-04-12 21:45:53 +0000212 void writeSection(const SectionIndexMapTy &SectionIndexMap,
213 uint32_t GroupSymbolIndex, uint64_t Offset, uint64_t Size,
214 const MCSectionELF &Section);
215};
Eugene Zelenkod3a6c892017-02-11 00:27:28 +0000216
Peter Collingbournea29fe572018-05-21 19:18:28 +0000217class ELFObjectWriter : public MCObjectWriter {
Peter Collingbournea29fe572018-05-21 19:18:28 +0000218 /// The target specific ELF writer instance.
219 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
220
221 DenseMap<const MCSectionELF *, std::vector<ELFRelocationEntry>> Relocations;
222
223 DenseMap<const MCSymbolELF *, const MCSymbolELF *> Renames;
224
225 bool hasRelocationAddend() const;
226
227 bool shouldRelocateWithSymbol(const MCAssembler &Asm,
228 const MCSymbolRefExpr *RefA,
229 const MCSymbolELF *Sym, uint64_t C,
230 unsigned Type) const;
231
232public:
Peter Collingbournef0226e62018-05-21 19:30:59 +0000233 ELFObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW)
234 : TargetObjectWriter(std::move(MOTW)) {}
Peter Collingbournea29fe572018-05-21 19:18:28 +0000235
236 void reset() override {
237 Relocations.clear();
238 Renames.clear();
239 MCObjectWriter::reset();
240 }
241
242 bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
243 const MCSymbol &SymA,
244 const MCFragment &FB, bool InSet,
245 bool IsPCRel) const override;
246
247 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
248 const MCFragment *Fragment, const MCFixup &Fixup,
249 MCValue Target, uint64_t &FixedValue) override;
250
Peter Collingbournea29fe572018-05-21 19:18:28 +0000251 void executePostLayoutBinding(MCAssembler &Asm,
252 const MCAsmLayout &Layout) override;
253
254 friend struct ELFWriter;
255};
256
Peter Collingbournef0226e62018-05-21 19:30:59 +0000257class ELFSingleObjectWriter : public ELFObjectWriter {
258 raw_pwrite_stream &OS;
259 bool IsLittleEndian;
260
261public:
262 ELFSingleObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
263 raw_pwrite_stream &OS, bool IsLittleEndian)
264 : ELFObjectWriter(std::move(MOTW)), OS(OS),
265 IsLittleEndian(IsLittleEndian) {}
266
267 uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override {
268 return ELFWriter(*this, OS, IsLittleEndian).writeObject(Asm, Layout);
269 }
270};
271
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000272} // end anonymous namespace
Rafael Espindola29abd972011-12-22 03:38:00 +0000273
Peter Collingbournea29fe572018-05-21 19:18:28 +0000274void ELFWriter::align(unsigned Alignment) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000275 uint64_t Padding = OffsetToAlignment(W.OS.tell(), Alignment);
276 W.OS.write_zeros(Padding);
Rafael Espindolab20fbb82015-06-05 18:21:00 +0000277}
278
Peter Collingbournea29fe572018-05-21 19:18:28 +0000279unsigned ELFWriter::addToSectionTable(const MCSectionELF *Sec) {
Rafael Espindola03d7abb2015-04-30 20:53:27 +0000280 SectionTable.push_back(Sec);
Rafael Espindola5960cee2015-05-22 23:58:30 +0000281 StrTabBuilder.add(Sec->getSectionName());
Rafael Espindola03d7abb2015-04-30 20:53:27 +0000282 return SectionTable.size();
283}
284
Rafael Espindola10be0832014-03-25 23:44:25 +0000285void SymbolTableWriter::createSymtabShndx() {
Rafael Espindola91fd2772015-04-29 21:09:32 +0000286 if (!ShndxIndexes.empty())
Rafael Espindola10be0832014-03-25 23:44:25 +0000287 return;
288
Rafael Espindola91fd2772015-04-29 21:09:32 +0000289 ShndxIndexes.resize(NumWritten);
Rafael Espindola10be0832014-03-25 23:44:25 +0000290}
291
Rafael Espindola91fd2772015-04-29 21:09:32 +0000292template <typename T> void SymbolTableWriter::write(T Value) {
293 EWriter.write(Value);
Rafael Espindola10be0832014-03-25 23:44:25 +0000294}
295
Peter Collingbournea29fe572018-05-21 19:18:28 +0000296SymbolTableWriter::SymbolTableWriter(ELFWriter &EWriter, bool Is64Bit)
Rafael Espindola91fd2772015-04-29 21:09:32 +0000297 : EWriter(EWriter), Is64Bit(Is64Bit), NumWritten(0) {}
Rafael Espindola10be0832014-03-25 23:44:25 +0000298
299void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
300 uint64_t size, uint8_t other,
301 uint32_t shndx, bool Reserved) {
302 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
303
304 if (LargeIndex)
305 createSymtabShndx();
306
Rafael Espindola91fd2772015-04-29 21:09:32 +0000307 if (!ShndxIndexes.empty()) {
Rafael Espindola10be0832014-03-25 23:44:25 +0000308 if (LargeIndex)
Rafael Espindola91fd2772015-04-29 21:09:32 +0000309 ShndxIndexes.push_back(shndx);
Rafael Espindola10be0832014-03-25 23:44:25 +0000310 else
Rafael Espindola91fd2772015-04-29 21:09:32 +0000311 ShndxIndexes.push_back(0);
Rafael Espindola10be0832014-03-25 23:44:25 +0000312 }
313
314 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
315
Rafael Espindola10be0832014-03-25 23:44:25 +0000316 if (Is64Bit) {
Rafael Espindola91fd2772015-04-29 21:09:32 +0000317 write(name); // st_name
318 write(info); // st_info
319 write(other); // st_other
320 write(Index); // st_shndx
321 write(value); // st_value
322 write(size); // st_size
Rafael Espindola10be0832014-03-25 23:44:25 +0000323 } else {
Rafael Espindola91fd2772015-04-29 21:09:32 +0000324 write(name); // st_name
325 write(uint32_t(value)); // st_value
326 write(uint32_t(size)); // st_size
327 write(info); // st_info
328 write(other); // st_other
329 write(Index); // st_shndx
Rafael Espindola10be0832014-03-25 23:44:25 +0000330 }
331
332 ++NumWritten;
333}
334
Peter Collingbournea29fe572018-05-21 19:18:28 +0000335bool ELFWriter::is64Bit() const {
336 return OWriter.TargetObjectWriter->is64Bit();
337}
338
339bool ELFWriter::hasRelocationAddend() const {
340 return OWriter.hasRelocationAddend();
341}
342
Matt Fleming6c1ad482010-08-16 18:57:57 +0000343// Emit the ELF header.
Peter Collingbournea29fe572018-05-21 19:18:28 +0000344void ELFWriter::writeHeader(const MCAssembler &Asm) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000345 // ELF Header
346 // ----------
347 //
348 // Note
349 // ----
350 // emitWord method behaves differently for ELF32 and ELF64, writing
351 // 4 bytes in the former and 8 in the latter.
352
Peter Collingbournef17b1492018-05-21 18:17:42 +0000353 W.OS << ELF::ElfMagic; // e_ident[EI_MAG0] to e_ident[EI_MAG3]
Matt Fleming6c1ad482010-08-16 18:57:57 +0000354
Peter Collingbournef17b1492018-05-21 18:17:42 +0000355 W.OS << char(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
Matt Fleming6c1ad482010-08-16 18:57:57 +0000356
357 // e_ident[EI_DATA]
Peter Collingbournef17b1492018-05-21 18:17:42 +0000358 W.OS << char(W.Endian == support::little ? ELF::ELFDATA2LSB
359 : ELF::ELFDATA2MSB);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000360
Peter Collingbournef17b1492018-05-21 18:17:42 +0000361 W.OS << char(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky3b727f52010-09-09 17:57:50 +0000362 // e_ident[EI_OSABI]
Peter Collingbournea29fe572018-05-21 19:18:28 +0000363 W.OS << char(OWriter.TargetObjectWriter->getOSABI());
Peter Collingbournef17b1492018-05-21 18:17:42 +0000364 W.OS << char(0); // e_ident[EI_ABIVERSION]
Matt Fleming6c1ad482010-08-16 18:57:57 +0000365
Peter Collingbournef17b1492018-05-21 18:17:42 +0000366 W.OS.write_zeros(ELF::EI_NIDENT - ELF::EI_PAD);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000367
Peter Collingbournef17b1492018-05-21 18:17:42 +0000368 W.write<uint16_t>(ELF::ET_REL); // e_type
Matt Fleming6c1ad482010-08-16 18:57:57 +0000369
Peter Collingbournea29fe572018-05-21 19:18:28 +0000370 W.write<uint16_t>(OWriter.TargetObjectWriter->getEMachine()); // e_machine = target
Matt Fleming6c1ad482010-08-16 18:57:57 +0000371
Peter Collingbournef17b1492018-05-21 18:17:42 +0000372 W.write<uint32_t>(ELF::EV_CURRENT); // e_version
Matt Fleming6c1ad482010-08-16 18:57:57 +0000373 WriteWord(0); // e_entry, no entry point in .o file
374 WriteWord(0); // e_phoff, no program header for .o
Rafael Espindola642a2212015-04-14 22:54:16 +0000375 WriteWord(0); // e_shoff = sec hdr table off in bytes
Matt Fleming6c1ad482010-08-16 18:57:57 +0000376
Jason W Kim4761fba2011-02-04 21:41:11 +0000377 // e_flags = whatever the target wants
Peter Collingbournef17b1492018-05-21 18:17:42 +0000378 W.write<uint32_t>(Asm.getELFHeaderEFlags());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000379
380 // e_ehsize = ELF header size
Peter Collingbournef17b1492018-05-21 18:17:42 +0000381 W.write<uint16_t>(is64Bit() ? sizeof(ELF::Elf64_Ehdr)
382 : sizeof(ELF::Elf32_Ehdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000383
Peter Collingbournef17b1492018-05-21 18:17:42 +0000384 W.write<uint16_t>(0); // e_phentsize = prog header entry size
385 W.write<uint16_t>(0); // e_phnum = # prog header entries = 0
Matt Fleming6c1ad482010-08-16 18:57:57 +0000386
387 // e_shentsize = Section header entry size
Peter Collingbournef17b1492018-05-21 18:17:42 +0000388 W.write<uint16_t>(is64Bit() ? sizeof(ELF::Elf64_Shdr)
389 : sizeof(ELF::Elf32_Shdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000390
391 // e_shnum = # of section header ents
Peter Collingbournef17b1492018-05-21 18:17:42 +0000392 W.write<uint16_t>(0);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000393
394 // e_shstrndx = Section # of '.shstrtab'
Rafael Espindola5960cee2015-05-22 23:58:30 +0000395 assert(StringTableIndex < ELF::SHN_LORESERVE);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000396 W.write<uint16_t>(StringTableIndex);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000397}
398
Peter Collingbournea29fe572018-05-21 19:18:28 +0000399uint64_t ELFWriter::SymbolValue(const MCSymbol &Sym,
400 const MCAsmLayout &Layout) {
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000401 if (Sym.isCommon() && Sym.isExternal())
Rafael Espindola14672502015-05-29 17:48:04 +0000402 return Sym.getCommonAlignment();
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000403
Rafael Espindolafee224f2014-04-30 21:51:13 +0000404 uint64_t Res;
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +0000405 if (!Layout.getSymbolOffset(Sym, Res))
Rafael Espindola553e5eb2014-04-30 16:59:35 +0000406 return 0;
407
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +0000408 if (Layout.getAssembler().isThumbFunc(&Sym))
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000409 Res |= 1;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000410
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000411 return Res;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000412}
413
Roman Divacky5a1c5492014-01-07 20:17:03 +0000414static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
415 uint8_t Type = newType;
416
417 // Propagation rules:
418 // IFUNC > FUNC > OBJECT > NOTYPE
419 // TLS_OBJECT > OBJECT > NOTYPE
420 //
421 // dont let the new type degrade the old type
422 switch (origType) {
423 default:
424 break;
425 case ELF::STT_GNU_IFUNC:
426 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
427 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
428 Type = ELF::STT_GNU_IFUNC;
429 break;
430 case ELF::STT_FUNC:
431 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
432 Type == ELF::STT_TLS)
433 Type = ELF::STT_FUNC;
434 break;
435 case ELF::STT_OBJECT:
436 if (Type == ELF::STT_NOTYPE)
437 Type = ELF::STT_OBJECT;
438 break;
439 case ELF::STT_TLS:
440 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
441 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
442 Type = ELF::STT_TLS;
443 break;
444 }
445
446 return Type;
447}
448
Peter Collingbournea29fe572018-05-21 19:18:28 +0000449void ELFWriter::writeSymbol(SymbolTableWriter &Writer, uint32_t StringIndex,
450 ELFSymbolData &MSD, const MCAsmLayout &Layout) {
Rafael Espindola95fb9b92015-06-02 20:38:46 +0000451 const auto &Symbol = cast<MCSymbolELF>(*MSD.Symbol);
Rafael Espindolaa8695762015-06-02 00:25:12 +0000452 const MCSymbolELF *Base =
453 cast_or_null<MCSymbolELF>(Layout.getBaseSymbol(Symbol));
Rafael Espindola85a84912014-03-26 00:16:43 +0000454
455 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
456 // SHN_COMMON.
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000457 bool IsReserved = !Base || Symbol.isCommon();
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000458
Jack Carter2f8d9d92013-02-19 21:57:35 +0000459 // Binding and Type share the same byte as upper and lower nibbles
Rafael Espindola95fb9b92015-06-02 20:38:46 +0000460 uint8_t Binding = Symbol.getBinding();
461 uint8_t Type = Symbol.getType();
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000462 if (Base) {
Rafael Espindola95fb9b92015-06-02 20:38:46 +0000463 Type = mergeTypeForSet(Type, Base->getType());
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000464 }
Rafael Espindolaf8794ff2015-06-04 00:47:43 +0000465 uint8_t Info = (Binding << 4) | Type;
Jack Carter2f8d9d92013-02-19 21:57:35 +0000466
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000467 // Other and Visibility share the same byte with Visibility using the lower
Jack Carter2f8d9d92013-02-19 21:57:35 +0000468 // 2 bits
Rafael Espindola95fb9b92015-06-02 20:38:46 +0000469 uint8_t Visibility = Symbol.getVisibility();
Rafael Espindola8c006ee2015-06-04 05:59:23 +0000470 uint8_t Other = Symbol.getOther() | Visibility;
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000471
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +0000472 uint64_t Value = SymbolValue(*MSD.Symbol, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000473 uint64_t Size = 0;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000474
Rafael Espindola7c23cba2015-05-29 17:24:52 +0000475 const MCExpr *ESize = MSD.Symbol->getSize();
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000476 if (!ESize && Base)
Rafael Espindola7c23cba2015-05-29 17:24:52 +0000477 ESize = Base->getSize();
Rafael Espindolaf0591c12010-09-21 00:24:38 +0000478
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000479 if (ESize) {
480 int64_t Res;
Rafael Espindola94a88d72015-04-06 15:27:57 +0000481 if (!ESize->evaluateKnownAbsolute(Res, Layout))
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000482 report_fatal_error("Size expression must be absolute.");
483 Size = Res;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000484 }
485
486 // Write out the symbol table entry
Rafael Espindolae48421f2015-05-28 20:25:29 +0000487 Writer.writeSymbol(StringIndex, Info, Value, Size, Other, MSD.SectionIndex,
488 IsReserved);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000489}
490
Rafael Espindoladb8a5862015-04-17 20:05:17 +0000491// True if the assembler knows nothing about the final value of the symbol.
492// This doesn't cover the comdat issues, since in those cases the assembler
493// can at least know that all symbols in the section will move together.
Rafael Espindola95fb9b92015-06-02 20:38:46 +0000494static bool isWeak(const MCSymbolELF &Sym) {
495 if (Sym.getType() == ELF::STT_GNU_IFUNC)
Rafael Espindolaa635d832015-04-17 08:46:11 +0000496 return true;
497
Rafael Espindola95fb9b92015-06-02 20:38:46 +0000498 switch (Sym.getBinding()) {
Rafael Espindolaa635d832015-04-17 08:46:11 +0000499 default:
500 llvm_unreachable("Unknown binding");
501 case ELF::STB_LOCAL:
502 return false;
503 case ELF::STB_GLOBAL:
Rafael Espindoladb8a5862015-04-17 20:05:17 +0000504 return false;
Rafael Espindolaa635d832015-04-17 08:46:11 +0000505 case ELF::STB_WEAK:
506 case ELF::STB_GNU_UNIQUE:
507 return true;
508 }
Rafael Espindolac9e70682015-03-24 23:48:44 +0000509}
510
Peter Collingbournea29fe572018-05-21 19:18:28 +0000511bool ELFWriter::isInSymtab(const MCAsmLayout &Layout, const MCSymbolELF &Symbol,
512 bool Used, bool Renamed) {
Rafael Espindola7fadc0e2014-03-20 02:12:01 +0000513 if (Symbol.isVariable()) {
514 const MCExpr *Expr = Symbol.getVariableValue();
515 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
516 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
517 return false;
518 }
519 }
Rafael Espindola16145972010-11-01 14:28:48 +0000520
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000521 if (Used)
522 return true;
523
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000524 if (Renamed)
525 return false;
526
Rafael Espindolaef1e8632015-06-03 21:23:21 +0000527 if (Symbol.isVariable() && Symbol.isUndefined()) {
528 // FIXME: this is here just to diagnose the case of a var = commmon_sym.
529 Layout.getBaseSymbol(Symbol);
530 return false;
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000531 }
Rafael Espindola9e18e962011-02-23 20:22:07 +0000532
Rafael Espindolaef1e8632015-06-03 21:23:21 +0000533 if (Symbol.isUndefined() && !Symbol.isBindingSet())
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +0000534 return false;
535
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000536 if (Symbol.isTemporary())
Rafael Espindolab1d07892010-10-05 18:01:23 +0000537 return false;
538
Rafael Espindolaa401eee2015-06-04 15:33:30 +0000539 if (Symbol.getType() == ELF::STT_SECTION)
540 return false;
541
Rafael Espindolab1d07892010-10-05 18:01:23 +0000542 return true;
543}
544
Peter Collingbournea29fe572018-05-21 19:18:28 +0000545void ELFWriter::computeSymbolTable(
Rafael Espindolaea1b3942015-04-07 19:00:17 +0000546 MCAssembler &Asm, const MCAsmLayout &Layout,
Rafael Espindolaaa486e92015-05-28 17:54:01 +0000547 const SectionIndexMapTy &SectionIndexMap, const RevGroupMapTy &RevGroupMap,
548 SectionOffsetsTy &SectionOffsets) {
Rafael Espindola5960cee2015-05-22 23:58:30 +0000549 MCContext &Ctx = Asm.getContext();
Rafael Espindolaaa486e92015-05-28 17:54:01 +0000550 SymbolTableWriter Writer(*this, is64Bit());
551
Rafael Espindola5960cee2015-05-22 23:58:30 +0000552 // Symbol table
553 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
554 MCSectionELF *SymtabSection =
555 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0, EntrySize, "");
556 SymtabSection->setAlignment(is64Bit() ? 8 : 4);
557 SymbolTableIndex = addToSectionTable(SymtabSection);
558
Rafael Espindolab20fbb82015-06-05 18:21:00 +0000559 align(SymtabSection->getAlignment());
Peter Collingbournef17b1492018-05-21 18:17:42 +0000560 uint64_t SecStart = W.OS.tell();
Rafael Espindolaaa486e92015-05-28 17:54:01 +0000561
562 // The first entry is the undefined symbol entry.
563 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
564
Rafael Espindolacfbd35c2015-05-28 20:11:34 +0000565 std::vector<ELFSymbolData> LocalSymbolData;
566 std::vector<ELFSymbolData> ExternalSymbolData;
Rafael Espindolacfbd35c2015-05-28 20:11:34 +0000567
Rafael Espindolabee6e9f2010-10-14 16:34:44 +0000568 // Add the data for the symbols.
Rafael Espindola5960cee2015-05-22 23:58:30 +0000569 bool HasLargeSectionIndex = false;
Rafael Espindola95fb9b92015-06-02 20:38:46 +0000570 for (const MCSymbol &S : Asm.symbols()) {
571 const auto &Symbol = cast<MCSymbolELF>(S);
Rafael Espindolaada43f62015-06-03 21:30:10 +0000572 bool Used = Symbol.isUsedInReloc();
Rafael Espindola212fdde2015-06-03 21:52:06 +0000573 bool WeakrefUsed = Symbol.isWeakrefUsedInReloc();
Rafael Espindola8c52a9b2015-06-03 21:41:59 +0000574 bool isSignature = Symbol.isSignature();
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000575
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +0000576 if (!isInSymtab(Layout, Symbol, Used || WeakrefUsed || isSignature,
Peter Collingbournea29fe572018-05-21 19:18:28 +0000577 OWriter.Renames.count(&Symbol)))
Matt Fleming6c1ad482010-08-16 18:57:57 +0000578 continue;
579
Oliver Stannard9be59af2015-11-17 10:00:43 +0000580 if (Symbol.isTemporary() && Symbol.isUndefined()) {
581 Ctx.reportError(SMLoc(), "Undefined temporary symbol");
582 continue;
583 }
Rafael Espindola6dff8142015-06-25 20:10:45 +0000584
Matt Fleming6c1ad482010-08-16 18:57:57 +0000585 ELFSymbolData MSD;
Rafael Espindolaa8695762015-06-02 00:25:12 +0000586 MSD.Symbol = cast<MCSymbolELF>(&Symbol);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000587
Rafael Espindola8c52a9b2015-06-03 21:41:59 +0000588 bool Local = Symbol.getBinding() == ELF::STB_LOCAL;
Rafael Espindola6dff8142015-06-25 20:10:45 +0000589 assert(Local || !Symbol.isTemporary());
590
Rafael Espindolaf4b44302015-05-29 15:07:27 +0000591 if (Symbol.isAbsolute()) {
Rafael Espindola022bb762014-03-24 03:43:21 +0000592 MSD.SectionIndex = ELF::SHN_ABS;
Rafael Espindola14672502015-05-29 17:48:04 +0000593 } else if (Symbol.isCommon()) {
Rafael Espindolabee6e9f2010-10-14 16:34:44 +0000594 assert(!Local);
Rafael Espindolaf0591c12010-09-21 00:24:38 +0000595 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindolaf4b44302015-05-29 15:07:27 +0000596 } else if (Symbol.isUndefined()) {
Rafael Espindola5960cee2015-05-22 23:58:30 +0000597 if (isSignature && !Used) {
Rafael Espindola89feff32015-04-28 22:59:58 +0000598 MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
Rafael Espindola5960cee2015-05-22 23:58:30 +0000599 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
600 HasLargeSectionIndex = true;
601 } else {
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000602 MSD.SectionIndex = ELF::SHN_UNDEF;
Rafael Espindola5960cee2015-05-22 23:58:30 +0000603 }
Matt Fleming6c1ad482010-08-16 18:57:57 +0000604 } else {
Rafael Espindolad6340032010-11-10 21:51:05 +0000605 const MCSectionELF &Section =
Rafael Espindolaf4b44302015-05-29 15:07:27 +0000606 static_cast<const MCSectionELF &>(Symbol.getSection());
Rafael Espindolad6340032010-11-10 21:51:05 +0000607 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000608 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindola5960cee2015-05-22 23:58:30 +0000609 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
610 HasLargeSectionIndex = true;
Rafael Espindolafbcf0db2010-10-15 15:39:06 +0000611 }
612
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000613 StringRef Name = Symbol.getName();
Rafael Espindolab6613022014-10-17 01:48:58 +0000614
615 // Sections have their own string table
Rafael Espindolafc063e82015-10-22 18:32:06 +0000616 if (Symbol.getType() != ELF::STT_SECTION) {
617 MSD.Name = Name;
618 StrTabBuilder.add(Name);
619 }
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000620
Rafael Espindola10d23872015-05-29 14:20:40 +0000621 if (Local)
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +0000622 LocalSymbolData.push_back(MSD);
623 else
624 ExternalSymbolData.push_back(MSD);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000625 }
626
Rafael Espindola2cd19512015-07-02 16:59:57 +0000627 // This holds the .symtab_shndx section index.
628 unsigned SymtabShndxSectionIndex = 0;
629
Rafael Espindola5960cee2015-05-22 23:58:30 +0000630 if (HasLargeSectionIndex) {
631 MCSectionELF *SymtabShndxSection =
632 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
633 SymtabShndxSectionIndex = addToSectionTable(SymtabShndxSection);
634 SymtabShndxSection->setAlignment(4);
635 }
636
Rafael Espindola1fd36272015-05-28 19:29:15 +0000637 ArrayRef<std::string> FileNames = Asm.getFileNames();
638 for (const std::string &Name : FileNames)
Rafael Espindola66f3c9c2015-05-28 18:03:20 +0000639 StrTabBuilder.add(Name);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000640
Rafael Espindola21956e42015-10-23 21:48:05 +0000641 StrTabBuilder.finalize();
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000642
Peter Collingbourne5b75fd92017-03-03 21:22:06 +0000643 // File symbols are emitted first and handled separately from normal symbols,
644 // i.e. a non-STT_FILE symbol with the same name may appear.
Rafael Espindola0cbea292015-05-28 20:00:13 +0000645 for (const std::string &Name : FileNames)
646 Writer.writeSymbol(StrTabBuilder.getOffset(Name),
647 ELF::STT_FILE | ELF::STB_LOCAL, 0, 0, ELF::STV_DEFAULT,
648 ELF::SHN_ABS, true);
649
Matt Fleming6c1ad482010-08-16 18:57:57 +0000650 // Symbols are required to be in lexicographic order.
651 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
652 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000653
654 // Set the symbol indices. Local symbols must come before all other
655 // symbols with non-local bindings.
Rafael Espindola1fd36272015-05-28 19:29:15 +0000656 unsigned Index = FileNames.size() + 1;
Rafael Espindola0e3decf2010-11-14 03:12:24 +0000657
Rafael Espindolaaa486e92015-05-28 17:54:01 +0000658 for (ELFSymbolData &MSD : LocalSymbolData) {
Daniel Jasper41de8022015-06-23 11:31:32 +0000659 unsigned StringIndex = MSD.Symbol->getType() == ELF::STT_SECTION
660 ? 0
661 : StrTabBuilder.getOffset(MSD.Name);
Rafael Espindolaaa486e92015-05-28 17:54:01 +0000662 MSD.Symbol->setIndex(Index++);
Rafael Espindolae48421f2015-05-28 20:25:29 +0000663 writeSymbol(Writer, StringIndex, MSD, Layout);
Rafael Espindolaaa486e92015-05-28 17:54:01 +0000664 }
Rafael Espindolaaa486e92015-05-28 17:54:01 +0000665
666 // Write the symbol table entries.
Rafael Espindola0cbea292015-05-28 20:00:13 +0000667 LastLocalSymbolIndex = Index;
Rafael Espindolaaa486e92015-05-28 17:54:01 +0000668
Rafael Espindoladcda9972015-05-28 19:43:20 +0000669 for (ELFSymbolData &MSD : ExternalSymbolData) {
Rafael Espindolae48421f2015-05-28 20:25:29 +0000670 unsigned StringIndex = StrTabBuilder.getOffset(MSD.Name);
Rafael Espindola0cbea292015-05-28 20:00:13 +0000671 MSD.Symbol->setIndex(Index++);
Rafael Espindolae48421f2015-05-28 20:25:29 +0000672 writeSymbol(Writer, StringIndex, MSD, Layout);
Rafael Espindola95fb9b92015-06-02 20:38:46 +0000673 assert(MSD.Symbol->getBinding() != ELF::STB_LOCAL);
Rafael Espindolaaa486e92015-05-28 17:54:01 +0000674 }
Rafael Espindolaaa486e92015-05-28 17:54:01 +0000675
Peter Collingbournef17b1492018-05-21 18:17:42 +0000676 uint64_t SecEnd = W.OS.tell();
Rafael Espindolaaa486e92015-05-28 17:54:01 +0000677 SectionOffsets[SymtabSection] = std::make_pair(SecStart, SecEnd);
678
679 ArrayRef<uint32_t> ShndxIndexes = Writer.getShndxIndexes();
680 if (ShndxIndexes.empty()) {
681 assert(SymtabShndxSectionIndex == 0);
682 return;
683 }
684 assert(SymtabShndxSectionIndex != 0);
685
Peter Collingbournef17b1492018-05-21 18:17:42 +0000686 SecStart = W.OS.tell();
Rafael Espindolaaa486e92015-05-28 17:54:01 +0000687 const MCSectionELF *SymtabShndxSection =
688 SectionTable[SymtabShndxSectionIndex - 1];
689 for (uint32_t Index : ShndxIndexes)
690 write(Index);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000691 SecEnd = W.OS.tell();
Rafael Espindolaaa486e92015-05-28 17:54:01 +0000692 SectionOffsets[SymtabShndxSection] = std::make_pair(SecStart, SecEnd);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000693}
694
Peter Collingbournea29fe572018-05-21 19:18:28 +0000695MCSectionELF *ELFWriter::createRelocationSection(MCContext &Ctx,
696 const MCSectionELF &Sec) {
697 if (OWriter.Relocations[&Sec].empty())
Rafael Espindolabda19802015-04-30 14:21:49 +0000698 return nullptr;
Rafael Espindola1557fd62011-03-20 18:44:20 +0000699
Rafael Espindola34948e52015-04-30 00:45:46 +0000700 const StringRef SectionName = Sec.getSectionName();
Rafael Espindolaead85492015-02-17 20:31:13 +0000701 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
702 RelaSectionName += SectionName;
Benjamin Kramerfd054152010-08-17 17:56:13 +0000703
Rafael Espindolaead85492015-02-17 20:31:13 +0000704 unsigned EntrySize;
705 if (hasRelocationAddend())
706 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
707 else
708 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000709
Rafael Espindolaead85492015-02-17 20:31:13 +0000710 unsigned Flags = 0;
Rafael Espindola34948e52015-04-30 00:45:46 +0000711 if (Sec.getFlags() & ELF::SHF_GROUP)
Rafael Espindolaead85492015-02-17 20:31:13 +0000712 Flags = ELF::SHF_GROUP;
Rafael Espindolaead85492015-02-17 20:31:13 +0000713
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000714 MCSectionELF *RelaSection = Ctx.createELFRelSection(
Rafael Espindolaead85492015-02-17 20:31:13 +0000715 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
Rafael Espindola34948e52015-04-30 00:45:46 +0000716 Flags, EntrySize, Sec.getGroup(), &Sec);
Rafael Espindola0a82ad72015-05-21 20:43:13 +0000717 RelaSection->setAlignment(is64Bit() ? 8 : 4);
Rafael Espindolabda19802015-04-30 14:21:49 +0000718 return RelaSection;
Rafael Espindola1557fd62011-03-20 18:44:20 +0000719}
Matt Fleming6c1ad482010-08-16 18:57:57 +0000720
George Rimarc91e38c2016-05-27 12:27:32 +0000721// Include the debug info compression header.
Peter Collingbournea29fe572018-05-21 19:18:28 +0000722bool ELFWriter::maybeWriteCompression(
George Rimarc91e38c2016-05-27 12:27:32 +0000723 uint64_t Size, SmallVectorImpl<char> &CompressedContents, bool ZLibStyle,
724 unsigned Alignment) {
725 if (ZLibStyle) {
726 uint64_t HdrSize =
727 is64Bit() ? sizeof(ELF::Elf32_Chdr) : sizeof(ELF::Elf64_Chdr);
728 if (Size <= HdrSize + CompressedContents.size())
729 return false;
730 // Platform specific header is followed by compressed data.
731 if (is64Bit()) {
732 // Write Elf64_Chdr header.
733 write(static_cast<ELF::Elf64_Word>(ELF::ELFCOMPRESS_ZLIB));
734 write(static_cast<ELF::Elf64_Word>(0)); // ch_reserved field.
735 write(static_cast<ELF::Elf64_Xword>(Size));
736 write(static_cast<ELF::Elf64_Xword>(Alignment));
737 } else {
738 // Write Elf32_Chdr header otherwise.
739 write(static_cast<ELF::Elf32_Word>(ELF::ELFCOMPRESS_ZLIB));
740 write(static_cast<ELF::Elf32_Word>(Size));
741 write(static_cast<ELF::Elf32_Word>(Alignment));
742 }
743 return true;
744 }
745
746 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
747 // useful for consumers to preallocate a buffer to decompress into.
Richard Smithb910e562016-05-25 00:14:12 +0000748 const StringRef Magic = "ZLIB";
749 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
750 return false;
Peter Collingbournef17b1492018-05-21 18:17:42 +0000751 W.OS << Magic;
752 support::endian::write(W.OS, Size, support::big);
Richard Smithb910e562016-05-25 00:14:12 +0000753 return true;
754}
755
Peter Collingbournea29fe572018-05-21 19:18:28 +0000756void ELFWriter::writeSectionData(const MCAssembler &Asm, MCSection &Sec,
757 const MCAsmLayout &Layout) {
Rafael Espindolae15b1b72015-05-27 13:30:50 +0000758 MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
Rafael Espindola868b3f42015-04-30 21:51:58 +0000759 StringRef SectionName = Section.getSectionName();
David Blaikie8019bf82014-04-10 21:53:53 +0000760
Saleem Abdulrasool1f62f572017-06-09 00:40:19 +0000761 auto &MC = Asm.getContext();
762 const auto &MAI = MC.getAsmInfo();
763
Rafael Espindola868b3f42015-04-30 21:51:58 +0000764 // Compressing debug_frame requires handling alignment fragments which is
765 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
766 // for writing to arbitrary buffers) for little benefit.
George Rimarc91e38c2016-05-27 12:27:32 +0000767 bool CompressionEnabled =
Saleem Abdulrasool1f62f572017-06-09 00:40:19 +0000768 MAI->compressDebugSections() != DebugCompressionType::None;
George Rimarc91e38c2016-05-27 12:27:32 +0000769 if (!CompressionEnabled || !SectionName.startswith(".debug_") ||
770 SectionName == ".debug_frame") {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000771 Asm.writeSectionData(W.OS, &Section, Layout);
Rafael Espindola868b3f42015-04-30 21:51:58 +0000772 return;
773 }
774
Saleem Abdulrasool1f62f572017-06-09 00:40:19 +0000775 assert((MAI->compressDebugSections() == DebugCompressionType::Z ||
776 MAI->compressDebugSections() == DebugCompressionType::GNU) &&
777 "expected zlib or zlib-gnu style compression");
778
David Majnemerabdb2d2a2015-09-01 16:19:03 +0000779 SmallVector<char, 128> UncompressedData;
780 raw_svector_ostream VecOS(UncompressedData);
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000781 Asm.writeSectionData(VecOS, &Section, Layout);
David Blaikie8019bf82014-04-10 21:53:53 +0000782
Rafael Espindola868b3f42015-04-30 21:51:58 +0000783 SmallVector<char, 128> CompressedContents;
George Rimar167ca4a2017-01-17 15:45:07 +0000784 if (Error E = zlib::compress(
785 StringRef(UncompressedData.data(), UncompressedData.size()),
786 CompressedContents)) {
787 consumeError(std::move(E));
Peter Collingbournef17b1492018-05-21 18:17:42 +0000788 W.OS << UncompressedData;
David Blaikie8019bf82014-04-10 21:53:53 +0000789 return;
Rafael Espindola868b3f42015-04-30 21:51:58 +0000790 }
David Blaikie8019bf82014-04-10 21:53:53 +0000791
Saleem Abdulrasool1f62f572017-06-09 00:40:19 +0000792 bool ZlibStyle = MAI->compressDebugSections() == DebugCompressionType::Z;
George Rimarc91e38c2016-05-27 12:27:32 +0000793 if (!maybeWriteCompression(UncompressedData.size(), CompressedContents,
794 ZlibStyle, Sec.getAlignment())) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000795 W.OS << UncompressedData;
Rafael Espindola868b3f42015-04-30 21:51:58 +0000796 return;
797 }
George Rimarc91e38c2016-05-27 12:27:32 +0000798
799 if (ZlibStyle)
800 // Set the compressed flag. That is zlib style.
801 Section.setFlags(Section.getFlags() | ELF::SHF_COMPRESSED);
802 else
803 // Add "z" prefix to section name. This is zlib-gnu style.
Saleem Abdulrasool1f62f572017-06-09 00:40:19 +0000804 MC.renameELFSection(&Section, (".z" + SectionName.drop_front(1)).str());
Peter Collingbournef17b1492018-05-21 18:17:42 +0000805 W.OS << CompressedContents;
David Blaikie8019bf82014-04-10 21:53:53 +0000806}
807
Peter Collingbournea29fe572018-05-21 19:18:28 +0000808void ELFWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
809 uint64_t Address, uint64_t Offset,
810 uint64_t Size, uint32_t Link, uint32_t Info,
811 uint64_t Alignment, uint64_t EntrySize) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000812 W.write<uint32_t>(Name); // sh_name: index into string table
813 W.write<uint32_t>(Type); // sh_type
Matt Fleming6c1ad482010-08-16 18:57:57 +0000814 WriteWord(Flags); // sh_flags
815 WriteWord(Address); // sh_addr
816 WriteWord(Offset); // sh_offset
817 WriteWord(Size); // sh_size
Peter Collingbournef17b1492018-05-21 18:17:42 +0000818 W.write<uint32_t>(Link); // sh_link
819 W.write<uint32_t>(Info); // sh_info
Matt Fleming6c1ad482010-08-16 18:57:57 +0000820 WriteWord(Alignment); // sh_addralign
821 WriteWord(EntrySize); // sh_entsize
822}
823
Peter Collingbournea29fe572018-05-21 19:18:28 +0000824void ELFWriter::writeRelocations(const MCAssembler &Asm,
Rafael Espindola34948e52015-04-30 00:45:46 +0000825 const MCSectionELF &Sec) {
Peter Collingbournea29fe572018-05-21 19:18:28 +0000826 std::vector<ELFRelocationEntry> &Relocs = OWriter.Relocations[&Sec];
Akira Hatanaka64ad2cf2012-03-23 23:06:45 +0000827
Rafael Espindolaf44db242015-12-17 16:22:06 +0000828 // We record relocations by pushing to the end of a vector. Reverse the vector
829 // to get the relocations in the order they were created.
830 // In most cases that is not important, but it can be for special sections
831 // (.eh_frame) or specific relocations (TLS optimizations on SystemZ).
832 std::reverse(Relocs.begin(), Relocs.end());
Rafael Espindolad0e16522015-12-17 15:08:24 +0000833
Rafael Espindolaf44db242015-12-17 16:22:06 +0000834 // Sort the relocation entries. MIPS needs this.
Peter Collingbournea29fe572018-05-21 19:18:28 +0000835 OWriter.TargetObjectWriter->sortRelocs(Asm, Relocs);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000836
837 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
Rafael Espindola5904e122014-03-29 06:26:49 +0000838 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
Rafael Espindola5e9ed902015-05-28 20:53:09 +0000839 unsigned Index = Entry.Symbol ? Entry.Symbol->getIndex() : 0;
Rafael Espindola5904e122014-03-29 06:26:49 +0000840
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000841 if (is64Bit()) {
Rafael Espindolab8cbb262015-04-30 00:30:40 +0000842 write(Entry.Offset);
Peter Collingbournea29fe572018-05-21 19:18:28 +0000843 if (OWriter.TargetObjectWriter->getEMachine() == ELF::EM_MIPS) {
Rafael Espindolab8cbb262015-04-30 00:30:40 +0000844 write(uint32_t(Index));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +0000845
Peter Collingbournea29fe572018-05-21 19:18:28 +0000846 write(OWriter.TargetObjectWriter->getRSsym(Entry.Type));
847 write(OWriter.TargetObjectWriter->getRType3(Entry.Type));
848 write(OWriter.TargetObjectWriter->getRType2(Entry.Type));
849 write(OWriter.TargetObjectWriter->getRType(Entry.Type));
Rafael Espindola5904e122014-03-29 06:26:49 +0000850 } else {
Jack Carter8ad0c272012-06-27 22:28:30 +0000851 struct ELF::Elf64_Rela ERE64;
Rafael Espindola5904e122014-03-29 06:26:49 +0000852 ERE64.setSymbolAndType(Index, Entry.Type);
Rafael Espindolab8cbb262015-04-30 00:30:40 +0000853 write(ERE64.r_info);
Jack Carter8ad0c272012-06-27 22:28:30 +0000854 }
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000855 if (hasRelocationAddend())
Rafael Espindolab8cbb262015-04-30 00:30:40 +0000856 write(Entry.Addend);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +0000857 } else {
Rafael Espindolab8cbb262015-04-30 00:30:40 +0000858 write(uint32_t(Entry.Offset));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +0000859
Rafael Espindolabce26a12010-10-05 15:11:03 +0000860 struct ELF::Elf32_Rela ERE32;
Rafael Espindola5904e122014-03-29 06:26:49 +0000861 ERE32.setSymbolAndType(Index, Entry.Type);
Rafael Espindolab8cbb262015-04-30 00:30:40 +0000862 write(ERE32.r_info);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +0000863
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000864 if (hasRelocationAddend())
Rafael Espindolab8cbb262015-04-30 00:30:40 +0000865 write(uint32_t(Entry.Addend));
Simon Atanasyanede43b72017-09-21 14:04:53 +0000866
Peter Collingbournea29fe572018-05-21 19:18:28 +0000867 if (OWriter.TargetObjectWriter->getEMachine() == ELF::EM_MIPS) {
868 if (uint32_t RType =
869 OWriter.TargetObjectWriter->getRType2(Entry.Type)) {
Simon Atanasyanede43b72017-09-21 14:04:53 +0000870 write(uint32_t(Entry.Offset));
871
872 ERE32.setSymbolAndType(0, RType);
873 write(ERE32.r_info);
874 write(uint32_t(0));
875 }
Peter Collingbournea29fe572018-05-21 19:18:28 +0000876 if (uint32_t RType =
877 OWriter.TargetObjectWriter->getRType3(Entry.Type)) {
Simon Atanasyanede43b72017-09-21 14:04:53 +0000878 write(uint32_t(Entry.Offset));
879
880 ERE32.setSymbolAndType(0, RType);
881 write(ERE32.r_info);
882 write(uint32_t(0));
883 }
884 }
Benjamin Kramer6c3c3492010-09-09 18:01:29 +0000885 }
Matt Fleming6c1ad482010-08-16 18:57:57 +0000886 }
887}
888
Peter Collingbournea29fe572018-05-21 19:18:28 +0000889const MCSectionELF *ELFWriter::createStringTable(MCContext &Ctx) {
Rafael Espindola08850b32015-05-25 21:56:55 +0000890 const MCSectionELF *StrtabSection = SectionTable[StringTableIndex - 1];
Peter Collingbournef17b1492018-05-21 18:17:42 +0000891 StrTabBuilder.write(W.OS);
Rafael Espindolabda19802015-04-30 14:21:49 +0000892 return StrtabSection;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000893}
894
Peter Collingbournea29fe572018-05-21 19:18:28 +0000895void ELFWriter::writeSection(const SectionIndexMapTy &SectionIndexMap,
896 uint32_t GroupSymbolIndex, uint64_t Offset,
897 uint64_t Size, const MCSectionELF &Section) {
Rafael Espindola5a8d7812010-11-10 23:36:59 +0000898 uint64_t sh_link = 0;
899 uint64_t sh_info = 0;
900
901 switch(Section.getType()) {
Rafael Espindola86fe2fe2015-04-06 03:16:51 +0000902 default:
903 // Nothing to do.
904 break;
905
Rafael Espindola5a8d7812010-11-10 23:36:59 +0000906 case ELF::SHT_DYNAMIC:
Rafael Espindola74ef4802015-04-30 21:20:06 +0000907 llvm_unreachable("SHT_DYNAMIC in a relocatable object");
Rafael Espindola5a8d7812010-11-10 23:36:59 +0000908
909 case ELF::SHT_REL:
910 case ELF::SHT_RELA: {
Rafael Espindola3a7c0eb2015-02-17 20:37:50 +0000911 sh_link = SymbolTableIndex;
Rafael Espindola5a8d7812010-11-10 23:36:59 +0000912 assert(sh_link && ".symtab not found");
Evgeniy Stepanov43dcf4d2017-03-14 19:28:51 +0000913 const MCSection *InfoSection = Section.getAssociatedSection();
914 sh_info = SectionIndexMap.lookup(cast<MCSectionELF>(InfoSection));
Rafael Espindola5a8d7812010-11-10 23:36:59 +0000915 break;
916 }
917
918 case ELF::SHT_SYMTAB:
Rafael Espindola5a8d7812010-11-10 23:36:59 +0000919 sh_link = StringTableIndex;
920 sh_info = LastLocalSymbolIndex;
921 break;
922
923 case ELF::SHT_SYMTAB_SHNDX:
924 sh_link = SymbolTableIndex;
925 break;
926
Nick Lewyckyc6ac5f72011-10-07 23:28:32 +0000927 case ELF::SHT_GROUP:
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000928 sh_link = SymbolTableIndex;
929 sh_info = GroupSymbolIndex;
930 break;
Rafael Espindola5a8d7812010-11-10 23:36:59 +0000931 }
932
Evgeniy Stepanov43dcf4d2017-03-14 19:28:51 +0000933 if (Section.getFlags() & ELF::SHF_LINK_ORDER) {
934 const MCSymbol *Sym = Section.getAssociatedSymbol();
935 const MCSectionELF *Sec = cast<MCSectionELF>(&Sym->getSection());
936 sh_link = SectionIndexMap.lookup(Sec);
937 }
Logan Chien4b724422013-02-05 14:18:59 +0000938
Rafael Espindola5960cee2015-05-22 23:58:30 +0000939 WriteSecHdrEntry(StrTabBuilder.getOffset(Section.getSectionName()),
Rafael Espindola28687582015-05-21 19:36:43 +0000940 Section.getType(), Section.getFlags(), 0, Offset, Size,
941 sh_link, sh_info, Section.getAlignment(),
942 Section.getEntrySize());
Rafael Espindola5a8d7812010-11-10 23:36:59 +0000943}
944
Peter Collingbournea29fe572018-05-21 19:18:28 +0000945void ELFWriter::writeSectionHeader(
Rafael Espindola57c80832015-06-04 20:55:49 +0000946 const MCAsmLayout &Layout, const SectionIndexMapTy &SectionIndexMap,
Rafael Espindolaa8201692015-04-28 15:26:21 +0000947 const SectionOffsetsTy &SectionOffsets) {
Rafael Espindolab1863912015-04-30 21:10:06 +0000948 const unsigned NumSections = SectionTable.size();
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000949
Matt Fleming6c1ad482010-08-16 18:57:57 +0000950 // Null section first.
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000951 uint64_t FirstSectionSize =
Rafael Espindolabf0db6c2015-04-15 13:07:47 +0000952 (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
Rafael Espindola88d1f632015-04-29 20:25:24 +0000953 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000954
Rafael Espindola08850b32015-05-25 21:56:55 +0000955 for (const MCSectionELF *Section : SectionTable) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000956 uint32_t GroupSymbolIndex;
Rafael Espindola03d7abb2015-04-30 20:53:27 +0000957 unsigned Type = Section->getType();
958 if (Type != ELF::SHT_GROUP)
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000959 GroupSymbolIndex = 0;
960 else
Rafael Espindola5e9ed902015-05-28 20:53:09 +0000961 GroupSymbolIndex = Section->getGroup()->getIndex();
Matt Fleming6c1ad482010-08-16 18:57:57 +0000962
Rafael Espindolabda19802015-04-30 14:21:49 +0000963 const std::pair<uint64_t, uint64_t> &Offsets =
Rafael Espindola03d7abb2015-04-30 20:53:27 +0000964 SectionOffsets.find(Section)->second;
Rafael Espindola1aa20fc2015-05-21 19:46:39 +0000965 uint64_t Size;
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000966 if (Type == ELF::SHT_NOBITS)
967 Size = Layout.getSectionAddressSize(Section);
968 else
Rafael Espindola1aa20fc2015-05-21 19:46:39 +0000969 Size = Offsets.second - Offsets.first;
Rafael Espindola60ebca92010-12-02 03:09:06 +0000970
Rafael Espindolae92c1bf2015-05-21 19:42:35 +0000971 writeSection(SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
Rafael Espindola28687582015-05-21 19:36:43 +0000972 *Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000973 }
974}
975
Peter Collingbournea29fe572018-05-21 19:18:28 +0000976uint64_t ELFWriter::writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) {
Peter Collingbourne438390f2018-05-21 18:23:50 +0000977 uint64_t StartOffset = W.OS.tell();
978
Rafael Espindolabda19802015-04-30 14:21:49 +0000979 MCContext &Ctx = Asm.getContext();
Rafael Espindola5960cee2015-05-22 23:58:30 +0000980 MCSectionELF *StrtabSection =
981 Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
982 StringTableIndex = addToSectionTable(StrtabSection);
Rafael Espindolabda19802015-04-30 14:21:49 +0000983
Rafael Espindola1557fd62011-03-20 18:44:20 +0000984 RevGroupMapTy RevGroupMap;
985 SectionIndexMapTy SectionIndexMap;
986
Rafael Espindolabda19802015-04-30 14:21:49 +0000987 std::map<const MCSymbol *, std::vector<const MCSectionELF *>> GroupMembers;
Rafael Espindola1557fd62011-03-20 18:44:20 +0000988
Rafael Espindola1557fd62011-03-20 18:44:20 +0000989 // Write out the ELF header ...
Rafael Espindola8c7829b2015-04-29 20:39:37 +0000990 writeHeader(Asm);
Rafael Espindola1557fd62011-03-20 18:44:20 +0000991
Rafael Espindola7230f802015-04-08 11:41:24 +0000992 // ... then the sections ...
Rafael Espindolabda19802015-04-30 14:21:49 +0000993 SectionOffsetsTy SectionOffsets;
Rafael Espindola0a82ad72015-05-21 20:43:13 +0000994 std::vector<MCSectionELF *> Groups;
995 std::vector<MCSectionELF *> Relocations;
Rafael Espindolae15b1b72015-05-27 13:30:50 +0000996 for (MCSection &Sec : Asm) {
997 MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
Rafael Espindolabda19802015-04-30 14:21:49 +0000998
Rafael Espindolab20fbb82015-06-05 18:21:00 +0000999 align(Section.getAlignment());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001000
Rafael Espindola642a2212015-04-14 22:54:16 +00001001 // Remember the offset into the file for this section.
Peter Collingbournef17b1492018-05-21 18:17:42 +00001002 uint64_t SecStart = W.OS.tell();
Rafael Espindolab8cbb262015-04-30 00:30:40 +00001003
Rafael Espindola0ccf9b72015-06-02 21:30:13 +00001004 const MCSymbolELF *SignatureSymbol = Section.getGroup();
Rafael Espindolae15b1b72015-05-27 13:30:50 +00001005 writeSectionData(Asm, Section, Layout);
Rafael Espindolab8cbb262015-04-30 00:30:40 +00001006
Peter Collingbournef17b1492018-05-21 18:17:42 +00001007 uint64_t SecEnd = W.OS.tell();
Rafael Espindolabda19802015-04-30 14:21:49 +00001008 SectionOffsets[&Section] = std::make_pair(SecStart, SecEnd);
1009
Rafael Espindola0a82ad72015-05-21 20:43:13 +00001010 MCSectionELF *RelSection = createRelocationSection(Ctx, Section);
Rafael Espindolabda19802015-04-30 14:21:49 +00001011
1012 if (SignatureSymbol) {
Rafael Espindolab5d316b2015-05-29 20:21:02 +00001013 Asm.registerSymbol(*SignatureSymbol);
Rafael Espindolabda19802015-04-30 14:21:49 +00001014 unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
1015 if (!GroupIdx) {
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001016 MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
Rafael Espindola03d7abb2015-04-30 20:53:27 +00001017 GroupIdx = addToSectionTable(Group);
Rafael Espindola0a82ad72015-05-21 20:43:13 +00001018 Group->setAlignment(4);
1019 Groups.push_back(Group);
Rafael Espindolabda19802015-04-30 14:21:49 +00001020 }
Rafael Espindola7830fc82015-06-05 17:54:25 +00001021 std::vector<const MCSectionELF *> &Members =
1022 GroupMembers[SignatureSymbol];
1023 Members.push_back(&Section);
Rafael Espindolabda19802015-04-30 14:21:49 +00001024 if (RelSection)
Rafael Espindola7830fc82015-06-05 17:54:25 +00001025 Members.push_back(RelSection);
Rafael Espindolabda19802015-04-30 14:21:49 +00001026 }
1027
Rafael Espindola03d7abb2015-04-30 20:53:27 +00001028 SectionIndexMap[&Section] = addToSectionTable(&Section);
Rafael Espindola0a82ad72015-05-21 20:43:13 +00001029 if (RelSection) {
Rafael Espindola03d7abb2015-04-30 20:53:27 +00001030 SectionIndexMap[RelSection] = addToSectionTable(RelSection);
Rafael Espindola0a82ad72015-05-21 20:43:13 +00001031 Relocations.push_back(RelSection);
1032 }
Rafael Espindolabda19802015-04-30 14:21:49 +00001033 }
1034
Rafael Espindola0a82ad72015-05-21 20:43:13 +00001035 for (MCSectionELF *Group : Groups) {
Rafael Espindolab20fbb82015-06-05 18:21:00 +00001036 align(Group->getAlignment());
Rafael Espindola0a82ad72015-05-21 20:43:13 +00001037
1038 // Remember the offset into the file for this section.
Peter Collingbournef17b1492018-05-21 18:17:42 +00001039 uint64_t SecStart = W.OS.tell();
Rafael Espindola0a82ad72015-05-21 20:43:13 +00001040
1041 const MCSymbol *SignatureSymbol = Group->getGroup();
1042 assert(SignatureSymbol);
1043 write(uint32_t(ELF::GRP_COMDAT));
1044 for (const MCSectionELF *Member : GroupMembers[SignatureSymbol]) {
1045 uint32_t SecIndex = SectionIndexMap.lookup(Member);
1046 write(SecIndex);
1047 }
1048
Peter Collingbournef17b1492018-05-21 18:17:42 +00001049 uint64_t SecEnd = W.OS.tell();
Rafael Espindola0a82ad72015-05-21 20:43:13 +00001050 SectionOffsets[Group] = std::make_pair(SecStart, SecEnd);
1051 }
1052
1053 // Compute symbol table information.
Rafael Espindolaaa486e92015-05-28 17:54:01 +00001054 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap, SectionOffsets);
Rafael Espindola0a82ad72015-05-21 20:43:13 +00001055
1056 for (MCSectionELF *RelSection : Relocations) {
Rafael Espindolab20fbb82015-06-05 18:21:00 +00001057 align(RelSection->getAlignment());
Rafael Espindola0a82ad72015-05-21 20:43:13 +00001058
1059 // Remember the offset into the file for this section.
Peter Collingbournef17b1492018-05-21 18:17:42 +00001060 uint64_t SecStart = W.OS.tell();
Rafael Espindola0a82ad72015-05-21 20:43:13 +00001061
Evgeniy Stepanov43dcf4d2017-03-14 19:28:51 +00001062 writeRelocations(Asm,
1063 cast<MCSectionELF>(*RelSection->getAssociatedSection()));
Rafael Espindola0a82ad72015-05-21 20:43:13 +00001064
Peter Collingbournef17b1492018-05-21 18:17:42 +00001065 uint64_t SecEnd = W.OS.tell();
Rafael Espindola0a82ad72015-05-21 20:43:13 +00001066 SectionOffsets[RelSection] = std::make_pair(SecStart, SecEnd);
Rafael Espindola642a2212015-04-14 22:54:16 +00001067 }
1068
Rafael Espindola88d1f632015-04-29 20:25:24 +00001069 {
Peter Collingbournef17b1492018-05-21 18:17:42 +00001070 uint64_t SecStart = W.OS.tell();
Rafael Espindolab1863912015-04-30 21:10:06 +00001071 const MCSectionELF *Sec = createStringTable(Ctx);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001072 uint64_t SecEnd = W.OS.tell();
Rafael Espindolabda19802015-04-30 14:21:49 +00001073 SectionOffsets[Sec] = std::make_pair(SecStart, SecEnd);
Rafael Espindola88abc392015-04-29 20:34:31 +00001074 }
1075
Rafael Espindola642a2212015-04-14 22:54:16 +00001076 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
Rafael Espindolab20fbb82015-06-05 18:21:00 +00001077 align(NaturalAlignment);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001078
Peter Collingbournef17b1492018-05-21 18:17:42 +00001079 const uint64_t SectionHeaderOffset = W.OS.tell();
Rafael Espindola642a2212015-04-14 22:54:16 +00001080
Rafael Espindola1557fd62011-03-20 18:44:20 +00001081 // ... then the section header table ...
Rafael Espindola57c80832015-06-04 20:55:49 +00001082 writeSectionHeader(Layout, SectionIndexMap, SectionOffsets);
Rafael Espindola642a2212015-04-14 22:54:16 +00001083
Peter Collingbournef17b1492018-05-21 18:17:42 +00001084 uint16_t NumSections = support::endian::byte_swap<uint16_t>(
1085 (SectionTable.size() + 1 >= ELF::SHN_LORESERVE) ? (uint16_t)ELF::SHN_UNDEF
1086 : SectionTable.size() + 1,
1087 W.Endian);
Rafael Espindola8c7829b2015-04-29 20:39:37 +00001088 unsigned NumSectionsOffset;
1089
Peter Collingbournef17b1492018-05-21 18:17:42 +00001090 auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
Rafael Espindola642a2212015-04-14 22:54:16 +00001091 if (is64Bit()) {
Peter Collingbournef17b1492018-05-21 18:17:42 +00001092 uint64_t Val =
1093 support::endian::byte_swap<uint64_t>(SectionHeaderOffset, W.Endian);
1094 Stream.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1095 offsetof(ELF::Elf64_Ehdr, e_shoff));
Rafael Espindola8c7829b2015-04-29 20:39:37 +00001096 NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum);
Rafael Espindola642a2212015-04-14 22:54:16 +00001097 } else {
Peter Collingbournef17b1492018-05-21 18:17:42 +00001098 uint32_t Val =
1099 support::endian::byte_swap<uint32_t>(SectionHeaderOffset, W.Endian);
1100 Stream.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1101 offsetof(ELF::Elf32_Ehdr, e_shoff));
Rafael Espindola8c7829b2015-04-29 20:39:37 +00001102 NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum);
Rafael Espindola642a2212015-04-14 22:54:16 +00001103 }
Peter Collingbournef17b1492018-05-21 18:17:42 +00001104 Stream.pwrite(reinterpret_cast<char *>(&NumSections), sizeof(NumSections),
1105 NumSectionsOffset);
Peter Collingbourne438390f2018-05-21 18:23:50 +00001106
1107 return W.OS.tell() - StartOffset;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001108}
1109
Peter Collingbournea29fe572018-05-21 19:18:28 +00001110bool ELFObjectWriter::hasRelocationAddend() const {
1111 return TargetObjectWriter->hasRelocationAddend();
1112}
1113
1114void ELFObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
1115 const MCAsmLayout &Layout) {
1116 // The presence of symbol versions causes undefined symbols and
1117 // versions declared with @@@ to be renamed.
1118 for (const std::pair<StringRef, const MCSymbol *> &P : Asm.Symvers) {
1119 StringRef AliasName = P.first;
1120 const auto &Symbol = cast<MCSymbolELF>(*P.second);
1121 size_t Pos = AliasName.find('@');
1122 assert(Pos != StringRef::npos);
1123
1124 StringRef Prefix = AliasName.substr(0, Pos);
1125 StringRef Rest = AliasName.substr(Pos);
1126 StringRef Tail = Rest;
1127 if (Rest.startswith("@@@"))
1128 Tail = Rest.substr(Symbol.isUndefined() ? 2 : 1);
1129
1130 auto *Alias =
1131 cast<MCSymbolELF>(Asm.getContext().getOrCreateSymbol(Prefix + Tail));
1132 Asm.registerSymbol(*Alias);
1133 const MCExpr *Value = MCSymbolRefExpr::create(&Symbol, Asm.getContext());
1134 Alias->setVariableValue(Value);
1135
1136 // Aliases defined with .symvar copy the binding from the symbol they alias.
1137 // This is the first place we are able to copy this information.
1138 Alias->setExternal(Symbol.isExternal());
1139 Alias->setBinding(Symbol.getBinding());
1140
1141 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
1142 continue;
1143
1144 // FIXME: produce a better error message.
1145 if (Symbol.isUndefined() && Rest.startswith("@@") &&
1146 !Rest.startswith("@@@"))
1147 report_fatal_error("A @@ version cannot be undefined");
1148
1149 if (Renames.count(&Symbol) && Renames[&Symbol] != Alias)
1150 report_fatal_error(llvm::Twine("Multiple symbol versions defined for ") +
1151 Symbol.getName());
1152
1153 Renames.insert(std::make_pair(&Symbol, Alias));
1154 }
1155}
1156
1157// It is always valid to create a relocation with a symbol. It is preferable
1158// to use a relocation with a section if that is possible. Using the section
1159// allows us to omit some local symbols from the symbol table.
1160bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
1161 const MCSymbolRefExpr *RefA,
1162 const MCSymbolELF *Sym,
1163 uint64_t C,
1164 unsigned Type) const {
1165 // A PCRel relocation to an absolute value has no symbol (or section). We
1166 // represent that with a relocation to a null section.
1167 if (!RefA)
1168 return false;
1169
1170 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
1171 switch (Kind) {
1172 default:
1173 break;
1174 // The .odp creation emits a relocation against the symbol ".TOC." which
1175 // create a R_PPC64_TOC relocation. However the relocation symbol name
1176 // in final object creation should be NULL, since the symbol does not
1177 // really exist, it is just the reference to TOC base for the current
1178 // object file. Since the symbol is undefined, returning false results
1179 // in a relocation with a null section which is the desired result.
1180 case MCSymbolRefExpr::VK_PPC_TOCBASE:
1181 return false;
1182
1183 // These VariantKind cause the relocation to refer to something other than
1184 // the symbol itself, like a linker generated table. Since the address of
1185 // symbol is not relevant, we cannot replace the symbol with the
1186 // section and patch the difference in the addend.
1187 case MCSymbolRefExpr::VK_GOT:
1188 case MCSymbolRefExpr::VK_PLT:
1189 case MCSymbolRefExpr::VK_GOTPCREL:
1190 case MCSymbolRefExpr::VK_PPC_GOT_LO:
1191 case MCSymbolRefExpr::VK_PPC_GOT_HI:
1192 case MCSymbolRefExpr::VK_PPC_GOT_HA:
1193 return true;
1194 }
1195
1196 // An undefined symbol is not in any section, so the relocation has to point
1197 // to the symbol itself.
1198 assert(Sym && "Expected a symbol");
1199 if (Sym->isUndefined())
1200 return true;
1201
1202 unsigned Binding = Sym->getBinding();
1203 switch(Binding) {
1204 default:
1205 llvm_unreachable("Invalid Binding");
1206 case ELF::STB_LOCAL:
1207 break;
1208 case ELF::STB_WEAK:
1209 // If the symbol is weak, it might be overridden by a symbol in another
1210 // file. The relocation has to point to the symbol so that the linker
1211 // can update it.
1212 return true;
1213 case ELF::STB_GLOBAL:
1214 // Global ELF symbols can be preempted by the dynamic linker. The relocation
1215 // has to point to the symbol for a reason analogous to the STB_WEAK case.
1216 return true;
1217 }
1218
1219 // If a relocation points to a mergeable section, we have to be careful.
1220 // If the offset is zero, a relocation with the section will encode the
1221 // same information. With a non-zero offset, the situation is different.
1222 // For example, a relocation can point 42 bytes past the end of a string.
1223 // If we change such a relocation to use the section, the linker would think
1224 // that it pointed to another string and subtracting 42 at runtime will
1225 // produce the wrong value.
1226 if (Sym->isInSection()) {
1227 auto &Sec = cast<MCSectionELF>(Sym->getSection());
1228 unsigned Flags = Sec.getFlags();
1229 if (Flags & ELF::SHF_MERGE) {
1230 if (C != 0)
1231 return true;
1232
1233 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
1234 // only handle section relocations to mergeable sections if using RELA.
1235 if (!hasRelocationAddend())
1236 return true;
1237 }
1238
1239 // Most TLS relocations use a got, so they need the symbol. Even those that
1240 // are just an offset (@tpoff), require a symbol in gold versions before
1241 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
1242 // http://sourceware.org/PR16773.
1243 if (Flags & ELF::SHF_TLS)
1244 return true;
1245 }
1246
1247 // If the symbol is a thumb function the final relocation must set the lowest
1248 // bit. With a symbol that is done by just having the symbol have that bit
1249 // set, so we would lose the bit if we relocated with the section.
1250 // FIXME: We could use the section but add the bit to the relocation value.
1251 if (Asm.isThumbFunc(Sym))
1252 return true;
1253
1254 if (TargetObjectWriter->needsRelocateWithSymbol(*Sym, Type))
1255 return true;
1256 return false;
1257}
1258
1259void ELFObjectWriter::recordRelocation(MCAssembler &Asm,
1260 const MCAsmLayout &Layout,
1261 const MCFragment *Fragment,
1262 const MCFixup &Fixup, MCValue Target,
1263 uint64_t &FixedValue) {
1264 MCAsmBackend &Backend = Asm.getBackend();
1265 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
1266 MCFixupKindInfo::FKF_IsPCRel;
1267 const MCSectionELF &FixupSection = cast<MCSectionELF>(*Fragment->getParent());
1268 uint64_t C = Target.getConstant();
1269 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
1270 MCContext &Ctx = Asm.getContext();
1271
1272 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
1273 // Let A, B and C being the components of Target and R be the location of
1274 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
1275 // If it is pcrel, we want to compute (A - B + C - R).
1276
1277 // In general, ELF has no relocations for -B. It can only represent (A + C)
1278 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
1279 // replace B to implement it: (A - R - K + C)
1280 if (IsPCRel) {
1281 Ctx.reportError(
1282 Fixup.getLoc(),
1283 "No relocation available to represent this relative expression");
1284 return;
1285 }
1286
1287 const auto &SymB = cast<MCSymbolELF>(RefB->getSymbol());
1288
1289 if (SymB.isUndefined()) {
1290 Ctx.reportError(Fixup.getLoc(),
1291 Twine("symbol '") + SymB.getName() +
1292 "' can not be undefined in a subtraction expression");
1293 return;
1294 }
1295
1296 assert(!SymB.isAbsolute() && "Should have been folded");
1297 const MCSection &SecB = SymB.getSection();
1298 if (&SecB != &FixupSection) {
1299 Ctx.reportError(Fixup.getLoc(),
1300 "Cannot represent a difference across sections");
1301 return;
1302 }
1303
1304 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
1305 uint64_t K = SymBOffset - FixupOffset;
1306 IsPCRel = true;
1307 C -= K;
1308 }
1309
1310 // We either rejected the fixup or folded B into C at this point.
1311 const MCSymbolRefExpr *RefA = Target.getSymA();
1312 const auto *SymA = RefA ? cast<MCSymbolELF>(&RefA->getSymbol()) : nullptr;
1313
1314 bool ViaWeakRef = false;
1315 if (SymA && SymA->isVariable()) {
1316 const MCExpr *Expr = SymA->getVariableValue();
1317 if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr)) {
1318 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) {
1319 SymA = cast<MCSymbolELF>(&Inner->getSymbol());
1320 ViaWeakRef = true;
1321 }
1322 }
1323 }
1324
1325 unsigned Type = TargetObjectWriter->getRelocType(Ctx, Target, Fixup, IsPCRel);
1326 uint64_t OriginalC = C;
1327 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymA, C, Type);
1328 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
1329 C += Layout.getSymbolOffset(*SymA);
1330
1331 uint64_t Addend = 0;
1332 if (hasRelocationAddend()) {
1333 Addend = C;
1334 C = 0;
1335 }
1336
1337 FixedValue = C;
1338
1339 if (!RelocateWithSymbol) {
1340 const MCSection *SecA =
1341 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
1342 const auto *SectionSymbol =
1343 SecA ? cast<MCSymbolELF>(SecA->getBeginSymbol()) : nullptr;
1344 if (SectionSymbol)
1345 SectionSymbol->setUsedInReloc();
1346 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend, SymA,
1347 OriginalC);
1348 Relocations[&FixupSection].push_back(Rec);
1349 return;
1350 }
1351
1352 const auto *RenamedSymA = SymA;
1353 if (SymA) {
1354 if (const MCSymbolELF *R = Renames.lookup(SymA))
1355 RenamedSymA = R;
1356
1357 if (ViaWeakRef)
1358 RenamedSymA->setIsWeakrefUsedInReloc();
1359 else
1360 RenamedSymA->setUsedInReloc();
1361 }
1362 ELFRelocationEntry Rec(FixupOffset, RenamedSymA, Type, Addend, SymA,
1363 OriginalC);
1364 Relocations[&FixupSection].push_back(Rec);
1365}
1366
Jim Grosbach36e60e92015-06-04 22:24:41 +00001367bool ELFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
Rafael Espindola95fb9b92015-06-02 20:38:46 +00001368 const MCAssembler &Asm, const MCSymbol &SA, const MCFragment &FB,
Rafael Espindola35d61892015-04-17 21:15:17 +00001369 bool InSet, bool IsPCRel) const {
Rafael Espindola95fb9b92015-06-02 20:38:46 +00001370 const auto &SymA = cast<MCSymbolELF>(SA);
Rafael Espindola35d61892015-04-17 21:15:17 +00001371 if (IsPCRel) {
1372 assert(!InSet);
Peter Collingbourne36003052017-04-08 23:35:49 +00001373 if (isWeak(SymA))
Rafael Espindola35d61892015-04-17 21:15:17 +00001374 return false;
1375 }
Jim Grosbach36e60e92015-06-04 22:24:41 +00001376 return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
Rafael Espindola35d61892015-04-17 21:15:17 +00001377 InSet, IsPCRel);
Eli Friedmand92d17b2011-03-03 07:24:36 +00001378}
1379
Lang Hames60fbc7c2017-10-10 16:28:07 +00001380std::unique_ptr<MCObjectWriter>
Lang Hamesdcb312b2017-10-09 23:53:15 +00001381llvm::createELFObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
1382 raw_pwrite_stream &OS, bool IsLittleEndian) {
Peter Collingbournef0226e62018-05-21 19:30:59 +00001383 return llvm::make_unique<ELFSingleObjectWriter>(std::move(MOTW), OS,
1384 IsLittleEndian);
Rafael Espindolab264d332011-12-21 17:30:17 +00001385}