blob: 78b5fa2a52165836e57b5ed19714f1d6639b0197 [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
Chandler Carruthed0881b2012-12-03 16:50:05 +000014#include "llvm/MC/MCELFObjectWriter.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/STLExtras.h"
Rafael Espindola29abd972011-12-22 03:38:00 +000016#include "llvm/ADT/SmallPtrSet.h"
17#include "llvm/ADT/SmallString.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000018#include "llvm/ADT/StringMap.h"
Evan Cheng5928e692011-07-25 23:24:55 +000019#include "llvm/MC/MCAsmBackend.h"
David Blaikie8019bf82014-04-10 21:53:53 +000020#include "llvm/MC/MCAsmInfo.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000021#include "llvm/MC/MCAsmLayout.h"
Rafael Espindola29abd972011-12-22 03:38:00 +000022#include "llvm/MC/MCAssembler.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000023#include "llvm/MC/MCContext.h"
Tim Northover5cc3dc82012-12-07 16:50:23 +000024#include "llvm/MC/MCELF.h"
Rafael Espindola29abd972011-12-22 03:38:00 +000025#include "llvm/MC/MCELFSymbolFlags.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000026#include "llvm/MC/MCExpr.h"
Craig Topper6e80c282012-03-26 06:58:25 +000027#include "llvm/MC/MCFixupKindInfo.h"
28#include "llvm/MC/MCObjectWriter.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000029#include "llvm/MC/MCSectionELF.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000030#include "llvm/MC/MCValue.h"
Rafael Espindola97de4742014-07-03 02:01:39 +000031#include "llvm/MC/StringTableBuilder.h"
David Blaikie8019bf82014-04-10 21:53:53 +000032#include "llvm/Support/Compression.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000033#include "llvm/Support/Debug.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000034#include "llvm/Support/ELF.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000035#include "llvm/Support/Endian.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Support/ErrorHandling.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000037#include <vector>
38using namespace llvm;
39
Jason W Kimc09e7262011-05-11 22:53:06 +000040#undef DEBUG_TYPE
41#define DEBUG_TYPE "reloc-info"
42
Rafael Espindola29abd972011-12-22 03:38:00 +000043namespace {
Rafael Espindola0ce09712014-03-25 22:43:53 +000044
Rafael Espindola10be0832014-03-25 23:44:25 +000045typedef DenseMap<const MCSectionELF *, uint32_t> SectionIndexMapTy;
46
Rafael Espindola91fd2772015-04-29 21:09:32 +000047class ELFObjectWriter;
48
Rafael Espindola10be0832014-03-25 23:44:25 +000049class SymbolTableWriter {
Rafael Espindola91fd2772015-04-29 21:09:32 +000050 ELFObjectWriter &EWriter;
Rafael Espindola10be0832014-03-25 23:44:25 +000051 bool Is64Bit;
Rafael Espindola10be0832014-03-25 23:44:25 +000052
Rafael Espindola91fd2772015-04-29 21:09:32 +000053 // indexes we are going to write to .symtab_shndx.
54 std::vector<uint32_t> ShndxIndexes;
Rafael Espindola10be0832014-03-25 23:44:25 +000055
56 // The numbel of symbols written so far.
57 unsigned NumWritten;
58
59 void createSymtabShndx();
60
Rafael Espindola91fd2772015-04-29 21:09:32 +000061 template <typename T> void write(T Value);
Rafael Espindola10be0832014-03-25 23:44:25 +000062
63public:
Rafael Espindola91fd2772015-04-29 21:09:32 +000064 SymbolTableWriter(ELFObjectWriter &EWriter, bool Is64Bit);
Rafael Espindola10be0832014-03-25 23:44:25 +000065
66 void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
67 uint8_t other, uint32_t shndx, bool Reserved);
Rafael Espindola91fd2772015-04-29 21:09:32 +000068
69 ArrayRef<uint32_t> getShndxIndexes() const { return ShndxIndexes; }
Rafael Espindola10be0832014-03-25 23:44:25 +000070};
71
Rafael Espindola29abd972011-12-22 03:38:00 +000072class ELFObjectWriter : public MCObjectWriter {
Rafael Espindola29abd972011-12-22 03:38:00 +000073 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +000074 static uint64_t SymbolValue(const MCSymbol &Sym, const MCAsmLayout &Layout);
75 static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbol &Symbol,
Rafael Espindola29abd972011-12-22 03:38:00 +000076 bool Used, bool Renamed);
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +000077 static bool isLocal(const MCSymbol &Symbol, bool isUsedInReloc);
Rafael Espindola29abd972011-12-22 03:38:00 +000078
Rafael Espindola6cd21802015-04-07 22:35:40 +000079 /// Helper struct for containing some precomputed information on symbols.
Rafael Espindola29abd972011-12-22 03:38:00 +000080 struct ELFSymbolData {
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +000081 const MCSymbol *Symbol;
Rafael Espindola29abd972011-12-22 03:38:00 +000082 uint64_t StringIndex;
83 uint32_t SectionIndex;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +000084 StringRef Name;
Rafael Espindola29abd972011-12-22 03:38:00 +000085
86 // Support lexicographic sorting.
87 bool operator<(const ELFSymbolData &RHS) const {
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +000088 unsigned LHSType = MCELF::GetType(Symbol->getData());
89 unsigned RHSType = MCELF::GetType(RHS.Symbol->getData());
Rafael Espindolab6613022014-10-17 01:48:58 +000090 if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
91 return false;
92 if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
93 return true;
94 if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
95 return SectionIndex < RHS.SectionIndex;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +000096 return Name < RHS.Name;
Rafael Espindola29abd972011-12-22 03:38:00 +000097 }
98 };
99
Rafael Espindola29abd972011-12-22 03:38:00 +0000100 /// The target specific ELF writer instance.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000101 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
Rafael Espindola29abd972011-12-22 03:38:00 +0000102
103 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
104 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
105 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
106
Rafael Espindola34948e52015-04-30 00:45:46 +0000107 llvm::DenseMap<const MCSectionELF *, std::vector<ELFRelocationEntry>>
108 Relocations;
Rafael Espindola29abd972011-12-22 03:38:00 +0000109
110 /// @}
111 /// @name Symbol Table Data
112 /// @{
113
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000114 StringTableBuilder StrTabBuilder;
Rafael Espindola29abd972011-12-22 03:38:00 +0000115 std::vector<ELFSymbolData> LocalSymbolData;
116 std::vector<ELFSymbolData> ExternalSymbolData;
117 std::vector<ELFSymbolData> UndefinedSymbolData;
118
119 /// @}
120
Rafael Espindola29abd972011-12-22 03:38:00 +0000121 // This holds the symbol table index of the last local symbol.
122 unsigned LastLocalSymbolIndex;
123 // This holds the .strtab section index.
124 unsigned StringTableIndex;
125 // This holds the .symtab section index.
126 unsigned SymbolTableIndex;
Rafael Espindola5960cee2015-05-22 23:58:30 +0000127 // This holds the .symtab_shndx section index.
128 unsigned SymtabShndxSectionIndex = 0;
Rafael Espindola29abd972011-12-22 03:38:00 +0000129
Rafael Espindola03d7abb2015-04-30 20:53:27 +0000130 // Sections in the order they are to be output in the section table.
Rafael Espindola08850b32015-05-25 21:56:55 +0000131 std::vector<const MCSectionELF *> SectionTable;
132 unsigned addToSectionTable(const MCSectionELF *Sec);
Rafael Espindola29abd972011-12-22 03:38:00 +0000133
Rafael Espindola29abd972011-12-22 03:38:00 +0000134 // TargetObjectWriter wrappers.
Rafael Espindola29abd972011-12-22 03:38:00 +0000135 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
136 bool hasRelocationAddend() const {
137 return TargetObjectWriter->hasRelocationAddend();
138 }
Rafael Espindola29abd972011-12-22 03:38:00 +0000139 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000140 bool IsPCRel) const {
141 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindola29abd972011-12-22 03:38:00 +0000142 }
143
Rafael Espindola29abd972011-12-22 03:38:00 +0000144 public:
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000145 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_pwrite_stream &OS,
Rafael Espindola0ce09712014-03-25 22:43:53 +0000146 bool IsLittleEndian)
Rafael Espindolae2b355d2015-05-28 15:20:00 +0000147 : MCObjectWriter(OS, IsLittleEndian), TargetObjectWriter(MOTW) {}
Rafael Espindola29abd972011-12-22 03:38:00 +0000148
Yaron Keren7773a722015-03-23 18:35:01 +0000149 void reset() override {
150 UsedInReloc.clear();
151 WeakrefUsedInReloc.clear();
152 Renames.clear();
153 Relocations.clear();
Yaron Keren7773a722015-03-23 18:35:01 +0000154 StrTabBuilder.clear();
Yaron Keren7773a722015-03-23 18:35:01 +0000155 LocalSymbolData.clear();
156 ExternalSymbolData.clear();
157 UndefinedSymbolData.clear();
Yaron Kerenf3465e12015-05-13 15:17:19 +0000158 SectionTable.clear();
Yaron Keren7773a722015-03-23 18:35:01 +0000159 MCObjectWriter::reset();
160 }
161
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000162 ~ELFObjectWriter() override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000163
164 void WriteWord(uint64_t W) {
165 if (is64Bit())
166 Write64(W);
167 else
168 Write32(W);
169 }
170
Rafael Espindola91fd2772015-04-29 21:09:32 +0000171 template <typename T> void write(T Val) {
172 if (IsLittleEndian)
173 support::endian::Writer<support::little>(OS).write(Val);
174 else
175 support::endian::Writer<support::big>(OS).write(Val);
176 }
177
Rafael Espindola8c7829b2015-04-29 20:39:37 +0000178 void writeHeader(const MCAssembler &Asm);
Rafael Espindola29abd972011-12-22 03:38:00 +0000179
Rafael Espindola10be0832014-03-25 23:44:25 +0000180 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Rafael Espindola29abd972011-12-22 03:38:00 +0000181 const MCAsmLayout &Layout);
182
Rafael Espindola91fd2772015-04-29 21:09:32 +0000183 // Start and end offset of each section
Rafael Espindolabda19802015-04-30 14:21:49 +0000184 typedef std::map<const MCSectionELF *, std::pair<uint64_t, uint64_t>>
185 SectionOffsetsTy;
Rafael Espindola91fd2772015-04-29 21:09:32 +0000186
Rafael Espindolab60c8292014-04-29 12:46:50 +0000187 bool shouldRelocateWithSymbol(const MCAssembler &Asm,
188 const MCSymbolRefExpr *RefA,
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +0000189 const MCSymbol *Sym, uint64_t C,
Rafael Espindola5904e122014-03-29 06:26:49 +0000190 unsigned Type) const;
191
Rafael Espindola26585542015-01-19 21:11:14 +0000192 void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
Craig Topper34a61bc2014-03-08 07:02:02 +0000193 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindola5904e122014-03-29 06:26:49 +0000194 MCValue Target, bool &IsPCRel,
195 uint64_t &FixedValue) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000196
197 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
198 const MCSymbol *S);
199
Rafael Espindola89feff32015-04-28 22:59:58 +0000200 // Map from a signature symbol to the group section index
201 typedef DenseMap<const MCSymbol *, unsigned> RevGroupMapTy;
Rafael Espindola29abd972011-12-22 03:38:00 +0000202
Rafael Espindola022bb762014-03-24 03:43:21 +0000203 /// Compute the symbol table data
Rafael Espindola29abd972011-12-22 03:38:00 +0000204 ///
Rafael Espindola073ee7d2012-08-27 16:04:24 +0000205 /// \param Asm - The assembler.
206 /// \param SectionIndexMap - Maps a section to its index.
207 /// \param RevGroupMap - Maps a signature symbol to the group section.
Rafael Espindola022bb762014-03-24 03:43:21 +0000208 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
Rafael Espindola29abd972011-12-22 03:38:00 +0000209 const SectionIndexMapTy &SectionIndexMap,
Rafael Espindolaaa486e92015-05-28 17:54:01 +0000210 const RevGroupMapTy &RevGroupMap,
211 SectionOffsetsTy &SectionOffsets);
Rafael Espindola29abd972011-12-22 03:38:00 +0000212
Rafael Espindola0a82ad72015-05-21 20:43:13 +0000213 MCSectionELF *createRelocationSection(MCContext &Ctx,
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000214 const MCSectionELF &Sec);
Rafael Espindola29abd972011-12-22 03:38:00 +0000215
Rafael Espindolab1863912015-04-30 21:10:06 +0000216 const MCSectionELF *createStringTable(MCContext &Ctx);
Rafael Espindola29abd972011-12-22 03:38:00 +0000217
Craig Topper34a61bc2014-03-08 07:02:02 +0000218 void ExecutePostLayoutBinding(MCAssembler &Asm,
219 const MCAsmLayout &Layout) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000220
Rafael Espindola1aa20fc2015-05-21 19:46:39 +0000221 void writeSectionHeader(const MCAssembler &Asm, const MCAsmLayout &Layout,
Rafael Espindola29abd972011-12-22 03:38:00 +0000222 const SectionIndexMapTy &SectionIndexMap,
Rafael Espindolaa8201692015-04-28 15:26:21 +0000223 const SectionOffsetsTy &SectionOffsets);
Rafael Espindola29abd972011-12-22 03:38:00 +0000224
Rafael Espindolae15b1b72015-05-27 13:30:50 +0000225 void writeSectionData(const MCAssembler &Asm, MCSection &Sec,
Rafael Espindola868b3f42015-04-30 21:51:58 +0000226 const MCAsmLayout &Layout);
227
Rafael Espindola29abd972011-12-22 03:38:00 +0000228 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
Rafael Espindola868b3f42015-04-30 21:51:58 +0000229 uint64_t Address, uint64_t Offset, uint64_t Size,
230 uint32_t Link, uint32_t Info, uint64_t Alignment,
231 uint64_t EntrySize);
Rafael Espindola29abd972011-12-22 03:38:00 +0000232
Rafael Espindola34948e52015-04-30 00:45:46 +0000233 void writeRelocations(const MCAssembler &Asm, const MCSectionELF &Sec);
Rafael Espindola29abd972011-12-22 03:38:00 +0000234
Duncan P. N. Exon Smithd81ba532015-05-16 01:01:55 +0000235 bool IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
236 const MCSymbol &SymA,
237 const MCFragment &FB,
238 bool InSet,
239 bool IsPCRel) const override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000240
Duncan P. N. Exon Smith5266ad92015-05-20 15:10:03 +0000241 bool isWeak(const MCSymbol &Sym) const override;
Rafael Espindolaf275ad82015-03-25 13:16:53 +0000242
Craig Topper34a61bc2014-03-08 07:02:02 +0000243 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Rafael Espindolae92c1bf2015-05-21 19:42:35 +0000244 void writeSection(const SectionIndexMapTy &SectionIndexMap,
Rafael Espindola28687582015-05-21 19:36:43 +0000245 uint32_t GroupSymbolIndex, uint64_t Offset, uint64_t Size,
Rafael Espindola29abd972011-12-22 03:38:00 +0000246 const MCSectionELF &Section);
247 };
248}
249
Rafael Espindola08850b32015-05-25 21:56:55 +0000250unsigned ELFObjectWriter::addToSectionTable(const MCSectionELF *Sec) {
Rafael Espindola03d7abb2015-04-30 20:53:27 +0000251 SectionTable.push_back(Sec);
Rafael Espindola5960cee2015-05-22 23:58:30 +0000252 StrTabBuilder.add(Sec->getSectionName());
Rafael Espindola03d7abb2015-04-30 20:53:27 +0000253 return SectionTable.size();
254}
255
Rafael Espindola10be0832014-03-25 23:44:25 +0000256void SymbolTableWriter::createSymtabShndx() {
Rafael Espindola91fd2772015-04-29 21:09:32 +0000257 if (!ShndxIndexes.empty())
Rafael Espindola10be0832014-03-25 23:44:25 +0000258 return;
259
Rafael Espindola91fd2772015-04-29 21:09:32 +0000260 ShndxIndexes.resize(NumWritten);
Rafael Espindola10be0832014-03-25 23:44:25 +0000261}
262
Rafael Espindola91fd2772015-04-29 21:09:32 +0000263template <typename T> void SymbolTableWriter::write(T Value) {
264 EWriter.write(Value);
Rafael Espindola10be0832014-03-25 23:44:25 +0000265}
266
Rafael Espindola91fd2772015-04-29 21:09:32 +0000267SymbolTableWriter::SymbolTableWriter(ELFObjectWriter &EWriter, bool Is64Bit)
268 : EWriter(EWriter), Is64Bit(Is64Bit), NumWritten(0) {}
Rafael Espindola10be0832014-03-25 23:44:25 +0000269
270void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
271 uint64_t size, uint8_t other,
272 uint32_t shndx, bool Reserved) {
273 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
274
275 if (LargeIndex)
276 createSymtabShndx();
277
Rafael Espindola91fd2772015-04-29 21:09:32 +0000278 if (!ShndxIndexes.empty()) {
Rafael Espindola10be0832014-03-25 23:44:25 +0000279 if (LargeIndex)
Rafael Espindola91fd2772015-04-29 21:09:32 +0000280 ShndxIndexes.push_back(shndx);
Rafael Espindola10be0832014-03-25 23:44:25 +0000281 else
Rafael Espindola91fd2772015-04-29 21:09:32 +0000282 ShndxIndexes.push_back(0);
Rafael Espindola10be0832014-03-25 23:44:25 +0000283 }
284
285 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
286
Rafael Espindola10be0832014-03-25 23:44:25 +0000287 if (Is64Bit) {
Rafael Espindola91fd2772015-04-29 21:09:32 +0000288 write(name); // st_name
289 write(info); // st_info
290 write(other); // st_other
291 write(Index); // st_shndx
292 write(value); // st_value
293 write(size); // st_size
Rafael Espindola10be0832014-03-25 23:44:25 +0000294 } else {
Rafael Espindola91fd2772015-04-29 21:09:32 +0000295 write(name); // st_name
296 write(uint32_t(value)); // st_value
297 write(uint32_t(size)); // st_size
298 write(info); // st_info
299 write(other); // st_other
300 write(Index); // st_shndx
Rafael Espindola10be0832014-03-25 23:44:25 +0000301 }
302
303 ++NumWritten;
304}
305
Jan Sjödin30a52de2011-02-28 21:45:04 +0000306bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
307 const MCFixupKindInfo &FKI =
308 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
309
310 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
311}
312
Jason W Kim96f4c012010-11-15 16:18:39 +0000313ELFObjectWriter::~ELFObjectWriter()
314{}
315
Matt Fleming6c1ad482010-08-16 18:57:57 +0000316// Emit the ELF header.
Rafael Espindola8c7829b2015-04-29 20:39:37 +0000317void ELFObjectWriter::writeHeader(const MCAssembler &Asm) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000318 // ELF Header
319 // ----------
320 //
321 // Note
322 // ----
323 // emitWord method behaves differently for ELF32 and ELF64, writing
324 // 4 bytes in the former and 8 in the latter.
325
Benjamin Kramer97fbdd52015-04-17 11:12:43 +0000326 WriteBytes(ELF::ElfMagic); // e_ident[EI_MAG0] to e_ident[EI_MAG3]
Matt Fleming6c1ad482010-08-16 18:57:57 +0000327
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000328 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
Matt Fleming6c1ad482010-08-16 18:57:57 +0000329
330 // e_ident[EI_DATA]
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000331 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000332
333 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky3b727f52010-09-09 17:57:50 +0000334 // e_ident[EI_OSABI]
Rafael Espindola1ad40952011-12-21 17:00:36 +0000335 Write8(TargetObjectWriter->getOSABI());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000336 Write8(0); // e_ident[EI_ABIVERSION]
337
338 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
339
340 Write16(ELF::ET_REL); // e_type
341
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000342 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
Matt Fleming6c1ad482010-08-16 18:57:57 +0000343
344 Write32(ELF::EV_CURRENT); // e_version
345 WriteWord(0); // e_entry, no entry point in .o file
346 WriteWord(0); // e_phoff, no program header for .o
Rafael Espindola642a2212015-04-14 22:54:16 +0000347 WriteWord(0); // e_shoff = sec hdr table off in bytes
Matt Fleming6c1ad482010-08-16 18:57:57 +0000348
Jason W Kim4761fba2011-02-04 21:41:11 +0000349 // e_flags = whatever the target wants
Jack Carter1bd90ff2013-01-30 02:09:52 +0000350 Write32(Asm.getELFHeaderEFlags());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000351
352 // e_ehsize = ELF header size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000353 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000354
355 Write16(0); // e_phentsize = prog header entry size
356 Write16(0); // e_phnum = # prog header entries = 0
357
358 // e_shentsize = Section header entry size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000359 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000360
361 // e_shnum = # of section header ents
Rafael Espindola8c7829b2015-04-29 20:39:37 +0000362 Write16(0);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000363
364 // e_shstrndx = Section # of '.shstrtab'
Rafael Espindola5960cee2015-05-22 23:58:30 +0000365 assert(StringTableIndex < ELF::SHN_LORESERVE);
366 Write16(StringTableIndex);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000367}
368
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +0000369uint64_t ELFObjectWriter::SymbolValue(const MCSymbol &Sym,
Jan Sjödin30a52de2011-02-28 21:45:04 +0000370 const MCAsmLayout &Layout) {
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +0000371 MCSymbolData &Data = Sym.getData();
Rafael Espindolafee224f2014-04-30 21:51:13 +0000372 if (Data.isCommon() && Data.isExternal())
373 return Data.getCommonAlignment();
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000374
Rafael Espindolafee224f2014-04-30 21:51:13 +0000375 uint64_t Res;
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +0000376 if (!Layout.getSymbolOffset(Sym, Res))
Rafael Espindola553e5eb2014-04-30 16:59:35 +0000377 return 0;
378
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +0000379 if (Layout.getAssembler().isThumbFunc(&Sym))
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000380 Res |= 1;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000381
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000382 return Res;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000383}
384
Rafael Espindola93e3cf02010-12-07 00:27:36 +0000385void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
386 const MCAsmLayout &Layout) {
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000387 // The presence of symbol versions causes undefined symbols and
388 // versions declared with @@@ to be renamed.
389
Duncan P. N. Exon Smithf48de1c2015-05-16 00:35:24 +0000390 for (const MCSymbol &Alias : Asm.symbols()) {
391 MCSymbolData &OriginalData = Alias.getData();
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000392
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000393 // Not an alias.
Rafael Espindola6efaf112014-04-28 17:05:36 +0000394 if (!Alias.isVariable())
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000395 continue;
Rafael Espindola6efaf112014-04-28 17:05:36 +0000396 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
397 if (!Ref)
398 continue;
399 const MCSymbol &Symbol = Ref->getSymbol();
400 MCSymbolData &SD = Asm.getSymbolData(Symbol);
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000401
Benjamin Kramer14807272010-10-27 19:53:52 +0000402 StringRef AliasName = Alias.getName();
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000403 size_t Pos = AliasName.find('@');
404 if (Pos == StringRef::npos)
405 continue;
406
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000407 // Aliases defined with .symvar copy the binding from the symbol they alias.
408 // This is the first place we are able to copy this information.
David Blaikie583a31c2014-04-18 18:24:25 +0000409 OriginalData.setExternal(SD.isExternal());
410 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000411
Benjamin Kramer14807272010-10-27 19:53:52 +0000412 StringRef Rest = AliasName.substr(Pos);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000413 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
414 continue;
415
Rafael Espindola26496e62010-10-27 17:56:18 +0000416 // FIXME: produce a better error message.
417 if (Symbol.isUndefined() && Rest.startswith("@@") &&
418 !Rest.startswith("@@@"))
419 report_fatal_error("A @@ version cannot be undefined");
420
Benjamin Kramer14807272010-10-27 19:53:52 +0000421 Renames.insert(std::make_pair(&Symbol, &Alias));
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000422 }
423}
424
Roman Divacky5a1c5492014-01-07 20:17:03 +0000425static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
426 uint8_t Type = newType;
427
428 // Propagation rules:
429 // IFUNC > FUNC > OBJECT > NOTYPE
430 // TLS_OBJECT > OBJECT > NOTYPE
431 //
432 // dont let the new type degrade the old type
433 switch (origType) {
434 default:
435 break;
436 case ELF::STT_GNU_IFUNC:
437 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
438 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
439 Type = ELF::STT_GNU_IFUNC;
440 break;
441 case ELF::STT_FUNC:
442 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
443 Type == ELF::STT_TLS)
444 Type = ELF::STT_FUNC;
445 break;
446 case ELF::STT_OBJECT:
447 if (Type == ELF::STT_NOTYPE)
448 Type = ELF::STT_OBJECT;
449 break;
450 case ELF::STT_TLS:
451 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
452 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
453 Type = ELF::STT_TLS;
454 break;
455 }
456
457 return Type;
458}
459
Rafael Espindola10be0832014-03-25 23:44:25 +0000460void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000461 const MCAsmLayout &Layout) {
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +0000462 MCSymbolData &OrigData = MSD.Symbol->getData();
David Blaikieb5956d22014-04-19 00:50:15 +0000463 assert((!OrigData.getFragment() ||
Rafael Espindola7549f872015-05-26 00:36:57 +0000464 (OrigData.getFragment()->getParent() == &MSD.Symbol->getSection())) &&
David Blaikieb5956d22014-04-19 00:50:15 +0000465 "The symbol's section doesn't match the fragment's symbol");
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +0000466 const MCSymbol *Base = Layout.getBaseSymbol(*MSD.Symbol);
Rafael Espindola85a84912014-03-26 00:16:43 +0000467
468 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
469 // SHN_COMMON.
470 bool IsReserved = !Base || OrigData.isCommon();
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000471
Jack Carter2f8d9d92013-02-19 21:57:35 +0000472 // Binding and Type share the same byte as upper and lower nibbles
Jan Sjödin30a52de2011-02-28 21:45:04 +0000473 uint8_t Binding = MCELF::GetBinding(OrigData);
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000474 uint8_t Type = MCELF::GetType(OrigData);
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000475 MCSymbolData *BaseSD = nullptr;
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000476 if (Base) {
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000477 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
478 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000479 }
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000480 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000481
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000482 // Other and Visibility share the same byte with Visibility using the lower
Jack Carter2f8d9d92013-02-19 21:57:35 +0000483 // 2 bits
484 uint8_t Visibility = MCELF::GetVisibility(OrigData);
Logan Chienee365952013-12-05 00:34:11 +0000485 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000486 Other |= Visibility;
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000487
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +0000488 uint64_t Value = SymbolValue(*MSD.Symbol, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000489 uint64_t Size = 0;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000490
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000491 const MCExpr *ESize = OrigData.getSize();
492 if (!ESize && Base)
493 ESize = BaseSD->getSize();
Rafael Espindolaf0591c12010-09-21 00:24:38 +0000494
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000495 if (ESize) {
496 int64_t Res;
Rafael Espindola94a88d72015-04-06 15:27:57 +0000497 if (!ESize->evaluateKnownAbsolute(Res, Layout))
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000498 report_fatal_error("Size expression must be absolute.");
499 Size = Res;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000500 }
501
502 // Write out the symbol table entry
Rafael Espindola10be0832014-03-25 23:44:25 +0000503 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
504 MSD.SectionIndex, IsReserved);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000505}
506
Rafael Espindola5904e122014-03-29 06:26:49 +0000507// It is always valid to create a relocation with a symbol. It is preferable
508// to use a relocation with a section if that is possible. Using the section
509// allows us to omit some local symbols from the symbol table.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000510bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
511 const MCSymbolRefExpr *RefA,
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +0000512 const MCSymbol *Sym, uint64_t C,
Rafael Espindola5904e122014-03-29 06:26:49 +0000513 unsigned Type) const {
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +0000514 MCSymbolData *SD = Sym ? &Sym->getData() : nullptr;
515
Rafael Espindola5904e122014-03-29 06:26:49 +0000516 // A PCRel relocation to an absolute value has no symbol (or section). We
517 // represent that with a relocation to a null section.
518 if (!RefA)
519 return false;
Rafael Espindola240028d2010-11-14 23:53:26 +0000520
Rafael Espindola5904e122014-03-29 06:26:49 +0000521 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
522 switch (Kind) {
523 default:
524 break;
525 // The .odp creation emits a relocation against the symbol ".TOC." which
526 // create a R_PPC64_TOC relocation. However the relocation symbol name
527 // in final object creation should be NULL, since the symbol does not
528 // really exist, it is just the reference to TOC base for the current
529 // object file. Since the symbol is undefined, returning false results
530 // in a relocation with a null section which is the desired result.
531 case MCSymbolRefExpr::VK_PPC_TOCBASE:
532 return false;
533
534 // These VariantKind cause the relocation to refer to something other than
535 // the symbol itself, like a linker generated table. Since the address of
536 // symbol is not relevant, we cannot replace the symbol with the
537 // section and patch the difference in the addend.
538 case MCSymbolRefExpr::VK_GOT:
539 case MCSymbolRefExpr::VK_PLT:
540 case MCSymbolRefExpr::VK_GOTPCREL:
541 case MCSymbolRefExpr::VK_Mips_GOT:
542 case MCSymbolRefExpr::VK_PPC_GOT_LO:
543 case MCSymbolRefExpr::VK_PPC_GOT_HI:
544 case MCSymbolRefExpr::VK_PPC_GOT_HA:
545 return true;
Rafael Espindola240028d2010-11-14 23:53:26 +0000546 }
Rafael Espindola240028d2010-11-14 23:53:26 +0000547
Rafael Espindola5904e122014-03-29 06:26:49 +0000548 // An undefined symbol is not in any section, so the relocation has to point
549 // to the symbol itself.
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +0000550 assert(Sym && "Expected a symbol");
551 if (Sym->isUndefined())
Rafael Espindola5904e122014-03-29 06:26:49 +0000552 return true;
553
554 unsigned Binding = MCELF::GetBinding(*SD);
555 switch(Binding) {
556 default:
557 llvm_unreachable("Invalid Binding");
558 case ELF::STB_LOCAL:
559 break;
560 case ELF::STB_WEAK:
561 // If the symbol is weak, it might be overridden by a symbol in another
562 // file. The relocation has to point to the symbol so that the linker
563 // can update it.
564 return true;
565 case ELF::STB_GLOBAL:
566 // Global ELF symbols can be preempted by the dynamic linker. The relocation
567 // has to point to the symbol for a reason analogous to the STB_WEAK case.
568 return true;
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000569 }
Rafael Espindola75d65b92010-09-25 05:42:19 +0000570
Rafael Espindola5904e122014-03-29 06:26:49 +0000571 // If a relocation points to a mergeable section, we have to be careful.
572 // If the offset is zero, a relocation with the section will encode the
573 // same information. With a non-zero offset, the situation is different.
574 // For example, a relocation can point 42 bytes past the end of a string.
575 // If we change such a relocation to use the section, the linker would think
576 // that it pointed to another string and subtracting 42 at runtime will
577 // produce the wrong value.
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +0000578 auto &Sec = cast<MCSectionELF>(Sym->getSection());
Rafael Espindola5904e122014-03-29 06:26:49 +0000579 unsigned Flags = Sec.getFlags();
580 if (Flags & ELF::SHF_MERGE) {
581 if (C != 0)
582 return true;
Rafael Espindolab1b49782014-04-02 12:15:20 +0000583
584 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
585 // only handle section relocations to mergeable sections if using RELA.
586 if (!hasRelocationAddend())
587 return true;
Rafael Espindola9f75d5d2010-11-24 21:57:39 +0000588 }
589
Rafael Espindola5904e122014-03-29 06:26:49 +0000590 // Most TLS relocations use a got, so they need the symbol. Even those that
Rafael Espindola11527a12014-10-06 12:33:27 +0000591 // are just an offset (@tpoff), require a symbol in gold versions before
592 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
593 // http://sourceware.org/PR16773.
Rafael Espindola5904e122014-03-29 06:26:49 +0000594 if (Flags & ELF::SHF_TLS)
595 return true;
Rafael Espindolad7565c32010-10-05 23:57:26 +0000596
Rafael Espindola9ef84412014-04-11 19:18:01 +0000597 // If the symbol is a thumb function the final relocation must set the lowest
598 // bit. With a symbol that is done by just having the symbol have that bit
599 // set, so we would lose the bit if we relocated with the section.
600 // FIXME: We could use the section but add the bit to the relocation value.
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +0000601 if (Asm.isThumbFunc(Sym))
Rafael Espindola9ef84412014-04-11 19:18:01 +0000602 return true;
603
Ulrich Weigand46797c62014-07-20 23:15:06 +0000604 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
Rafael Espindola5904e122014-03-29 06:26:49 +0000605 return true;
606 return false;
Rafael Espindola75d65b92010-09-25 05:42:19 +0000607}
608
Rafael Espindola3d082fa2014-05-03 19:57:04 +0000609static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
610 const MCSymbol &Sym = Ref.getSymbol();
611
612 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
613 return &Sym;
614
615 if (!Sym.isVariable())
616 return nullptr;
617
618 const MCExpr *Expr = Sym.getVariableValue();
619 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
620 if (!Inner)
621 return nullptr;
622
623 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
624 return &Inner->getSymbol();
625 return nullptr;
626}
627
Rafael Espindoladb8a5862015-04-17 20:05:17 +0000628// True if the assembler knows nothing about the final value of the symbol.
629// This doesn't cover the comdat issues, since in those cases the assembler
630// can at least know that all symbols in the section will move together.
Rafael Espindolac9e70682015-03-24 23:48:44 +0000631static bool isWeak(const MCSymbolData &D) {
Rafael Espindolaa635d832015-04-17 08:46:11 +0000632 if (MCELF::GetType(D) == ELF::STT_GNU_IFUNC)
633 return true;
634
635 switch (MCELF::GetBinding(D)) {
636 default:
637 llvm_unreachable("Unknown binding");
638 case ELF::STB_LOCAL:
639 return false;
640 case ELF::STB_GLOBAL:
Rafael Espindoladb8a5862015-04-17 20:05:17 +0000641 return false;
Rafael Espindolaa635d832015-04-17 08:46:11 +0000642 case ELF::STB_WEAK:
643 case ELF::STB_GNU_UNIQUE:
644 return true;
645 }
Rafael Espindolac9e70682015-03-24 23:48:44 +0000646}
647
Rafael Espindola26585542015-01-19 21:11:14 +0000648void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
Jason W Kim495c2bb2010-12-06 21:57:34 +0000649 const MCAsmLayout &Layout,
650 const MCFragment *Fragment,
Rafael Espindola26585542015-01-19 21:11:14 +0000651 const MCFixup &Fixup, MCValue Target,
652 bool &IsPCRel, uint64_t &FixedValue) {
Rafael Espindola7549f872015-05-26 00:36:57 +0000653 const MCSectionELF &FixupSection = cast<MCSectionELF>(*Fragment->getParent());
Rafael Espindola5904e122014-03-29 06:26:49 +0000654 uint64_t C = Target.getConstant();
655 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000656
Rafael Espindola5904e122014-03-29 06:26:49 +0000657 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
658 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
659 "Should not have constructed this");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000660
Rafael Espindola5904e122014-03-29 06:26:49 +0000661 // Let A, B and C being the components of Target and R be the location of
662 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
663 // If it is pcrel, we want to compute (A - B + C - R).
Jason W Kim495c2bb2010-12-06 21:57:34 +0000664
Rafael Espindola5904e122014-03-29 06:26:49 +0000665 // In general, ELF has no relocations for -B. It can only represent (A + C)
666 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
667 // replace B to implement it: (A - R - K + C)
668 if (IsPCRel)
Jim Grosbach6f482002015-05-18 18:43:14 +0000669 Asm.getContext().reportFatalError(
Rafael Espindola5904e122014-03-29 06:26:49 +0000670 Fixup.getLoc(),
671 "No relocation available to represent this relative expression");
David Majnemera45a1762014-01-06 07:39:46 +0000672
Rafael Espindola5904e122014-03-29 06:26:49 +0000673 const MCSymbol &SymB = RefB->getSymbol();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000674
Rafael Espindola5904e122014-03-29 06:26:49 +0000675 if (SymB.isUndefined())
Jim Grosbach6f482002015-05-18 18:43:14 +0000676 Asm.getContext().reportFatalError(
Rafael Espindola5904e122014-03-29 06:26:49 +0000677 Fixup.getLoc(),
678 Twine("symbol '") + SymB.getName() +
679 "' can not be undefined in a subtraction expression");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000680
Rafael Espindola5904e122014-03-29 06:26:49 +0000681 assert(!SymB.isAbsolute() && "Should have been folded");
682 const MCSection &SecB = SymB.getSection();
Rafael Espindola34948e52015-04-30 00:45:46 +0000683 if (&SecB != &FixupSection)
Jim Grosbach6f482002015-05-18 18:43:14 +0000684 Asm.getContext().reportFatalError(
Rafael Espindola5904e122014-03-29 06:26:49 +0000685 Fixup.getLoc(), "Cannot represent a difference across sections");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000686
Duncan P. N. Exon Smith2a404832015-05-19 23:53:20 +0000687 if (::isWeak(SymB.getData()))
Jim Grosbach6f482002015-05-18 18:43:14 +0000688 Asm.getContext().reportFatalError(
Rafael Espindolac9e70682015-03-24 23:48:44 +0000689 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
690
Duncan P. N. Exon Smith2a404832015-05-19 23:53:20 +0000691 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
Rafael Espindola5904e122014-03-29 06:26:49 +0000692 uint64_t K = SymBOffset - FixupOffset;
693 IsPCRel = true;
694 C -= K;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000695 }
696
Rafael Espindola5904e122014-03-29 06:26:49 +0000697 // We either rejected the fixup or folded B into C at this point.
698 const MCSymbolRefExpr *RefA = Target.getSymA();
699 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
Rafael Espindola5904e122014-03-29 06:26:49 +0000700
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000701 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +0000702 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymA, C, Type);
Rafael Espindola5904e122014-03-29 06:26:49 +0000703 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
Duncan P. N. Exon Smith2a404832015-05-19 23:53:20 +0000704 C += Layout.getSymbolOffset(*SymA);
Rafael Espindola5904e122014-03-29 06:26:49 +0000705
706 uint64_t Addend = 0;
707 if (hasRelocationAddend()) {
708 Addend = C;
709 C = 0;
710 }
711
712 FixedValue = C;
713
Rafael Espindola5904e122014-03-29 06:26:49 +0000714 if (!RelocateWithSymbol) {
715 const MCSection *SecA =
716 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
Rafael Espindolab6613022014-10-17 01:48:58 +0000717 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000718 const MCSymbol *SectionSymbol = ELFSec ? ELFSec->getBeginSymbol() : nullptr;
Rafael Espindolab6613022014-10-17 01:48:58 +0000719 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
Rafael Espindola34948e52015-04-30 00:45:46 +0000720 Relocations[&FixupSection].push_back(Rec);
Rafael Espindola5904e122014-03-29 06:26:49 +0000721 return;
722 }
Roman Divackydfbecd12011-08-04 19:08:19 +0000723
Rafael Espindola5904e122014-03-29 06:26:49 +0000724 if (SymA) {
725 if (const MCSymbol *R = Renames.lookup(SymA))
726 SymA = R;
Rafael Espindolad7facaf2011-08-04 13:05:26 +0000727
Rafael Espindola3d082fa2014-05-03 19:57:04 +0000728 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
729 WeakrefUsedInReloc.insert(WeakRef);
Rafael Espindola5904e122014-03-29 06:26:49 +0000730 else
731 UsedInReloc.insert(SymA);
732 }
733 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
Rafael Espindola34948e52015-04-30 00:45:46 +0000734 Relocations[&FixupSection].push_back(Rec);
Rafael Espindola5904e122014-03-29 06:26:49 +0000735 return;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000736}
737
738
Benjamin Kramer86511dc2010-08-23 21:19:37 +0000739uint64_t
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000740ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
741 const MCSymbol *S) {
Duncan P. N. Exon Smith1247bbd2015-05-22 05:54:01 +0000742 assert(S->hasData());
743 return S->getIndex();
Matt Fleming6c1ad482010-08-16 18:57:57 +0000744}
745
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000746bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +0000747 const MCSymbol &Symbol, bool Used,
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000748 bool Renamed) {
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +0000749 const MCSymbolData &Data = Symbol.getData();
Rafael Espindola7fadc0e2014-03-20 02:12:01 +0000750 if (Symbol.isVariable()) {
751 const MCExpr *Expr = Symbol.getVariableValue();
752 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
753 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
754 return false;
755 }
756 }
Rafael Espindola16145972010-11-01 14:28:48 +0000757
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000758 if (Used)
759 return true;
760
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000761 if (Renamed)
762 return false;
763
Rafael Espindola45834a02010-10-29 23:09:31 +0000764 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
765 return true;
766
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000767 if (Symbol.isVariable()) {
Rafael Espindola2aeac7a2014-05-01 13:24:25 +0000768 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000769 if (Base && Base->isUndefined())
770 return false;
771 }
Rafael Espindola9e18e962011-02-23 20:22:07 +0000772
Jan Sjödin30a52de2011-02-28 21:45:04 +0000773 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
Rafael Espindola9e18e962011-02-23 20:22:07 +0000774 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +0000775 return false;
776
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000777 if (MCELF::GetType(Data) == ELF::STT_SECTION)
778 return true;
779
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000780 if (Symbol.isTemporary())
Rafael Espindolab1d07892010-10-05 18:01:23 +0000781 return false;
782
783 return true;
784}
785
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +0000786bool ELFObjectWriter::isLocal(const MCSymbol &Symbol, bool isUsedInReloc) {
787 const MCSymbolData &Data = Symbol.getData();
Rafael Espindolab1d07892010-10-05 18:01:23 +0000788 if (Data.isExternal())
789 return false;
790
Rafael Espindola39f50422014-04-28 14:24:44 +0000791 if (Symbol.isDefined())
792 return true;
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000793
Rafael Espindola39f50422014-04-28 14:24:44 +0000794 if (isUsedInReloc)
Rafael Espindolab1d07892010-10-05 18:01:23 +0000795 return false;
796
797 return true;
798}
799
Rafael Espindolaea1b3942015-04-07 19:00:17 +0000800void ELFObjectWriter::computeSymbolTable(
801 MCAssembler &Asm, const MCAsmLayout &Layout,
Rafael Espindolaaa486e92015-05-28 17:54:01 +0000802 const SectionIndexMapTy &SectionIndexMap, const RevGroupMapTy &RevGroupMap,
803 SectionOffsetsTy &SectionOffsets) {
Rafael Espindola5960cee2015-05-22 23:58:30 +0000804 MCContext &Ctx = Asm.getContext();
Rafael Espindolaaa486e92015-05-28 17:54:01 +0000805 SymbolTableWriter Writer(*this, is64Bit());
806
Rafael Espindola5960cee2015-05-22 23:58:30 +0000807 // Symbol table
808 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
809 MCSectionELF *SymtabSection =
810 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0, EntrySize, "");
811 SymtabSection->setAlignment(is64Bit() ? 8 : 4);
812 SymbolTableIndex = addToSectionTable(SymtabSection);
813
Rafael Espindolaaa486e92015-05-28 17:54:01 +0000814 uint64_t Padding =
815 OffsetToAlignment(OS.tell(), SymtabSection->getAlignment());
816 WriteZeros(Padding);
817
818 uint64_t SecStart = OS.tell();
819
820 // The first entry is the undefined symbol entry.
821 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
822
Rafael Espindolabee6e9f2010-10-14 16:34:44 +0000823 // Add the data for the symbols.
Rafael Espindola5960cee2015-05-22 23:58:30 +0000824 bool HasLargeSectionIndex = false;
Duncan P. N. Exon Smithf48de1c2015-05-16 00:35:24 +0000825 for (const MCSymbol &Symbol : Asm.symbols()) {
826 MCSymbolData &SD = Symbol.getData();
Matt Fleming6c1ad482010-08-16 18:57:57 +0000827
Rafael Espindola16145972010-11-01 14:28:48 +0000828 bool Used = UsedInReloc.count(&Symbol);
829 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000830 bool isSignature = RevGroupMap.count(&Symbol);
831
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +0000832 if (!isInSymtab(Layout, Symbol, Used || WeakrefUsed || isSignature,
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000833 Renames.count(&Symbol)))
Matt Fleming6c1ad482010-08-16 18:57:57 +0000834 continue;
835
Matt Fleming6c1ad482010-08-16 18:57:57 +0000836 ELFSymbolData MSD;
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +0000837 MSD.Symbol = &Symbol;
Rafael Espindola2aeac7a2014-05-01 13:24:25 +0000838 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000839
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000840 // Undefined symbols are global, but this is the first place we
841 // are able to set it.
Duncan P. N. Exon Smith469f9db2015-05-20 04:39:01 +0000842 bool Local = isLocal(Symbol, Used);
David Blaikie583a31c2014-04-18 18:24:25 +0000843 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
Rafael Espindola022bb762014-03-24 03:43:21 +0000844 assert(BaseSymbol);
David Blaikie583a31c2014-04-18 18:24:25 +0000845 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000846 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
David Blaikie583a31c2014-04-18 18:24:25 +0000847 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000848 }
849
Rafael Espindola022bb762014-03-24 03:43:21 +0000850 if (!BaseSymbol) {
851 MSD.SectionIndex = ELF::SHN_ABS;
David Blaikie583a31c2014-04-18 18:24:25 +0000852 } else if (SD.isCommon()) {
Rafael Espindolabee6e9f2010-10-14 16:34:44 +0000853 assert(!Local);
Rafael Espindolaf0591c12010-09-21 00:24:38 +0000854 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindola022bb762014-03-24 03:43:21 +0000855 } else if (BaseSymbol->isUndefined()) {
Rafael Espindola5960cee2015-05-22 23:58:30 +0000856 if (isSignature && !Used) {
Rafael Espindola89feff32015-04-28 22:59:58 +0000857 MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
Rafael Espindola5960cee2015-05-22 23:58:30 +0000858 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
859 HasLargeSectionIndex = true;
860 } else {
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000861 MSD.SectionIndex = ELF::SHN_UNDEF;
Rafael Espindola5960cee2015-05-22 23:58:30 +0000862 }
Rafael Espindola022bb762014-03-24 03:43:21 +0000863 if (!Used && WeakrefUsed)
David Blaikie583a31c2014-04-18 18:24:25 +0000864 MCELF::SetBinding(SD, ELF::STB_WEAK);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000865 } else {
Rafael Espindolad6340032010-11-10 21:51:05 +0000866 const MCSectionELF &Section =
Rafael Espindola022bb762014-03-24 03:43:21 +0000867 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
Rafael Espindolad6340032010-11-10 21:51:05 +0000868 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000869 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindola5960cee2015-05-22 23:58:30 +0000870 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
871 HasLargeSectionIndex = true;
Rafael Espindolafbcf0db2010-10-15 15:39:06 +0000872 }
873
Rafael Espindola5a67ed12015-01-22 14:20:45 +0000874 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
875 // in defined ones.
876 //
877 // FIXME: All name handling should be done before we get to the writer,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +0000878 // including dealing with GNU-style version suffixes. Fixing this isn't
Rafael Espindola5a67ed12015-01-22 14:20:45 +0000879 // trivial.
880 //
881 // We thus have to be careful to not perform the symbol version replacement
882 // blindly:
883 //
884 // The ELF format is used on Windows by the MCJIT engine. Thus, on
885 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
886 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
887 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
888 // the EFLObjectWriter should not interpret the "@@@" sub-string as
889 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
890 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
891 // "__imp_?" or "__imp_@?".
892 //
893 // It would have been interesting to perform the MS mangling prefix check
894 // only when the target triple is of the form *-pc-windows-elf. But, it
895 // seems that this information is not easily accessible from the
896 // ELFObjectWriter.
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000897 StringRef Name = Symbol.getName();
Rafael Espindola5a67ed12015-01-22 14:20:45 +0000898 if (!Name.startswith("?") && !Name.startswith("@?") &&
899 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
900 // This symbol isn't following the MSVC C++ name mangling convention. We
901 // can thus safely interpret the @@@ in symbol names as specifying symbol
902 // versioning.
903 SmallString<32> Buf;
904 size_t Pos = Name.find("@@@");
905 if (Pos != StringRef::npos) {
906 Buf += Name.substr(0, Pos);
907 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
908 Buf += Name.substr(Pos + Skip);
909 Name = Buf;
910 }
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000911 }
Rafael Espindolab6613022014-10-17 01:48:58 +0000912
913 // Sections have their own string table
914 if (MCELF::GetType(SD) != ELF::STT_SECTION)
915 MSD.Name = StrTabBuilder.add(Name);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000916
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +0000917 if (MSD.SectionIndex == ELF::SHN_UNDEF)
918 UndefinedSymbolData.push_back(MSD);
919 else if (Local)
920 LocalSymbolData.push_back(MSD);
921 else
922 ExternalSymbolData.push_back(MSD);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000923 }
924
Rafael Espindola5960cee2015-05-22 23:58:30 +0000925 if (HasLargeSectionIndex) {
926 MCSectionELF *SymtabShndxSection =
927 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
928 SymtabShndxSectionIndex = addToSectionTable(SymtabShndxSection);
929 SymtabShndxSection->setAlignment(4);
930 }
931
Rafael Espindola1fd36272015-05-28 19:29:15 +0000932 ArrayRef<std::string> FileNames = Asm.getFileNames();
933 for (const std::string &Name : FileNames)
Rafael Espindola66f3c9c2015-05-28 18:03:20 +0000934 StrTabBuilder.add(Name);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000935
Hans Wennborgf26bfc12014-09-29 22:43:20 +0000936 StrTabBuilder.finalize(StringTableBuilder::ELF);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000937
Matt Fleming6c1ad482010-08-16 18:57:57 +0000938 // Symbols are required to be in lexicographic order.
939 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
940 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
941 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
942
943 // Set the symbol indices. Local symbols must come before all other
944 // symbols with non-local bindings.
Rafael Espindola1fd36272015-05-28 19:29:15 +0000945 unsigned Index = FileNames.size() + 1;
Rafael Espindola0e3decf2010-11-14 03:12:24 +0000946
Rafael Espindolaaa486e92015-05-28 17:54:01 +0000947 for (ELFSymbolData &MSD : LocalSymbolData) {
948 MSD.StringIndex = MCELF::GetType(MSD.Symbol->getData()) == ELF::STT_SECTION
949 ? 0
950 : StrTabBuilder.getOffset(MSD.Name);
951 MSD.Symbol->setIndex(Index++);
952 }
953 for (ELFSymbolData &MSD : ExternalSymbolData) {
954 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
955 MSD.Symbol->setIndex(Index++);
956 }
957 for (ELFSymbolData &MSD : UndefinedSymbolData) {
958 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
959 MSD.Symbol->setIndex(Index++);
960 }
961
Rafael Espindola1fd36272015-05-28 19:29:15 +0000962 for (const std::string &Name : FileNames)
963 Writer.writeSymbol(StrTabBuilder.getOffset(Name),
964 ELF::STT_FILE | ELF::STB_LOCAL, 0, 0, ELF::STV_DEFAULT,
965 ELF::SHN_ABS, true);
Rafael Espindolaaa486e92015-05-28 17:54:01 +0000966
967 // Write the symbol table entries.
Rafael Espindola1fd36272015-05-28 19:29:15 +0000968 LastLocalSymbolIndex = FileNames.size() + LocalSymbolData.size() + 1;
Rafael Espindolaaa486e92015-05-28 17:54:01 +0000969
970 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
971 ELFSymbolData &MSD = LocalSymbolData[i];
972 WriteSymbol(Writer, MSD, Layout);
973 }
974
975 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
976 ELFSymbolData &MSD = ExternalSymbolData[i];
977 MCSymbolData &Data = MSD.Symbol->getData();
978 assert(((Data.getFlags() & ELF_STB_Global) ||
979 (Data.getFlags() & ELF_STB_Weak)) &&
980 "External symbol requires STB_GLOBAL or STB_WEAK flag");
981 WriteSymbol(Writer, MSD, Layout);
982 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
983 LastLocalSymbolIndex++;
984 }
985
986 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
987 ELFSymbolData &MSD = UndefinedSymbolData[i];
988 MCSymbolData &Data = MSD.Symbol->getData();
989 WriteSymbol(Writer, MSD, Layout);
990 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
991 LastLocalSymbolIndex++;
992 }
993
994 uint64_t SecEnd = OS.tell();
995 SectionOffsets[SymtabSection] = std::make_pair(SecStart, SecEnd);
996
997 ArrayRef<uint32_t> ShndxIndexes = Writer.getShndxIndexes();
998 if (ShndxIndexes.empty()) {
999 assert(SymtabShndxSectionIndex == 0);
1000 return;
1001 }
1002 assert(SymtabShndxSectionIndex != 0);
1003
1004 SecStart = OS.tell();
1005 const MCSectionELF *SymtabShndxSection =
1006 SectionTable[SymtabShndxSectionIndex - 1];
1007 for (uint32_t Index : ShndxIndexes)
1008 write(Index);
1009 SecEnd = OS.tell();
1010 SectionOffsets[SymtabShndxSection] = std::make_pair(SecStart, SecEnd);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001011}
1012
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001013MCSectionELF *
Rafael Espindola0a82ad72015-05-21 20:43:13 +00001014ELFObjectWriter::createRelocationSection(MCContext &Ctx,
Rafael Espindolabda19802015-04-30 14:21:49 +00001015 const MCSectionELF &Sec) {
Rafael Espindola34948e52015-04-30 00:45:46 +00001016 if (Relocations[&Sec].empty())
Rafael Espindolabda19802015-04-30 14:21:49 +00001017 return nullptr;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001018
Rafael Espindola34948e52015-04-30 00:45:46 +00001019 const StringRef SectionName = Sec.getSectionName();
Rafael Espindolaead85492015-02-17 20:31:13 +00001020 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1021 RelaSectionName += SectionName;
Benjamin Kramerfd054152010-08-17 17:56:13 +00001022
Rafael Espindolaead85492015-02-17 20:31:13 +00001023 unsigned EntrySize;
1024 if (hasRelocationAddend())
1025 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1026 else
1027 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001028
Rafael Espindolaead85492015-02-17 20:31:13 +00001029 unsigned Flags = 0;
Rafael Espindola34948e52015-04-30 00:45:46 +00001030 if (Sec.getFlags() & ELF::SHF_GROUP)
Rafael Espindolaead85492015-02-17 20:31:13 +00001031 Flags = ELF::SHF_GROUP;
Rafael Espindolaead85492015-02-17 20:31:13 +00001032
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001033 MCSectionELF *RelaSection = Ctx.createELFRelSection(
Rafael Espindolaead85492015-02-17 20:31:13 +00001034 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
Rafael Espindola34948e52015-04-30 00:45:46 +00001035 Flags, EntrySize, Sec.getGroup(), &Sec);
Rafael Espindola0a82ad72015-05-21 20:43:13 +00001036 RelaSection->setAlignment(is64Bit() ? 8 : 4);
Rafael Espindolabda19802015-04-30 14:21:49 +00001037 return RelaSection;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001038}
Matt Fleming6c1ad482010-08-16 18:57:57 +00001039
David Blaikiee06e8012014-04-11 22:11:50 +00001040static SmallVector<char, 128>
Rafael Espindolaae7e4992015-04-29 19:20:10 +00001041getUncompressedData(const MCAsmLayout &Layout,
Rafael Espindolaa32d0e92015-05-27 15:14:11 +00001042 const MCSection::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001043 SmallVector<char, 128> UncompressedData;
1044 for (const MCFragment &F : Fragments) {
1045 const SmallVectorImpl<char> *Contents;
1046 switch (F.getKind()) {
1047 case MCFragment::FT_Data:
1048 Contents = &cast<MCDataFragment>(F).getContents();
1049 break;
1050 case MCFragment::FT_Dwarf:
1051 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1052 break;
1053 case MCFragment::FT_DwarfFrame:
1054 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1055 break;
1056 default:
1057 llvm_unreachable(
1058 "Not expecting any other fragment types in a debug_* section");
1059 }
1060 UncompressedData.append(Contents->begin(), Contents->end());
1061 }
1062 return UncompressedData;
1063}
1064
1065// Include the debug info compression header:
1066// "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1067// useful for consumers to preallocate a buffer to decompress into.
David Blaikie76d3a3c2014-04-18 21:52:26 +00001068static bool
David Blaikiee06e8012014-04-11 22:11:50 +00001069prependCompressionHeader(uint64_t Size,
1070 SmallVectorImpl<char> &CompressedContents) {
Benjamin Kramer7149aab2015-03-01 18:09:56 +00001071 const StringRef Magic = "ZLIB";
David Blaikie76d3a3c2014-04-18 21:52:26 +00001072 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1073 return false;
David Blaikie8019bf82014-04-10 21:53:53 +00001074 if (sys::IsLittleEndianHost)
Artyom Skrobov9aea8432014-06-14 13:18:07 +00001075 sys::swapByteOrder(Size);
David Blaikie8019bf82014-04-10 21:53:53 +00001076 CompressedContents.insert(CompressedContents.begin(),
1077 Magic.size() + sizeof(Size), 0);
1078 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1079 std::copy(reinterpret_cast<char *>(&Size),
1080 reinterpret_cast<char *>(&Size + 1),
1081 CompressedContents.begin() + Magic.size());
David Blaikie76d3a3c2014-04-18 21:52:26 +00001082 return true;
David Blaikie8019bf82014-04-10 21:53:53 +00001083}
1084
Rafael Espindolae15b1b72015-05-27 13:30:50 +00001085void ELFObjectWriter::writeSectionData(const MCAssembler &Asm, MCSection &Sec,
Rafael Espindola868b3f42015-04-30 21:51:58 +00001086 const MCAsmLayout &Layout) {
Rafael Espindolae15b1b72015-05-27 13:30:50 +00001087 MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
Rafael Espindola868b3f42015-04-30 21:51:58 +00001088 StringRef SectionName = Section.getSectionName();
David Blaikie8019bf82014-04-10 21:53:53 +00001089
Rafael Espindola868b3f42015-04-30 21:51:58 +00001090 // Compressing debug_frame requires handling alignment fragments which is
1091 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1092 // for writing to arbitrary buffers) for little benefit.
1093 if (!Asm.getContext().getAsmInfo()->compressDebugSections() ||
1094 !SectionName.startswith(".debug_") || SectionName == ".debug_frame") {
Rafael Espindola64acc7f2015-05-26 02:17:21 +00001095 Asm.writeSectionData(&Section, Layout);
Rafael Espindola868b3f42015-04-30 21:51:58 +00001096 return;
1097 }
1098
1099 // Gather the uncompressed data from all the fragments.
Rafael Espindolaa32d0e92015-05-27 15:14:11 +00001100 const MCSection::FragmentListType &Fragments = Section.getFragmentList();
David Blaikie8019bf82014-04-10 21:53:53 +00001101 SmallVector<char, 128> UncompressedData =
1102 getUncompressedData(Layout, Fragments);
1103
Rafael Espindola868b3f42015-04-30 21:51:58 +00001104 SmallVector<char, 128> CompressedContents;
David Blaikie8019bf82014-04-10 21:53:53 +00001105 zlib::Status Success = zlib::compress(
1106 StringRef(UncompressedData.data(), UncompressedData.size()),
1107 CompressedContents);
Rafael Espindola868b3f42015-04-30 21:51:58 +00001108 if (Success != zlib::StatusOK) {
Rafael Espindola64acc7f2015-05-26 02:17:21 +00001109 Asm.writeSectionData(&Section, Layout);
David Blaikie8019bf82014-04-10 21:53:53 +00001110 return;
Rafael Espindola868b3f42015-04-30 21:51:58 +00001111 }
David Blaikie8019bf82014-04-10 21:53:53 +00001112
Rafael Espindola868b3f42015-04-30 21:51:58 +00001113 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents)) {
Rafael Espindola64acc7f2015-05-26 02:17:21 +00001114 Asm.writeSectionData(&Section, Layout);
Rafael Espindola868b3f42015-04-30 21:51:58 +00001115 return;
1116 }
David Blaikie8019bf82014-04-10 21:53:53 +00001117 Asm.getContext().renameELFSection(&Section,
1118 (".z" + SectionName.drop_front(1)).str());
Rafael Espindola868b3f42015-04-30 21:51:58 +00001119 OS << CompressedContents;
David Blaikie8019bf82014-04-10 21:53:53 +00001120}
1121
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001122void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1123 uint64_t Flags, uint64_t Address,
1124 uint64_t Offset, uint64_t Size,
1125 uint32_t Link, uint32_t Info,
1126 uint64_t Alignment,
1127 uint64_t EntrySize) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001128 Write32(Name); // sh_name: index into string table
1129 Write32(Type); // sh_type
1130 WriteWord(Flags); // sh_flags
1131 WriteWord(Address); // sh_addr
1132 WriteWord(Offset); // sh_offset
1133 WriteWord(Size); // sh_size
1134 Write32(Link); // sh_link
1135 Write32(Info); // sh_info
1136 WriteWord(Alignment); // sh_addralign
1137 WriteWord(EntrySize); // sh_entsize
1138}
1139
Rafael Espindolab8cbb262015-04-30 00:30:40 +00001140void ELFObjectWriter::writeRelocations(const MCAssembler &Asm,
Rafael Espindola34948e52015-04-30 00:45:46 +00001141 const MCSectionELF &Sec) {
1142 std::vector<ELFRelocationEntry> &Relocs = Relocations[&Sec];
Akira Hatanaka64ad2cf2012-03-23 23:06:45 +00001143
Petar Jovanovic0380d0b2015-04-14 13:23:34 +00001144 // Sort the relocation entries. Most targets just sort by Offset, but some
1145 // (e.g., MIPS) have additional constraints.
1146 TargetObjectWriter->sortRelocs(Asm, Relocs);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001147
1148 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001149 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
Rafael Espindolab6613022014-10-17 01:48:58 +00001150 unsigned Index =
1151 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
Rafael Espindola5904e122014-03-29 06:26:49 +00001152
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001153 if (is64Bit()) {
Rafael Espindolab8cbb262015-04-30 00:30:40 +00001154 write(Entry.Offset);
Jack Carter8ad0c272012-06-27 22:28:30 +00001155 if (TargetObjectWriter->isN64()) {
Rafael Espindolab8cbb262015-04-30 00:30:40 +00001156 write(uint32_t(Index));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001157
Rafael Espindolab8cbb262015-04-30 00:30:40 +00001158 write(TargetObjectWriter->getRSsym(Entry.Type));
1159 write(TargetObjectWriter->getRType3(Entry.Type));
1160 write(TargetObjectWriter->getRType2(Entry.Type));
1161 write(TargetObjectWriter->getRType(Entry.Type));
Rafael Espindola5904e122014-03-29 06:26:49 +00001162 } else {
Jack Carter8ad0c272012-06-27 22:28:30 +00001163 struct ELF::Elf64_Rela ERE64;
Rafael Espindola5904e122014-03-29 06:26:49 +00001164 ERE64.setSymbolAndType(Index, Entry.Type);
Rafael Espindolab8cbb262015-04-30 00:30:40 +00001165 write(ERE64.r_info);
Jack Carter8ad0c272012-06-27 22:28:30 +00001166 }
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001167 if (hasRelocationAddend())
Rafael Espindolab8cbb262015-04-30 00:30:40 +00001168 write(Entry.Addend);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001169 } else {
Rafael Espindolab8cbb262015-04-30 00:30:40 +00001170 write(uint32_t(Entry.Offset));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001171
Rafael Espindolabce26a12010-10-05 15:11:03 +00001172 struct ELF::Elf32_Rela ERE32;
Rafael Espindola5904e122014-03-29 06:26:49 +00001173 ERE32.setSymbolAndType(Index, Entry.Type);
Rafael Espindolab8cbb262015-04-30 00:30:40 +00001174 write(ERE32.r_info);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001175
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001176 if (hasRelocationAddend())
Rafael Espindolab8cbb262015-04-30 00:30:40 +00001177 write(uint32_t(Entry.Addend));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001178 }
Matt Fleming6c1ad482010-08-16 18:57:57 +00001179 }
1180}
1181
Rafael Espindolab1863912015-04-30 21:10:06 +00001182const MCSectionELF *ELFObjectWriter::createStringTable(MCContext &Ctx) {
Rafael Espindola08850b32015-05-25 21:56:55 +00001183 const MCSectionELF *StrtabSection = SectionTable[StringTableIndex - 1];
Rafael Espindola88abc392015-04-29 20:34:31 +00001184 OS << StrTabBuilder.data();
Rafael Espindolabda19802015-04-30 14:21:49 +00001185 return StrtabSection;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001186}
1187
Rafael Espindolae92c1bf2015-05-21 19:42:35 +00001188void ELFObjectWriter::writeSection(const SectionIndexMapTy &SectionIndexMap,
1189 uint32_t GroupSymbolIndex, uint64_t Offset,
1190 uint64_t Size, const MCSectionELF &Section) {
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001191 uint64_t sh_link = 0;
1192 uint64_t sh_info = 0;
1193
1194 switch(Section.getType()) {
Rafael Espindola86fe2fe2015-04-06 03:16:51 +00001195 default:
1196 // Nothing to do.
1197 break;
1198
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001199 case ELF::SHT_DYNAMIC:
Rafael Espindola74ef4802015-04-30 21:20:06 +00001200 llvm_unreachable("SHT_DYNAMIC in a relocatable object");
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001201
1202 case ELF::SHT_REL:
1203 case ELF::SHT_RELA: {
Rafael Espindola3a7c0eb2015-02-17 20:37:50 +00001204 sh_link = SymbolTableIndex;
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001205 assert(sh_link && ".symtab not found");
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001206 const MCSectionELF *InfoSection = Section.getAssociatedSection();
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001207 sh_info = SectionIndexMap.lookup(InfoSection);
1208 break;
1209 }
1210
1211 case ELF::SHT_SYMTAB:
1212 case ELF::SHT_DYNSYM:
1213 sh_link = StringTableIndex;
1214 sh_info = LastLocalSymbolIndex;
1215 break;
1216
1217 case ELF::SHT_SYMTAB_SHNDX:
1218 sh_link = SymbolTableIndex;
1219 break;
1220
Nick Lewyckyc6ac5f72011-10-07 23:28:32 +00001221 case ELF::SHT_GROUP:
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001222 sh_link = SymbolTableIndex;
1223 sh_info = GroupSymbolIndex;
1224 break;
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001225 }
1226
Logan Chien4b724422013-02-05 14:18:59 +00001227 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
Rafael Espindola61e8ce32015-04-06 04:25:18 +00001228 Section.getType() == ELF::SHT_ARM_EXIDX)
1229 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
Logan Chien4b724422013-02-05 14:18:59 +00001230
Rafael Espindola5960cee2015-05-22 23:58:30 +00001231 WriteSecHdrEntry(StrTabBuilder.getOffset(Section.getSectionName()),
Rafael Espindola28687582015-05-21 19:36:43 +00001232 Section.getType(), Section.getFlags(), 0, Offset, Size,
1233 sh_link, sh_info, Section.getAlignment(),
1234 Section.getEntrySize());
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001235}
1236
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001237void ELFObjectWriter::writeSectionHeader(
Rafael Espindola1aa20fc2015-05-21 19:46:39 +00001238 const MCAssembler &Asm, const MCAsmLayout &Layout,
Rafael Espindola03d7abb2015-04-30 20:53:27 +00001239 const SectionIndexMapTy &SectionIndexMap,
Rafael Espindolaa8201692015-04-28 15:26:21 +00001240 const SectionOffsetsTy &SectionOffsets) {
Rafael Espindolab1863912015-04-30 21:10:06 +00001241 const unsigned NumSections = SectionTable.size();
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001242
Matt Fleming6c1ad482010-08-16 18:57:57 +00001243 // Null section first.
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001244 uint64_t FirstSectionSize =
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001245 (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
Rafael Espindola88d1f632015-04-29 20:25:24 +00001246 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001247
Rafael Espindola08850b32015-05-25 21:56:55 +00001248 for (const MCSectionELF *Section : SectionTable) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001249 uint32_t GroupSymbolIndex;
Rafael Espindola03d7abb2015-04-30 20:53:27 +00001250 unsigned Type = Section->getType();
1251 if (Type != ELF::SHT_GROUP)
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001252 GroupSymbolIndex = 0;
1253 else
Rafael Espindola03d7abb2015-04-30 20:53:27 +00001254 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, Section->getGroup());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001255
Rafael Espindolabda19802015-04-30 14:21:49 +00001256 const std::pair<uint64_t, uint64_t> &Offsets =
Rafael Espindola03d7abb2015-04-30 20:53:27 +00001257 SectionOffsets.find(Section)->second;
Rafael Espindola1aa20fc2015-05-21 19:46:39 +00001258 uint64_t Size;
Rafael Espindola5a1e80b2015-05-26 02:00:36 +00001259 if (Type == ELF::SHT_NOBITS)
1260 Size = Layout.getSectionAddressSize(Section);
1261 else
Rafael Espindola1aa20fc2015-05-21 19:46:39 +00001262 Size = Offsets.second - Offsets.first;
Rafael Espindola60ebca92010-12-02 03:09:06 +00001263
Rafael Espindolae92c1bf2015-05-21 19:42:35 +00001264 writeSection(SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
Rafael Espindola28687582015-05-21 19:36:43 +00001265 *Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001266 }
1267}
1268
Rafael Espindola1557fd62011-03-20 18:44:20 +00001269void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1270 const MCAsmLayout &Layout) {
Rafael Espindolabda19802015-04-30 14:21:49 +00001271 MCContext &Ctx = Asm.getContext();
Rafael Espindola5960cee2015-05-22 23:58:30 +00001272 MCSectionELF *StrtabSection =
1273 Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1274 StringTableIndex = addToSectionTable(StrtabSection);
Rafael Espindolabda19802015-04-30 14:21:49 +00001275
Rafael Espindola1557fd62011-03-20 18:44:20 +00001276 RevGroupMapTy RevGroupMap;
1277 SectionIndexMapTy SectionIndexMap;
1278
Rafael Espindolabda19802015-04-30 14:21:49 +00001279 std::map<const MCSymbol *, std::vector<const MCSectionELF *>> GroupMembers;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001280
Rafael Espindola1557fd62011-03-20 18:44:20 +00001281 // Write out the ELF header ...
Rafael Espindola8c7829b2015-04-29 20:39:37 +00001282 writeHeader(Asm);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001283
Rafael Espindola7230f802015-04-08 11:41:24 +00001284 // ... then the sections ...
Rafael Espindolabda19802015-04-30 14:21:49 +00001285 SectionOffsetsTy SectionOffsets;
Rafael Espindola0a82ad72015-05-21 20:43:13 +00001286 std::vector<MCSectionELF *> Groups;
1287 std::vector<MCSectionELF *> Relocations;
Rafael Espindolae15b1b72015-05-27 13:30:50 +00001288 for (MCSection &Sec : Asm) {
1289 MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
Rafael Espindolabda19802015-04-30 14:21:49 +00001290
Rafael Espindola967d6a62015-05-21 21:02:35 +00001291 uint64_t Padding = OffsetToAlignment(OS.tell(), Section.getAlignment());
Rafael Espindola642a2212015-04-14 22:54:16 +00001292 WriteZeros(Padding);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001293
Rafael Espindola642a2212015-04-14 22:54:16 +00001294 // Remember the offset into the file for this section.
Rafael Espindolab6417502015-04-28 15:04:09 +00001295 uint64_t SecStart = OS.tell();
Rafael Espindolab8cbb262015-04-30 00:30:40 +00001296
Rafael Espindolabda19802015-04-30 14:21:49 +00001297 const MCSymbol *SignatureSymbol = Section.getGroup();
Rafael Espindolae15b1b72015-05-27 13:30:50 +00001298 writeSectionData(Asm, Section, Layout);
Rafael Espindolab8cbb262015-04-30 00:30:40 +00001299
Rafael Espindolab6417502015-04-28 15:04:09 +00001300 uint64_t SecEnd = OS.tell();
Rafael Espindolabda19802015-04-30 14:21:49 +00001301 SectionOffsets[&Section] = std::make_pair(SecStart, SecEnd);
1302
Rafael Espindola0a82ad72015-05-21 20:43:13 +00001303 MCSectionELF *RelSection = createRelocationSection(Ctx, Section);
Rafael Espindolabda19802015-04-30 14:21:49 +00001304
1305 if (SignatureSymbol) {
1306 Asm.getOrCreateSymbolData(*SignatureSymbol);
1307 unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
1308 if (!GroupIdx) {
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001309 MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
Rafael Espindola03d7abb2015-04-30 20:53:27 +00001310 GroupIdx = addToSectionTable(Group);
Rafael Espindola0a82ad72015-05-21 20:43:13 +00001311 Group->setAlignment(4);
1312 Groups.push_back(Group);
Rafael Espindolabda19802015-04-30 14:21:49 +00001313 }
1314 GroupMembers[SignatureSymbol].push_back(&Section);
1315 if (RelSection)
1316 GroupMembers[SignatureSymbol].push_back(RelSection);
1317 }
1318
Rafael Espindola03d7abb2015-04-30 20:53:27 +00001319 SectionIndexMap[&Section] = addToSectionTable(&Section);
Rafael Espindola0a82ad72015-05-21 20:43:13 +00001320 if (RelSection) {
Rafael Espindola03d7abb2015-04-30 20:53:27 +00001321 SectionIndexMap[RelSection] = addToSectionTable(RelSection);
Rafael Espindola0a82ad72015-05-21 20:43:13 +00001322 Relocations.push_back(RelSection);
1323 }
Rafael Espindolabda19802015-04-30 14:21:49 +00001324 }
1325
Rafael Espindola0a82ad72015-05-21 20:43:13 +00001326 for (MCSectionELF *Group : Groups) {
1327 uint64_t Padding = OffsetToAlignment(OS.tell(), Group->getAlignment());
1328 WriteZeros(Padding);
1329
1330 // Remember the offset into the file for this section.
1331 uint64_t SecStart = OS.tell();
1332
1333 const MCSymbol *SignatureSymbol = Group->getGroup();
1334 assert(SignatureSymbol);
1335 write(uint32_t(ELF::GRP_COMDAT));
1336 for (const MCSectionELF *Member : GroupMembers[SignatureSymbol]) {
1337 uint32_t SecIndex = SectionIndexMap.lookup(Member);
1338 write(SecIndex);
1339 }
1340
1341 uint64_t SecEnd = OS.tell();
1342 SectionOffsets[Group] = std::make_pair(SecStart, SecEnd);
1343 }
1344
1345 // Compute symbol table information.
Rafael Espindolaaa486e92015-05-28 17:54:01 +00001346 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap, SectionOffsets);
Rafael Espindola0a82ad72015-05-21 20:43:13 +00001347
1348 for (MCSectionELF *RelSection : Relocations) {
1349 uint64_t Padding = OffsetToAlignment(OS.tell(), RelSection->getAlignment());
1350 WriteZeros(Padding);
1351
1352 // Remember the offset into the file for this section.
1353 uint64_t SecStart = OS.tell();
1354
1355 writeRelocations(Asm, *RelSection->getAssociatedSection());
1356
1357 uint64_t SecEnd = OS.tell();
1358 SectionOffsets[RelSection] = std::make_pair(SecStart, SecEnd);
Rafael Espindola642a2212015-04-14 22:54:16 +00001359 }
1360
Rafael Espindola88d1f632015-04-29 20:25:24 +00001361 {
1362 uint64_t SecStart = OS.tell();
Rafael Espindolab1863912015-04-30 21:10:06 +00001363 const MCSectionELF *Sec = createStringTable(Ctx);
Rafael Espindola88abc392015-04-29 20:34:31 +00001364 uint64_t SecEnd = OS.tell();
Rafael Espindolabda19802015-04-30 14:21:49 +00001365 SectionOffsets[Sec] = std::make_pair(SecStart, SecEnd);
Rafael Espindola88abc392015-04-29 20:34:31 +00001366 }
1367
Rafael Espindola642a2212015-04-14 22:54:16 +00001368 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001369 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001370 WriteZeros(Padding);
1371
Rafael Espindola642a2212015-04-14 22:54:16 +00001372 const unsigned SectionHeaderOffset = OS.tell();
1373
Rafael Espindola1557fd62011-03-20 18:44:20 +00001374 // ... then the section header table ...
Rafael Espindola03d7abb2015-04-30 20:53:27 +00001375 writeSectionHeader(Asm, Layout, SectionIndexMap, SectionOffsets);
Rafael Espindola642a2212015-04-14 22:54:16 +00001376
Rafael Espindola03d7abb2015-04-30 20:53:27 +00001377 uint16_t NumSections = (SectionTable.size() + 1 >= ELF::SHN_LORESERVE)
Aaron Ballman9cab7322015-04-30 14:03:12 +00001378 ? (uint16_t)ELF::SHN_UNDEF
Rafael Espindola03d7abb2015-04-30 20:53:27 +00001379 : SectionTable.size() + 1;
Rafael Espindola8c7829b2015-04-29 20:39:37 +00001380 if (sys::IsLittleEndianHost != IsLittleEndian)
1381 sys::swapByteOrder(NumSections);
1382 unsigned NumSectionsOffset;
1383
Rafael Espindola642a2212015-04-14 22:54:16 +00001384 if (is64Bit()) {
1385 uint64_t Val = SectionHeaderOffset;
1386 if (sys::IsLittleEndianHost != IsLittleEndian)
1387 sys::swapByteOrder(Val);
1388 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1389 offsetof(ELF::Elf64_Ehdr, e_shoff));
Rafael Espindola8c7829b2015-04-29 20:39:37 +00001390 NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum);
Rafael Espindola642a2212015-04-14 22:54:16 +00001391 } else {
1392 uint32_t Val = SectionHeaderOffset;
1393 if (sys::IsLittleEndianHost != IsLittleEndian)
1394 sys::swapByteOrder(Val);
1395 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1396 offsetof(ELF::Elf32_Ehdr, e_shoff));
Rafael Espindola8c7829b2015-04-29 20:39:37 +00001397 NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum);
Rafael Espindola642a2212015-04-14 22:54:16 +00001398 }
Rafael Espindola8c7829b2015-04-29 20:39:37 +00001399 OS.pwrite(reinterpret_cast<char *>(&NumSections), sizeof(NumSections),
1400 NumSectionsOffset);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001401}
1402
Rafael Espindola94a88d72015-04-06 15:27:57 +00001403bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
Duncan P. N. Exon Smithd81ba532015-05-16 01:01:55 +00001404 const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
Rafael Espindola35d61892015-04-17 21:15:17 +00001405 bool InSet, bool IsPCRel) const {
1406 if (IsPCRel) {
1407 assert(!InSet);
Duncan P. N. Exon Smithd81ba532015-05-16 01:01:55 +00001408 if (::isWeak(SymA.getData()))
Rafael Espindola35d61892015-04-17 21:15:17 +00001409 return false;
1410 }
Duncan P. N. Exon Smithd81ba532015-05-16 01:01:55 +00001411 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
Rafael Espindola35d61892015-04-17 21:15:17 +00001412 InSet, IsPCRel);
Eli Friedmand92d17b2011-03-03 07:24:36 +00001413}
1414
Duncan P. N. Exon Smith5266ad92015-05-20 15:10:03 +00001415bool ELFObjectWriter::isWeak(const MCSymbol &Sym) const {
1416 const MCSymbolData &SD = Sym.getData();
Rafael Espindoladb8a5862015-04-17 20:05:17 +00001417 if (::isWeak(SD))
1418 return true;
1419
Rafael Espindoladb8a5862015-04-17 20:05:17 +00001420 // It is invalid to replace a reference to a global in a comdat
1421 // with a reference to a local since out of comdat references
1422 // to a local are forbidden.
1423 // We could try to return false for more cases, like the reference
1424 // being in the same comdat or Sym being an alias to another global,
1425 // but it is not clear if it is worth the effort.
Rafael Espindola29c82702015-04-20 12:44:06 +00001426 if (MCELF::GetBinding(SD) != ELF::STB_GLOBAL)
1427 return false;
Rafael Espindoladb8a5862015-04-17 20:05:17 +00001428
Rafael Espindola29c82702015-04-20 12:44:06 +00001429 if (!Sym.isInSection())
1430 return false;
1431
1432 const auto &Sec = cast<MCSectionELF>(Sym.getSection());
1433 return Sec.getGroup();
Rafael Espindolaf275ad82015-03-25 13:16:53 +00001434}
1435
Rafael Espindola6b5e56c2010-12-17 17:45:22 +00001436MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
Rafael Espindola5560a4c2015-04-14 22:14:34 +00001437 raw_pwrite_stream &OS,
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001438 bool IsLittleEndian) {
Rafael Espindola34a68af2011-12-22 03:24:43 +00001439 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
Rafael Espindolab264d332011-12-21 17:30:17 +00001440}