blob: 93ea77a0e1c5dfc965f31d8d76547f3788c314d5 [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 Espindola9302bd62010-11-11 17:24:43 +0000473 MCExpr::ExprKind Kind = Value->getKind();
474 switch (Kind) {
475 case MCExpr::SymbolRef: {
476 const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Value);
477 S = &Ref->getSymbol();
478 break;
479 }
480 case MCExpr::Target: {
481 const MCTargetExpr *TExp = static_cast<const MCTargetExpr*>(Value);
482 MCValue Res;
483 TExp->EvaluateAsRelocatableImpl(Res, NULL);
484 S = &Res.getSymA()->getSymbol();
485 break;
486 }
487 default:
Rafael Espindolaa6866962010-10-27 14:44:52 +0000488 return *S;
Rafael Espindola9302bd62010-11-11 17:24:43 +0000489 }
Rafael Espindolade89b012010-10-15 18:25:33 +0000490 }
491 return *S;
492}
493
Rafael Espindola88182132010-10-27 15:18:17 +0000494void ELFObjectWriterImpl::ExecutePostLayoutBinding(MCAssembler &Asm) {
495 // The presence of symbol versions causes undefined symbols and
496 // versions declared with @@@ to be renamed.
497
498 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
499 ie = Asm.symbol_end(); it != ie; ++it) {
500 const MCSymbol &Alias = it->getSymbol();
Rafael Espindola88182132010-10-27 15:18:17 +0000501 const MCSymbol &Symbol = AliasedSymbol(Alias);
Rafael Espindolaf571f9a2010-10-28 18:33:03 +0000502 MCSymbolData &SD = Asm.getSymbolData(Symbol);
503
504 // Undefined symbols are global, but this is the first place we
505 // are able to set it.
506 if (Symbol.isUndefined() && !Symbol.isVariable()) {
507 if (GetBinding(SD) == ELF::STB_LOCAL) {
508 SetBinding(SD, ELF::STB_GLOBAL);
509 SetBinding(*it, ELF::STB_GLOBAL);
510 }
511 }
512
513 // Not an alias.
514 if (&Symbol == &Alias)
515 continue;
516
Benjamin Kramer07ee6322010-10-27 19:53:52 +0000517 StringRef AliasName = Alias.getName();
Rafael Espindola88182132010-10-27 15:18:17 +0000518 size_t Pos = AliasName.find('@');
519 if (Pos == StringRef::npos)
520 continue;
521
Rafael Espindolaf571f9a2010-10-28 18:33:03 +0000522 // Aliases defined with .symvar copy the binding from the symbol they alias.
523 // This is the first place we are able to copy this information.
524 it->setExternal(SD.isExternal());
525 SetBinding(*it, GetBinding(SD));
526
Benjamin Kramer07ee6322010-10-27 19:53:52 +0000527 StringRef Rest = AliasName.substr(Pos);
Rafael Espindola88182132010-10-27 15:18:17 +0000528 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
529 continue;
530
Rafael Espindola83ff4d22010-10-27 17:56:18 +0000531 // FIXME: produce a better error message.
532 if (Symbol.isUndefined() && Rest.startswith("@@") &&
533 !Rest.startswith("@@@"))
534 report_fatal_error("A @@ version cannot be undefined");
535
Benjamin Kramer07ee6322010-10-27 19:53:52 +0000536 Renames.insert(std::make_pair(&Symbol, &Alias));
Rafael Espindola88182132010-10-27 15:18:17 +0000537 }
538}
539
Rafael Espindola7be2c332010-10-31 00:16:26 +0000540void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *SymtabF,
541 MCDataFragment *ShndxF,
542 ELFSymbolData &MSD,
Matt Fleming3565a062010-08-16 18:57:57 +0000543 const MCAsmLayout &Layout) {
Rafael Espindola152c1062010-10-06 21:02:29 +0000544 MCSymbolData &OrigData = *MSD.SymbolData;
Rafael Espindolade89b012010-10-15 18:25:33 +0000545 MCSymbolData &Data =
546 Layout.getAssembler().getSymbolData(AliasedSymbol(OrigData.getSymbol()));
Rafael Espindola152c1062010-10-06 21:02:29 +0000547
Rafael Espindola7be2c332010-10-31 00:16:26 +0000548 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
549 Data.getSymbol().isVariable();
550
Rafael Espindola152c1062010-10-06 21:02:29 +0000551 uint8_t Binding = GetBinding(OrigData);
552 uint8_t Visibility = GetVisibility(OrigData);
553 uint8_t Type = GetType(Data);
554
555 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
556 uint8_t Other = Visibility;
557
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000558 uint64_t Value = SymbolValue(Data, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000559 uint64_t Size = 0;
560 const MCExpr *ESize;
561
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000562 assert(!(Data.isCommon() && !Data.isExternal()));
563
Matt Fleming3565a062010-08-16 18:57:57 +0000564 ESize = Data.getSize();
565 if (Data.getSize()) {
566 MCValue Res;
567 if (ESize->getKind() == MCExpr::Binary) {
568 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
569
570 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
Benjamin Kramer24f12062010-10-17 07:38:40 +0000571 assert(!Res.getSymA() || !Res.getSymA()->getSymbol().isDefined());
572 assert(!Res.getSymB() || !Res.getSymB()->getSymbol().isDefined());
Rafael Espindolaf230df92010-10-16 18:23:53 +0000573 Size = Res.getConstant();
Matt Fleming3565a062010-08-16 18:57:57 +0000574 }
575 } else if (ESize->getKind() == MCExpr::Constant) {
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000576 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
Matt Fleming3565a062010-08-16 18:57:57 +0000577 } else {
578 assert(0 && "Unsupported size expression");
579 }
580 }
581
582 // Write out the symbol table entry
Rafael Espindola7be2c332010-10-31 00:16:26 +0000583 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
584 Size, Other, MSD.SectionIndex, IsReserved);
Matt Fleming3565a062010-08-16 18:57:57 +0000585}
586
Rafael Espindola7be2c332010-10-31 00:16:26 +0000587void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *SymtabF,
588 MCDataFragment *ShndxF,
Matt Fleming3565a062010-08-16 18:57:57 +0000589 const MCAssembler &Asm,
Rafael Espindola71859c62010-09-16 19:46:31 +0000590 const MCAsmLayout &Layout,
Rafael Espindola4beee3d2010-11-10 22:16:43 +0000591 const SectionIndexMapTy &SectionIndexMap) {
Matt Fleming3565a062010-08-16 18:57:57 +0000592 // The string table must be emitted first because we need the index
593 // into the string table for all the symbol names.
594 assert(StringTable.size() && "Missing string table");
595
596 // FIXME: Make sure the start of the symbol table is aligned.
597
598 // The first entry is the undefined symbol entry.
Rafael Espindola7be2c332010-10-31 00:16:26 +0000599 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
Matt Fleming3565a062010-08-16 18:57:57 +0000600
601 // Write the symbol table entries.
602 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
603 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
604 ELFSymbolData &MSD = LocalSymbolData[i];
Rafael Espindola7be2c332010-10-31 00:16:26 +0000605 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000606 }
607
Rafael Espindola71859c62010-09-16 19:46:31 +0000608 // Write out a symbol table entry for each regular section.
Rafael Espindola4beee3d2010-11-10 22:16:43 +0000609 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
610 ++i) {
Eli Friedmana44fa242010-08-16 21:17:09 +0000611 const MCSectionELF &Section =
Rafael Espindola4beee3d2010-11-10 22:16:43 +0000612 static_cast<const MCSectionELF&>(i->getSection());
613 if (Section.getType() == ELF::SHT_RELA ||
614 Section.getType() == ELF::SHT_REL ||
615 Section.getType() == ELF::SHT_STRTAB ||
616 Section.getType() == ELF::SHT_SYMTAB)
Eli Friedmana44fa242010-08-16 21:17:09 +0000617 continue;
Rafael Espindola7be2c332010-10-31 00:16:26 +0000618 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
Rafael Espindola4beee3d2010-11-10 22:16:43 +0000619 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section), false);
Eli Friedmana44fa242010-08-16 21:17:09 +0000620 LastLocalSymbolIndex++;
621 }
Matt Fleming3565a062010-08-16 18:57:57 +0000622
623 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
624 ELFSymbolData &MSD = ExternalSymbolData[i];
625 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola3223f192010-10-06 16:47:31 +0000626 assert(((Data.getFlags() & ELF_STB_Global) ||
627 (Data.getFlags() & ELF_STB_Weak)) &&
628 "External symbol requires STB_GLOBAL or STB_WEAK flag");
Rafael Espindola7be2c332010-10-31 00:16:26 +0000629 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
Rafael Espindolae15eb4e2010-09-23 19:55:14 +0000630 if (GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming3565a062010-08-16 18:57:57 +0000631 LastLocalSymbolIndex++;
632 }
633
634 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
635 ELFSymbolData &MSD = UndefinedSymbolData[i];
636 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola7be2c332010-10-31 00:16:26 +0000637 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
Rafael Espindolae15eb4e2010-09-23 19:55:14 +0000638 if (GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming3565a062010-08-16 18:57:57 +0000639 LastLocalSymbolIndex++;
640 }
641}
642
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000643static bool ShouldRelocOnSymbol(const MCSymbolData &SD,
Rafael Espindola3729d002010-10-05 23:57:26 +0000644 const MCValue &Target,
645 const MCFragment &F) {
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000646 const MCSymbol &Symbol = SD.getSymbol();
647 if (Symbol.isUndefined())
648 return true;
Rafael Espindola73ffea42010-09-25 05:42:19 +0000649
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000650 const MCSectionELF &Section =
651 static_cast<const MCSectionELF&>(Symbol.getSection());
652
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000653 if (SD.isExternal())
654 return true;
655
Rafael Espindola8cecf252010-10-06 16:23:36 +0000656 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
Rafael Espindola3729d002010-10-05 23:57:26 +0000657 const MCSectionELF &Sec2 =
658 static_cast<const MCSectionELF&>(F.getParent()->getSection());
659
Rafael Espindolace2d3c52010-10-18 20:25:33 +0000660 if (Section.getKind().isBSS())
661 return false;
662
Rafael Espindola8cecf252010-10-06 16:23:36 +0000663 if (&Sec2 != &Section &&
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000664 (Kind == MCSymbolRefExpr::VK_PLT ||
665 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
666 Kind == MCSymbolRefExpr::VK_GOTOFF))
Rafael Espindola3729d002010-10-05 23:57:26 +0000667 return true;
668
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000669 if (Section.getFlags() & MCSectionELF::SHF_MERGE)
670 return Target.getConstant() != 0;
671
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000672 return false;
Rafael Espindola73ffea42010-09-25 05:42:19 +0000673}
674
Benjamin Kramere5b57342010-08-17 18:20:28 +0000675// FIXME: this is currently X86/X86_64 only
Matt Fleming3565a062010-08-16 18:57:57 +0000676void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
677 const MCAsmLayout &Layout,
678 const MCFragment *Fragment,
679 const MCFixup &Fixup,
680 MCValue Target,
681 uint64_t &FixedValue) {
Matt Fleming3565a062010-08-16 18:57:57 +0000682 int64_t Addend = 0;
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000683 int Index = 0;
Benjamin Kramer95c602a2010-08-27 10:38:39 +0000684 int64_t Value = Target.getConstant();
Rafael Espindola03f1b742010-11-11 16:48:11 +0000685 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
686 const MCSymbol &ASymbol = AliasedSymbol(Symbol);
687 const MCSymbol *RenamedP = Renames.lookup(&Symbol);
688 if (!RenamedP)
689 RenamedP = &ASymbol;
690 const MCSymbol &Renamed = *RenamedP;
Matt Fleming3565a062010-08-16 18:57:57 +0000691
Rafael Espindola00074892010-09-17 22:34:41 +0000692 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
Benjamin Kramer81cfb852010-08-17 19:45:05 +0000693 if (!Target.isAbsolute()) {
Rafael Espindola03f1b742010-11-11 16:48:11 +0000694 MCSymbolData &SD = Asm.getSymbolData(Symbol);
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000695 MCFragment *F = SD.getFragment();
Matt Fleming3565a062010-08-16 18:57:57 +0000696
Rafael Espindola9d8b7552010-10-03 00:46:57 +0000697 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
698 const MCSymbol &SymbolB = RefB->getSymbol();
699 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
700 IsPCRel = true;
Rafael Espindola55fb1022010-10-04 15:59:01 +0000701 MCSectionData *Sec = Fragment->getParent();
702
703 // Offset of the symbol in the section
704 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
705
706 // Ofeset of the relocation in the section
707 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
708 Value += b - a;
Rafael Espindola9d8b7552010-10-03 00:46:57 +0000709 }
710
Rafael Espindola3729d002010-10-05 23:57:26 +0000711 bool RelocOnSymbol = ShouldRelocOnSymbol(SD, Target, *Fragment);
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000712 if (!RelocOnSymbol) {
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000713 Index = F->getParent()->getOrdinal();
Rafael Espindolaa6489182010-09-24 21:19:03 +0000714
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000715 MCSectionData *FSD = F->getParent();
716 // Offset of the symbol in the section
717 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000718 } else {
Rafael Espindola03f1b742010-11-11 16:48:11 +0000719 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
720 WeakrefUsedInReloc.insert(&Renamed);
721 else
722 UsedInReloc.insert(&Renamed);
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000723 Index = -1;
724 }
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000725 Addend = Value;
726 // Compensate for the addend on i386.
727 if (Is64Bit)
728 Value = 0;
Matt Fleming3565a062010-08-16 18:57:57 +0000729 }
730
Benjamin Kramer95c602a2010-08-27 10:38:39 +0000731 FixedValue = Value;
732
Matt Fleming3565a062010-08-16 18:57:57 +0000733 // determine the type of the relocation
Rafael Espindola28f9ac82010-10-04 18:44:25 +0000734
735 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000736 unsigned Type;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000737 if (Is64Bit) {
738 if (IsPCRel) {
Rafael Espindola92bf6682010-10-04 19:04:13 +0000739 switch (Modifier) {
Rafael Espindola9edab3a2010-10-18 16:58:03 +0000740 default:
741 llvm_unreachable("Unimplemented");
Rafael Espindola92bf6682010-10-04 19:04:13 +0000742 case MCSymbolRefExpr::VK_None:
743 Type = ELF::R_X86_64_PC32;
744 break;
745 case MCSymbolRefExpr::VK_PLT:
746 Type = ELF::R_X86_64_PLT32;
747 break;
Rafael Espindolaa0a2f872010-10-28 14:22:44 +0000748 case MCSymbolRefExpr::VK_GOTPCREL:
Rafael Espindola607d1f62010-10-04 19:51:39 +0000749 Type = ELF::R_X86_64_GOTPCREL;
750 break;
Rafael Espindolabc82d8b2010-10-27 20:28:07 +0000751 case MCSymbolRefExpr::VK_GOTTPOFF:
752 Type = ELF::R_X86_64_GOTTPOFF;
753 break;
754 case MCSymbolRefExpr::VK_TLSGD:
755 Type = ELF::R_X86_64_TLSGD;
756 break;
Rafael Espindolab4d17212010-10-28 15:02:40 +0000757 case MCSymbolRefExpr::VK_TLSLD:
758 Type = ELF::R_X86_64_TLSLD;
759 break;
Rafael Espindola92bf6682010-10-04 19:04:13 +0000760 }
Benjamin Kramere5b57342010-08-17 18:20:28 +0000761 } else {
762 switch ((unsigned)Fixup.getKind()) {
763 default: llvm_unreachable("invalid fixup kind!");
764 case FK_Data_8: Type = ELF::R_X86_64_64; break;
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000765 case X86::reloc_signed_4byte:
Benjamin Kramere5b57342010-08-17 18:20:28 +0000766 case X86::reloc_pcrel_4byte:
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000767 assert(isInt<32>(Target.getConstant()));
Rafael Espindola28f9ac82010-10-04 18:44:25 +0000768 switch (Modifier) {
Rafael Espindola9edab3a2010-10-18 16:58:03 +0000769 default:
770 llvm_unreachable("Unimplemented");
Rafael Espindola28f9ac82010-10-04 18:44:25 +0000771 case MCSymbolRefExpr::VK_None:
772 Type = ELF::R_X86_64_32S;
773 break;
774 case MCSymbolRefExpr::VK_GOT:
775 Type = ELF::R_X86_64_GOT32;
776 break;
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000777 case MCSymbolRefExpr::VK_GOTPCREL:
Rafael Espindola8cecf252010-10-06 16:23:36 +0000778 Type = ELF::R_X86_64_GOTPCREL;
779 break;
Rafael Espindolabc82d8b2010-10-27 20:28:07 +0000780 case MCSymbolRefExpr::VK_TPOFF:
781 Type = ELF::R_X86_64_TPOFF32;
782 break;
Rafael Espindolaaa8f1f02010-10-28 15:11:03 +0000783 case MCSymbolRefExpr::VK_DTPOFF:
784 Type = ELF::R_X86_64_DTPOFF32;
785 break;
Rafael Espindola28f9ac82010-10-04 18:44:25 +0000786 }
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000787 break;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000788 case FK_Data_4:
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000789 Type = ELF::R_X86_64_32;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000790 break;
791 case FK_Data_2: Type = ELF::R_X86_64_16; break;
792 case X86::reloc_pcrel_1byte:
793 case FK_Data_1: Type = ELF::R_X86_64_8; break;
794 }
795 }
Matt Fleming3565a062010-08-16 18:57:57 +0000796 } else {
Benjamin Kramere5b57342010-08-17 18:20:28 +0000797 if (IsPCRel) {
Rafael Espindola9edab3a2010-10-18 16:58:03 +0000798 switch (Modifier) {
799 default:
Rafael Espindola24dc9ec2010-10-18 19:33:01 +0000800 llvm_unreachable("Unimplemented");
801 case MCSymbolRefExpr::VK_None:
Rafael Espindola9baee3b2010-10-18 18:03:28 +0000802 Type = ELF::R_386_PC32;
Rafael Espindola9baee3b2010-10-18 18:03:28 +0000803 break;
Rafael Espindola9edab3a2010-10-18 16:58:03 +0000804 case MCSymbolRefExpr::VK_PLT:
805 Type = ELF::R_386_PLT32;
806 break;
807 }
Benjamin Kramere5b57342010-08-17 18:20:28 +0000808 } else {
809 switch ((unsigned)Fixup.getKind()) {
810 default: llvm_unreachable("invalid fixup kind!");
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000811
Rafael Espindola24ba4f72010-10-24 17:35:42 +0000812 case X86::reloc_global_offset_table:
813 Type = ELF::R_386_GOTPC;
814 break;
815
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000816 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
817 // instead?
818 case X86::reloc_signed_4byte:
Benjamin Kramere5b57342010-08-17 18:20:28 +0000819 case X86::reloc_pcrel_4byte:
Rafael Espindolabd701182010-10-19 19:31:37 +0000820 case FK_Data_4:
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000821 switch (Modifier) {
Rafael Espindola9edab3a2010-10-18 16:58:03 +0000822 default:
823 llvm_unreachable("Unimplemented");
Rafael Espindolabd701182010-10-19 19:31:37 +0000824 case MCSymbolRefExpr::VK_None:
Rafael Espindola24ba4f72010-10-24 17:35:42 +0000825 Type = ELF::R_386_32;
Rafael Espindolabd701182010-10-19 19:31:37 +0000826 break;
Rafael Espindolaeada3042010-10-18 20:47:21 +0000827 case MCSymbolRefExpr::VK_GOT:
828 Type = ELF::R_386_GOT32;
829 break;
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000830 case MCSymbolRefExpr::VK_GOTOFF:
831 Type = ELF::R_386_GOTOFF;
832 break;
Rafael Espindola3cede2d2010-10-27 21:23:52 +0000833 case MCSymbolRefExpr::VK_TLSGD:
834 Type = ELF::R_386_TLS_GD;
835 break;
836 case MCSymbolRefExpr::VK_TPOFF:
837 Type = ELF::R_386_TLS_LE_32;
838 break;
839 case MCSymbolRefExpr::VK_INDNTPOFF:
840 Type = ELF::R_386_TLS_IE;
841 break;
842 case MCSymbolRefExpr::VK_NTPOFF:
843 Type = ELF::R_386_TLS_LE;
844 break;
Rafael Espindolaa0a2f872010-10-28 14:22:44 +0000845 case MCSymbolRefExpr::VK_GOTNTPOFF:
846 Type = ELF::R_386_TLS_GOTIE;
847 break;
Rafael Espindolaa264f722010-10-28 14:37:09 +0000848 case MCSymbolRefExpr::VK_TLSLDM:
849 Type = ELF::R_386_TLS_LDM;
850 break;
Rafael Espindola0cf15d62010-10-28 14:48:59 +0000851 case MCSymbolRefExpr::VK_DTPOFF:
852 Type = ELF::R_386_TLS_LDO_32;
853 break;
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000854 }
855 break;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000856 case FK_Data_2: Type = ELF::R_386_16; break;
857 case X86::reloc_pcrel_1byte:
858 case FK_Data_1: Type = ELF::R_386_8; break;
859 }
Matt Fleming3565a062010-08-16 18:57:57 +0000860 }
861 }
862
Rafael Espindolaa0a2f872010-10-28 14:22:44 +0000863 if (RelocNeedsGOT(Modifier))
Rafael Espindola5c77c162010-10-05 15:48:37 +0000864 NeedsGOT = true;
865
Benjamin Kramere5b57342010-08-17 18:20:28 +0000866 ELFRelocationEntry ERE;
867
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000868 ERE.Index = Index;
869 ERE.Type = Type;
Rafael Espindola03f1b742010-11-11 16:48:11 +0000870 ERE.Symbol = &Renamed;
Matt Fleming3565a062010-08-16 18:57:57 +0000871
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000872 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
Benjamin Kramere5b57342010-08-17 18:20:28 +0000873
Matt Fleming3565a062010-08-16 18:57:57 +0000874 if (HasRelocationAddend)
875 ERE.r_addend = Addend;
Benjamin Kramer172d7d62010-08-17 00:33:24 +0000876 else
877 ERE.r_addend = 0; // Silence compiler warning.
Matt Fleming3565a062010-08-16 18:57:57 +0000878
879 Relocations[Fragment->getParent()].push_back(ERE);
880}
881
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000882uint64_t
883ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
884 const MCSymbol *S) {
Benjamin Kramer7b83c262010-08-25 20:09:43 +0000885 MCSymbolData &SD = Asm.getSymbolData(*S);
Eli Friedmanf8020a32010-08-16 19:15:06 +0000886
Benjamin Kramer7b83c262010-08-25 20:09:43 +0000887 // Local symbol.
888 if (!SD.isExternal() && !S->isUndefined())
889 return SD.getIndex() + /* empty symbol */ 1;
890
891 // External or undefined symbol.
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000892 return SD.getIndex() + NumRegularSections + /* empty symbol */ 1;
Matt Fleming3565a062010-08-16 18:57:57 +0000893}
894
Rafael Espindola737cd212010-10-05 18:01:23 +0000895static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
Rafael Espindola88182132010-10-27 15:18:17 +0000896 bool Used, bool Renamed) {
Rafael Espindola484291c2010-11-01 14:28:48 +0000897 if (Data.getFlags() & ELF_Other_Weakref)
898 return false;
899
Rafael Espindolabd701182010-10-19 19:31:37 +0000900 if (Used)
901 return true;
902
Rafael Espindola88182132010-10-27 15:18:17 +0000903 if (Renamed)
904 return false;
905
Rafael Espindola737cd212010-10-05 18:01:23 +0000906 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindolaa6866962010-10-27 14:44:52 +0000907
Rafael Espindolad1798862010-10-29 23:09:31 +0000908 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
909 return true;
910
Rafael Espindolaa6866962010-10-27 14:44:52 +0000911 const MCSymbol &A = AliasedSymbol(Symbol);
Rafael Espindolad1798862010-10-29 23:09:31 +0000912 if (!A.isVariable() && A.isUndefined() && !Data.isCommon())
Rafael Espindolaa6866962010-10-27 14:44:52 +0000913 return false;
914
Rafael Espindola737cd212010-10-05 18:01:23 +0000915 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
916 return false;
917
Rafael Espindolabd701182010-10-19 19:31:37 +0000918 if (Symbol.isTemporary())
Rafael Espindola737cd212010-10-05 18:01:23 +0000919 return false;
920
921 return true;
922}
923
924static bool isLocal(const MCSymbolData &Data) {
925 if (Data.isExternal())
926 return false;
927
928 const MCSymbol &Symbol = Data.getSymbol();
929 if (Symbol.isUndefined() && !Symbol.isVariable())
930 return false;
931
932 return true;
933}
934
Rafael Espindolabab2a802010-11-10 21:51:05 +0000935void ELFObjectWriterImpl::ComputeIndexMap(MCAssembler &Asm,
936 SectionIndexMapTy &SectionIndexMap) {
937 unsigned Index = 1;
938 for (MCAssembler::iterator it = Asm.begin(),
939 ie = Asm.end(); it != ie; ++it) {
940 const MCSectionELF &Section =
941 static_cast<const MCSectionELF &>(it->getSection());
942 SectionIndexMap[&Section] = Index++;
943 }
944}
945
946void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm,
947 const SectionIndexMapTy &SectionIndexMap) {
Rafael Espindola5c77c162010-10-05 15:48:37 +0000948 // FIXME: Is this the correct place to do this?
949 if (NeedsGOT) {
950 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
951 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
952 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
953 Data.setExternal(true);
Rafael Espindolaf571f9a2010-10-28 18:33:03 +0000954 SetBinding(Data, ELF::STB_GLOBAL);
Rafael Espindola5c77c162010-10-05 15:48:37 +0000955 }
956
Matt Fleming3565a062010-08-16 18:57:57 +0000957 // Build section lookup table.
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000958 NumRegularSections = Asm.size();
Matt Fleming3565a062010-08-16 18:57:57 +0000959
960 // Index 0 is always the empty string.
961 StringMap<uint64_t> StringIndexMap;
962 StringTable += '\x00';
963
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000964 // Add the data for the symbols.
Matt Fleming3565a062010-08-16 18:57:57 +0000965 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
966 ie = Asm.symbol_end(); it != ie; ++it) {
967 const MCSymbol &Symbol = it->getSymbol();
968
Rafael Espindola484291c2010-11-01 14:28:48 +0000969 bool Used = UsedInReloc.count(&Symbol);
970 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
971 if (!isInSymtab(Asm, *it, Used || WeakrefUsed,
Rafael Espindola88182132010-10-27 15:18:17 +0000972 Renames.count(&Symbol)))
Matt Fleming3565a062010-08-16 18:57:57 +0000973 continue;
974
Matt Fleming3565a062010-08-16 18:57:57 +0000975 ELFSymbolData MSD;
976 MSD.SymbolData = it;
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000977 bool Local = isLocal(*it);
Rafael Espindola88182132010-10-27 15:18:17 +0000978 const MCSymbol &RefSymbol = AliasedSymbol(Symbol);
Matt Fleming3565a062010-08-16 18:57:57 +0000979
Rafael Espindola484291c2010-11-01 14:28:48 +0000980 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
981 SetBinding(*it, ELF::STB_WEAK);
982
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000983 if (it->isCommon()) {
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000984 assert(!Local);
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000985 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindolabf052ac2010-10-27 16:04:30 +0000986 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000987 MSD.SectionIndex = ELF::SHN_ABS;
Rafael Espindola88182132010-10-27 15:18:17 +0000988 } else if (RefSymbol.isUndefined()) {
Matt Fleming3565a062010-08-16 18:57:57 +0000989 MSD.SectionIndex = ELF::SHN_UNDEF;
Matt Fleming3565a062010-08-16 18:57:57 +0000990 } else {
Rafael Espindolabab2a802010-11-10 21:51:05 +0000991 const MCSectionELF &Section =
992 static_cast<const MCSectionELF&>(RefSymbol.getSection());
993 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
Rafael Espindola7be2c332010-10-31 00:16:26 +0000994 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
995 NeedsSymtabShndx = true;
Matt Fleming3565a062010-08-16 18:57:57 +0000996 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindola5df0b652010-10-15 15:39:06 +0000997 }
998
Rafael Espindola88182132010-10-27 15:18:17 +0000999 // The @@@ in symbol version is replaced with @ in undefined symbols and
1000 // @@ in defined ones.
1001 StringRef Name = Symbol.getName();
1002 size_t Pos = Name.find("@@@");
1003 std::string FinalName;
1004 if (Pos != StringRef::npos) {
Benjamin Kramer07ee6322010-10-27 19:53:52 +00001005 StringRef Prefix = Name.substr(0, Pos);
Rafael Espindola88182132010-10-27 15:18:17 +00001006 unsigned n = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
Benjamin Kramer07ee6322010-10-27 19:53:52 +00001007 StringRef Suffix = Name.substr(Pos + n);
Rafael Espindola88182132010-10-27 15:18:17 +00001008 FinalName = Prefix.str() + Suffix.str();
1009 } else {
1010 FinalName = Name.str();
1011 }
1012
1013 uint64_t &Entry = StringIndexMap[FinalName];
Rafael Espindolaa6866962010-10-27 14:44:52 +00001014 if (!Entry) {
1015 Entry = StringTable.size();
Rafael Espindola88182132010-10-27 15:18:17 +00001016 StringTable += FinalName;
Rafael Espindolaa6866962010-10-27 14:44:52 +00001017 StringTable += '\x00';
Matt Fleming3565a062010-08-16 18:57:57 +00001018 }
Rafael Espindolaa6866962010-10-27 14:44:52 +00001019 MSD.StringIndex = Entry;
1020 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1021 UndefinedSymbolData.push_back(MSD);
1022 else if (Local)
1023 LocalSymbolData.push_back(MSD);
1024 else
1025 ExternalSymbolData.push_back(MSD);
Matt Fleming3565a062010-08-16 18:57:57 +00001026 }
1027
1028 // Symbols are required to be in lexicographic order.
1029 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1030 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1031 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1032
1033 // Set the symbol indices. Local symbols must come before all other
1034 // symbols with non-local bindings.
Rafael Espindolabab2a802010-11-10 21:51:05 +00001035 unsigned Index = 0;
Matt Fleming3565a062010-08-16 18:57:57 +00001036 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1037 LocalSymbolData[i].SymbolData->setIndex(Index++);
1038 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1039 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1040 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1041 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1042}
1043
1044void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
1045 const MCSectionData &SD) {
1046 if (!Relocations[&SD].empty()) {
1047 MCContext &Ctx = Asm.getContext();
Rafael Espindola4283f4b2010-11-10 19:05:07 +00001048 const MCSectionELF *RelaSection;
Matt Fleming3565a062010-08-16 18:57:57 +00001049 const MCSectionELF &Section =
1050 static_cast<const MCSectionELF&>(SD.getSection());
1051
1052 const StringRef SectionName = Section.getSectionName();
Benjamin Kramer377a5722010-08-17 17:30:07 +00001053 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
Matt Fleming3565a062010-08-16 18:57:57 +00001054 RelaSectionName += SectionName;
Benjamin Kramer299fbe32010-08-17 17:56:13 +00001055
1056 unsigned EntrySize;
1057 if (HasRelocationAddend)
1058 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1059 else
1060 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming3565a062010-08-16 18:57:57 +00001061
Benjamin Kramer377a5722010-08-17 17:30:07 +00001062 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
1063 ELF::SHT_RELA : ELF::SHT_REL, 0,
Matt Fleming3565a062010-08-16 18:57:57 +00001064 SectionKind::getReadOnly(),
Rafael Espindola34be3962010-11-09 23:42:07 +00001065 EntrySize);
Matt Fleming3565a062010-08-16 18:57:57 +00001066
1067 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001068 RelaSD.setAlignment(Is64Bit ? 8 : 4);
Matt Fleming3565a062010-08-16 18:57:57 +00001069
1070 MCDataFragment *F = new MCDataFragment(&RelaSD);
1071
1072 WriteRelocationsFragment(Asm, F, &SD);
1073
Rafael Espindola70703872010-09-30 02:22:20 +00001074 Asm.AddSectionToTheEnd(*Writer, RelaSD, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +00001075 }
1076}
1077
1078void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1079 uint64_t Flags, uint64_t Address,
1080 uint64_t Offset, uint64_t Size,
1081 uint32_t Link, uint32_t Info,
1082 uint64_t Alignment,
1083 uint64_t EntrySize) {
1084 Write32(Name); // sh_name: index into string table
1085 Write32(Type); // sh_type
1086 WriteWord(Flags); // sh_flags
1087 WriteWord(Address); // sh_addr
1088 WriteWord(Offset); // sh_offset
1089 WriteWord(Size); // sh_size
1090 Write32(Link); // sh_link
1091 Write32(Info); // sh_info
1092 WriteWord(Alignment); // sh_addralign
1093 WriteWord(EntrySize); // sh_entsize
1094}
1095
1096void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
1097 MCDataFragment *F,
1098 const MCSectionData *SD) {
1099 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1100 // sort by the r_offset just like gnu as does
1101 array_pod_sort(Relocs.begin(), Relocs.end());
1102
1103 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1104 ELFRelocationEntry entry = Relocs[e - i - 1];
1105
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001106 if (entry.Index < 0)
1107 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1108 else
1109 entry.Index += LocalSymbolData.size() + 1;
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001110 if (Is64Bit) {
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001111 String64(*F, entry.r_offset);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001112
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001113 struct ELF::Elf64_Rela ERE64;
1114 ERE64.setSymbolAndType(entry.Index, entry.Type);
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001115 String64(*F, ERE64.r_info);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001116
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001117 if (HasRelocationAddend)
1118 String64(*F, entry.r_addend);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001119 } else {
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001120 String32(*F, entry.r_offset);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001121
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001122 struct ELF::Elf32_Rela ERE32;
1123 ERE32.setSymbolAndType(entry.Index, entry.Type);
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001124 String32(*F, ERE32.r_info);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001125
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001126 if (HasRelocationAddend)
1127 String32(*F, entry.r_addend);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001128 }
Matt Fleming3565a062010-08-16 18:57:57 +00001129 }
1130}
1131
1132void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
Rafael Espindola4beee3d2010-11-10 22:16:43 +00001133 MCAsmLayout &Layout,
1134 const SectionIndexMapTy &SectionIndexMap) {
Matt Fleming3565a062010-08-16 18:57:57 +00001135 MCContext &Ctx = Asm.getContext();
1136 MCDataFragment *F;
1137
Matt Fleming3565a062010-08-16 18:57:57 +00001138 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1139
Rafael Espindola38738bf2010-09-22 19:04:41 +00001140 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola4283f4b2010-11-10 19:05:07 +00001141 const MCSectionELF *ShstrtabSection =
Rafael Espindola7be2c332010-10-31 00:16:26 +00001142 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
Rafael Espindola3f2d13c2010-11-11 03:40:25 +00001143 SectionKind::getReadOnly());
Rafael Espindola71859c62010-09-16 19:46:31 +00001144 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1145 ShstrtabSD.setAlignment(1);
1146 ShstrtabIndex = Asm.size();
1147
Rafael Espindola4283f4b2010-11-10 19:05:07 +00001148 const MCSectionELF *SymtabSection =
Rafael Espindola7be2c332010-10-31 00:16:26 +00001149 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1150 SectionKind::getReadOnly(),
Rafael Espindola34be3962010-11-09 23:42:07 +00001151 EntrySize);
Matt Fleming3565a062010-08-16 18:57:57 +00001152 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Matt Fleming3565a062010-08-16 18:57:57 +00001153 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
Rafael Espindola7be2c332010-10-31 00:16:26 +00001154 SymbolTableIndex = Asm.size();
1155
1156 MCSectionData *SymtabShndxSD = NULL;
1157
1158 if (NeedsSymtabShndx) {
Rafael Espindola4283f4b2010-11-10 19:05:07 +00001159 const MCSectionELF *SymtabShndxSection =
Rafael Espindola7be2c332010-10-31 00:16:26 +00001160 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
Rafael Espindola34be3962010-11-09 23:42:07 +00001161 SectionKind::getReadOnly(), 4);
Rafael Espindola7be2c332010-10-31 00:16:26 +00001162 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1163 SymtabShndxSD->setAlignment(4);
1164 }
Matt Fleming3565a062010-08-16 18:57:57 +00001165
Matt Fleming3565a062010-08-16 18:57:57 +00001166 const MCSection *StrtabSection;
1167 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
Rafael Espindola3f2d13c2010-11-11 03:40:25 +00001168 SectionKind::getReadOnly());
Matt Fleming3565a062010-08-16 18:57:57 +00001169 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1170 StrtabSD.setAlignment(1);
Matt Fleming3565a062010-08-16 18:57:57 +00001171 StringTableIndex = Asm.size();
1172
Rafael Espindolac3c413f2010-09-27 22:04:54 +00001173 WriteRelocations(Asm, Layout);
Rafael Espindola71859c62010-09-16 19:46:31 +00001174
1175 // Symbol table
1176 F = new MCDataFragment(&SymtabSD);
Rafael Espindola7be2c332010-10-31 00:16:26 +00001177 MCDataFragment *ShndxF = NULL;
1178 if (NeedsSymtabShndx) {
1179 ShndxF = new MCDataFragment(SymtabShndxSD);
1180 Asm.AddSectionToTheEnd(*Writer, *SymtabShndxSD, Layout);
1181 }
Rafael Espindola4beee3d2010-11-10 22:16:43 +00001182 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
Rafael Espindola70703872010-09-30 02:22:20 +00001183 Asm.AddSectionToTheEnd(*Writer, SymtabSD, Layout);
Rafael Espindola71859c62010-09-16 19:46:31 +00001184
Matt Fleming3565a062010-08-16 18:57:57 +00001185 F = new MCDataFragment(&StrtabSD);
1186 F->getContents().append(StringTable.begin(), StringTable.end());
Rafael Espindola70703872010-09-30 02:22:20 +00001187 Asm.AddSectionToTheEnd(*Writer, StrtabSD, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +00001188
Matt Fleming3565a062010-08-16 18:57:57 +00001189 F = new MCDataFragment(&ShstrtabSD);
1190
Matt Fleming3565a062010-08-16 18:57:57 +00001191 // Section header string table.
1192 //
1193 // The first entry of a string table holds a null character so skip
1194 // section 0.
1195 uint64_t Index = 1;
1196 F->getContents() += '\x00';
1197
1198 for (MCAssembler::const_iterator it = Asm.begin(),
1199 ie = Asm.end(); it != ie; ++it) {
Matt Fleming3565a062010-08-16 18:57:57 +00001200 const MCSectionELF &Section =
Benjamin Kramer368ae7e2010-08-17 00:00:46 +00001201 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola51efe7a2010-09-23 14:14:56 +00001202 // FIXME: We could merge suffixes like in .text and .rela.text.
Matt Fleming3565a062010-08-16 18:57:57 +00001203
1204 // Remember the index into the string table so we can write it
1205 // into the sh_name field of the section header table.
1206 SectionStringTableIndex[&it->getSection()] = Index;
1207
1208 Index += Section.getSectionName().size() + 1;
1209 F->getContents() += Section.getSectionName();
1210 F->getContents() += '\x00';
1211 }
1212
Rafael Espindola70703872010-09-30 02:22:20 +00001213 Asm.AddSectionToTheEnd(*Writer, ShstrtabSD, Layout);
1214}
1215
1216bool ELFObjectWriterImpl::IsFixupFullyResolved(const MCAssembler &Asm,
1217 const MCValue Target,
1218 bool IsPCRel,
1219 const MCFragment *DF) const {
1220 // If this is a PCrel relocation, find the section this fixup value is
1221 // relative to.
1222 const MCSection *BaseSection = 0;
1223 if (IsPCRel) {
1224 BaseSection = &DF->getParent()->getSection();
1225 assert(BaseSection);
1226 }
1227
1228 const MCSection *SectionA = 0;
1229 const MCSymbol *SymbolA = 0;
1230 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1231 SymbolA = &A->getSymbol();
1232 SectionA = &SymbolA->getSection();
1233 }
1234
1235 const MCSection *SectionB = 0;
1236 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1237 SectionB = &B->getSymbol().getSection();
1238 }
1239
1240 if (!BaseSection)
1241 return SectionA == SectionB;
1242
1243 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1244 if (DataA.isExternal())
1245 return false;
1246
1247 return !SectionB && BaseSection == SectionA;
Matt Fleming3565a062010-08-16 18:57:57 +00001248}
1249
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001250void ELFObjectWriterImpl::WriteSection(MCAssembler &Asm,
1251 const SectionIndexMapTy &SectionIndexMap,
1252 uint64_t Offset, uint64_t Size,
1253 uint64_t Alignment,
1254 const MCSectionELF &Section) {
1255 uint64_t sh_link = 0;
1256 uint64_t sh_info = 0;
1257
1258 switch(Section.getType()) {
1259 case ELF::SHT_DYNAMIC:
1260 sh_link = SectionStringTableIndex[&Section];
1261 sh_info = 0;
1262 break;
1263
1264 case ELF::SHT_REL:
1265 case ELF::SHT_RELA: {
1266 const MCSectionELF *SymtabSection;
1267 const MCSectionELF *InfoSection;
1268 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1269 0,
Rafael Espindola3f2d13c2010-11-11 03:40:25 +00001270 SectionKind::getReadOnly());
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001271 sh_link = SectionIndexMap.lookup(SymtabSection);
1272 assert(sh_link && ".symtab not found");
1273
1274 // Remove ".rel" and ".rela" prefixes.
1275 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1276 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1277
1278 InfoSection = Asm.getContext().getELFSection(SectionName,
1279 ELF::SHT_PROGBITS, 0,
Rafael Espindola3f2d13c2010-11-11 03:40:25 +00001280 SectionKind::getReadOnly());
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001281 sh_info = SectionIndexMap.lookup(InfoSection);
1282 break;
1283 }
1284
1285 case ELF::SHT_SYMTAB:
1286 case ELF::SHT_DYNSYM:
1287 sh_link = StringTableIndex;
1288 sh_info = LastLocalSymbolIndex;
1289 break;
1290
1291 case ELF::SHT_SYMTAB_SHNDX:
1292 sh_link = SymbolTableIndex;
1293 break;
1294
1295 case ELF::SHT_PROGBITS:
1296 case ELF::SHT_STRTAB:
1297 case ELF::SHT_NOBITS:
1298 case ELF::SHT_NULL:
1299 case ELF::SHT_ARM_ATTRIBUTES:
1300 // Nothing to do.
1301 break;
1302
1303 default:
1304 assert(0 && "FIXME: sh_type value not supported!");
1305 break;
1306 }
1307
1308 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1309 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1310 Alignment, Section.getEntrySize());
1311}
1312
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001313void ELFObjectWriterImpl::WriteObject(MCAssembler &Asm,
Matt Fleming3565a062010-08-16 18:57:57 +00001314 const MCAsmLayout &Layout) {
Rafael Espindolabab2a802010-11-10 21:51:05 +00001315 SectionIndexMapTy SectionIndexMap;
1316
1317 ComputeIndexMap(Asm, SectionIndexMap);
1318
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001319 // Compute symbol table information.
Rafael Espindolabab2a802010-11-10 21:51:05 +00001320 ComputeSymbolTable(Asm, SectionIndexMap);
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001321
Matt Fleming3565a062010-08-16 18:57:57 +00001322 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
Rafael Espindola4beee3d2010-11-10 22:16:43 +00001323 const_cast<MCAsmLayout&>(Layout),
1324 SectionIndexMap);
Matt Fleming3565a062010-08-16 18:57:57 +00001325
Rafael Espindola1d739a02010-11-10 22:34:07 +00001326 // Update to include the metadata sections.
1327 ComputeIndexMap(Asm, SectionIndexMap);
1328
Matt Fleming3565a062010-08-16 18:57:57 +00001329 // Add 1 for the null section.
1330 unsigned NumSections = Asm.size() + 1;
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001331 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1332 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1333 uint64_t FileOff = HeaderSize;
Matt Fleming3565a062010-08-16 18:57:57 +00001334
1335 for (MCAssembler::const_iterator it = Asm.begin(),
1336 ie = Asm.end(); it != ie; ++it) {
1337 const MCSectionData &SD = *it;
Matt Fleming3565a062010-08-16 18:57:57 +00001338
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001339 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1340
Matt Fleming3565a062010-08-16 18:57:57 +00001341 // Get the size of the section in the output file (including padding).
1342 uint64_t Size = Layout.getSectionFileSize(&SD);
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001343
1344 FileOff += Size;
Matt Fleming3565a062010-08-16 18:57:57 +00001345 }
1346
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001347 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1348
Matt Fleming3565a062010-08-16 18:57:57 +00001349 // Write out the ELF header ...
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001350 WriteHeader(FileOff - HeaderSize, NumSections);
1351
1352 FileOff = HeaderSize;
Matt Fleming3565a062010-08-16 18:57:57 +00001353
1354 // ... then all of the sections ...
1355 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1356
1357 for (MCAssembler::const_iterator it = Asm.begin(),
1358 ie = Asm.end(); it != ie; ++it) {
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001359 const MCSectionData &SD = *it;
1360
1361 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1362 WriteZeros(Padding);
1363 FileOff += Padding;
1364
Matt Fleming3565a062010-08-16 18:57:57 +00001365 // Remember the offset into the file for this section.
1366 SectionOffsetMap[&it->getSection()] = FileOff;
Benjamin Kramer44cbde82010-08-19 13:44:49 +00001367
Matt Fleming3565a062010-08-16 18:57:57 +00001368 FileOff += Layout.getSectionFileSize(&SD);
1369
1370 Asm.WriteSectionData(it, Layout, Writer);
1371 }
1372
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001373 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1374 WriteZeros(Padding);
1375 FileOff += Padding;
1376
Matt Fleming3565a062010-08-16 18:57:57 +00001377 // ... and then the section header table.
1378 // Should we align the section header table?
1379 //
1380 // Null section first.
Rafael Espindola7be2c332010-10-31 00:16:26 +00001381 uint64_t FirstSectionSize =
1382 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1383 uint32_t FirstSectionLink =
1384 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1385 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
Matt Fleming3565a062010-08-16 18:57:57 +00001386
1387 for (MCAssembler::const_iterator it = Asm.begin(),
1388 ie = Asm.end(); it != ie; ++it) {
1389 const MCSectionData &SD = *it;
1390 const MCSectionELF &Section =
1391 static_cast<const MCSectionELF&>(SD.getSection());
1392
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001393 WriteSection(Asm, SectionIndexMap, SectionOffsetMap[&Section],
1394 Layout.getSectionSize(&SD),
1395 SD.getAlignment(), Section);
Matt Fleming3565a062010-08-16 18:57:57 +00001396 }
1397}
1398
1399ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1400 bool Is64Bit,
Roman Divacky5baf79e2010-09-09 17:57:50 +00001401 Triple::OSType OSType,
Wesley Peckeecb8582010-10-22 15:52:49 +00001402 uint16_t EMachine,
Matt Fleming3565a062010-08-16 18:57:57 +00001403 bool IsLittleEndian,
1404 bool HasRelocationAddend)
1405 : MCObjectWriter(OS, IsLittleEndian)
1406{
Wesley Peckeecb8582010-10-22 15:52:49 +00001407 Impl = new ELFObjectWriterImpl(this, Is64Bit, EMachine,
1408 HasRelocationAddend, OSType);
Matt Fleming3565a062010-08-16 18:57:57 +00001409}
1410
1411ELFObjectWriter::~ELFObjectWriter() {
1412 delete (ELFObjectWriterImpl*) Impl;
1413}
1414
1415void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1416 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1417}
1418
1419void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1420 const MCAsmLayout &Layout,
1421 const MCFragment *Fragment,
1422 const MCFixup &Fixup, MCValue Target,
1423 uint64_t &FixedValue) {
1424 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1425 Target, FixedValue);
1426}
1427
Rafael Espindola70703872010-09-30 02:22:20 +00001428bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1429 const MCValue Target,
1430 bool IsPCRel,
1431 const MCFragment *DF) const {
1432 return ((ELFObjectWriterImpl*) Impl)->IsFixupFullyResolved(Asm, Target,
1433 IsPCRel, DF);
1434}
1435
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001436void ELFObjectWriter::WriteObject(MCAssembler &Asm,
Matt Fleming3565a062010-08-16 18:57:57 +00001437 const MCAsmLayout &Layout) {
1438 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);
1439}