blob: 5c0d466ced6ceab412bb6bcc4c0b13334e7b6bcf [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"
David Blaikie8019bf82014-04-10 21:53:53 +000031#include "llvm/Support/Compression.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000032#include "llvm/Support/Debug.h"
Rafael Espindola0ce09712014-03-25 22:43:53 +000033#include "llvm/Support/Endian.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000034#include "llvm/Support/ELF.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Support/ErrorHandling.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000036#include <vector>
37using namespace llvm;
38
Jason W Kimc09e7262011-05-11 22:53:06 +000039#undef DEBUG_TYPE
40#define DEBUG_TYPE "reloc-info"
41
Rafael Espindola29abd972011-12-22 03:38:00 +000042namespace {
Rafael Espindola0ce09712014-03-25 22:43:53 +000043class FragmentWriter {
44 bool IsLittleEndian;
45
46public:
47 FragmentWriter(bool IsLittleEndian);
48 template <typename T> void write(MCDataFragment &F, T Val);
49};
50
Rafael Espindola10be0832014-03-25 23:44:25 +000051typedef DenseMap<const MCSectionELF *, uint32_t> SectionIndexMapTy;
52
53class SymbolTableWriter {
54 MCAssembler &Asm;
55 FragmentWriter &FWriter;
56 bool Is64Bit;
57 SectionIndexMapTy &SectionIndexMap;
58
59 // The symbol .symtab fragment we are writting to.
60 MCDataFragment *SymtabF;
61
62 // .symtab_shndx fragment we are writting to.
63 MCDataFragment *ShndxF;
64
65 // The numbel of symbols written so far.
66 unsigned NumWritten;
67
68 void createSymtabShndx();
69
70 template <typename T> void write(MCDataFragment &F, T Value);
71
72public:
73 SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter, bool Is64Bit,
74 SectionIndexMapTy &SectionIndexMap,
75 MCDataFragment *SymtabF);
76
77 void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
78 uint8_t other, uint32_t shndx, bool Reserved);
79};
80
Rafael Espindola5904e122014-03-29 06:26:49 +000081struct ELFRelocationEntry {
82 uint64_t Offset; // Where is the relocation.
83 bool UseSymbol; // Relocate with a symbol, not the section.
84 union {
85 const MCSymbol *Symbol; // The symbol to relocate with.
86 const MCSectionData *Section; // The section to relocate with.
87 };
88 unsigned Type; // The type of the relocation.
89 uint64_t Addend; // The addend to use.
90
91 ELFRelocationEntry(uint64_t Offset, const MCSymbol *Symbol, unsigned Type,
92 uint64_t Addend)
93 : Offset(Offset), UseSymbol(true), Symbol(Symbol), Type(Type),
94 Addend(Addend) {}
95
96 ELFRelocationEntry(uint64_t Offset, const MCSectionData *Section,
97 unsigned Type, uint64_t Addend)
98 : Offset(Offset), UseSymbol(false), Section(Section), Type(Type),
99 Addend(Addend) {}
100};
101
Rafael Espindola29abd972011-12-22 03:38:00 +0000102class ELFObjectWriter : public MCObjectWriter {
Rafael Espindola0ce09712014-03-25 22:43:53 +0000103 FragmentWriter FWriter;
104
Rafael Espindola29abd972011-12-22 03:38:00 +0000105 protected:
106
107 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
108 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
109 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000110 static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolData &Data,
Rafael Espindola29abd972011-12-22 03:38:00 +0000111 bool Used, bool Renamed);
Rafael Espindola39f50422014-04-28 14:24:44 +0000112 static bool isLocal(const MCSymbolData &Data, bool isUsedInReloc);
Rafael Espindola29abd972011-12-22 03:38:00 +0000113 static bool IsELFMetaDataSection(const MCSectionData &SD);
114 static uint64_t DataSectionSize(const MCSectionData &SD);
115 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
116 const MCSectionData &SD);
117 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
118 const MCSectionData &SD);
119
120 void WriteDataSectionData(MCAssembler &Asm,
121 const MCAsmLayout &Layout,
122 const MCSectionELF &Section);
123
124 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
125 return Kind == X86::reloc_riprel_4byte ||
126 Kind == X86::reloc_riprel_4byte_movq_load;
127 }*/
128
129 /// ELFSymbolData - Helper struct for containing some precomputed
130 /// information on symbols.
131 struct ELFSymbolData {
132 MCSymbolData *SymbolData;
133 uint64_t StringIndex;
134 uint32_t SectionIndex;
135
136 // Support lexicographic sorting.
137 bool operator<(const ELFSymbolData &RHS) const {
Rafael Espindola29abd972011-12-22 03:38:00 +0000138 return SymbolData->getSymbol().getName() <
139 RHS.SymbolData->getSymbol().getName();
140 }
141 };
142
Rafael Espindola29abd972011-12-22 03:38:00 +0000143 /// The target specific ELF writer instance.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000144 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
Rafael Espindola29abd972011-12-22 03:38:00 +0000145
146 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
147 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
148 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
149
Rafael Espindola5904e122014-03-29 06:26:49 +0000150 llvm::DenseMap<const MCSectionData *, std::vector<ELFRelocationEntry>>
151 Relocations;
Rafael Espindola29abd972011-12-22 03:38:00 +0000152 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
153
154 /// @}
155 /// @name Symbol Table Data
156 /// @{
157
158 SmallString<256> StringTable;
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000159 std::vector<uint64_t> FileSymbolData;
Rafael Espindola29abd972011-12-22 03:38:00 +0000160 std::vector<ELFSymbolData> LocalSymbolData;
161 std::vector<ELFSymbolData> ExternalSymbolData;
162 std::vector<ELFSymbolData> UndefinedSymbolData;
163
164 /// @}
165
166 bool NeedsGOT;
167
Rafael Espindola29abd972011-12-22 03:38:00 +0000168 // This holds the symbol table index of the last local symbol.
169 unsigned LastLocalSymbolIndex;
170 // This holds the .strtab section index.
171 unsigned StringTableIndex;
172 // This holds the .symtab section index.
173 unsigned SymbolTableIndex;
174
175 unsigned ShstrtabIndex;
176
177
Rafael Espindola29abd972011-12-22 03:38:00 +0000178 // TargetObjectWriter wrappers.
Rafael Espindola29abd972011-12-22 03:38:00 +0000179 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
180 bool hasRelocationAddend() const {
181 return TargetObjectWriter->hasRelocationAddend();
182 }
Rafael Espindola29abd972011-12-22 03:38:00 +0000183 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000184 bool IsPCRel) const {
185 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindola29abd972011-12-22 03:38:00 +0000186 }
187
Rafael Espindola29abd972011-12-22 03:38:00 +0000188 public:
Rafael Espindola0ce09712014-03-25 22:43:53 +0000189 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_ostream &_OS,
190 bool IsLittleEndian)
191 : MCObjectWriter(_OS, IsLittleEndian), FWriter(IsLittleEndian),
Rafael Espindola10be0832014-03-25 23:44:25 +0000192 TargetObjectWriter(MOTW), NeedsGOT(false) {}
Rafael Espindola29abd972011-12-22 03:38:00 +0000193
194 virtual ~ELFObjectWriter();
195
196 void WriteWord(uint64_t W) {
197 if (is64Bit())
198 Write64(W);
199 else
200 Write32(W);
201 }
202
Rafael Espindola0ce09712014-03-25 22:43:53 +0000203 template <typename T> void write(MCDataFragment &F, T Value) {
204 FWriter.write(F, Value);
Rafael Espindola29abd972011-12-22 03:38:00 +0000205 }
206
Jack Carter1bd90ff2013-01-30 02:09:52 +0000207 void WriteHeader(const MCAssembler &Asm,
208 uint64_t SectionDataSize,
Rafael Espindola29abd972011-12-22 03:38:00 +0000209 unsigned NumberOfSections);
210
Rafael Espindola10be0832014-03-25 23:44:25 +0000211 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Rafael Espindola29abd972011-12-22 03:38:00 +0000212 const MCAsmLayout &Layout);
213
Rafael Espindola10be0832014-03-25 23:44:25 +0000214 void WriteSymbolTable(MCDataFragment *SymtabF, MCAssembler &Asm,
Rafael Espindola29abd972011-12-22 03:38:00 +0000215 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000216 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000217
Rafael Espindola5904e122014-03-29 06:26:49 +0000218 bool shouldRelocateWithSymbol(const MCSymbolRefExpr *RefA,
219 const MCSymbolData *SD, uint64_t C,
220 unsigned Type) const;
221
Craig Topper34a61bc2014-03-08 07:02:02 +0000222 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
223 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindola5904e122014-03-29 06:26:49 +0000224 MCValue Target, bool &IsPCRel,
225 uint64_t &FixedValue) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000226
227 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
228 const MCSymbol *S);
229
230 // Map from a group section to the signature symbol
231 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
232 // Map from a signature symbol to the group section
233 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
234 // Map from a section to the section with the relocations
235 typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
236 // Map from a section to its offset
237 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
238
Rafael Espindola022bb762014-03-24 03:43:21 +0000239 /// Compute the symbol table data
Rafael Espindola29abd972011-12-22 03:38:00 +0000240 ///
Rafael Espindola073ee7d2012-08-27 16:04:24 +0000241 /// \param Asm - The assembler.
242 /// \param SectionIndexMap - Maps a section to its index.
243 /// \param RevGroupMap - Maps a signature symbol to the group section.
244 /// \param NumRegularSections - Number of non-relocation sections.
Rafael Espindola022bb762014-03-24 03:43:21 +0000245 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
Rafael Espindola29abd972011-12-22 03:38:00 +0000246 const SectionIndexMapTy &SectionIndexMap,
247 RevGroupMapTy RevGroupMap,
248 unsigned NumRegularSections);
249
250 void ComputeIndexMap(MCAssembler &Asm,
251 SectionIndexMapTy &SectionIndexMap,
252 const RelMapTy &RelMap);
253
254 void CreateRelocationSections(MCAssembler &Asm, MCAsmLayout &Layout,
255 RelMapTy &RelMap);
256
David Blaikie8019bf82014-04-10 21:53:53 +0000257 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
258
Rafael Espindola29abd972011-12-22 03:38:00 +0000259 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
260 const RelMapTy &RelMap);
261
262 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
263 SectionIndexMapTy &SectionIndexMap,
264 const RelMapTy &RelMap);
265
266 // Create the sections that show up in the symbol table. Currently
267 // those are the .note.GNU-stack section and the group sections.
268 void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
269 GroupMapTy &GroupMap,
270 RevGroupMapTy &RevGroupMap,
271 SectionIndexMapTy &SectionIndexMap,
272 const RelMapTy &RelMap);
273
Craig Topper34a61bc2014-03-08 07:02:02 +0000274 void ExecutePostLayoutBinding(MCAssembler &Asm,
275 const MCAsmLayout &Layout) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000276
277 void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
278 const MCAsmLayout &Layout,
279 const SectionIndexMapTy &SectionIndexMap,
280 const SectionOffsetMapTy &SectionOffsetMap);
281
282 void ComputeSectionOrder(MCAssembler &Asm,
283 std::vector<const MCSectionELF*> &Sections);
284
285 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
286 uint64_t Address, uint64_t Offset,
287 uint64_t Size, uint32_t Link, uint32_t Info,
288 uint64_t Alignment, uint64_t EntrySize);
289
290 void WriteRelocationsFragment(const MCAssembler &Asm,
291 MCDataFragment *F,
292 const MCSectionData *SD);
293
Craig Topper34a61bc2014-03-08 07:02:02 +0000294 bool
Rafael Espindola29abd972011-12-22 03:38:00 +0000295 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
296 const MCSymbolData &DataA,
297 const MCFragment &FB,
298 bool InSet,
Craig Topper34a61bc2014-03-08 07:02:02 +0000299 bool IsPCRel) const override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000300
Craig Topper34a61bc2014-03-08 07:02:02 +0000301 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000302 void WriteSection(MCAssembler &Asm,
303 const SectionIndexMapTy &SectionIndexMap,
304 uint32_t GroupSymbolIndex,
305 uint64_t Offset, uint64_t Size, uint64_t Alignment,
306 const MCSectionELF &Section);
307 };
308}
309
Rafael Espindola0ce09712014-03-25 22:43:53 +0000310FragmentWriter::FragmentWriter(bool IsLittleEndian)
311 : IsLittleEndian(IsLittleEndian) {}
312
313template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
314 if (IsLittleEndian)
315 Val = support::endian::byte_swap<T, support::little>(Val);
316 else
317 Val = support::endian::byte_swap<T, support::big>(Val);
318 const char *Start = (const char *)&Val;
319 F.getContents().append(Start, Start + sizeof(T));
320}
321
Rafael Espindola10be0832014-03-25 23:44:25 +0000322void SymbolTableWriter::createSymtabShndx() {
323 if (ShndxF)
324 return;
325
326 MCContext &Ctx = Asm.getContext();
327 const MCSectionELF *SymtabShndxSection =
328 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0,
329 SectionKind::getReadOnly(), 4, "");
330 MCSectionData *SymtabShndxSD =
331 &Asm.getOrCreateSectionData(*SymtabShndxSection);
332 SymtabShndxSD->setAlignment(4);
333 ShndxF = new MCDataFragment(SymtabShndxSD);
334 unsigned Index = SectionIndexMap.size() + 1;
335 SectionIndexMap[SymtabShndxSection] = Index;
336
337 for (unsigned I = 0; I < NumWritten; ++I)
338 write(*ShndxF, uint32_t(0));
339}
340
341template <typename T>
342void SymbolTableWriter::write(MCDataFragment &F, T Value) {
343 FWriter.write(F, Value);
344}
345
346SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
347 bool Is64Bit,
348 SectionIndexMapTy &SectionIndexMap,
349 MCDataFragment *SymtabF)
350 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
351 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
352 NumWritten(0) {}
353
354void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
355 uint64_t size, uint8_t other,
356 uint32_t shndx, bool Reserved) {
357 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
358
359 if (LargeIndex)
360 createSymtabShndx();
361
362 if (ShndxF) {
363 if (LargeIndex)
364 write(*ShndxF, shndx);
365 else
366 write(*ShndxF, uint32_t(0));
367 }
368
369 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
370
371 raw_svector_ostream OS(SymtabF->getContents());
372
373 if (Is64Bit) {
374 write(*SymtabF, name); // st_name
375 write(*SymtabF, info); // st_info
376 write(*SymtabF, other); // st_other
377 write(*SymtabF, Index); // st_shndx
378 write(*SymtabF, value); // st_value
379 write(*SymtabF, size); // st_size
380 } else {
381 write(*SymtabF, name); // st_name
382 write(*SymtabF, uint32_t(value)); // st_value
383 write(*SymtabF, uint32_t(size)); // st_size
384 write(*SymtabF, info); // st_info
385 write(*SymtabF, other); // st_other
386 write(*SymtabF, Index); // st_shndx
387 }
388
389 ++NumWritten;
390}
391
Jan Sjödin30a52de2011-02-28 21:45:04 +0000392bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
393 const MCFixupKindInfo &FKI =
394 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
395
396 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
397}
398
399bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
400 switch (Variant) {
401 default:
402 return false;
403 case MCSymbolRefExpr::VK_GOT:
404 case MCSymbolRefExpr::VK_PLT:
405 case MCSymbolRefExpr::VK_GOTPCREL:
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000406 case MCSymbolRefExpr::VK_GOTOFF:
Jan Sjödin30a52de2011-02-28 21:45:04 +0000407 case MCSymbolRefExpr::VK_TPOFF:
408 case MCSymbolRefExpr::VK_TLSGD:
409 case MCSymbolRefExpr::VK_GOTTPOFF:
410 case MCSymbolRefExpr::VK_INDNTPOFF:
411 case MCSymbolRefExpr::VK_NTPOFF:
412 case MCSymbolRefExpr::VK_GOTNTPOFF:
413 case MCSymbolRefExpr::VK_TLSLDM:
414 case MCSymbolRefExpr::VK_DTPOFF:
415 case MCSymbolRefExpr::VK_TLSLD:
416 return true;
417 }
418}
419
Jason W Kim96f4c012010-11-15 16:18:39 +0000420ELFObjectWriter::~ELFObjectWriter()
421{}
422
Matt Fleming6c1ad482010-08-16 18:57:57 +0000423// Emit the ELF header.
Jack Carter1bd90ff2013-01-30 02:09:52 +0000424void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
425 uint64_t SectionDataSize,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000426 unsigned NumberOfSections) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000427 // ELF Header
428 // ----------
429 //
430 // Note
431 // ----
432 // emitWord method behaves differently for ELF32 and ELF64, writing
433 // 4 bytes in the former and 8 in the latter.
434
435 Write8(0x7f); // e_ident[EI_MAG0]
436 Write8('E'); // e_ident[EI_MAG1]
437 Write8('L'); // e_ident[EI_MAG2]
438 Write8('F'); // e_ident[EI_MAG3]
439
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000440 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
Matt Fleming6c1ad482010-08-16 18:57:57 +0000441
442 // e_ident[EI_DATA]
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000443 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000444
445 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky3b727f52010-09-09 17:57:50 +0000446 // e_ident[EI_OSABI]
Rafael Espindola1ad40952011-12-21 17:00:36 +0000447 Write8(TargetObjectWriter->getOSABI());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000448 Write8(0); // e_ident[EI_ABIVERSION]
449
450 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
451
452 Write16(ELF::ET_REL); // e_type
453
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000454 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
Matt Fleming6c1ad482010-08-16 18:57:57 +0000455
456 Write32(ELF::EV_CURRENT); // e_version
457 WriteWord(0); // e_entry, no entry point in .o file
458 WriteWord(0); // e_phoff, no program header for .o
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000459 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
Benjamin Kramer896bd7e2010-08-17 17:02:29 +0000460 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
Matt Fleming6c1ad482010-08-16 18:57:57 +0000461
Jason W Kim4761fba2011-02-04 21:41:11 +0000462 // e_flags = whatever the target wants
Jack Carter1bd90ff2013-01-30 02:09:52 +0000463 Write32(Asm.getELFHeaderEFlags());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000464
465 // e_ehsize = ELF header size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000466 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000467
468 Write16(0); // e_phentsize = prog header entry size
469 Write16(0); // e_phnum = # prog header entries = 0
470
471 // e_shentsize = Section header entry size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000472 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000473
474 // e_shnum = # of section header ents
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000475 if (NumberOfSections >= ELF::SHN_LORESERVE)
Nick Lewycky4eb11432011-10-07 20:56:23 +0000476 Write16(ELF::SHN_UNDEF);
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000477 else
478 Write16(NumberOfSections);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000479
480 // e_shstrndx = Section # of '.shstrtab'
Nick Lewycky8b02d362011-10-07 20:58:24 +0000481 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000482 Write16(ELF::SHN_XINDEX);
483 else
484 Write16(ShstrtabIndex);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000485}
486
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000487uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &OrigData,
Jan Sjödin30a52de2011-02-28 21:45:04 +0000488 const MCAsmLayout &Layout) {
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000489 MCSymbolData *Data = &OrigData;
490 if (Data->isCommon() && Data->isExternal())
491 return Data->getCommonAlignment();
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000492
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000493 const MCSymbol *Symbol = &Data->getSymbol();
Roman Divacky55184dd2010-12-20 21:14:39 +0000494
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000495 uint64_t Res = 0;
496 if (Symbol->isVariable()) {
497 const MCExpr *Expr = Symbol->getVariableValue();
498 MCValue Value;
499 if (!Expr->EvaluateAsRelocatable(Value, &Layout))
500 llvm_unreachable("Invalid expression");
501
502 assert(!Value.getSymB());
503
504 Res = Value.getConstant();
505
506 if (const MCSymbolRefExpr *A = Value.getSymA()) {
507 Symbol = &A->getSymbol();
508 Data = &Layout.getAssembler().getSymbolData(*Symbol);
509 } else {
Craig Topperbb694de2014-04-13 04:57:38 +0000510 Symbol = nullptr;
511 Data = nullptr;
Rafael Espindola7bbd5c22014-03-19 00:13:43 +0000512 }
Roman Divacky55184dd2010-12-20 21:14:39 +0000513 }
514
Rafael Espindola6a4a0792014-04-23 14:42:32 +0000515 if ((Data && Data->getFlags() & ELF_Other_ThumbFunc) ||
516 OrigData.getFlags() & ELF_Other_ThumbFunc)
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000517 Res |= 1;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000518
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000519 if (!Symbol || !Symbol->isInSection())
520 return Res;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000521
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000522 Res += Layout.getSymbolOffset(Data);
523
524 return Res;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000525}
526
Rafael Espindola93e3cf02010-12-07 00:27:36 +0000527void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
528 const MCAsmLayout &Layout) {
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000529 // The presence of symbol versions causes undefined symbols and
530 // versions declared with @@@ to be renamed.
531
David Blaikie583a31c2014-04-18 18:24:25 +0000532 for (MCSymbolData &OriginalData : Asm.symbols()) {
533 const MCSymbol &Alias = OriginalData.getSymbol();
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000534 const MCSymbol &Symbol = Alias.AliasedSymbol();
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000535 MCSymbolData &SD = Asm.getSymbolData(Symbol);
536
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000537 // Not an alias.
538 if (&Symbol == &Alias)
539 continue;
540
Benjamin Kramer14807272010-10-27 19:53:52 +0000541 StringRef AliasName = Alias.getName();
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000542 size_t Pos = AliasName.find('@');
543 if (Pos == StringRef::npos)
544 continue;
545
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000546 // Aliases defined with .symvar copy the binding from the symbol they alias.
547 // This is the first place we are able to copy this information.
David Blaikie583a31c2014-04-18 18:24:25 +0000548 OriginalData.setExternal(SD.isExternal());
549 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000550
Benjamin Kramer14807272010-10-27 19:53:52 +0000551 StringRef Rest = AliasName.substr(Pos);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000552 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
553 continue;
554
Rafael Espindola26496e62010-10-27 17:56:18 +0000555 // FIXME: produce a better error message.
556 if (Symbol.isUndefined() && Rest.startswith("@@") &&
557 !Rest.startswith("@@@"))
558 report_fatal_error("A @@ version cannot be undefined");
559
Benjamin Kramer14807272010-10-27 19:53:52 +0000560 Renames.insert(std::make_pair(&Symbol, &Alias));
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000561 }
562}
563
Roman Divacky5a1c5492014-01-07 20:17:03 +0000564static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
565 uint8_t Type = newType;
566
567 // Propagation rules:
568 // IFUNC > FUNC > OBJECT > NOTYPE
569 // TLS_OBJECT > OBJECT > NOTYPE
570 //
571 // dont let the new type degrade the old type
572 switch (origType) {
573 default:
574 break;
575 case ELF::STT_GNU_IFUNC:
576 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
577 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
578 Type = ELF::STT_GNU_IFUNC;
579 break;
580 case ELF::STT_FUNC:
581 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
582 Type == ELF::STT_TLS)
583 Type = ELF::STT_FUNC;
584 break;
585 case ELF::STT_OBJECT:
586 if (Type == ELF::STT_NOTYPE)
587 Type = ELF::STT_OBJECT;
588 break;
589 case ELF::STT_TLS:
590 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
591 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
592 Type = ELF::STT_TLS;
593 break;
594 }
595
596 return Type;
597}
598
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000599static const MCSymbol *getBaseSymbol(const MCAsmLayout &Layout,
600 const MCSymbol &Symbol) {
601 if (!Symbol.isVariable())
602 return &Symbol;
603
604 const MCExpr *Expr = Symbol.getVariableValue();
605 MCValue Value;
606 if (!Expr->EvaluateAsRelocatable(Value, &Layout))
607 llvm_unreachable("Invalid Expression");
Rafael Espindola96450902014-04-28 12:40:50 +0000608 const MCSymbolRefExpr *RefB = Value.getSymB();
609 if (RefB) {
610 Layout.getAssembler().getContext().FatalError(
611 SMLoc(), Twine("symbol '") + RefB->getSymbol().getName() +
612 "' could not be evaluated in a subtraction expression");
613 }
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000614 const MCSymbolRefExpr *A = Value.getSymA();
615 if (!A)
616 return nullptr;
617 return getBaseSymbol(Layout, A->getSymbol());
618}
619
Rafael Espindola10be0832014-03-25 23:44:25 +0000620void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000621 const MCAsmLayout &Layout) {
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000622 MCSymbolData &OrigData = *MSD.SymbolData;
David Blaikieb5956d22014-04-19 00:50:15 +0000623 assert((!OrigData.getFragment() ||
624 (&OrigData.getFragment()->getParent()->getSection() ==
625 &OrigData.getSymbol().getSection())) &&
626 "The symbol's section doesn't match the fragment's symbol");
Rafael Espindola85a84912014-03-26 00:16:43 +0000627 const MCSymbol *Base = getBaseSymbol(Layout, OrigData.getSymbol());
628
629 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
630 // SHN_COMMON.
631 bool IsReserved = !Base || OrigData.isCommon();
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000632
Jack Carter2f8d9d92013-02-19 21:57:35 +0000633 // Binding and Type share the same byte as upper and lower nibbles
Jan Sjödin30a52de2011-02-28 21:45:04 +0000634 uint8_t Binding = MCELF::GetBinding(OrigData);
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000635 uint8_t Type = MCELF::GetType(OrigData);
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000636 MCSymbolData *BaseSD = nullptr;
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000637 if (Base) {
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000638 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
639 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000640 }
Saleem Abdulrasool39f773f2014-03-20 06:05:33 +0000641 if (OrigData.getFlags() & ELF_Other_ThumbFunc)
642 Type = ELF::STT_FUNC;
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000643 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000644
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000645 // Other and Visibility share the same byte with Visibility using the lower
Jack Carter2f8d9d92013-02-19 21:57:35 +0000646 // 2 bits
647 uint8_t Visibility = MCELF::GetVisibility(OrigData);
Logan Chienee365952013-12-05 00:34:11 +0000648 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000649 Other |= Visibility;
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000650
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000651 uint64_t Value = SymbolValue(OrigData, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000652 uint64_t Size = 0;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000653
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000654 const MCExpr *ESize = OrigData.getSize();
655 if (!ESize && Base)
656 ESize = BaseSD->getSize();
Rafael Espindolaf0591c12010-09-21 00:24:38 +0000657
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000658 if (ESize) {
659 int64_t Res;
660 if (!ESize->EvaluateAsAbsolute(Res, Layout))
661 report_fatal_error("Size expression must be absolute.");
662 Size = Res;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000663 }
664
665 // Write out the symbol table entry
Rafael Espindola10be0832014-03-25 23:44:25 +0000666 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
667 MSD.SectionIndex, IsReserved);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000668}
669
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000670void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
Rafael Espindola10be0832014-03-25 23:44:25 +0000671 MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000672 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000673 SectionIndexMapTy &SectionIndexMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000674 // The string table must be emitted first because we need the index
675 // into the string table for all the symbol names.
676 assert(StringTable.size() && "Missing string table");
677
678 // FIXME: Make sure the start of the symbol table is aligned.
679
Rafael Espindola10be0832014-03-25 23:44:25 +0000680 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
681
Matt Fleming6c1ad482010-08-16 18:57:57 +0000682 // The first entry is the undefined symbol entry.
Rafael Espindola10be0832014-03-25 23:44:25 +0000683 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000684
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000685 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
Rafael Espindola10be0832014-03-25 23:44:25 +0000686 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
687 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000688 }
689
Matt Fleming6c1ad482010-08-16 18:57:57 +0000690 // Write the symbol table entries.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000691 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
692
Matt Fleming6c1ad482010-08-16 18:57:57 +0000693 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
694 ELFSymbolData &MSD = LocalSymbolData[i];
Rafael Espindola10be0832014-03-25 23:44:25 +0000695 WriteSymbol(Writer, MSD, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000696 }
697
Rafael Espindola44bf2662010-09-16 19:46:31 +0000698 // Write out a symbol table entry for each regular section.
Rafael Espindola18014102010-11-10 22:16:43 +0000699 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
700 ++i) {
Eli Friedman1fe0d532010-08-16 21:17:09 +0000701 const MCSectionELF &Section =
Rafael Espindola18014102010-11-10 22:16:43 +0000702 static_cast<const MCSectionELF&>(i->getSection());
703 if (Section.getType() == ELF::SHT_RELA ||
704 Section.getType() == ELF::SHT_REL ||
705 Section.getType() == ELF::SHT_STRTAB ||
Nick Lewycky133a1682011-10-07 23:29:53 +0000706 Section.getType() == ELF::SHT_SYMTAB ||
707 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
Eli Friedman1fe0d532010-08-16 21:17:09 +0000708 continue;
Rafael Espindola10be0832014-03-25 23:44:25 +0000709 Writer.writeSymbol(0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT,
710 SectionIndexMap.lookup(&Section), false);
Eli Friedman1fe0d532010-08-16 21:17:09 +0000711 LastLocalSymbolIndex++;
712 }
Matt Fleming6c1ad482010-08-16 18:57:57 +0000713
714 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
715 ELFSymbolData &MSD = ExternalSymbolData[i];
716 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola83b2a332010-10-06 16:47:31 +0000717 assert(((Data.getFlags() & ELF_STB_Global) ||
718 (Data.getFlags() & ELF_STB_Weak)) &&
719 "External symbol requires STB_GLOBAL or STB_WEAK flag");
Rafael Espindola10be0832014-03-25 23:44:25 +0000720 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000721 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000722 LastLocalSymbolIndex++;
723 }
724
725 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
726 ELFSymbolData &MSD = UndefinedSymbolData[i];
727 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola10be0832014-03-25 23:44:25 +0000728 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000729 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000730 LastLocalSymbolIndex++;
731 }
732}
733
Rafael Espindola5904e122014-03-29 06:26:49 +0000734// It is always valid to create a relocation with a symbol. It is preferable
735// to use a relocation with a section if that is possible. Using the section
736// allows us to omit some local symbols from the symbol table.
737bool ELFObjectWriter::shouldRelocateWithSymbol(const MCSymbolRefExpr *RefA,
738 const MCSymbolData *SD,
739 uint64_t C,
740 unsigned Type) const {
741 // A PCRel relocation to an absolute value has no symbol (or section). We
742 // represent that with a relocation to a null section.
743 if (!RefA)
744 return false;
Rafael Espindola240028d2010-11-14 23:53:26 +0000745
Rafael Espindola5904e122014-03-29 06:26:49 +0000746 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
747 switch (Kind) {
748 default:
749 break;
750 // The .odp creation emits a relocation against the symbol ".TOC." which
751 // create a R_PPC64_TOC relocation. However the relocation symbol name
752 // in final object creation should be NULL, since the symbol does not
753 // really exist, it is just the reference to TOC base for the current
754 // object file. Since the symbol is undefined, returning false results
755 // in a relocation with a null section which is the desired result.
756 case MCSymbolRefExpr::VK_PPC_TOCBASE:
757 return false;
758
759 // These VariantKind cause the relocation to refer to something other than
760 // the symbol itself, like a linker generated table. Since the address of
761 // symbol is not relevant, we cannot replace the symbol with the
762 // section and patch the difference in the addend.
763 case MCSymbolRefExpr::VK_GOT:
764 case MCSymbolRefExpr::VK_PLT:
765 case MCSymbolRefExpr::VK_GOTPCREL:
766 case MCSymbolRefExpr::VK_Mips_GOT:
767 case MCSymbolRefExpr::VK_PPC_GOT_LO:
768 case MCSymbolRefExpr::VK_PPC_GOT_HI:
769 case MCSymbolRefExpr::VK_PPC_GOT_HA:
770 return true;
Rafael Espindola240028d2010-11-14 23:53:26 +0000771 }
Rafael Espindola240028d2010-11-14 23:53:26 +0000772
Rafael Espindola5904e122014-03-29 06:26:49 +0000773 // An undefined symbol is not in any section, so the relocation has to point
774 // to the symbol itself.
775 const MCSymbol &Sym = SD->getSymbol();
776 if (Sym.isUndefined())
777 return true;
778
779 unsigned Binding = MCELF::GetBinding(*SD);
780 switch(Binding) {
781 default:
782 llvm_unreachable("Invalid Binding");
783 case ELF::STB_LOCAL:
784 break;
785 case ELF::STB_WEAK:
786 // If the symbol is weak, it might be overridden by a symbol in another
787 // file. The relocation has to point to the symbol so that the linker
788 // can update it.
789 return true;
790 case ELF::STB_GLOBAL:
791 // Global ELF symbols can be preempted by the dynamic linker. The relocation
792 // has to point to the symbol for a reason analogous to the STB_WEAK case.
793 return true;
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000794 }
Rafael Espindola75d65b92010-09-25 05:42:19 +0000795
Rafael Espindola5904e122014-03-29 06:26:49 +0000796 // If a relocation points to a mergeable section, we have to be careful.
797 // If the offset is zero, a relocation with the section will encode the
798 // same information. With a non-zero offset, the situation is different.
799 // For example, a relocation can point 42 bytes past the end of a string.
800 // If we change such a relocation to use the section, the linker would think
801 // that it pointed to another string and subtracting 42 at runtime will
802 // produce the wrong value.
803 auto &Sec = cast<MCSectionELF>(Sym.getSection());
804 unsigned Flags = Sec.getFlags();
805 if (Flags & ELF::SHF_MERGE) {
806 if (C != 0)
807 return true;
Rafael Espindolab1b49782014-04-02 12:15:20 +0000808
809 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
810 // only handle section relocations to mergeable sections if using RELA.
811 if (!hasRelocationAddend())
812 return true;
Rafael Espindola9f75d5d2010-11-24 21:57:39 +0000813 }
814
Rafael Espindola5904e122014-03-29 06:26:49 +0000815 // Most TLS relocations use a got, so they need the symbol. Even those that
816 // are just an offset (@tpoff), require a symbol in some linkers (gold,
817 // but not bfd ld).
818 if (Flags & ELF::SHF_TLS)
819 return true;
Rafael Espindolad7565c32010-10-05 23:57:26 +0000820
Rafael Espindola9ef84412014-04-11 19:18:01 +0000821 // If the symbol is a thumb function the final relocation must set the lowest
822 // bit. With a symbol that is done by just having the symbol have that bit
823 // set, so we would lose the bit if we relocated with the section.
824 // FIXME: We could use the section but add the bit to the relocation value.
825 if (SD->getFlags() & ELF_Other_ThumbFunc)
826 return true;
827
Rafael Espindola5904e122014-03-29 06:26:49 +0000828 if (TargetObjectWriter->needsRelocateWithSymbol(Type))
829 return true;
830 return false;
Rafael Espindola75d65b92010-09-25 05:42:19 +0000831}
832
Jason W Kim495c2bb2010-12-06 21:57:34 +0000833void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
834 const MCAsmLayout &Layout,
835 const MCFragment *Fragment,
836 const MCFixup &Fixup,
837 MCValue Target,
Rafael Espindola5904e122014-03-29 06:26:49 +0000838 bool &IsPCRel,
Jason W Kim495c2bb2010-12-06 21:57:34 +0000839 uint64_t &FixedValue) {
Rafael Espindola5904e122014-03-29 06:26:49 +0000840 const MCSectionData *FixupSection = Fragment->getParent();
841 uint64_t C = Target.getConstant();
842 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000843
Rafael Espindola5904e122014-03-29 06:26:49 +0000844 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
845 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
846 "Should not have constructed this");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000847
Rafael Espindola5904e122014-03-29 06:26:49 +0000848 // Let A, B and C being the components of Target and R be the location of
849 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
850 // If it is pcrel, we want to compute (A - B + C - R).
Jason W Kim495c2bb2010-12-06 21:57:34 +0000851
Rafael Espindola5904e122014-03-29 06:26:49 +0000852 // In general, ELF has no relocations for -B. It can only represent (A + C)
853 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
854 // replace B to implement it: (A - R - K + C)
855 if (IsPCRel)
856 Asm.getContext().FatalError(
857 Fixup.getLoc(),
858 "No relocation available to represent this relative expression");
David Majnemera45a1762014-01-06 07:39:46 +0000859
Rafael Espindola5904e122014-03-29 06:26:49 +0000860 const MCSymbol &SymB = RefB->getSymbol();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000861
Rafael Espindola5904e122014-03-29 06:26:49 +0000862 if (SymB.isUndefined())
863 Asm.getContext().FatalError(
864 Fixup.getLoc(),
865 Twine("symbol '") + SymB.getName() +
866 "' can not be undefined in a subtraction expression");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000867
Rafael Espindola5904e122014-03-29 06:26:49 +0000868 assert(!SymB.isAbsolute() && "Should have been folded");
869 const MCSection &SecB = SymB.getSection();
870 if (&SecB != &FixupSection->getSection())
871 Asm.getContext().FatalError(
872 Fixup.getLoc(), "Cannot represent a difference across sections");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000873
Rafael Espindola5904e122014-03-29 06:26:49 +0000874 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
875 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
876 uint64_t K = SymBOffset - FixupOffset;
877 IsPCRel = true;
878 C -= K;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000879 }
880
Rafael Espindola5904e122014-03-29 06:26:49 +0000881 // We either rejected the fixup or folded B into C at this point.
882 const MCSymbolRefExpr *RefA = Target.getSymA();
883 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
884 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
885
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000886 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindola5904e122014-03-29 06:26:49 +0000887 bool RelocateWithSymbol = shouldRelocateWithSymbol(RefA, SymAD, C, Type);
888 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
889 C += Layout.getSymbolOffset(SymAD);
890
891 uint64_t Addend = 0;
892 if (hasRelocationAddend()) {
893 Addend = C;
894 C = 0;
895 }
896
897 FixedValue = C;
898
899 // FIXME: What is this!?!?
900 MCSymbolRefExpr::VariantKind Modifier =
901 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
Rafael Espindola9e252bf2011-12-21 14:26:29 +0000902 if (RelocNeedsGOT(Modifier))
903 NeedsGOT = true;
Jan Sjödin30a52de2011-02-28 21:45:04 +0000904
Rafael Espindola5904e122014-03-29 06:26:49 +0000905 if (!RelocateWithSymbol) {
906 const MCSection *SecA =
907 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
908 const MCSectionData *SecAD = SecA ? &Asm.getSectionData(*SecA) : nullptr;
909 ELFRelocationEntry Rec(FixupOffset, SecAD, Type, Addend);
910 Relocations[FixupSection].push_back(Rec);
911 return;
912 }
Roman Divackydfbecd12011-08-04 19:08:19 +0000913
Rafael Espindola5904e122014-03-29 06:26:49 +0000914 if (SymA) {
915 if (const MCSymbol *R = Renames.lookup(SymA))
916 SymA = R;
Rafael Espindolad7facaf2011-08-04 13:05:26 +0000917
Rafael Espindola5904e122014-03-29 06:26:49 +0000918 if (RefA->getKind() == MCSymbolRefExpr::VK_WEAKREF)
919 WeakrefUsedInReloc.insert(SymA);
920 else
921 UsedInReloc.insert(SymA);
922 }
923 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
924 Relocations[FixupSection].push_back(Rec);
925 return;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000926}
927
928
Benjamin Kramer86511dc2010-08-23 21:19:37 +0000929uint64_t
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000930ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
931 const MCSymbol *S) {
David Blaikie908f4d42014-04-24 16:59:40 +0000932 const MCSymbolData &SD = Asm.getSymbolData(*S);
Rafael Espindola0e3decf2010-11-14 03:12:24 +0000933 return SD.getIndex();
Matt Fleming6c1ad482010-08-16 18:57:57 +0000934}
935
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000936bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
937 const MCSymbolData &Data, bool Used,
938 bool Renamed) {
Rafael Espindola7fadc0e2014-03-20 02:12:01 +0000939 const MCSymbol &Symbol = Data.getSymbol();
940 if (Symbol.isVariable()) {
941 const MCExpr *Expr = Symbol.getVariableValue();
942 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
943 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
944 return false;
945 }
946 }
Rafael Espindola16145972010-11-01 14:28:48 +0000947
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000948 if (Used)
949 return true;
950
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000951 if (Renamed)
952 return false;
953
Rafael Espindola45834a02010-10-29 23:09:31 +0000954 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
955 return true;
956
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000957 if (Symbol.isVariable()) {
958 const MCSymbol *Base = getBaseSymbol(Layout, Symbol);
959 if (Base && Base->isUndefined())
960 return false;
961 }
Rafael Espindola9e18e962011-02-23 20:22:07 +0000962
Jan Sjödin30a52de2011-02-28 21:45:04 +0000963 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
Rafael Espindola9e18e962011-02-23 20:22:07 +0000964 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +0000965 return false;
966
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000967 if (Symbol.isTemporary())
Rafael Espindolab1d07892010-10-05 18:01:23 +0000968 return false;
969
970 return true;
971}
972
Rafael Espindola39f50422014-04-28 14:24:44 +0000973bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
Rafael Espindolab1d07892010-10-05 18:01:23 +0000974 if (Data.isExternal())
975 return false;
976
977 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindola39f50422014-04-28 14:24:44 +0000978 if (Symbol.isDefined())
979 return true;
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000980
Rafael Espindola39f50422014-04-28 14:24:44 +0000981 if (isUsedInReloc)
Rafael Espindolab1d07892010-10-05 18:01:23 +0000982 return false;
983
984 return true;
985}
986
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000987void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
Rafael Espindola1557fd62011-03-20 18:44:20 +0000988 SectionIndexMapTy &SectionIndexMap,
989 const RelMapTy &RelMap) {
Rafael Espindolad6340032010-11-10 21:51:05 +0000990 unsigned Index = 1;
991 for (MCAssembler::iterator it = Asm.begin(),
992 ie = Asm.end(); it != ie; ++it) {
993 const MCSectionELF &Section =
994 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000995 if (Section.getType() != ELF::SHT_GROUP)
996 continue;
997 SectionIndexMap[&Section] = Index++;
998 }
999
1000 for (MCAssembler::iterator it = Asm.begin(),
1001 ie = Asm.end(); it != ie; ++it) {
1002 const MCSectionELF &Section =
1003 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001004 if (Section.getType() == ELF::SHT_GROUP ||
1005 Section.getType() == ELF::SHT_REL ||
1006 Section.getType() == ELF::SHT_RELA)
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001007 continue;
Rafael Espindolad6340032010-11-10 21:51:05 +00001008 SectionIndexMap[&Section] = Index++;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001009 const MCSectionELF *RelSection = RelMap.lookup(&Section);
1010 if (RelSection)
1011 SectionIndexMap[RelSection] = Index++;
Rafael Espindolad6340032010-11-10 21:51:05 +00001012 }
1013}
1014
Rafael Espindola022bb762014-03-24 03:43:21 +00001015void
1016ELFObjectWriter::computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
1017 const SectionIndexMapTy &SectionIndexMap,
1018 RevGroupMapTy RevGroupMap,
1019 unsigned NumRegularSections) {
Rafael Espindolad03e81d2010-10-05 15:48:37 +00001020 // FIXME: Is this the correct place to do this?
Rafael Espindola940a0ee2011-06-05 01:20:06 +00001021 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
Rafael Espindolad03e81d2010-10-05 15:48:37 +00001022 if (NeedsGOT) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +00001023 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
Rafael Espindolad03e81d2010-10-05 15:48:37 +00001024 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
1025 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
1026 Data.setExternal(true);
Jan Sjödin30a52de2011-02-28 21:45:04 +00001027 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
Rafael Espindolad03e81d2010-10-05 15:48:37 +00001028 }
1029
Matt Fleming6c1ad482010-08-16 18:57:57 +00001030 // Index 0 is always the empty string.
1031 StringMap<uint64_t> StringIndexMap;
1032 StringTable += '\x00';
1033
Rafael Espindolab80875e2011-04-07 23:21:52 +00001034 // FIXME: We could optimize suffixes in strtab in the same way we
1035 // optimize them in shstrtab.
1036
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +00001037 for (MCAssembler::const_file_name_iterator it = Asm.file_names_begin(),
1038 ie = Asm.file_names_end();
1039 it != ie;
1040 ++it) {
1041 StringRef Name = *it;
1042 uint64_t &Entry = StringIndexMap[Name];
1043 if (!Entry) {
1044 Entry = StringTable.size();
1045 StringTable += Name;
1046 StringTable += '\x00';
1047 }
1048 FileSymbolData.push_back(Entry);
1049 }
1050
Rafael Espindolabee6e9f2010-10-14 16:34:44 +00001051 // Add the data for the symbols.
David Blaikie583a31c2014-04-18 18:24:25 +00001052 for (MCSymbolData &SD : Asm.symbols()) {
1053 const MCSymbol &Symbol = SD.getSymbol();
Matt Fleming6c1ad482010-08-16 18:57:57 +00001054
Rafael Espindola16145972010-11-01 14:28:48 +00001055 bool Used = UsedInReloc.count(&Symbol);
1056 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001057 bool isSignature = RevGroupMap.count(&Symbol);
1058
Rafael Espindola3b5ee552014-04-28 13:39:57 +00001059 if (!isInSymtab(Layout, SD,
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001060 Used || WeakrefUsed || isSignature,
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001061 Renames.count(&Symbol)))
Matt Fleming6c1ad482010-08-16 18:57:57 +00001062 continue;
1063
Matt Fleming6c1ad482010-08-16 18:57:57 +00001064 ELFSymbolData MSD;
David Blaikie583a31c2014-04-18 18:24:25 +00001065 MSD.SymbolData = &SD;
Rafael Espindola022bb762014-03-24 03:43:21 +00001066 const MCSymbol *BaseSymbol = getBaseSymbol(Layout, Symbol);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001067
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001068 // Undefined symbols are global, but this is the first place we
1069 // are able to set it.
Rafael Espindola39f50422014-04-28 14:24:44 +00001070 bool Local = isLocal(SD, Used);
David Blaikie583a31c2014-04-18 18:24:25 +00001071 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
Rafael Espindola022bb762014-03-24 03:43:21 +00001072 assert(BaseSymbol);
David Blaikie583a31c2014-04-18 18:24:25 +00001073 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
Jan Sjödin30a52de2011-02-28 21:45:04 +00001074 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
David Blaikie583a31c2014-04-18 18:24:25 +00001075 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001076 }
1077
Rafael Espindola022bb762014-03-24 03:43:21 +00001078 if (!BaseSymbol) {
1079 MSD.SectionIndex = ELF::SHN_ABS;
David Blaikie583a31c2014-04-18 18:24:25 +00001080 } else if (SD.isCommon()) {
Rafael Espindolabee6e9f2010-10-14 16:34:44 +00001081 assert(!Local);
Rafael Espindolaf0591c12010-09-21 00:24:38 +00001082 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindola022bb762014-03-24 03:43:21 +00001083 } else if (BaseSymbol->isUndefined()) {
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001084 if (isSignature && !Used)
1085 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
1086 else
1087 MSD.SectionIndex = ELF::SHN_UNDEF;
Rafael Espindola022bb762014-03-24 03:43:21 +00001088 if (!Used && WeakrefUsed)
David Blaikie583a31c2014-04-18 18:24:25 +00001089 MCELF::SetBinding(SD, ELF::STB_WEAK);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001090 } else {
Rafael Espindolad6340032010-11-10 21:51:05 +00001091 const MCSectionELF &Section =
Rafael Espindola022bb762014-03-24 03:43:21 +00001092 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
Rafael Espindolad6340032010-11-10 21:51:05 +00001093 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001094 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindolafbcf0db2010-10-15 15:39:06 +00001095 }
1096
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001097 // The @@@ in symbol version is replaced with @ in undefined symbols and
1098 // @@ in defined ones.
1099 StringRef Name = Symbol.getName();
Benjamin Kramerdcc77322010-11-12 19:26:04 +00001100 SmallString<32> Buf;
1101
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001102 size_t Pos = Name.find("@@@");
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001103 if (Pos != StringRef::npos) {
Benjamin Kramerdcc77322010-11-12 19:26:04 +00001104 Buf += Name.substr(0, Pos);
1105 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1106 Buf += Name.substr(Pos + Skip);
1107 Name = Buf;
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001108 }
1109
Benjamin Kramerdcc77322010-11-12 19:26:04 +00001110 uint64_t &Entry = StringIndexMap[Name];
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +00001111 if (!Entry) {
1112 Entry = StringTable.size();
Benjamin Kramerdcc77322010-11-12 19:26:04 +00001113 StringTable += Name;
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +00001114 StringTable += '\x00';
Matt Fleming6c1ad482010-08-16 18:57:57 +00001115 }
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +00001116 MSD.StringIndex = Entry;
1117 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1118 UndefinedSymbolData.push_back(MSD);
1119 else if (Local)
1120 LocalSymbolData.push_back(MSD);
1121 else
1122 ExternalSymbolData.push_back(MSD);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001123 }
1124
1125 // Symbols are required to be in lexicographic order.
1126 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1127 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1128 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1129
1130 // Set the symbol indices. Local symbols must come before all other
1131 // symbols with non-local bindings.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +00001132 unsigned Index = FileSymbolData.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001133 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1134 LocalSymbolData[i].SymbolData->setIndex(Index++);
Rafael Espindola0e3decf2010-11-14 03:12:24 +00001135
1136 Index += NumRegularSections;
1137
Matt Fleming6c1ad482010-08-16 18:57:57 +00001138 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1139 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1140 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1141 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1142}
1143
Rafael Espindola1557fd62011-03-20 18:44:20 +00001144void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
1145 MCAsmLayout &Layout,
1146 RelMapTy &RelMap) {
1147 for (MCAssembler::const_iterator it = Asm.begin(),
1148 ie = Asm.end(); it != ie; ++it) {
1149 const MCSectionData &SD = *it;
1150 if (Relocations[&SD].empty())
1151 continue;
1152
Matt Fleming6c1ad482010-08-16 18:57:57 +00001153 MCContext &Ctx = Asm.getContext();
Matt Fleming6c1ad482010-08-16 18:57:57 +00001154 const MCSectionELF &Section =
1155 static_cast<const MCSectionELF&>(SD.getSection());
1156
1157 const StringRef SectionName = Section.getSectionName();
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001158 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
Matt Fleming6c1ad482010-08-16 18:57:57 +00001159 RelaSectionName += SectionName;
Benjamin Kramerfd054152010-08-17 17:56:13 +00001160
1161 unsigned EntrySize;
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001162 if (hasRelocationAddend())
1163 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
Benjamin Kramerfd054152010-08-17 17:56:13 +00001164 else
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001165 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001166
Tim Northovera630fb02013-07-10 20:58:17 +00001167 unsigned Flags = 0;
1168 StringRef Group = "";
1169 if (Section.getFlags() & ELF::SHF_GROUP) {
David Blaikie1e412ea2013-10-22 20:34:30 +00001170 Flags = ELF::SHF_GROUP;
1171 Group = Section.getGroup()->getName();
Tim Northovera630fb02013-07-10 20:58:17 +00001172 }
1173
Rafael Espindola1557fd62011-03-20 18:44:20 +00001174 const MCSectionELF *RelaSection =
1175 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
Tim Northovera630fb02013-07-10 20:58:17 +00001176 ELF::SHT_RELA : ELF::SHT_REL, Flags,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001177 SectionKind::getReadOnly(),
Tim Northovera630fb02013-07-10 20:58:17 +00001178 EntrySize, Group);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001179 RelMap[&Section] = RelaSection;
1180 Asm.getOrCreateSectionData(*RelaSection);
1181 }
1182}
Matt Fleming6c1ad482010-08-16 18:57:57 +00001183
David Blaikiee06e8012014-04-11 22:11:50 +00001184static SmallVector<char, 128>
1185getUncompressedData(MCAsmLayout &Layout,
1186 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001187 SmallVector<char, 128> UncompressedData;
1188 for (const MCFragment &F : Fragments) {
1189 const SmallVectorImpl<char> *Contents;
1190 switch (F.getKind()) {
1191 case MCFragment::FT_Data:
1192 Contents = &cast<MCDataFragment>(F).getContents();
1193 break;
1194 case MCFragment::FT_Dwarf:
1195 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1196 break;
1197 case MCFragment::FT_DwarfFrame:
1198 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1199 break;
1200 default:
1201 llvm_unreachable(
1202 "Not expecting any other fragment types in a debug_* section");
1203 }
1204 UncompressedData.append(Contents->begin(), Contents->end());
1205 }
1206 return UncompressedData;
1207}
1208
1209// Include the debug info compression header:
1210// "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1211// useful for consumers to preallocate a buffer to decompress into.
David Blaikie76d3a3c2014-04-18 21:52:26 +00001212static bool
David Blaikiee06e8012014-04-11 22:11:50 +00001213prependCompressionHeader(uint64_t Size,
1214 SmallVectorImpl<char> &CompressedContents) {
David Blaikie8019bf82014-04-10 21:53:53 +00001215 static const StringRef Magic = "ZLIB";
David Blaikie76d3a3c2014-04-18 21:52:26 +00001216 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1217 return false;
David Blaikie8019bf82014-04-10 21:53:53 +00001218 if (sys::IsLittleEndianHost)
1219 Size = sys::SwapByteOrder(Size);
1220 CompressedContents.insert(CompressedContents.begin(),
1221 Magic.size() + sizeof(Size), 0);
1222 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1223 std::copy(reinterpret_cast<char *>(&Size),
1224 reinterpret_cast<char *>(&Size + 1),
1225 CompressedContents.begin() + Magic.size());
David Blaikie76d3a3c2014-04-18 21:52:26 +00001226 return true;
David Blaikie8019bf82014-04-10 21:53:53 +00001227}
1228
1229// Return a single fragment containing the compressed contents of the whole
1230// section. Null if the section was not compressed for any reason.
David Blaikiee06e8012014-04-11 22:11:50 +00001231static std::unique_ptr<MCDataFragment>
1232getCompressedFragment(MCAsmLayout &Layout,
1233 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001234 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1235
1236 // Gather the uncompressed data from all the fragments, recording the
1237 // alignment fragment, if seen, and any fixups.
1238 SmallVector<char, 128> UncompressedData =
1239 getUncompressedData(Layout, Fragments);
1240
1241 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1242
1243 zlib::Status Success = zlib::compress(
1244 StringRef(UncompressedData.data(), UncompressedData.size()),
1245 CompressedContents);
1246 if (Success != zlib::StatusOK)
1247 return nullptr;
1248
David Blaikie76d3a3c2014-04-18 21:52:26 +00001249 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1250 return nullptr;
David Blaikie8019bf82014-04-10 21:53:53 +00001251
1252 return CompressedFragment;
1253}
1254
David Blaikie39fa6a22014-04-25 00:48:01 +00001255typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1256DefiningSymbolMap;
1257
1258static void UpdateSymbols(const MCAsmLayout &Layout,
1259 const std::vector<MCSymbolData *> &Symbols,
1260 MCFragment &NewFragment) {
1261 for (MCSymbolData *Sym : Symbols) {
1262 Sym->setOffset(Sym->getOffset() +
1263 Layout.getFragmentOffset(Sym->getFragment()));
1264 Sym->setFragment(&NewFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001265 }
1266}
1267
David Blaikie8019bf82014-04-10 21:53:53 +00001268static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
David Blaikie39fa6a22014-04-25 00:48:01 +00001269 const DefiningSymbolMap &DefiningSymbols,
David Blaikie8019bf82014-04-10 21:53:53 +00001270 const MCSectionELF &Section,
1271 MCSectionData &SD) {
1272 StringRef SectionName = Section.getSectionName();
1273 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1274
1275 std::unique_ptr<MCDataFragment> CompressedFragment =
1276 getCompressedFragment(Layout, Fragments);
1277
1278 // Leave the section as-is if the fragments could not be compressed.
1279 if (!CompressedFragment)
1280 return;
1281
David Blaikiec029ab42014-04-18 21:24:12 +00001282 // Update the fragment+offsets of any symbols referring to fragments in this
1283 // section to refer to the new fragment.
David Blaikie39fa6a22014-04-25 00:48:01 +00001284 auto I = DefiningSymbols.find(&SD);
1285 if (I != DefiningSymbols.end())
1286 UpdateSymbols(Layout, I->second, *CompressedFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001287
David Blaikie8019bf82014-04-10 21:53:53 +00001288 // Invalidate the layout for the whole section since it will have new and
1289 // different fragments now.
1290 Layout.invalidateFragmentsFrom(&Fragments.front());
1291 Fragments.clear();
1292
1293 // Complete the initialization of the new fragment
1294 CompressedFragment->setParent(&SD);
1295 CompressedFragment->setLayoutOrder(0);
1296 Fragments.push_back(CompressedFragment.release());
1297
1298 // Rename from .debug_* to .zdebug_*
1299 Asm.getContext().renameELFSection(&Section,
1300 (".z" + SectionName.drop_front(1)).str());
1301}
1302
1303void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1304 MCAsmLayout &Layout) {
1305 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1306 return;
1307
David Blaikie39fa6a22014-04-25 00:48:01 +00001308 DefiningSymbolMap DefiningSymbols;
1309
1310 for (MCSymbolData &SD : Asm.symbols())
1311 if (MCFragment *F = SD.getFragment())
1312 DefiningSymbols[F->getParent()].push_back(&SD);
1313
David Blaikie8019bf82014-04-10 21:53:53 +00001314 for (MCSectionData &SD : Asm) {
David Blaikiee06e8012014-04-11 22:11:50 +00001315 const MCSectionELF &Section =
1316 static_cast<const MCSectionELF &>(SD.getSection());
David Blaikie8019bf82014-04-10 21:53:53 +00001317 StringRef SectionName = Section.getSectionName();
1318
1319 // Compressing debug_frame requires handling alignment fragments which is
1320 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1321 // for writing to arbitrary buffers) for little benefit.
1322 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1323 continue;
1324
David Blaikie39fa6a22014-04-25 00:48:01 +00001325 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
David Blaikie8019bf82014-04-10 21:53:53 +00001326 }
1327}
1328
Rafael Espindola1557fd62011-03-20 18:44:20 +00001329void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1330 const RelMapTy &RelMap) {
1331 for (MCAssembler::const_iterator it = Asm.begin(),
1332 ie = Asm.end(); it != ie; ++it) {
1333 const MCSectionData &SD = *it;
1334 const MCSectionELF &Section =
1335 static_cast<const MCSectionELF&>(SD.getSection());
1336
1337 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1338 if (!RelaSection)
1339 continue;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001340 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001341 RelaSD.setAlignment(is64Bit() ? 8 : 4);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001342
1343 MCDataFragment *F = new MCDataFragment(&RelaSD);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001344 WriteRelocationsFragment(Asm, F, &*it);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001345 }
1346}
1347
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001348void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1349 uint64_t Flags, uint64_t Address,
1350 uint64_t Offset, uint64_t Size,
1351 uint32_t Link, uint32_t Info,
1352 uint64_t Alignment,
1353 uint64_t EntrySize) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001354 Write32(Name); // sh_name: index into string table
1355 Write32(Type); // sh_type
1356 WriteWord(Flags); // sh_flags
1357 WriteWord(Address); // sh_addr
1358 WriteWord(Offset); // sh_offset
1359 WriteWord(Size); // sh_size
1360 Write32(Link); // sh_link
1361 Write32(Info); // sh_info
1362 WriteWord(Alignment); // sh_addralign
1363 WriteWord(EntrySize); // sh_entsize
1364}
1365
Rafael Espindola5904e122014-03-29 06:26:49 +00001366// ELF doesn't require relocations to be in any order. We sort by the r_offset,
1367// just to match gnu as for easier comparison. The use type is an arbitrary way
1368// of making the sort deterministic.
1369static int cmpRel(const ELFRelocationEntry *AP, const ELFRelocationEntry *BP) {
1370 const ELFRelocationEntry &A = *AP;
1371 const ELFRelocationEntry &B = *BP;
1372 if (A.Offset != B.Offset)
1373 return B.Offset - A.Offset;
1374 if (B.Type != A.Type)
1375 return A.Type - B.Type;
1376 llvm_unreachable("ELFRelocs might be unstable!");
1377}
1378
1379static void sortRelocs(const MCAssembler &Asm,
1380 std::vector<ELFRelocationEntry> &Relocs) {
1381 array_pod_sort(Relocs.begin(), Relocs.end(), cmpRel);
1382}
1383
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001384void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1385 MCDataFragment *F,
1386 const MCSectionData *SD) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001387 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
Akira Hatanaka64ad2cf2012-03-23 23:06:45 +00001388
Rafael Espindola5904e122014-03-29 06:26:49 +00001389 sortRelocs(Asm, Relocs);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001390
1391 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001392 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
Matt Fleming6c1ad482010-08-16 18:57:57 +00001393
Rafael Espindola5904e122014-03-29 06:26:49 +00001394 unsigned Index;
1395 if (Entry.UseSymbol) {
1396 Index = getSymbolIndexInSymbolTable(Asm, Entry.Symbol);
1397 } else {
1398 const MCSectionData *Sec = Entry.Section;
1399 if (Sec)
1400 Index = Sec->getOrdinal() + FileSymbolData.size() +
1401 LocalSymbolData.size() + 1;
1402 else
1403 Index = 0;
1404 }
1405
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001406 if (is64Bit()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001407 write(*F, Entry.Offset);
Jack Carter8ad0c272012-06-27 22:28:30 +00001408 if (TargetObjectWriter->isN64()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001409 write(*F, uint32_t(Index));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001410
Rafael Espindola5904e122014-03-29 06:26:49 +00001411 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1412 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1413 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1414 write(*F, TargetObjectWriter->getRType(Entry.Type));
1415 } else {
Jack Carter8ad0c272012-06-27 22:28:30 +00001416 struct ELF::Elf64_Rela ERE64;
Rafael Espindola5904e122014-03-29 06:26:49 +00001417 ERE64.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001418 write(*F, ERE64.r_info);
Jack Carter8ad0c272012-06-27 22:28:30 +00001419 }
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001420 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001421 write(*F, Entry.Addend);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001422 } else {
Rafael Espindola5904e122014-03-29 06:26:49 +00001423 write(*F, uint32_t(Entry.Offset));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001424
Rafael Espindolabce26a12010-10-05 15:11:03 +00001425 struct ELF::Elf32_Rela ERE32;
Rafael Espindola5904e122014-03-29 06:26:49 +00001426 ERE32.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001427 write(*F, ERE32.r_info);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001428
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001429 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001430 write(*F, uint32_t(Entry.Addend));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001431 }
Matt Fleming6c1ad482010-08-16 18:57:57 +00001432 }
1433}
1434
Benjamin Kramer8817cca2013-09-22 14:09:50 +00001435static int compareBySuffix(const MCSectionELF *const *a,
1436 const MCSectionELF *const *b) {
1437 const StringRef &NameA = (*a)->getSectionName();
1438 const StringRef &NameB = (*b)->getSectionName();
Rafael Espindolab80875e2011-04-07 23:21:52 +00001439 const unsigned sizeA = NameA.size();
1440 const unsigned sizeB = NameB.size();
1441 const unsigned len = std::min(sizeA, sizeB);
1442 for (unsigned int i = 0; i < len; ++i) {
1443 char ca = NameA[sizeA - i - 1];
1444 char cb = NameB[sizeB - i - 1];
1445 if (ca != cb)
1446 return cb - ca;
1447 }
1448
1449 return sizeB - sizeA;
1450}
1451
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001452void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1453 MCAsmLayout &Layout,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001454 SectionIndexMapTy &SectionIndexMap,
1455 const RelMapTy &RelMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001456 MCContext &Ctx = Asm.getContext();
1457 MCDataFragment *F;
1458
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001459 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001460
Rafael Espindola0e527b72010-09-22 19:04:41 +00001461 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001462 const MCSectionELF *ShstrtabSection =
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001463 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
Rafael Espindola19fa3802010-11-11 03:40:25 +00001464 SectionKind::getReadOnly());
Rafael Espindola44bf2662010-09-16 19:46:31 +00001465 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1466 ShstrtabSD.setAlignment(1);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001467
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001468 const MCSectionELF *SymtabSection =
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001469 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1470 SectionKind::getReadOnly(),
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001471 EntrySize, "");
Matt Fleming6c1ad482010-08-16 18:57:57 +00001472 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001473 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001474
Rafael Espindola1557fd62011-03-20 18:44:20 +00001475 const MCSectionELF *StrtabSection;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001476 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
Rafael Espindola19fa3802010-11-11 03:40:25 +00001477 SectionKind::getReadOnly());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001478 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1479 StrtabSD.setAlignment(1);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001480
Rafael Espindola1557fd62011-03-20 18:44:20 +00001481 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1482
1483 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1484 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1485 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001486
1487 // Symbol table
1488 F = new MCDataFragment(&SymtabSD);
Rafael Espindola10be0832014-03-25 23:44:25 +00001489 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001490
Matt Fleming6c1ad482010-08-16 18:57:57 +00001491 F = new MCDataFragment(&StrtabSD);
1492 F->getContents().append(StringTable.begin(), StringTable.end());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001493
Matt Fleming6c1ad482010-08-16 18:57:57 +00001494 F = new MCDataFragment(&ShstrtabSD);
1495
Rafael Espindolab80875e2011-04-07 23:21:52 +00001496 std::vector<const MCSectionELF*> Sections;
1497 for (MCAssembler::const_iterator it = Asm.begin(),
1498 ie = Asm.end(); it != ie; ++it) {
1499 const MCSectionELF &Section =
1500 static_cast<const MCSectionELF&>(it->getSection());
1501 Sections.push_back(&Section);
1502 }
1503 array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
1504
Matt Fleming6c1ad482010-08-16 18:57:57 +00001505 // Section header string table.
1506 //
1507 // The first entry of a string table holds a null character so skip
1508 // section 0.
1509 uint64_t Index = 1;
Eli Bendersky84b2a792012-12-07 22:06:56 +00001510 F->getContents().push_back('\x00');
Matt Fleming6c1ad482010-08-16 18:57:57 +00001511
Rafael Espindolab80875e2011-04-07 23:21:52 +00001512 for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
1513 const MCSectionELF &Section = *Sections[I];
Matt Fleming6c1ad482010-08-16 18:57:57 +00001514
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001515 StringRef Name = Section.getSectionName();
Rafael Espindolab80875e2011-04-07 23:21:52 +00001516 if (I != 0) {
1517 StringRef PreviousName = Sections[I - 1]->getSectionName();
1518 if (PreviousName.endswith(Name)) {
1519 SectionStringTableIndex[&Section] = Index - Name.size() - 1;
1520 continue;
1521 }
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001522 }
Matt Fleming6c1ad482010-08-16 18:57:57 +00001523 // Remember the index into the string table so we can write it
1524 // into the sh_name field of the section header table.
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001525 SectionStringTableIndex[&Section] = Index;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001526
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001527 Index += Name.size() + 1;
Eli Bendersky84b2a792012-12-07 22:06:56 +00001528 F->getContents().append(Name.begin(), Name.end());
1529 F->getContents().push_back('\x00');
Matt Fleming6c1ad482010-08-16 18:57:57 +00001530 }
Rafael Espindola2ebaee92010-09-30 02:22:20 +00001531}
1532
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001533void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1534 MCAsmLayout &Layout,
1535 GroupMapTy &GroupMap,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001536 RevGroupMapTy &RevGroupMap,
1537 SectionIndexMapTy &SectionIndexMap,
1538 const RelMapTy &RelMap) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001539 // Create the .note.GNU-stack section if needed.
1540 MCContext &Ctx = Asm.getContext();
1541 if (Asm.getNoExecStack()) {
1542 const MCSectionELF *GnuStackSection =
1543 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1544 SectionKind::getReadOnly());
1545 Asm.getOrCreateSectionData(*GnuStackSection);
1546 }
1547
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001548 // Build the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001549 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1550 it != ie; ++it) {
1551 const MCSectionELF &Section =
1552 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001553 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001554 continue;
1555
1556 const MCSymbol *SignatureSymbol = Section.getGroup();
1557 Asm.getOrCreateSymbolData(*SignatureSymbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001558 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001559 if (!Group) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001560 Group = Ctx.CreateELFGroupSection();
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001561 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1562 Data.setAlignment(4);
1563 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001564 write(*F, uint32_t(ELF::GRP_COMDAT));
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001565 }
1566 GroupMap[Group] = SignatureSymbol;
1567 }
1568
Rafael Espindola1557fd62011-03-20 18:44:20 +00001569 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1570
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001571 // Add sections to the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001572 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
Rafael Espindola1557fd62011-03-20 18:44:20 +00001573 it != ie; ++it) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001574 const MCSectionELF &Section =
1575 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001576 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001577 continue;
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001578 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001579 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1580 // FIXME: we could use the previous fragment
1581 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001582 uint32_t Index = SectionIndexMap.lookup(&Section);
1583 write(*F, Index);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001584 }
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001585}
1586
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001587void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1588 const SectionIndexMapTy &SectionIndexMap,
1589 uint32_t GroupSymbolIndex,
1590 uint64_t Offset, uint64_t Size,
1591 uint64_t Alignment,
1592 const MCSectionELF &Section) {
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001593 uint64_t sh_link = 0;
1594 uint64_t sh_info = 0;
1595
1596 switch(Section.getType()) {
1597 case ELF::SHT_DYNAMIC:
1598 sh_link = SectionStringTableIndex[&Section];
1599 sh_info = 0;
1600 break;
1601
1602 case ELF::SHT_REL:
1603 case ELF::SHT_RELA: {
1604 const MCSectionELF *SymtabSection;
1605 const MCSectionELF *InfoSection;
1606 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1607 0,
Rafael Espindola19fa3802010-11-11 03:40:25 +00001608 SectionKind::getReadOnly());
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001609 sh_link = SectionIndexMap.lookup(SymtabSection);
1610 assert(sh_link && ".symtab not found");
1611
1612 // Remove ".rel" and ".rela" prefixes.
1613 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1614 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
David Blaikie15b25df2013-10-22 23:41:52 +00001615 StringRef GroupName =
1616 Section.getGroup() ? Section.getGroup()->getName() : "";
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001617
David Blaikie15b25df2013-10-22 23:41:52 +00001618 InfoSection = Asm.getContext().getELFSection(SectionName, ELF::SHT_PROGBITS,
1619 0, SectionKind::getReadOnly(),
1620 0, GroupName);
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001621 sh_info = SectionIndexMap.lookup(InfoSection);
1622 break;
1623 }
1624
1625 case ELF::SHT_SYMTAB:
1626 case ELF::SHT_DYNSYM:
1627 sh_link = StringTableIndex;
1628 sh_info = LastLocalSymbolIndex;
1629 break;
1630
1631 case ELF::SHT_SYMTAB_SHNDX:
1632 sh_link = SymbolTableIndex;
1633 break;
1634
1635 case ELF::SHT_PROGBITS:
1636 case ELF::SHT_STRTAB:
1637 case ELF::SHT_NOBITS:
Rafael Espindola9ae2d052010-12-26 21:30:59 +00001638 case ELF::SHT_NOTE:
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001639 case ELF::SHT_NULL:
1640 case ELF::SHT_ARM_ATTRIBUTES:
Jason W Kim9c5b65d2011-01-12 00:19:25 +00001641 case ELF::SHT_INIT_ARRAY:
1642 case ELF::SHT_FINI_ARRAY:
1643 case ELF::SHT_PREINIT_ARRAY:
Rafael Espindola4b7b7fb2011-01-23 05:43:40 +00001644 case ELF::SHT_X86_64_UNWIND:
Jack Carterc1b17ed2013-01-18 21:20:38 +00001645 case ELF::SHT_MIPS_REGINFO:
1646 case ELF::SHT_MIPS_OPTIONS:
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001647 // Nothing to do.
1648 break;
1649
Nick Lewyckyc6ac5f72011-10-07 23:28:32 +00001650 case ELF::SHT_GROUP:
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001651 sh_link = SymbolTableIndex;
1652 sh_info = GroupSymbolIndex;
1653 break;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001654
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001655 default:
1656 assert(0 && "FIXME: sh_type value not supported!");
1657 break;
1658 }
1659
Logan Chien4b724422013-02-05 14:18:59 +00001660 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1661 Section.getType() == ELF::SHT_ARM_EXIDX) {
1662 StringRef SecName(Section.getSectionName());
1663 if (SecName == ".ARM.exidx") {
1664 sh_link = SectionIndexMap.lookup(
1665 Asm.getContext().getELFSection(".text",
1666 ELF::SHT_PROGBITS,
1667 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC,
1668 SectionKind::getText()));
1669 } else if (SecName.startswith(".ARM.exidx")) {
David Blaikie15b25df2013-10-22 23:41:52 +00001670 StringRef GroupName =
1671 Section.getGroup() ? Section.getGroup()->getName() : "";
1672 sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1673 SecName.substr(sizeof(".ARM.exidx") - 1), ELF::SHT_PROGBITS,
1674 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC, SectionKind::getText(), 0,
1675 GroupName));
Logan Chien4b724422013-02-05 14:18:59 +00001676 }
1677 }
1678
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001679 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1680 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1681 Alignment, Section.getEntrySize());
1682}
1683
Jan Sjödin30a52de2011-02-28 21:45:04 +00001684bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
Rafael Espindolabaf2f3b2010-12-06 03:48:09 +00001685 return SD.getOrdinal() == ~UINT32_C(0) &&
Rafael Espindola60ebca92010-12-02 03:09:06 +00001686 !SD.getSection().isVirtualSection();
1687}
1688
Jan Sjödin30a52de2011-02-28 21:45:04 +00001689uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001690 uint64_t Ret = 0;
1691 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1692 ++i) {
1693 const MCFragment &F = *i;
1694 assert(F.getKind() == MCFragment::FT_Data);
1695 Ret += cast<MCDataFragment>(F).getContents().size();
1696 }
1697 return Ret;
1698}
1699
Jan Sjödin30a52de2011-02-28 21:45:04 +00001700uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1701 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001702 if (IsELFMetaDataSection(SD))
1703 return DataSectionSize(SD);
1704 return Layout.getSectionFileSize(&SD);
1705}
1706
Jan Sjödin30a52de2011-02-28 21:45:04 +00001707uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1708 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001709 if (IsELFMetaDataSection(SD))
1710 return DataSectionSize(SD);
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001711 return Layout.getSectionAddressSize(&SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001712}
1713
Rafael Espindola1557fd62011-03-20 18:44:20 +00001714void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1715 const MCAsmLayout &Layout,
1716 const MCSectionELF &Section) {
Rafael Espindola1557fd62011-03-20 18:44:20 +00001717 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1718
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001719 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001720 WriteZeros(Padding);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001721
1722 if (IsELFMetaDataSection(SD)) {
1723 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1724 ++i) {
1725 const MCFragment &F = *i;
1726 assert(F.getKind() == MCFragment::FT_Data);
Eli Bendersky84b2a792012-12-07 22:06:56 +00001727 WriteBytes(cast<MCDataFragment>(F).getContents());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001728 }
1729 } else {
Jim Grosbach18e2fe42011-12-06 00:03:48 +00001730 Asm.writeSectionData(&SD, Layout);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001731 }
1732}
1733
Rafael Espindola1557fd62011-03-20 18:44:20 +00001734void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1735 const GroupMapTy &GroupMap,
1736 const MCAsmLayout &Layout,
1737 const SectionIndexMapTy &SectionIndexMap,
1738 const SectionOffsetMapTy &SectionOffsetMap) {
1739 const unsigned NumSections = Asm.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001740
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001741 std::vector<const MCSectionELF*> Sections;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001742 Sections.resize(NumSections - 1);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001743
1744 for (SectionIndexMapTy::const_iterator i=
1745 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1746 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001747 Sections[p.second - 1] = p.first;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001748 }
1749
Matt Fleming6c1ad482010-08-16 18:57:57 +00001750 // Null section first.
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001751 uint64_t FirstSectionSize =
1752 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1753 uint32_t FirstSectionLink =
1754 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1755 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001756
Rafael Espindola1557fd62011-03-20 18:44:20 +00001757 for (unsigned i = 0; i < NumSections - 1; ++i) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001758 const MCSectionELF &Section = *Sections[i];
1759 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1760 uint32_t GroupSymbolIndex;
1761 if (Section.getType() != ELF::SHT_GROUP)
1762 GroupSymbolIndex = 0;
1763 else
Rafael Espindola1557fd62011-03-20 18:44:20 +00001764 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1765 GroupMap.lookup(&Section));
Matt Fleming6c1ad482010-08-16 18:57:57 +00001766
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001767 uint64_t Size = GetSectionAddressSize(Layout, SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001768
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001769 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001770 SectionOffsetMap.lookup(&Section), Size,
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001771 SD.getAlignment(), Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001772 }
1773}
1774
Rafael Espindola1557fd62011-03-20 18:44:20 +00001775void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1776 std::vector<const MCSectionELF*> &Sections) {
1777 for (MCAssembler::iterator it = Asm.begin(),
1778 ie = Asm.end(); it != ie; ++it) {
1779 const MCSectionELF &Section =
1780 static_cast<const MCSectionELF &>(it->getSection());
1781 if (Section.getType() == ELF::SHT_GROUP)
1782 Sections.push_back(&Section);
1783 }
1784
1785 for (MCAssembler::iterator it = Asm.begin(),
1786 ie = Asm.end(); it != ie; ++it) {
1787 const MCSectionELF &Section =
1788 static_cast<const MCSectionELF &>(it->getSection());
1789 if (Section.getType() != ELF::SHT_GROUP &&
1790 Section.getType() != ELF::SHT_REL &&
1791 Section.getType() != ELF::SHT_RELA)
1792 Sections.push_back(&Section);
1793 }
1794
1795 for (MCAssembler::iterator it = Asm.begin(),
1796 ie = Asm.end(); it != ie; ++it) {
1797 const MCSectionELF &Section =
1798 static_cast<const MCSectionELF &>(it->getSection());
1799 if (Section.getType() == ELF::SHT_REL ||
1800 Section.getType() == ELF::SHT_RELA)
1801 Sections.push_back(&Section);
1802 }
1803}
1804
1805void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1806 const MCAsmLayout &Layout) {
1807 GroupMapTy GroupMap;
1808 RevGroupMapTy RevGroupMap;
1809 SectionIndexMapTy SectionIndexMap;
1810
1811 unsigned NumUserSections = Asm.size();
1812
David Blaikiee06e8012014-04-11 22:11:50 +00001813 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
David Blaikie8019bf82014-04-10 21:53:53 +00001814
Rafael Espindola1557fd62011-03-20 18:44:20 +00001815 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1816 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1817
1818 const unsigned NumUserAndRelocSections = Asm.size();
1819 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1820 RevGroupMap, SectionIndexMap, RelMap);
1821 const unsigned AllSections = Asm.size();
1822 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1823
1824 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1825
1826 // Compute symbol table information.
Rafael Espindola022bb762014-03-24 03:43:21 +00001827 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1828 NumRegularSections);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001829
1830 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1831
1832 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1833 const_cast<MCAsmLayout&>(Layout),
1834 SectionIndexMap,
1835 RelMap);
1836
1837 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1838 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1839 sizeof(ELF::Elf32_Ehdr);
1840 uint64_t FileOff = HeaderSize;
1841
1842 std::vector<const MCSectionELF*> Sections;
1843 ComputeSectionOrder(Asm, Sections);
1844 unsigned NumSections = Sections.size();
1845 SectionOffsetMapTy SectionOffsetMap;
1846 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1847 const MCSectionELF &Section = *Sections[i];
1848 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1849
1850 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1851
1852 // Remember the offset into the file for this section.
1853 SectionOffsetMap[&Section] = FileOff;
1854
1855 // Get the size of the section in the output file (including padding).
1856 FileOff += GetSectionFileSize(Layout, SD);
1857 }
1858
1859 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1860
1861 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1862
1863 uint64_t SectionHeaderEntrySize = is64Bit() ?
1864 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1865 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1866
1867 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1868 const MCSectionELF &Section = *Sections[i];
1869 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1870
1871 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1872
1873 // Remember the offset into the file for this section.
1874 SectionOffsetMap[&Section] = FileOff;
1875
1876 // Get the size of the section in the output file (including padding).
1877 FileOff += GetSectionFileSize(Layout, SD);
1878 }
1879
1880 // Write out the ELF header ...
Jack Carter1bd90ff2013-01-30 02:09:52 +00001881 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001882
1883 // ... then the regular sections ...
1884 // + because of .shstrtab
1885 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1886 WriteDataSectionData(Asm, Layout, *Sections[i]);
1887
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001888 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001889 WriteZeros(Padding);
1890
1891 // ... then the section header table ...
1892 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1893 SectionOffsetMap);
1894
Nick Lewycky4eb11432011-10-07 20:56:23 +00001895 // ... and then the remaining sections ...
Rafael Espindola1557fd62011-03-20 18:44:20 +00001896 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1897 WriteDataSectionData(Asm, Layout, *Sections[i]);
1898}
1899
Eli Friedmand92d17b2011-03-03 07:24:36 +00001900bool
1901ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1902 const MCSymbolData &DataA,
1903 const MCFragment &FB,
1904 bool InSet,
1905 bool IsPCRel) const {
Roman Divackyfb4d3902014-01-08 18:50:32 +00001906 if (DataA.getFlags() & ELF_STB_Weak || MCELF::GetType(DataA) == ELF::STT_GNU_IFUNC)
Eli Friedmand92d17b2011-03-03 07:24:36 +00001907 return false;
1908 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1909 Asm, DataA, FB,InSet, IsPCRel);
1910}
1911
Rafael Espindola6b5e56c2010-12-17 17:45:22 +00001912MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1913 raw_ostream &OS,
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001914 bool IsLittleEndian) {
Rafael Espindola34a68af2011-12-22 03:24:43 +00001915 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
Rafael Espindolab264d332011-12-21 17:30:17 +00001916}