blob: 4adc188b6166b60a8d01e55614ddeeaf9a0ae1dd [file] [log] [blame]
Matt Fleming3565a062010-08-16 18:57:57 +00001//===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -------------------===//
2//
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
14#include "llvm/MC/ELFObjectWriter.h"
Rafael Espindola8f413fa2010-10-05 15:11:03 +000015#include "llvm/ADT/SmallPtrSet.h"
Matt Fleming3565a062010-08-16 18:57:57 +000016#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/StringMap.h"
18#include "llvm/ADT/Twine.h"
19#include "llvm/MC/MCAssembler.h"
20#include "llvm/MC/MCAsmLayout.h"
21#include "llvm/MC/MCContext.h"
22#include "llvm/MC/MCELFSymbolFlags.h"
23#include "llvm/MC/MCExpr.h"
24#include "llvm/MC/MCObjectWriter.h"
25#include "llvm/MC/MCSectionELF.h"
26#include "llvm/MC/MCSymbol.h"
27#include "llvm/MC/MCValue.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/ELF.h"
31#include "llvm/Target/TargetAsmBackend.h"
32
33#include "../Target/X86/X86FixupKinds.h"
34
35#include <vector>
36using namespace llvm;
37
Rafael Espindolaad49cf52010-09-18 15:03:21 +000038static unsigned GetType(const MCSymbolData &SD) {
39 uint32_t Type = (SD.getFlags() & (0xf << ELF_STT_Shift)) >> ELF_STT_Shift;
40 assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
41 Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
42 Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
43 Type == ELF::STT_TLS);
44 return Type;
45}
46
Rafael Espindolae15eb4e2010-09-23 19:55:14 +000047static unsigned GetBinding(const MCSymbolData &SD) {
48 uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
49 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
50 Binding == ELF::STB_WEAK);
51 return Binding;
52}
53
54static void SetBinding(MCSymbolData &SD, unsigned Binding) {
55 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
56 Binding == ELF::STB_WEAK);
57 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
58 SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
59}
60
Rafael Espindola152c1062010-10-06 21:02:29 +000061static unsigned GetVisibility(MCSymbolData &SD) {
62 unsigned Visibility =
63 (SD.getFlags() & (0xf << ELF_STV_Shift)) >> ELF_STV_Shift;
64 assert(Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_INTERNAL ||
65 Visibility == ELF::STV_HIDDEN || Visibility == ELF::STV_PROTECTED);
66 return Visibility;
67}
68
Rafael Espindolacebdc012010-10-04 19:46:28 +000069static bool isFixupKindX86PCRel(unsigned Kind) {
70 switch (Kind) {
71 default:
72 return false;
73 case X86::reloc_pcrel_1byte:
74 case X86::reloc_pcrel_4byte:
75 case X86::reloc_riprel_4byte:
76 case X86::reloc_riprel_4byte_movq_load:
77 return true;
78 }
79}
80
Rafael Espindolaa0a2f872010-10-28 14:22:44 +000081static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
82 switch (Variant) {
Rafael Espindola5c77c162010-10-05 15:48:37 +000083 default:
84 return false;
Rafael Espindolaa0a2f872010-10-28 14:22:44 +000085 case MCSymbolRefExpr::VK_GOT:
86 case MCSymbolRefExpr::VK_PLT:
87 case MCSymbolRefExpr::VK_GOTPCREL:
88 case MCSymbolRefExpr::VK_TPOFF:
89 case MCSymbolRefExpr::VK_TLSGD:
90 case MCSymbolRefExpr::VK_GOTTPOFF:
91 case MCSymbolRefExpr::VK_INDNTPOFF:
92 case MCSymbolRefExpr::VK_NTPOFF:
93 case MCSymbolRefExpr::VK_GOTNTPOFF:
Rafael Espindolaa264f722010-10-28 14:37:09 +000094 case MCSymbolRefExpr::VK_TLSLDM:
Rafael Espindola0cf15d62010-10-28 14:48:59 +000095 case MCSymbolRefExpr::VK_DTPOFF:
Rafael Espindolab4d17212010-10-28 15:02:40 +000096 case MCSymbolRefExpr::VK_TLSLD:
Rafael Espindola5c77c162010-10-05 15:48:37 +000097 return true;
98 }
99}
100
Matt Fleming3565a062010-08-16 18:57:57 +0000101namespace {
102
103 class ELFObjectWriterImpl {
Chris Lattnerb188a372010-08-28 03:21:03 +0000104 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
Matt Fleming3565a062010-08-16 18:57:57 +0000105 return Kind == X86::reloc_riprel_4byte ||
106 Kind == X86::reloc_riprel_4byte_movq_load;
Chris Lattnerb188a372010-08-28 03:21:03 +0000107 }*/
Matt Fleming3565a062010-08-16 18:57:57 +0000108
109
110 /// ELFSymbolData - Helper struct for containing some precomputed information
111 /// on symbols.
112 struct ELFSymbolData {
113 MCSymbolData *SymbolData;
114 uint64_t StringIndex;
115 uint32_t SectionIndex;
116
117 // Support lexicographic sorting.
118 bool operator<(const ELFSymbolData &RHS) const {
Rafael Espindolaad49cf52010-09-18 15:03:21 +0000119 if (GetType(*SymbolData) == ELF::STT_FILE)
120 return true;
121 if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
122 return false;
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000123 return SymbolData->getSymbol().getName() <
124 RHS.SymbolData->getSymbol().getName();
Matt Fleming3565a062010-08-16 18:57:57 +0000125 }
126 };
127
128 /// @name Relocation Data
129 /// @{
130
131 struct ELFRelocationEntry {
132 // Make these big enough for both 32-bit and 64-bit
133 uint64_t r_offset;
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000134 int Index;
135 unsigned Type;
136 const MCSymbol *Symbol;
Matt Fleming3565a062010-08-16 18:57:57 +0000137 uint64_t r_addend;
138
139 // Support lexicographic sorting.
140 bool operator<(const ELFRelocationEntry &RE) const {
141 return RE.r_offset < r_offset;
142 }
143 };
144
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000145 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
Rafael Espindola484291c2010-11-01 14:28:48 +0000146 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
Rafael Espindola88182132010-10-27 15:18:17 +0000147 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000148
Matt Fleming3565a062010-08-16 18:57:57 +0000149 llvm::DenseMap<const MCSectionData*,
150 std::vector<ELFRelocationEntry> > Relocations;
151 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
152
153 /// @}
154 /// @name Symbol Table Data
155 /// @{
156
157 SmallString<256> StringTable;
158 std::vector<ELFSymbolData> LocalSymbolData;
159 std::vector<ELFSymbolData> ExternalSymbolData;
160 std::vector<ELFSymbolData> UndefinedSymbolData;
161
162 /// @}
163
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000164 int NumRegularSections;
165
Rafael Espindola5c77c162010-10-05 15:48:37 +0000166 bool NeedsGOT;
167
Rafael Espindola7be2c332010-10-31 00:16:26 +0000168 bool NeedsSymtabShndx;
169
Matt Fleming3565a062010-08-16 18:57:57 +0000170 ELFObjectWriter *Writer;
171
172 raw_ostream &OS;
173
Matt Fleming3565a062010-08-16 18:57:57 +0000174 unsigned Is64Bit : 1;
175
176 bool HasRelocationAddend;
177
Roman Divacky5baf79e2010-09-09 17:57:50 +0000178 Triple::OSType OSType;
179
Wesley Peckeecb8582010-10-22 15:52:49 +0000180 uint16_t EMachine;
181
Matt Fleming3565a062010-08-16 18:57:57 +0000182 // This holds the symbol table index of the last local symbol.
183 unsigned LastLocalSymbolIndex;
184 // This holds the .strtab section index.
185 unsigned StringTableIndex;
Rafael Espindola7be2c332010-10-31 00:16:26 +0000186 // This holds the .symtab section index.
187 unsigned SymbolTableIndex;
Matt Fleming3565a062010-08-16 18:57:57 +0000188
189 unsigned ShstrtabIndex;
190
191 public:
192 ELFObjectWriterImpl(ELFObjectWriter *_Writer, bool _Is64Bit,
Wesley Peckeecb8582010-10-22 15:52:49 +0000193 uint16_t _EMachine, bool _HasRelAddend,
194 Triple::OSType _OSType)
Rafael Espindola7be2c332010-10-31 00:16:26 +0000195 : NeedsGOT(false), NeedsSymtabShndx(false), Writer(_Writer),
196 OS(Writer->getStream()),
Roman Divacky5baf79e2010-09-09 17:57:50 +0000197 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
Wesley Peckeecb8582010-10-22 15:52:49 +0000198 OSType(_OSType), EMachine(_EMachine) {
Matt Fleming3565a062010-08-16 18:57:57 +0000199 }
200
201 void Write8(uint8_t Value) { Writer->Write8(Value); }
202 void Write16(uint16_t Value) { Writer->Write16(Value); }
203 void Write32(uint32_t Value) { Writer->Write32(Value); }
Chris Lattnerb188a372010-08-28 03:21:03 +0000204 //void Write64(uint64_t Value) { Writer->Write64(Value); }
Matt Fleming3565a062010-08-16 18:57:57 +0000205 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
Chris Lattnerb188a372010-08-28 03:21:03 +0000206 //void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
207 // Writer->WriteBytes(Str, ZeroFillSize);
208 //}
Matt Fleming3565a062010-08-16 18:57:57 +0000209
210 void WriteWord(uint64_t W) {
Chris Lattnerb188a372010-08-28 03:21:03 +0000211 if (Is64Bit)
Matt Fleming3565a062010-08-16 18:57:57 +0000212 Writer->Write64(W);
Chris Lattnerb188a372010-08-28 03:21:03 +0000213 else
Matt Fleming3565a062010-08-16 18:57:57 +0000214 Writer->Write32(W);
Matt Fleming3565a062010-08-16 18:57:57 +0000215 }
216
Matt Fleming3565a062010-08-16 18:57:57 +0000217 void StringLE16(char *buf, uint16_t Value) {
218 buf[0] = char(Value >> 0);
219 buf[1] = char(Value >> 8);
220 }
221
222 void StringLE32(char *buf, uint32_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000223 StringLE16(buf, uint16_t(Value >> 0));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000224 StringLE16(buf + 2, uint16_t(Value >> 16));
Matt Fleming3565a062010-08-16 18:57:57 +0000225 }
226
227 void StringLE64(char *buf, uint64_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000228 StringLE32(buf, uint32_t(Value >> 0));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000229 StringLE32(buf + 4, uint32_t(Value >> 32));
Matt Fleming3565a062010-08-16 18:57:57 +0000230 }
231
232 void StringBE16(char *buf ,uint16_t Value) {
233 buf[0] = char(Value >> 8);
234 buf[1] = char(Value >> 0);
235 }
236
237 void StringBE32(char *buf, uint32_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000238 StringBE16(buf, uint16_t(Value >> 16));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000239 StringBE16(buf + 2, uint16_t(Value >> 0));
Matt Fleming3565a062010-08-16 18:57:57 +0000240 }
241
242 void StringBE64(char *buf, uint64_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000243 StringBE32(buf, uint32_t(Value >> 32));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000244 StringBE32(buf + 4, uint32_t(Value >> 0));
Matt Fleming3565a062010-08-16 18:57:57 +0000245 }
246
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000247 void String8(MCDataFragment &F, uint8_t Value) {
248 char buf[1];
249 buf[0] = Value;
250 F.getContents() += StringRef(buf, 1);
251 }
252
253 void String16(MCDataFragment &F, uint16_t Value) {
254 char buf[2];
Matt Fleming3565a062010-08-16 18:57:57 +0000255 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000256 StringLE16(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000257 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000258 StringBE16(buf, Value);
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000259 F.getContents() += StringRef(buf, 2);
Matt Fleming3565a062010-08-16 18:57:57 +0000260 }
261
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000262 void String32(MCDataFragment &F, uint32_t Value) {
263 char buf[4];
Matt Fleming3565a062010-08-16 18:57:57 +0000264 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000265 StringLE32(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000266 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000267 StringBE32(buf, Value);
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000268 F.getContents() += StringRef(buf, 4);
Matt Fleming3565a062010-08-16 18:57:57 +0000269 }
270
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000271 void String64(MCDataFragment &F, uint64_t Value) {
272 char buf[8];
Matt Fleming3565a062010-08-16 18:57:57 +0000273 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000274 StringLE64(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000275 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000276 StringBE64(buf, Value);
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000277 F.getContents() += StringRef(buf, 8);
Matt Fleming3565a062010-08-16 18:57:57 +0000278 }
279
280 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
281
Rafael Espindola7be2c332010-10-31 00:16:26 +0000282 void WriteSymbolEntry(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
283 uint64_t name, uint8_t info,
Matt Fleming3565a062010-08-16 18:57:57 +0000284 uint64_t value, uint64_t size,
Rafael Espindola7be2c332010-10-31 00:16:26 +0000285 uint8_t other, uint32_t shndx,
286 bool Reserved);
Matt Fleming3565a062010-08-16 18:57:57 +0000287
Rafael Espindola7be2c332010-10-31 00:16:26 +0000288 void WriteSymbol(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
289 ELFSymbolData &MSD,
Matt Fleming3565a062010-08-16 18:57:57 +0000290 const MCAsmLayout &Layout);
291
Rafael Espindolabab2a802010-11-10 21:51:05 +0000292 typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
Rafael Espindola7be2c332010-10-31 00:16:26 +0000293 void WriteSymbolTable(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
294 const MCAssembler &Asm,
Rafael Espindola71859c62010-09-16 19:46:31 +0000295 const MCAsmLayout &Layout,
Rafael Espindola4beee3d2010-11-10 22:16:43 +0000296 const SectionIndexMapTy &SectionIndexMap);
Matt Fleming3565a062010-08-16 18:57:57 +0000297
298 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
299 const MCFragment *Fragment, const MCFixup &Fixup,
300 MCValue Target, uint64_t &FixedValue);
301
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000302 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
303 const MCSymbol *S);
Matt Fleming3565a062010-08-16 18:57:57 +0000304
305 /// ComputeSymbolTable - Compute the symbol table data
306 ///
307 /// \param StringTable [out] - The string table data.
308 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
309 /// string table.
Rafael Espindolabab2a802010-11-10 21:51:05 +0000310 void ComputeSymbolTable(MCAssembler &Asm,
311 const SectionIndexMapTy &SectionIndexMap);
312
313 void ComputeIndexMap(MCAssembler &Asm,
314 SectionIndexMapTy &SectionIndexMap);
Matt Fleming3565a062010-08-16 18:57:57 +0000315
316 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
317 const MCSectionData &SD);
318
319 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
320 for (MCAssembler::const_iterator it = Asm.begin(),
321 ie = Asm.end(); it != ie; ++it) {
322 WriteRelocation(Asm, Layout, *it);
323 }
324 }
325
Rafael Espindola4beee3d2010-11-10 22:16:43 +0000326 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
327 const SectionIndexMapTy &SectionIndexMap);
Matt Fleming3565a062010-08-16 18:57:57 +0000328
Rafael Espindola88182132010-10-27 15:18:17 +0000329 void ExecutePostLayoutBinding(MCAssembler &Asm);
Matt Fleming3565a062010-08-16 18:57:57 +0000330
331 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
332 uint64_t Address, uint64_t Offset,
333 uint64_t Size, uint32_t Link, uint32_t Info,
334 uint64_t Alignment, uint64_t EntrySize);
335
336 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
337 const MCSectionData *SD);
338
Rafael Espindola70703872010-09-30 02:22:20 +0000339 bool IsFixupFullyResolved(const MCAssembler &Asm,
340 const MCValue Target,
341 bool IsPCRel,
342 const MCFragment *DF) const;
343
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000344 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
Rafael Espindolac87a94a2010-11-10 23:36:59 +0000345 void WriteSection(MCAssembler &Asm,
346 const SectionIndexMapTy &SectionIndexMap,
347 uint64_t Offset, uint64_t Size, uint64_t Alignment,
348 const MCSectionELF &Section);
Matt Fleming3565a062010-08-16 18:57:57 +0000349 };
350
351}
352
353// Emit the ELF header.
354void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
355 unsigned NumberOfSections) {
356 // ELF Header
357 // ----------
358 //
359 // Note
360 // ----
361 // emitWord method behaves differently for ELF32 and ELF64, writing
362 // 4 bytes in the former and 8 in the latter.
363
364 Write8(0x7f); // e_ident[EI_MAG0]
365 Write8('E'); // e_ident[EI_MAG1]
366 Write8('L'); // e_ident[EI_MAG2]
367 Write8('F'); // e_ident[EI_MAG3]
368
369 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
370
371 // e_ident[EI_DATA]
372 Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
373
374 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky5baf79e2010-09-09 17:57:50 +0000375 // e_ident[EI_OSABI]
376 switch (OSType) {
377 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
378 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
379 default: Write8(ELF::ELFOSABI_NONE); break;
380 }
Matt Fleming3565a062010-08-16 18:57:57 +0000381 Write8(0); // e_ident[EI_ABIVERSION]
382
383 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
384
385 Write16(ELF::ET_REL); // e_type
386
Wesley Peckeecb8582010-10-22 15:52:49 +0000387 Write16(EMachine); // e_machine = target
Matt Fleming3565a062010-08-16 18:57:57 +0000388
389 Write32(ELF::EV_CURRENT); // e_version
390 WriteWord(0); // e_entry, no entry point in .o file
391 WriteWord(0); // e_phoff, no program header for .o
Benjamin Kramereb976772010-08-17 17:02:29 +0000392 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
393 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
Matt Fleming3565a062010-08-16 18:57:57 +0000394
395 // FIXME: Make this configurable.
396 Write32(0); // e_flags = whatever the target wants
397
398 // e_ehsize = ELF header size
399 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
400
401 Write16(0); // e_phentsize = prog header entry size
402 Write16(0); // e_phnum = # prog header entries = 0
403
404 // e_shentsize = Section header entry size
405 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
406
407 // e_shnum = # of section header ents
Rafael Espindola7be2c332010-10-31 00:16:26 +0000408 if (NumberOfSections >= ELF::SHN_LORESERVE)
409 Write16(0);
410 else
411 Write16(NumberOfSections);
Matt Fleming3565a062010-08-16 18:57:57 +0000412
413 // e_shstrndx = Section # of '.shstrtab'
Rafael Espindola7be2c332010-10-31 00:16:26 +0000414 if (NumberOfSections >= ELF::SHN_LORESERVE)
415 Write16(ELF::SHN_XINDEX);
416 else
417 Write16(ShstrtabIndex);
Matt Fleming3565a062010-08-16 18:57:57 +0000418}
419
Rafael Espindola7be2c332010-10-31 00:16:26 +0000420void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *SymtabF,
421 MCDataFragment *ShndxF,
422 uint64_t name,
Matt Fleming3565a062010-08-16 18:57:57 +0000423 uint8_t info, uint64_t value,
424 uint64_t size, uint8_t other,
Rafael Espindola7be2c332010-10-31 00:16:26 +0000425 uint32_t shndx,
426 bool Reserved) {
427 if (ShndxF) {
Rafael Espindola7be2c332010-10-31 00:16:26 +0000428 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000429 String32(*ShndxF, shndx);
Rafael Espindola7be2c332010-10-31 00:16:26 +0000430 else
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000431 String32(*ShndxF, 0);
Rafael Espindola7be2c332010-10-31 00:16:26 +0000432 }
433
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000434 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
435 uint16_t(ELF::SHN_XINDEX) : shndx;
436
Matt Fleming3565a062010-08-16 18:57:57 +0000437 if (Is64Bit) {
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000438 String32(*SymtabF, name); // st_name
439 String8(*SymtabF, info); // st_info
440 String8(*SymtabF, other); // st_other
441 String16(*SymtabF, Index); // st_shndx
442 String64(*SymtabF, value); // st_value
443 String64(*SymtabF, size); // st_size
Matt Fleming3565a062010-08-16 18:57:57 +0000444 } else {
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000445 String32(*SymtabF, name); // st_name
446 String32(*SymtabF, value); // st_value
447 String32(*SymtabF, size); // st_size
448 String8(*SymtabF, info); // st_info
449 String8(*SymtabF, other); // st_other
450 String16(*SymtabF, Index); // st_shndx
Matt Fleming3565a062010-08-16 18:57:57 +0000451 }
452}
453
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000454static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
455 if (Data.isCommon() && Data.isExternal())
456 return Data.getCommonAlignment();
457
458 const MCSymbol &Symbol = Data.getSymbol();
459 if (!Symbol.isInSection())
460 return 0;
461
Rafael Espindola1973d432010-10-28 19:39:57 +0000462 if (MCFragment *FF = Data.getFragment())
463 return Layout.getSymbolAddress(&Data) -
464 Layout.getSectionAddress(FF->getParent());
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000465
466 return 0;
467}
468
Rafael Espindolade89b012010-10-15 18:25:33 +0000469static const MCSymbol &AliasedSymbol(const MCSymbol &Symbol) {
470 const MCSymbol *S = &Symbol;
471 while (S->isVariable()) {
472 const MCExpr *Value = S->getVariableValue();
Rafael Espindolaa6866962010-10-27 14:44:52 +0000473 if (Value->getKind() != MCExpr::SymbolRef)
474 return *S;
Rafael Espindolade89b012010-10-15 18:25:33 +0000475 const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Value);
476 S = &Ref->getSymbol();
477 }
478 return *S;
479}
480
Rafael Espindola88182132010-10-27 15:18:17 +0000481void ELFObjectWriterImpl::ExecutePostLayoutBinding(MCAssembler &Asm) {
482 // The presence of symbol versions causes undefined symbols and
483 // versions declared with @@@ to be renamed.
484
485 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
486 ie = Asm.symbol_end(); it != ie; ++it) {
487 const MCSymbol &Alias = it->getSymbol();
Rafael Espindola88182132010-10-27 15:18:17 +0000488 const MCSymbol &Symbol = AliasedSymbol(Alias);
Rafael Espindolaf571f9a2010-10-28 18:33:03 +0000489 MCSymbolData &SD = Asm.getSymbolData(Symbol);
490
491 // Undefined symbols are global, but this is the first place we
492 // are able to set it.
493 if (Symbol.isUndefined() && !Symbol.isVariable()) {
494 if (GetBinding(SD) == ELF::STB_LOCAL) {
495 SetBinding(SD, ELF::STB_GLOBAL);
496 SetBinding(*it, ELF::STB_GLOBAL);
497 }
498 }
499
500 // Not an alias.
501 if (&Symbol == &Alias)
502 continue;
503
Benjamin Kramer07ee6322010-10-27 19:53:52 +0000504 StringRef AliasName = Alias.getName();
Rafael Espindola88182132010-10-27 15:18:17 +0000505 size_t Pos = AliasName.find('@');
506 if (Pos == StringRef::npos)
507 continue;
508
Rafael Espindolaf571f9a2010-10-28 18:33:03 +0000509 // Aliases defined with .symvar copy the binding from the symbol they alias.
510 // This is the first place we are able to copy this information.
511 it->setExternal(SD.isExternal());
512 SetBinding(*it, GetBinding(SD));
513
Benjamin Kramer07ee6322010-10-27 19:53:52 +0000514 StringRef Rest = AliasName.substr(Pos);
Rafael Espindola88182132010-10-27 15:18:17 +0000515 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
516 continue;
517
Rafael Espindola83ff4d22010-10-27 17:56:18 +0000518 // FIXME: produce a better error message.
519 if (Symbol.isUndefined() && Rest.startswith("@@") &&
520 !Rest.startswith("@@@"))
521 report_fatal_error("A @@ version cannot be undefined");
522
Benjamin Kramer07ee6322010-10-27 19:53:52 +0000523 Renames.insert(std::make_pair(&Symbol, &Alias));
Rafael Espindola88182132010-10-27 15:18:17 +0000524 }
525}
526
Rafael Espindola7be2c332010-10-31 00:16:26 +0000527void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *SymtabF,
528 MCDataFragment *ShndxF,
529 ELFSymbolData &MSD,
Matt Fleming3565a062010-08-16 18:57:57 +0000530 const MCAsmLayout &Layout) {
Rafael Espindola152c1062010-10-06 21:02:29 +0000531 MCSymbolData &OrigData = *MSD.SymbolData;
Rafael Espindolade89b012010-10-15 18:25:33 +0000532 MCSymbolData &Data =
533 Layout.getAssembler().getSymbolData(AliasedSymbol(OrigData.getSymbol()));
Rafael Espindola152c1062010-10-06 21:02:29 +0000534
Rafael Espindola7be2c332010-10-31 00:16:26 +0000535 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
536 Data.getSymbol().isVariable();
537
Rafael Espindola152c1062010-10-06 21:02:29 +0000538 uint8_t Binding = GetBinding(OrigData);
539 uint8_t Visibility = GetVisibility(OrigData);
540 uint8_t Type = GetType(Data);
541
542 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
543 uint8_t Other = Visibility;
544
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000545 uint64_t Value = SymbolValue(Data, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000546 uint64_t Size = 0;
547 const MCExpr *ESize;
548
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000549 assert(!(Data.isCommon() && !Data.isExternal()));
550
Matt Fleming3565a062010-08-16 18:57:57 +0000551 ESize = Data.getSize();
552 if (Data.getSize()) {
553 MCValue Res;
554 if (ESize->getKind() == MCExpr::Binary) {
555 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
556
557 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
Benjamin Kramer24f12062010-10-17 07:38:40 +0000558 assert(!Res.getSymA() || !Res.getSymA()->getSymbol().isDefined());
559 assert(!Res.getSymB() || !Res.getSymB()->getSymbol().isDefined());
Rafael Espindolaf230df92010-10-16 18:23:53 +0000560 Size = Res.getConstant();
Matt Fleming3565a062010-08-16 18:57:57 +0000561 }
562 } else if (ESize->getKind() == MCExpr::Constant) {
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000563 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
Matt Fleming3565a062010-08-16 18:57:57 +0000564 } else {
565 assert(0 && "Unsupported size expression");
566 }
567 }
568
569 // Write out the symbol table entry
Rafael Espindola7be2c332010-10-31 00:16:26 +0000570 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
571 Size, Other, MSD.SectionIndex, IsReserved);
Matt Fleming3565a062010-08-16 18:57:57 +0000572}
573
Rafael Espindola7be2c332010-10-31 00:16:26 +0000574void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *SymtabF,
575 MCDataFragment *ShndxF,
Matt Fleming3565a062010-08-16 18:57:57 +0000576 const MCAssembler &Asm,
Rafael Espindola71859c62010-09-16 19:46:31 +0000577 const MCAsmLayout &Layout,
Rafael Espindola4beee3d2010-11-10 22:16:43 +0000578 const SectionIndexMapTy &SectionIndexMap) {
Matt Fleming3565a062010-08-16 18:57:57 +0000579 // The string table must be emitted first because we need the index
580 // into the string table for all the symbol names.
581 assert(StringTable.size() && "Missing string table");
582
583 // FIXME: Make sure the start of the symbol table is aligned.
584
585 // The first entry is the undefined symbol entry.
Rafael Espindola7be2c332010-10-31 00:16:26 +0000586 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
Matt Fleming3565a062010-08-16 18:57:57 +0000587
588 // Write the symbol table entries.
589 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
590 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
591 ELFSymbolData &MSD = LocalSymbolData[i];
Rafael Espindola7be2c332010-10-31 00:16:26 +0000592 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000593 }
594
Rafael Espindola71859c62010-09-16 19:46:31 +0000595 // Write out a symbol table entry for each regular section.
Rafael Espindola4beee3d2010-11-10 22:16:43 +0000596 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
597 ++i) {
Eli Friedmana44fa242010-08-16 21:17:09 +0000598 const MCSectionELF &Section =
Rafael Espindola4beee3d2010-11-10 22:16:43 +0000599 static_cast<const MCSectionELF&>(i->getSection());
600 if (Section.getType() == ELF::SHT_RELA ||
601 Section.getType() == ELF::SHT_REL ||
602 Section.getType() == ELF::SHT_STRTAB ||
603 Section.getType() == ELF::SHT_SYMTAB)
Eli Friedmana44fa242010-08-16 21:17:09 +0000604 continue;
Rafael Espindola7be2c332010-10-31 00:16:26 +0000605 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
Rafael Espindola4beee3d2010-11-10 22:16:43 +0000606 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section), false);
Eli Friedmana44fa242010-08-16 21:17:09 +0000607 LastLocalSymbolIndex++;
608 }
Matt Fleming3565a062010-08-16 18:57:57 +0000609
610 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
611 ELFSymbolData &MSD = ExternalSymbolData[i];
612 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola3223f192010-10-06 16:47:31 +0000613 assert(((Data.getFlags() & ELF_STB_Global) ||
614 (Data.getFlags() & ELF_STB_Weak)) &&
615 "External symbol requires STB_GLOBAL or STB_WEAK flag");
Rafael Espindola7be2c332010-10-31 00:16:26 +0000616 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
Rafael Espindolae15eb4e2010-09-23 19:55:14 +0000617 if (GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming3565a062010-08-16 18:57:57 +0000618 LastLocalSymbolIndex++;
619 }
620
621 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
622 ELFSymbolData &MSD = UndefinedSymbolData[i];
623 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola7be2c332010-10-31 00:16:26 +0000624 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
Rafael Espindolae15eb4e2010-09-23 19:55:14 +0000625 if (GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming3565a062010-08-16 18:57:57 +0000626 LastLocalSymbolIndex++;
627 }
628}
629
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000630static bool ShouldRelocOnSymbol(const MCSymbolData &SD,
Rafael Espindola3729d002010-10-05 23:57:26 +0000631 const MCValue &Target,
632 const MCFragment &F) {
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000633 const MCSymbol &Symbol = SD.getSymbol();
634 if (Symbol.isUndefined())
635 return true;
Rafael Espindola73ffea42010-09-25 05:42:19 +0000636
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000637 const MCSectionELF &Section =
638 static_cast<const MCSectionELF&>(Symbol.getSection());
639
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000640 if (SD.isExternal())
641 return true;
642
Rafael Espindola8cecf252010-10-06 16:23:36 +0000643 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
Rafael Espindola3729d002010-10-05 23:57:26 +0000644 const MCSectionELF &Sec2 =
645 static_cast<const MCSectionELF&>(F.getParent()->getSection());
646
Rafael Espindolace2d3c52010-10-18 20:25:33 +0000647 if (Section.getKind().isBSS())
648 return false;
649
Rafael Espindola8cecf252010-10-06 16:23:36 +0000650 if (&Sec2 != &Section &&
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000651 (Kind == MCSymbolRefExpr::VK_PLT ||
652 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
653 Kind == MCSymbolRefExpr::VK_GOTOFF))
Rafael Espindola3729d002010-10-05 23:57:26 +0000654 return true;
655
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000656 if (Section.getFlags() & MCSectionELF::SHF_MERGE)
657 return Target.getConstant() != 0;
658
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000659 return false;
Rafael Espindola73ffea42010-09-25 05:42:19 +0000660}
661
Benjamin Kramere5b57342010-08-17 18:20:28 +0000662// FIXME: this is currently X86/X86_64 only
Matt Fleming3565a062010-08-16 18:57:57 +0000663void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
664 const MCAsmLayout &Layout,
665 const MCFragment *Fragment,
666 const MCFixup &Fixup,
667 MCValue Target,
668 uint64_t &FixedValue) {
Matt Fleming3565a062010-08-16 18:57:57 +0000669 int64_t Addend = 0;
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000670 int Index = 0;
Benjamin Kramer95c602a2010-08-27 10:38:39 +0000671 int64_t Value = Target.getConstant();
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000672 const MCSymbol *Symbol = 0;
Rafael Espindola29129722010-10-28 19:08:03 +0000673 const MCSymbol *Renamed = 0;
Matt Fleming3565a062010-08-16 18:57:57 +0000674
Rafael Espindola00074892010-09-17 22:34:41 +0000675 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
Benjamin Kramer81cfb852010-08-17 19:45:05 +0000676 if (!Target.isAbsolute()) {
Rafael Espindolade89b012010-10-15 18:25:33 +0000677 Symbol = &AliasedSymbol(Target.getSymA()->getSymbol());
Rafael Espindola29129722010-10-28 19:08:03 +0000678 Renamed = Renames.lookup(Symbol);
679 if (!Renamed)
Rafael Espindola484291c2010-11-01 14:28:48 +0000680 Renamed = &Target.getSymA()->getSymbol();
Matt Fleming3565a062010-08-16 18:57:57 +0000681 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000682 MCFragment *F = SD.getFragment();
Matt Fleming3565a062010-08-16 18:57:57 +0000683
Rafael Espindola9d8b7552010-10-03 00:46:57 +0000684 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
685 const MCSymbol &SymbolB = RefB->getSymbol();
686 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
687 IsPCRel = true;
Rafael Espindola55fb1022010-10-04 15:59:01 +0000688 MCSectionData *Sec = Fragment->getParent();
689
690 // Offset of the symbol in the section
691 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
692
693 // Ofeset of the relocation in the section
694 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
695 Value += b - a;
Rafael Espindola9d8b7552010-10-03 00:46:57 +0000696 }
697
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000698 // Check that this case has already been fully resolved before we get
699 // here.
Rafael Espindola00074892010-09-17 22:34:41 +0000700 if (Symbol->isDefined() && !SD.isExternal() &&
701 IsPCRel &&
702 &Fragment->getParent()->getSection() == &Symbol->getSection()) {
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000703 llvm_unreachable("We don't need a relocation in this case.");
Rafael Espindola00074892010-09-17 22:34:41 +0000704 return;
705 }
706
Rafael Espindola3729d002010-10-05 23:57:26 +0000707 bool RelocOnSymbol = ShouldRelocOnSymbol(SD, Target, *Fragment);
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000708 if (!RelocOnSymbol) {
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000709 Index = F->getParent()->getOrdinal();
Rafael Espindolaa6489182010-09-24 21:19:03 +0000710
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000711 MCSectionData *FSD = F->getParent();
712 // Offset of the symbol in the section
713 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000714 } else {
Rafael Espindola29129722010-10-28 19:08:03 +0000715 UsedInReloc.insert(Renamed);
Rafael Espindola484291c2010-11-01 14:28:48 +0000716 MCSymbolData &RenamedSD = Asm.getSymbolData(*Renamed);
717 if (RenamedSD.getFlags() & ELF_Other_Weakref) {
718 WeakrefUsedInReloc.insert(Symbol);
719 }
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000720 Index = -1;
721 }
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000722 Addend = Value;
723 // Compensate for the addend on i386.
724 if (Is64Bit)
725 Value = 0;
Matt Fleming3565a062010-08-16 18:57:57 +0000726 }
727
Benjamin Kramer95c602a2010-08-27 10:38:39 +0000728 FixedValue = Value;
729
Matt Fleming3565a062010-08-16 18:57:57 +0000730 // determine the type of the relocation
Rafael Espindola28f9ac82010-10-04 18:44:25 +0000731
732 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000733 unsigned Type;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000734 if (Is64Bit) {
735 if (IsPCRel) {
Rafael Espindola92bf6682010-10-04 19:04:13 +0000736 switch (Modifier) {
Rafael Espindola9edab3a2010-10-18 16:58:03 +0000737 default:
738 llvm_unreachable("Unimplemented");
Rafael Espindola92bf6682010-10-04 19:04:13 +0000739 case MCSymbolRefExpr::VK_None:
740 Type = ELF::R_X86_64_PC32;
741 break;
742 case MCSymbolRefExpr::VK_PLT:
743 Type = ELF::R_X86_64_PLT32;
744 break;
Rafael Espindolaa0a2f872010-10-28 14:22:44 +0000745 case MCSymbolRefExpr::VK_GOTPCREL:
Rafael Espindola607d1f62010-10-04 19:51:39 +0000746 Type = ELF::R_X86_64_GOTPCREL;
747 break;
Rafael Espindolabc82d8b2010-10-27 20:28:07 +0000748 case MCSymbolRefExpr::VK_GOTTPOFF:
749 Type = ELF::R_X86_64_GOTTPOFF;
750 break;
751 case MCSymbolRefExpr::VK_TLSGD:
752 Type = ELF::R_X86_64_TLSGD;
753 break;
Rafael Espindolab4d17212010-10-28 15:02:40 +0000754 case MCSymbolRefExpr::VK_TLSLD:
755 Type = ELF::R_X86_64_TLSLD;
756 break;
Rafael Espindola92bf6682010-10-04 19:04:13 +0000757 }
Benjamin Kramere5b57342010-08-17 18:20:28 +0000758 } else {
759 switch ((unsigned)Fixup.getKind()) {
760 default: llvm_unreachable("invalid fixup kind!");
761 case FK_Data_8: Type = ELF::R_X86_64_64; break;
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000762 case X86::reloc_signed_4byte:
Benjamin Kramere5b57342010-08-17 18:20:28 +0000763 case X86::reloc_pcrel_4byte:
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000764 assert(isInt<32>(Target.getConstant()));
Rafael Espindola28f9ac82010-10-04 18:44:25 +0000765 switch (Modifier) {
Rafael Espindola9edab3a2010-10-18 16:58:03 +0000766 default:
767 llvm_unreachable("Unimplemented");
Rafael Espindola28f9ac82010-10-04 18:44:25 +0000768 case MCSymbolRefExpr::VK_None:
769 Type = ELF::R_X86_64_32S;
770 break;
771 case MCSymbolRefExpr::VK_GOT:
772 Type = ELF::R_X86_64_GOT32;
773 break;
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000774 case MCSymbolRefExpr::VK_GOTPCREL:
Rafael Espindola8cecf252010-10-06 16:23:36 +0000775 Type = ELF::R_X86_64_GOTPCREL;
776 break;
Rafael Espindolabc82d8b2010-10-27 20:28:07 +0000777 case MCSymbolRefExpr::VK_TPOFF:
778 Type = ELF::R_X86_64_TPOFF32;
779 break;
Rafael Espindolaaa8f1f02010-10-28 15:11:03 +0000780 case MCSymbolRefExpr::VK_DTPOFF:
781 Type = ELF::R_X86_64_DTPOFF32;
782 break;
Rafael Espindola28f9ac82010-10-04 18:44:25 +0000783 }
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000784 break;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000785 case FK_Data_4:
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000786 Type = ELF::R_X86_64_32;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000787 break;
788 case FK_Data_2: Type = ELF::R_X86_64_16; break;
789 case X86::reloc_pcrel_1byte:
790 case FK_Data_1: Type = ELF::R_X86_64_8; break;
791 }
792 }
Matt Fleming3565a062010-08-16 18:57:57 +0000793 } else {
Benjamin Kramere5b57342010-08-17 18:20:28 +0000794 if (IsPCRel) {
Rafael Espindola9edab3a2010-10-18 16:58:03 +0000795 switch (Modifier) {
796 default:
Rafael Espindola24dc9ec2010-10-18 19:33:01 +0000797 llvm_unreachable("Unimplemented");
798 case MCSymbolRefExpr::VK_None:
Rafael Espindola9baee3b2010-10-18 18:03:28 +0000799 Type = ELF::R_386_PC32;
Rafael Espindola9baee3b2010-10-18 18:03:28 +0000800 break;
Rafael Espindola9edab3a2010-10-18 16:58:03 +0000801 case MCSymbolRefExpr::VK_PLT:
802 Type = ELF::R_386_PLT32;
803 break;
804 }
Benjamin Kramere5b57342010-08-17 18:20:28 +0000805 } else {
806 switch ((unsigned)Fixup.getKind()) {
807 default: llvm_unreachable("invalid fixup kind!");
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000808
Rafael Espindola24ba4f72010-10-24 17:35:42 +0000809 case X86::reloc_global_offset_table:
810 Type = ELF::R_386_GOTPC;
811 break;
812
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000813 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
814 // instead?
815 case X86::reloc_signed_4byte:
Benjamin Kramere5b57342010-08-17 18:20:28 +0000816 case X86::reloc_pcrel_4byte:
Rafael Espindolabd701182010-10-19 19:31:37 +0000817 case FK_Data_4:
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000818 switch (Modifier) {
Rafael Espindola9edab3a2010-10-18 16:58:03 +0000819 default:
820 llvm_unreachable("Unimplemented");
Rafael Espindolabd701182010-10-19 19:31:37 +0000821 case MCSymbolRefExpr::VK_None:
Rafael Espindola24ba4f72010-10-24 17:35:42 +0000822 Type = ELF::R_386_32;
Rafael Espindolabd701182010-10-19 19:31:37 +0000823 break;
Rafael Espindolaeada3042010-10-18 20:47:21 +0000824 case MCSymbolRefExpr::VK_GOT:
825 Type = ELF::R_386_GOT32;
826 break;
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000827 case MCSymbolRefExpr::VK_GOTOFF:
828 Type = ELF::R_386_GOTOFF;
829 break;
Rafael Espindola3cede2d2010-10-27 21:23:52 +0000830 case MCSymbolRefExpr::VK_TLSGD:
831 Type = ELF::R_386_TLS_GD;
832 break;
833 case MCSymbolRefExpr::VK_TPOFF:
834 Type = ELF::R_386_TLS_LE_32;
835 break;
836 case MCSymbolRefExpr::VK_INDNTPOFF:
837 Type = ELF::R_386_TLS_IE;
838 break;
839 case MCSymbolRefExpr::VK_NTPOFF:
840 Type = ELF::R_386_TLS_LE;
841 break;
Rafael Espindolaa0a2f872010-10-28 14:22:44 +0000842 case MCSymbolRefExpr::VK_GOTNTPOFF:
843 Type = ELF::R_386_TLS_GOTIE;
844 break;
Rafael Espindolaa264f722010-10-28 14:37:09 +0000845 case MCSymbolRefExpr::VK_TLSLDM:
846 Type = ELF::R_386_TLS_LDM;
847 break;
Rafael Espindola0cf15d62010-10-28 14:48:59 +0000848 case MCSymbolRefExpr::VK_DTPOFF:
849 Type = ELF::R_386_TLS_LDO_32;
850 break;
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000851 }
852 break;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000853 case FK_Data_2: Type = ELF::R_386_16; break;
854 case X86::reloc_pcrel_1byte:
855 case FK_Data_1: Type = ELF::R_386_8; break;
856 }
Matt Fleming3565a062010-08-16 18:57:57 +0000857 }
858 }
859
Rafael Espindolaa0a2f872010-10-28 14:22:44 +0000860 if (RelocNeedsGOT(Modifier))
Rafael Espindola5c77c162010-10-05 15:48:37 +0000861 NeedsGOT = true;
862
Benjamin Kramere5b57342010-08-17 18:20:28 +0000863 ELFRelocationEntry ERE;
864
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000865 ERE.Index = Index;
866 ERE.Type = Type;
Rafael Espindola29129722010-10-28 19:08:03 +0000867 ERE.Symbol = Renamed;
Matt Fleming3565a062010-08-16 18:57:57 +0000868
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000869 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
Benjamin Kramere5b57342010-08-17 18:20:28 +0000870
Matt Fleming3565a062010-08-16 18:57:57 +0000871 if (HasRelocationAddend)
872 ERE.r_addend = Addend;
Benjamin Kramer172d7d62010-08-17 00:33:24 +0000873 else
874 ERE.r_addend = 0; // Silence compiler warning.
Matt Fleming3565a062010-08-16 18:57:57 +0000875
876 Relocations[Fragment->getParent()].push_back(ERE);
877}
878
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000879uint64_t
880ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
881 const MCSymbol *S) {
Benjamin Kramer7b83c262010-08-25 20:09:43 +0000882 MCSymbolData &SD = Asm.getSymbolData(*S);
Eli Friedmanf8020a32010-08-16 19:15:06 +0000883
Benjamin Kramer7b83c262010-08-25 20:09:43 +0000884 // Local symbol.
885 if (!SD.isExternal() && !S->isUndefined())
886 return SD.getIndex() + /* empty symbol */ 1;
887
888 // External or undefined symbol.
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000889 return SD.getIndex() + NumRegularSections + /* empty symbol */ 1;
Matt Fleming3565a062010-08-16 18:57:57 +0000890}
891
Rafael Espindola737cd212010-10-05 18:01:23 +0000892static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
Rafael Espindola88182132010-10-27 15:18:17 +0000893 bool Used, bool Renamed) {
Rafael Espindola484291c2010-11-01 14:28:48 +0000894 if (Data.getFlags() & ELF_Other_Weakref)
895 return false;
896
Rafael Espindolabd701182010-10-19 19:31:37 +0000897 if (Used)
898 return true;
899
Rafael Espindola88182132010-10-27 15:18:17 +0000900 if (Renamed)
901 return false;
902
Rafael Espindola737cd212010-10-05 18:01:23 +0000903 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindolaa6866962010-10-27 14:44:52 +0000904
Rafael Espindolad1798862010-10-29 23:09:31 +0000905 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
906 return true;
907
Rafael Espindolaa6866962010-10-27 14:44:52 +0000908 const MCSymbol &A = AliasedSymbol(Symbol);
Rafael Espindolad1798862010-10-29 23:09:31 +0000909 if (!A.isVariable() && A.isUndefined() && !Data.isCommon())
Rafael Espindolaa6866962010-10-27 14:44:52 +0000910 return false;
911
Rafael Espindola737cd212010-10-05 18:01:23 +0000912 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
913 return false;
914
Rafael Espindolabd701182010-10-19 19:31:37 +0000915 if (Symbol.isTemporary())
Rafael Espindola737cd212010-10-05 18:01:23 +0000916 return false;
917
918 return true;
919}
920
921static bool isLocal(const MCSymbolData &Data) {
922 if (Data.isExternal())
923 return false;
924
925 const MCSymbol &Symbol = Data.getSymbol();
926 if (Symbol.isUndefined() && !Symbol.isVariable())
927 return false;
928
929 return true;
930}
931
Rafael Espindolabab2a802010-11-10 21:51:05 +0000932void ELFObjectWriterImpl::ComputeIndexMap(MCAssembler &Asm,
933 SectionIndexMapTy &SectionIndexMap) {
934 unsigned Index = 1;
935 for (MCAssembler::iterator it = Asm.begin(),
936 ie = Asm.end(); it != ie; ++it) {
937 const MCSectionELF &Section =
938 static_cast<const MCSectionELF &>(it->getSection());
939 SectionIndexMap[&Section] = Index++;
940 }
941}
942
943void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm,
944 const SectionIndexMapTy &SectionIndexMap) {
Rafael Espindola5c77c162010-10-05 15:48:37 +0000945 // FIXME: Is this the correct place to do this?
946 if (NeedsGOT) {
947 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
948 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
949 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
950 Data.setExternal(true);
Rafael Espindolaf571f9a2010-10-28 18:33:03 +0000951 SetBinding(Data, ELF::STB_GLOBAL);
Rafael Espindola5c77c162010-10-05 15:48:37 +0000952 }
953
Matt Fleming3565a062010-08-16 18:57:57 +0000954 // Build section lookup table.
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000955 NumRegularSections = Asm.size();
Matt Fleming3565a062010-08-16 18:57:57 +0000956
957 // Index 0 is always the empty string.
958 StringMap<uint64_t> StringIndexMap;
959 StringTable += '\x00';
960
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000961 // Add the data for the symbols.
Matt Fleming3565a062010-08-16 18:57:57 +0000962 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
963 ie = Asm.symbol_end(); it != ie; ++it) {
964 const MCSymbol &Symbol = it->getSymbol();
965
Rafael Espindola484291c2010-11-01 14:28:48 +0000966 bool Used = UsedInReloc.count(&Symbol);
967 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
968 if (!isInSymtab(Asm, *it, Used || WeakrefUsed,
Rafael Espindola88182132010-10-27 15:18:17 +0000969 Renames.count(&Symbol)))
Matt Fleming3565a062010-08-16 18:57:57 +0000970 continue;
971
Matt Fleming3565a062010-08-16 18:57:57 +0000972 ELFSymbolData MSD;
973 MSD.SymbolData = it;
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000974 bool Local = isLocal(*it);
Rafael Espindola88182132010-10-27 15:18:17 +0000975 const MCSymbol &RefSymbol = AliasedSymbol(Symbol);
Matt Fleming3565a062010-08-16 18:57:57 +0000976
Rafael Espindola484291c2010-11-01 14:28:48 +0000977 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
978 SetBinding(*it, ELF::STB_WEAK);
979
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000980 if (it->isCommon()) {
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000981 assert(!Local);
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000982 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindolabf052ac2010-10-27 16:04:30 +0000983 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000984 MSD.SectionIndex = ELF::SHN_ABS;
Rafael Espindola88182132010-10-27 15:18:17 +0000985 } else if (RefSymbol.isUndefined()) {
Matt Fleming3565a062010-08-16 18:57:57 +0000986 MSD.SectionIndex = ELF::SHN_UNDEF;
Matt Fleming3565a062010-08-16 18:57:57 +0000987 } else {
Rafael Espindolabab2a802010-11-10 21:51:05 +0000988 const MCSectionELF &Section =
989 static_cast<const MCSectionELF&>(RefSymbol.getSection());
990 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
Rafael Espindola7be2c332010-10-31 00:16:26 +0000991 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
992 NeedsSymtabShndx = true;
Matt Fleming3565a062010-08-16 18:57:57 +0000993 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindola5df0b652010-10-15 15:39:06 +0000994 }
995
Rafael Espindola88182132010-10-27 15:18:17 +0000996 // The @@@ in symbol version is replaced with @ in undefined symbols and
997 // @@ in defined ones.
998 StringRef Name = Symbol.getName();
999 size_t Pos = Name.find("@@@");
1000 std::string FinalName;
1001 if (Pos != StringRef::npos) {
Benjamin Kramer07ee6322010-10-27 19:53:52 +00001002 StringRef Prefix = Name.substr(0, Pos);
Rafael Espindola88182132010-10-27 15:18:17 +00001003 unsigned n = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
Benjamin Kramer07ee6322010-10-27 19:53:52 +00001004 StringRef Suffix = Name.substr(Pos + n);
Rafael Espindola88182132010-10-27 15:18:17 +00001005 FinalName = Prefix.str() + Suffix.str();
1006 } else {
1007 FinalName = Name.str();
1008 }
1009
1010 uint64_t &Entry = StringIndexMap[FinalName];
Rafael Espindolaa6866962010-10-27 14:44:52 +00001011 if (!Entry) {
1012 Entry = StringTable.size();
Rafael Espindola88182132010-10-27 15:18:17 +00001013 StringTable += FinalName;
Rafael Espindolaa6866962010-10-27 14:44:52 +00001014 StringTable += '\x00';
Matt Fleming3565a062010-08-16 18:57:57 +00001015 }
Rafael Espindolaa6866962010-10-27 14:44:52 +00001016 MSD.StringIndex = Entry;
1017 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1018 UndefinedSymbolData.push_back(MSD);
1019 else if (Local)
1020 LocalSymbolData.push_back(MSD);
1021 else
1022 ExternalSymbolData.push_back(MSD);
Matt Fleming3565a062010-08-16 18:57:57 +00001023 }
1024
1025 // Symbols are required to be in lexicographic order.
1026 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1027 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1028 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1029
1030 // Set the symbol indices. Local symbols must come before all other
1031 // symbols with non-local bindings.
Rafael Espindolabab2a802010-11-10 21:51:05 +00001032 unsigned Index = 0;
Matt Fleming3565a062010-08-16 18:57:57 +00001033 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1034 LocalSymbolData[i].SymbolData->setIndex(Index++);
1035 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1036 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1037 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1038 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1039}
1040
1041void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
1042 const MCSectionData &SD) {
1043 if (!Relocations[&SD].empty()) {
1044 MCContext &Ctx = Asm.getContext();
Rafael Espindola4283f4b2010-11-10 19:05:07 +00001045 const MCSectionELF *RelaSection;
Matt Fleming3565a062010-08-16 18:57:57 +00001046 const MCSectionELF &Section =
1047 static_cast<const MCSectionELF&>(SD.getSection());
1048
1049 const StringRef SectionName = Section.getSectionName();
Benjamin Kramer377a5722010-08-17 17:30:07 +00001050 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
Matt Fleming3565a062010-08-16 18:57:57 +00001051 RelaSectionName += SectionName;
Benjamin Kramer299fbe32010-08-17 17:56:13 +00001052
1053 unsigned EntrySize;
1054 if (HasRelocationAddend)
1055 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1056 else
1057 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming3565a062010-08-16 18:57:57 +00001058
Benjamin Kramer377a5722010-08-17 17:30:07 +00001059 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
1060 ELF::SHT_RELA : ELF::SHT_REL, 0,
Matt Fleming3565a062010-08-16 18:57:57 +00001061 SectionKind::getReadOnly(),
Rafael Espindola34be3962010-11-09 23:42:07 +00001062 EntrySize);
Matt Fleming3565a062010-08-16 18:57:57 +00001063
1064 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001065 RelaSD.setAlignment(Is64Bit ? 8 : 4);
Matt Fleming3565a062010-08-16 18:57:57 +00001066
1067 MCDataFragment *F = new MCDataFragment(&RelaSD);
1068
1069 WriteRelocationsFragment(Asm, F, &SD);
1070
Rafael Espindola70703872010-09-30 02:22:20 +00001071 Asm.AddSectionToTheEnd(*Writer, RelaSD, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +00001072 }
1073}
1074
1075void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1076 uint64_t Flags, uint64_t Address,
1077 uint64_t Offset, uint64_t Size,
1078 uint32_t Link, uint32_t Info,
1079 uint64_t Alignment,
1080 uint64_t EntrySize) {
1081 Write32(Name); // sh_name: index into string table
1082 Write32(Type); // sh_type
1083 WriteWord(Flags); // sh_flags
1084 WriteWord(Address); // sh_addr
1085 WriteWord(Offset); // sh_offset
1086 WriteWord(Size); // sh_size
1087 Write32(Link); // sh_link
1088 Write32(Info); // sh_info
1089 WriteWord(Alignment); // sh_addralign
1090 WriteWord(EntrySize); // sh_entsize
1091}
1092
1093void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
1094 MCDataFragment *F,
1095 const MCSectionData *SD) {
1096 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1097 // sort by the r_offset just like gnu as does
1098 array_pod_sort(Relocs.begin(), Relocs.end());
1099
1100 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1101 ELFRelocationEntry entry = Relocs[e - i - 1];
1102
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001103 if (entry.Index < 0)
1104 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1105 else
1106 entry.Index += LocalSymbolData.size() + 1;
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001107 if (Is64Bit) {
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001108 String64(*F, entry.r_offset);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001109
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001110 struct ELF::Elf64_Rela ERE64;
1111 ERE64.setSymbolAndType(entry.Index, entry.Type);
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001112 String64(*F, ERE64.r_info);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001113
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001114 if (HasRelocationAddend)
1115 String64(*F, entry.r_addend);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001116 } else {
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001117 String32(*F, entry.r_offset);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001118
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001119 struct ELF::Elf32_Rela ERE32;
1120 ERE32.setSymbolAndType(entry.Index, entry.Type);
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001121 String32(*F, ERE32.r_info);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001122
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001123 if (HasRelocationAddend)
1124 String32(*F, entry.r_addend);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001125 }
Matt Fleming3565a062010-08-16 18:57:57 +00001126 }
1127}
1128
1129void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
Rafael Espindola4beee3d2010-11-10 22:16:43 +00001130 MCAsmLayout &Layout,
1131 const SectionIndexMapTy &SectionIndexMap) {
Matt Fleming3565a062010-08-16 18:57:57 +00001132 MCContext &Ctx = Asm.getContext();
1133 MCDataFragment *F;
1134
Matt Fleming3565a062010-08-16 18:57:57 +00001135 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1136
Rafael Espindola38738bf2010-09-22 19:04:41 +00001137 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola4283f4b2010-11-10 19:05:07 +00001138 const MCSectionELF *ShstrtabSection =
Rafael Espindola7be2c332010-10-31 00:16:26 +00001139 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
Rafael Espindola3f2d13c2010-11-11 03:40:25 +00001140 SectionKind::getReadOnly());
Rafael Espindola71859c62010-09-16 19:46:31 +00001141 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1142 ShstrtabSD.setAlignment(1);
1143 ShstrtabIndex = Asm.size();
1144
Rafael Espindola4283f4b2010-11-10 19:05:07 +00001145 const MCSectionELF *SymtabSection =
Rafael Espindola7be2c332010-10-31 00:16:26 +00001146 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1147 SectionKind::getReadOnly(),
Rafael Espindola34be3962010-11-09 23:42:07 +00001148 EntrySize);
Matt Fleming3565a062010-08-16 18:57:57 +00001149 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Matt Fleming3565a062010-08-16 18:57:57 +00001150 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
Rafael Espindola7be2c332010-10-31 00:16:26 +00001151 SymbolTableIndex = Asm.size();
1152
1153 MCSectionData *SymtabShndxSD = NULL;
1154
1155 if (NeedsSymtabShndx) {
Rafael Espindola4283f4b2010-11-10 19:05:07 +00001156 const MCSectionELF *SymtabShndxSection =
Rafael Espindola7be2c332010-10-31 00:16:26 +00001157 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
Rafael Espindola34be3962010-11-09 23:42:07 +00001158 SectionKind::getReadOnly(), 4);
Rafael Espindola7be2c332010-10-31 00:16:26 +00001159 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1160 SymtabShndxSD->setAlignment(4);
1161 }
Matt Fleming3565a062010-08-16 18:57:57 +00001162
Matt Fleming3565a062010-08-16 18:57:57 +00001163 const MCSection *StrtabSection;
1164 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
Rafael Espindola3f2d13c2010-11-11 03:40:25 +00001165 SectionKind::getReadOnly());
Matt Fleming3565a062010-08-16 18:57:57 +00001166 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1167 StrtabSD.setAlignment(1);
Matt Fleming3565a062010-08-16 18:57:57 +00001168 StringTableIndex = Asm.size();
1169
Rafael Espindolac3c413f2010-09-27 22:04:54 +00001170 WriteRelocations(Asm, Layout);
Rafael Espindola71859c62010-09-16 19:46:31 +00001171
1172 // Symbol table
1173 F = new MCDataFragment(&SymtabSD);
Rafael Espindola7be2c332010-10-31 00:16:26 +00001174 MCDataFragment *ShndxF = NULL;
1175 if (NeedsSymtabShndx) {
1176 ShndxF = new MCDataFragment(SymtabShndxSD);
1177 Asm.AddSectionToTheEnd(*Writer, *SymtabShndxSD, Layout);
1178 }
Rafael Espindola4beee3d2010-11-10 22:16:43 +00001179 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
Rafael Espindola70703872010-09-30 02:22:20 +00001180 Asm.AddSectionToTheEnd(*Writer, SymtabSD, Layout);
Rafael Espindola71859c62010-09-16 19:46:31 +00001181
Matt Fleming3565a062010-08-16 18:57:57 +00001182 F = new MCDataFragment(&StrtabSD);
1183 F->getContents().append(StringTable.begin(), StringTable.end());
Rafael Espindola70703872010-09-30 02:22:20 +00001184 Asm.AddSectionToTheEnd(*Writer, StrtabSD, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +00001185
Matt Fleming3565a062010-08-16 18:57:57 +00001186 F = new MCDataFragment(&ShstrtabSD);
1187
Matt Fleming3565a062010-08-16 18:57:57 +00001188 // Section header string table.
1189 //
1190 // The first entry of a string table holds a null character so skip
1191 // section 0.
1192 uint64_t Index = 1;
1193 F->getContents() += '\x00';
1194
1195 for (MCAssembler::const_iterator it = Asm.begin(),
1196 ie = Asm.end(); it != ie; ++it) {
Matt Fleming3565a062010-08-16 18:57:57 +00001197 const MCSectionELF &Section =
Benjamin Kramer368ae7e2010-08-17 00:00:46 +00001198 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola51efe7a2010-09-23 14:14:56 +00001199 // FIXME: We could merge suffixes like in .text and .rela.text.
Matt Fleming3565a062010-08-16 18:57:57 +00001200
1201 // Remember the index into the string table so we can write it
1202 // into the sh_name field of the section header table.
1203 SectionStringTableIndex[&it->getSection()] = Index;
1204
1205 Index += Section.getSectionName().size() + 1;
1206 F->getContents() += Section.getSectionName();
1207 F->getContents() += '\x00';
1208 }
1209
Rafael Espindola70703872010-09-30 02:22:20 +00001210 Asm.AddSectionToTheEnd(*Writer, ShstrtabSD, Layout);
1211}
1212
1213bool ELFObjectWriterImpl::IsFixupFullyResolved(const MCAssembler &Asm,
1214 const MCValue Target,
1215 bool IsPCRel,
1216 const MCFragment *DF) const {
1217 // If this is a PCrel relocation, find the section this fixup value is
1218 // relative to.
1219 const MCSection *BaseSection = 0;
1220 if (IsPCRel) {
1221 BaseSection = &DF->getParent()->getSection();
1222 assert(BaseSection);
1223 }
1224
1225 const MCSection *SectionA = 0;
1226 const MCSymbol *SymbolA = 0;
1227 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1228 SymbolA = &A->getSymbol();
1229 SectionA = &SymbolA->getSection();
1230 }
1231
1232 const MCSection *SectionB = 0;
1233 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1234 SectionB = &B->getSymbol().getSection();
1235 }
1236
1237 if (!BaseSection)
1238 return SectionA == SectionB;
1239
1240 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1241 if (DataA.isExternal())
1242 return false;
1243
1244 return !SectionB && BaseSection == SectionA;
Matt Fleming3565a062010-08-16 18:57:57 +00001245}
1246
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001247void ELFObjectWriterImpl::WriteSection(MCAssembler &Asm,
1248 const SectionIndexMapTy &SectionIndexMap,
1249 uint64_t Offset, uint64_t Size,
1250 uint64_t Alignment,
1251 const MCSectionELF &Section) {
1252 uint64_t sh_link = 0;
1253 uint64_t sh_info = 0;
1254
1255 switch(Section.getType()) {
1256 case ELF::SHT_DYNAMIC:
1257 sh_link = SectionStringTableIndex[&Section];
1258 sh_info = 0;
1259 break;
1260
1261 case ELF::SHT_REL:
1262 case ELF::SHT_RELA: {
1263 const MCSectionELF *SymtabSection;
1264 const MCSectionELF *InfoSection;
1265 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1266 0,
Rafael Espindola3f2d13c2010-11-11 03:40:25 +00001267 SectionKind::getReadOnly());
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001268 sh_link = SectionIndexMap.lookup(SymtabSection);
1269 assert(sh_link && ".symtab not found");
1270
1271 // Remove ".rel" and ".rela" prefixes.
1272 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1273 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1274
1275 InfoSection = Asm.getContext().getELFSection(SectionName,
1276 ELF::SHT_PROGBITS, 0,
Rafael Espindola3f2d13c2010-11-11 03:40:25 +00001277 SectionKind::getReadOnly());
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001278 sh_info = SectionIndexMap.lookup(InfoSection);
1279 break;
1280 }
1281
1282 case ELF::SHT_SYMTAB:
1283 case ELF::SHT_DYNSYM:
1284 sh_link = StringTableIndex;
1285 sh_info = LastLocalSymbolIndex;
1286 break;
1287
1288 case ELF::SHT_SYMTAB_SHNDX:
1289 sh_link = SymbolTableIndex;
1290 break;
1291
1292 case ELF::SHT_PROGBITS:
1293 case ELF::SHT_STRTAB:
1294 case ELF::SHT_NOBITS:
1295 case ELF::SHT_NULL:
1296 case ELF::SHT_ARM_ATTRIBUTES:
1297 // Nothing to do.
1298 break;
1299
1300 default:
1301 assert(0 && "FIXME: sh_type value not supported!");
1302 break;
1303 }
1304
1305 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1306 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1307 Alignment, Section.getEntrySize());
1308}
1309
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001310void ELFObjectWriterImpl::WriteObject(MCAssembler &Asm,
Matt Fleming3565a062010-08-16 18:57:57 +00001311 const MCAsmLayout &Layout) {
Rafael Espindolabab2a802010-11-10 21:51:05 +00001312 SectionIndexMapTy SectionIndexMap;
1313
1314 ComputeIndexMap(Asm, SectionIndexMap);
1315
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001316 // Compute symbol table information.
Rafael Espindolabab2a802010-11-10 21:51:05 +00001317 ComputeSymbolTable(Asm, SectionIndexMap);
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001318
Matt Fleming3565a062010-08-16 18:57:57 +00001319 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
Rafael Espindola4beee3d2010-11-10 22:16:43 +00001320 const_cast<MCAsmLayout&>(Layout),
1321 SectionIndexMap);
Matt Fleming3565a062010-08-16 18:57:57 +00001322
Rafael Espindola1d739a02010-11-10 22:34:07 +00001323 // Update to include the metadata sections.
1324 ComputeIndexMap(Asm, SectionIndexMap);
1325
Matt Fleming3565a062010-08-16 18:57:57 +00001326 // Add 1 for the null section.
1327 unsigned NumSections = Asm.size() + 1;
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001328 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1329 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1330 uint64_t FileOff = HeaderSize;
Matt Fleming3565a062010-08-16 18:57:57 +00001331
1332 for (MCAssembler::const_iterator it = Asm.begin(),
1333 ie = Asm.end(); it != ie; ++it) {
1334 const MCSectionData &SD = *it;
Matt Fleming3565a062010-08-16 18:57:57 +00001335
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001336 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1337
Matt Fleming3565a062010-08-16 18:57:57 +00001338 // Get the size of the section in the output file (including padding).
1339 uint64_t Size = Layout.getSectionFileSize(&SD);
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001340
1341 FileOff += Size;
Matt Fleming3565a062010-08-16 18:57:57 +00001342 }
1343
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001344 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1345
Matt Fleming3565a062010-08-16 18:57:57 +00001346 // Write out the ELF header ...
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001347 WriteHeader(FileOff - HeaderSize, NumSections);
1348
1349 FileOff = HeaderSize;
Matt Fleming3565a062010-08-16 18:57:57 +00001350
1351 // ... then all of the sections ...
1352 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1353
1354 for (MCAssembler::const_iterator it = Asm.begin(),
1355 ie = Asm.end(); it != ie; ++it) {
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001356 const MCSectionData &SD = *it;
1357
1358 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1359 WriteZeros(Padding);
1360 FileOff += Padding;
1361
Matt Fleming3565a062010-08-16 18:57:57 +00001362 // Remember the offset into the file for this section.
1363 SectionOffsetMap[&it->getSection()] = FileOff;
Benjamin Kramer44cbde82010-08-19 13:44:49 +00001364
Matt Fleming3565a062010-08-16 18:57:57 +00001365 FileOff += Layout.getSectionFileSize(&SD);
1366
1367 Asm.WriteSectionData(it, Layout, Writer);
1368 }
1369
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001370 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1371 WriteZeros(Padding);
1372 FileOff += Padding;
1373
Matt Fleming3565a062010-08-16 18:57:57 +00001374 // ... and then the section header table.
1375 // Should we align the section header table?
1376 //
1377 // Null section first.
Rafael Espindola7be2c332010-10-31 00:16:26 +00001378 uint64_t FirstSectionSize =
1379 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1380 uint32_t FirstSectionLink =
1381 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1382 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
Matt Fleming3565a062010-08-16 18:57:57 +00001383
1384 for (MCAssembler::const_iterator it = Asm.begin(),
1385 ie = Asm.end(); it != ie; ++it) {
1386 const MCSectionData &SD = *it;
1387 const MCSectionELF &Section =
1388 static_cast<const MCSectionELF&>(SD.getSection());
1389
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001390 WriteSection(Asm, SectionIndexMap, SectionOffsetMap[&Section],
1391 Layout.getSectionSize(&SD),
1392 SD.getAlignment(), Section);
Matt Fleming3565a062010-08-16 18:57:57 +00001393 }
1394}
1395
1396ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1397 bool Is64Bit,
Roman Divacky5baf79e2010-09-09 17:57:50 +00001398 Triple::OSType OSType,
Wesley Peckeecb8582010-10-22 15:52:49 +00001399 uint16_t EMachine,
Matt Fleming3565a062010-08-16 18:57:57 +00001400 bool IsLittleEndian,
1401 bool HasRelocationAddend)
1402 : MCObjectWriter(OS, IsLittleEndian)
1403{
Wesley Peckeecb8582010-10-22 15:52:49 +00001404 Impl = new ELFObjectWriterImpl(this, Is64Bit, EMachine,
1405 HasRelocationAddend, OSType);
Matt Fleming3565a062010-08-16 18:57:57 +00001406}
1407
1408ELFObjectWriter::~ELFObjectWriter() {
1409 delete (ELFObjectWriterImpl*) Impl;
1410}
1411
1412void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1413 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1414}
1415
1416void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1417 const MCAsmLayout &Layout,
1418 const MCFragment *Fragment,
1419 const MCFixup &Fixup, MCValue Target,
1420 uint64_t &FixedValue) {
1421 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1422 Target, FixedValue);
1423}
1424
Rafael Espindola70703872010-09-30 02:22:20 +00001425bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1426 const MCValue Target,
1427 bool IsPCRel,
1428 const MCFragment *DF) const {
1429 return ((ELFObjectWriterImpl*) Impl)->IsFixupFullyResolved(Asm, Target,
1430 IsPCRel, DF);
1431}
1432
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001433void ELFObjectWriter::WriteObject(MCAssembler &Asm,
Matt Fleming3565a062010-08-16 18:57:57 +00001434 const MCAsmLayout &Layout) {
1435 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);
1436}