blob: 1189b73a08a22ec41ecb59eb66eea1d3fc10db5d [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"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/StringMap.h"
17#include "llvm/ADT/Twine.h"
18#include "llvm/MC/MCAssembler.h"
19#include "llvm/MC/MCAsmLayout.h"
20#include "llvm/MC/MCContext.h"
21#include "llvm/MC/MCELFSymbolFlags.h"
22#include "llvm/MC/MCExpr.h"
23#include "llvm/MC/MCObjectWriter.h"
24#include "llvm/MC/MCSectionELF.h"
25#include "llvm/MC/MCSymbol.h"
26#include "llvm/MC/MCValue.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/ELF.h"
30#include "llvm/Target/TargetAsmBackend.h"
31
32#include "../Target/X86/X86FixupKinds.h"
33
34#include <vector>
35using namespace llvm;
36
Rafael Espindolaad49cf52010-09-18 15:03:21 +000037static unsigned GetType(const MCSymbolData &SD) {
38 uint32_t Type = (SD.getFlags() & (0xf << ELF_STT_Shift)) >> ELF_STT_Shift;
39 assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
40 Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
41 Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
42 Type == ELF::STT_TLS);
43 return Type;
44}
45
Rafael Espindolae15eb4e2010-09-23 19:55:14 +000046static unsigned GetBinding(const MCSymbolData &SD) {
47 uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
48 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
49 Binding == ELF::STB_WEAK);
50 return Binding;
51}
52
53static void SetBinding(MCSymbolData &SD, unsigned Binding) {
54 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
55 Binding == ELF::STB_WEAK);
56 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
57 SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
58}
59
Matt Fleming3565a062010-08-16 18:57:57 +000060namespace {
61
62 class ELFObjectWriterImpl {
63 static bool isFixupKindX86PCRel(unsigned Kind) {
64 switch (Kind) {
65 default:
66 return false;
67 case X86::reloc_pcrel_1byte:
68 case X86::reloc_pcrel_4byte:
69 case X86::reloc_riprel_4byte:
70 case X86::reloc_riprel_4byte_movq_load:
71 return true;
72 }
73 }
74
Chris Lattnerb188a372010-08-28 03:21:03 +000075 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
Matt Fleming3565a062010-08-16 18:57:57 +000076 return Kind == X86::reloc_riprel_4byte ||
77 Kind == X86::reloc_riprel_4byte_movq_load;
Chris Lattnerb188a372010-08-28 03:21:03 +000078 }*/
Matt Fleming3565a062010-08-16 18:57:57 +000079
80
81 /// ELFSymbolData - Helper struct for containing some precomputed information
82 /// on symbols.
83 struct ELFSymbolData {
84 MCSymbolData *SymbolData;
85 uint64_t StringIndex;
86 uint32_t SectionIndex;
87
88 // Support lexicographic sorting.
89 bool operator<(const ELFSymbolData &RHS) const {
Rafael Espindolaad49cf52010-09-18 15:03:21 +000090 if (GetType(*SymbolData) == ELF::STT_FILE)
91 return true;
92 if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
93 return false;
Benjamin Kramer36c6dc22010-08-23 21:23:52 +000094 return SymbolData->getSymbol().getName() <
95 RHS.SymbolData->getSymbol().getName();
Matt Fleming3565a062010-08-16 18:57:57 +000096 }
97 };
98
99 /// @name Relocation Data
100 /// @{
101
102 struct ELFRelocationEntry {
103 // Make these big enough for both 32-bit and 64-bit
104 uint64_t r_offset;
105 uint64_t r_info;
106 uint64_t r_addend;
107
108 // Support lexicographic sorting.
109 bool operator<(const ELFRelocationEntry &RE) const {
110 return RE.r_offset < r_offset;
111 }
112 };
113
114 llvm::DenseMap<const MCSectionData*,
115 std::vector<ELFRelocationEntry> > Relocations;
116 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
117
118 /// @}
119 /// @name Symbol Table Data
120 /// @{
121
122 SmallString<256> StringTable;
123 std::vector<ELFSymbolData> LocalSymbolData;
124 std::vector<ELFSymbolData> ExternalSymbolData;
125 std::vector<ELFSymbolData> UndefinedSymbolData;
126
127 /// @}
128
129 ELFObjectWriter *Writer;
130
131 raw_ostream &OS;
132
Matt Fleming3565a062010-08-16 18:57:57 +0000133 unsigned Is64Bit : 1;
134
135 bool HasRelocationAddend;
136
Roman Divacky5baf79e2010-09-09 17:57:50 +0000137 Triple::OSType OSType;
138
Matt Fleming3565a062010-08-16 18:57:57 +0000139 // This holds the symbol table index of the last local symbol.
140 unsigned LastLocalSymbolIndex;
141 // This holds the .strtab section index.
142 unsigned StringTableIndex;
143
144 unsigned ShstrtabIndex;
145
146 public:
147 ELFObjectWriterImpl(ELFObjectWriter *_Writer, bool _Is64Bit,
Roman Divacky5baf79e2010-09-09 17:57:50 +0000148 bool _HasRelAddend, Triple::OSType _OSType)
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000149 : Writer(_Writer), OS(Writer->getStream()),
Roman Divacky5baf79e2010-09-09 17:57:50 +0000150 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
151 OSType(_OSType) {
Matt Fleming3565a062010-08-16 18:57:57 +0000152 }
153
154 void Write8(uint8_t Value) { Writer->Write8(Value); }
155 void Write16(uint16_t Value) { Writer->Write16(Value); }
156 void Write32(uint32_t Value) { Writer->Write32(Value); }
Chris Lattnerb188a372010-08-28 03:21:03 +0000157 //void Write64(uint64_t Value) { Writer->Write64(Value); }
Matt Fleming3565a062010-08-16 18:57:57 +0000158 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
Chris Lattnerb188a372010-08-28 03:21:03 +0000159 //void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
160 // Writer->WriteBytes(Str, ZeroFillSize);
161 //}
Matt Fleming3565a062010-08-16 18:57:57 +0000162
163 void WriteWord(uint64_t W) {
Chris Lattnerb188a372010-08-28 03:21:03 +0000164 if (Is64Bit)
Matt Fleming3565a062010-08-16 18:57:57 +0000165 Writer->Write64(W);
Chris Lattnerb188a372010-08-28 03:21:03 +0000166 else
Matt Fleming3565a062010-08-16 18:57:57 +0000167 Writer->Write32(W);
Matt Fleming3565a062010-08-16 18:57:57 +0000168 }
169
170 void String8(char *buf, uint8_t Value) {
171 buf[0] = Value;
172 }
173
174 void StringLE16(char *buf, uint16_t Value) {
175 buf[0] = char(Value >> 0);
176 buf[1] = char(Value >> 8);
177 }
178
179 void StringLE32(char *buf, uint32_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000180 StringLE16(buf, uint16_t(Value >> 0));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000181 StringLE16(buf + 2, uint16_t(Value >> 16));
Matt Fleming3565a062010-08-16 18:57:57 +0000182 }
183
184 void StringLE64(char *buf, uint64_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000185 StringLE32(buf, uint32_t(Value >> 0));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000186 StringLE32(buf + 4, uint32_t(Value >> 32));
Matt Fleming3565a062010-08-16 18:57:57 +0000187 }
188
189 void StringBE16(char *buf ,uint16_t Value) {
190 buf[0] = char(Value >> 8);
191 buf[1] = char(Value >> 0);
192 }
193
194 void StringBE32(char *buf, uint32_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000195 StringBE16(buf, uint16_t(Value >> 16));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000196 StringBE16(buf + 2, uint16_t(Value >> 0));
Matt Fleming3565a062010-08-16 18:57:57 +0000197 }
198
199 void StringBE64(char *buf, uint64_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000200 StringBE32(buf, uint32_t(Value >> 32));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000201 StringBE32(buf + 4, uint32_t(Value >> 0));
Matt Fleming3565a062010-08-16 18:57:57 +0000202 }
203
204 void String16(char *buf, uint16_t Value) {
205 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000206 StringLE16(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000207 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000208 StringBE16(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000209 }
210
211 void String32(char *buf, uint32_t Value) {
212 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000213 StringLE32(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000214 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000215 StringBE32(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000216 }
217
218 void String64(char *buf, uint64_t Value) {
219 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000220 StringLE64(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000221 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000222 StringBE64(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000223 }
224
225 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
226
227 void WriteSymbolEntry(MCDataFragment *F, uint64_t name, uint8_t info,
228 uint64_t value, uint64_t size,
229 uint8_t other, uint16_t shndx);
230
231 void WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
232 const MCAsmLayout &Layout);
233
234 void WriteSymbolTable(MCDataFragment *F, const MCAssembler &Asm,
Rafael Espindola71859c62010-09-16 19:46:31 +0000235 const MCAsmLayout &Layout,
236 unsigned NumRegularSections);
Matt Fleming3565a062010-08-16 18:57:57 +0000237
238 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
239 const MCFragment *Fragment, const MCFixup &Fixup,
240 MCValue Target, uint64_t &FixedValue);
241
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000242 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
243 const MCSymbol *S);
Matt Fleming3565a062010-08-16 18:57:57 +0000244
245 /// ComputeSymbolTable - Compute the symbol table data
246 ///
247 /// \param StringTable [out] - The string table data.
248 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
249 /// string table.
250 void ComputeSymbolTable(MCAssembler &Asm);
251
252 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
253 const MCSectionData &SD);
254
255 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
256 for (MCAssembler::const_iterator it = Asm.begin(),
257 ie = Asm.end(); it != ie; ++it) {
258 WriteRelocation(Asm, Layout, *it);
259 }
260 }
261
262 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
263
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000264 void ExecutePostLayoutBinding(MCAssembler &Asm) {
265 // Compute symbol table information.
266 ComputeSymbolTable(Asm);
267 }
Matt Fleming3565a062010-08-16 18:57:57 +0000268
269 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
270 uint64_t Address, uint64_t Offset,
271 uint64_t Size, uint32_t Link, uint32_t Info,
272 uint64_t Alignment, uint64_t EntrySize);
273
274 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
275 const MCSectionData *SD);
276
277 void WriteObject(const MCAssembler &Asm, const MCAsmLayout &Layout);
278 };
279
280}
281
282// Emit the ELF header.
283void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
284 unsigned NumberOfSections) {
285 // ELF Header
286 // ----------
287 //
288 // Note
289 // ----
290 // emitWord method behaves differently for ELF32 and ELF64, writing
291 // 4 bytes in the former and 8 in the latter.
292
293 Write8(0x7f); // e_ident[EI_MAG0]
294 Write8('E'); // e_ident[EI_MAG1]
295 Write8('L'); // e_ident[EI_MAG2]
296 Write8('F'); // e_ident[EI_MAG3]
297
298 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
299
300 // e_ident[EI_DATA]
301 Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
302
303 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky5baf79e2010-09-09 17:57:50 +0000304 // e_ident[EI_OSABI]
305 switch (OSType) {
306 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
307 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
308 default: Write8(ELF::ELFOSABI_NONE); break;
309 }
Matt Fleming3565a062010-08-16 18:57:57 +0000310 Write8(0); // e_ident[EI_ABIVERSION]
311
312 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
313
314 Write16(ELF::ET_REL); // e_type
315
316 // FIXME: Make this configurable
Benjamin Kramereb976772010-08-17 17:02:29 +0000317 Write16(Is64Bit ? ELF::EM_X86_64 : ELF::EM_386); // e_machine = target
Matt Fleming3565a062010-08-16 18:57:57 +0000318
319 Write32(ELF::EV_CURRENT); // e_version
320 WriteWord(0); // e_entry, no entry point in .o file
321 WriteWord(0); // e_phoff, no program header for .o
Benjamin Kramereb976772010-08-17 17:02:29 +0000322 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
323 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
Matt Fleming3565a062010-08-16 18:57:57 +0000324
325 // FIXME: Make this configurable.
326 Write32(0); // e_flags = whatever the target wants
327
328 // e_ehsize = ELF header size
329 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
330
331 Write16(0); // e_phentsize = prog header entry size
332 Write16(0); // e_phnum = # prog header entries = 0
333
334 // e_shentsize = Section header entry size
335 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
336
337 // e_shnum = # of section header ents
338 Write16(NumberOfSections);
339
340 // e_shstrndx = Section # of '.shstrtab'
341 Write16(ShstrtabIndex);
342}
343
344void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
345 uint8_t info, uint64_t value,
346 uint64_t size, uint8_t other,
347 uint16_t shndx) {
348 if (Is64Bit) {
349 char buf[8];
350
351 String32(buf, name);
352 F->getContents() += StringRef(buf, 4); // st_name
353
354 String8(buf, info);
355 F->getContents() += StringRef(buf, 1); // st_info
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000356
Matt Fleming3565a062010-08-16 18:57:57 +0000357 String8(buf, other);
358 F->getContents() += StringRef(buf, 1); // st_other
359
360 String16(buf, shndx);
361 F->getContents() += StringRef(buf, 2); // st_shndx
362
363 String64(buf, value);
364 F->getContents() += StringRef(buf, 8); // st_value
365
366 String64(buf, size);
367 F->getContents() += StringRef(buf, 8); // st_size
368 } else {
369 char buf[4];
370
371 String32(buf, name);
372 F->getContents() += StringRef(buf, 4); // st_name
373
374 String32(buf, value);
375 F->getContents() += StringRef(buf, 4); // st_value
376
377 String32(buf, size);
378 F->getContents() += StringRef(buf, 4); // st_size
379
380 String8(buf, info);
381 F->getContents() += StringRef(buf, 1); // st_info
382
383 String8(buf, other);
384 F->getContents() += StringRef(buf, 1); // st_other
385
386 String16(buf, shndx);
387 F->getContents() += StringRef(buf, 2); // st_shndx
388 }
389}
390
391void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
392 const MCAsmLayout &Layout) {
393 MCSymbolData &Data = *MSD.SymbolData;
Matt Fleming3565a062010-08-16 18:57:57 +0000394 uint8_t Info = (Data.getFlags() & 0xff);
395 uint8_t Other = ((Data.getFlags() & 0xf00) >> ELF_STV_Shift);
396 uint64_t Value = 0;
397 uint64_t Size = 0;
398 const MCExpr *ESize;
399
400 if (Data.isCommon() && Data.isExternal())
401 Value = Data.getCommonAlignment();
402
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000403 assert(!(Data.isCommon() && !Data.isExternal()));
404
Roman Divacky563b38a2010-09-08 14:29:45 +0000405 if (!Data.isCommon() && !(Data.getFlags() & ELF_STB_Weak))
Benjamin Kramer6cc53be2010-08-30 17:20:17 +0000406 if (MCFragment *FF = Data.getFragment())
407 Value = Layout.getSymbolAddress(&Data) -
408 Layout.getSectionAddress(FF->getParent());
409
Matt Fleming3565a062010-08-16 18:57:57 +0000410 ESize = Data.getSize();
411 if (Data.getSize()) {
412 MCValue Res;
413 if (ESize->getKind() == MCExpr::Binary) {
414 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
415
416 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
417 MCSymbolData &A =
418 Layout.getAssembler().getSymbolData(Res.getSymA()->getSymbol());
419 MCSymbolData &B =
420 Layout.getAssembler().getSymbolData(Res.getSymB()->getSymbol());
421
422 Size = Layout.getSymbolAddress(&A) - Layout.getSymbolAddress(&B);
Matt Fleming3565a062010-08-16 18:57:57 +0000423 }
424 } else if (ESize->getKind() == MCExpr::Constant) {
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000425 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
Matt Fleming3565a062010-08-16 18:57:57 +0000426 } else {
427 assert(0 && "Unsupported size expression");
428 }
429 }
430
431 // Write out the symbol table entry
432 WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
433 Size, Other, MSD.SectionIndex);
434}
435
436void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
437 const MCAssembler &Asm,
Rafael Espindola71859c62010-09-16 19:46:31 +0000438 const MCAsmLayout &Layout,
439 unsigned NumRegularSections) {
Matt Fleming3565a062010-08-16 18:57:57 +0000440 // The string table must be emitted first because we need the index
441 // into the string table for all the symbol names.
442 assert(StringTable.size() && "Missing string table");
443
444 // FIXME: Make sure the start of the symbol table is aligned.
445
446 // The first entry is the undefined symbol entry.
447 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000448 F->getContents().append(EntrySize, '\x00');
Matt Fleming3565a062010-08-16 18:57:57 +0000449
450 // Write the symbol table entries.
451 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
452 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
453 ELFSymbolData &MSD = LocalSymbolData[i];
454 WriteSymbol(F, MSD, Layout);
455 }
456
Rafael Espindola71859c62010-09-16 19:46:31 +0000457 // Write out a symbol table entry for each regular section.
Eli Friedmana44fa242010-08-16 21:17:09 +0000458 unsigned Index = 1;
Rafael Espindola71859c62010-09-16 19:46:31 +0000459 for (MCAssembler::const_iterator it = Asm.begin();
460 Index <= NumRegularSections; ++it, ++Index) {
Eli Friedmana44fa242010-08-16 21:17:09 +0000461 const MCSectionELF &Section =
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000462 static_cast<const MCSectionELF&>(it->getSection());
Eli Friedmana44fa242010-08-16 21:17:09 +0000463 // Leave out relocations so we don't have indexes within
464 // the relocations messed up
Benjamin Kramer377a5722010-08-17 17:30:07 +0000465 if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
Eli Friedmana44fa242010-08-16 21:17:09 +0000466 continue;
Matt Fleming3565a062010-08-16 18:57:57 +0000467 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
Eli Friedmana44fa242010-08-16 21:17:09 +0000468 LastLocalSymbolIndex++;
469 }
Matt Fleming3565a062010-08-16 18:57:57 +0000470
471 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
472 ELFSymbolData &MSD = ExternalSymbolData[i];
473 MCSymbolData &Data = *MSD.SymbolData;
474 assert((Data.getFlags() & ELF_STB_Global) &&
475 "External symbol requires STB_GLOBAL flag");
476 WriteSymbol(F, MSD, Layout);
Rafael Espindolae15eb4e2010-09-23 19:55:14 +0000477 if (GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming3565a062010-08-16 18:57:57 +0000478 LastLocalSymbolIndex++;
479 }
480
481 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
482 ELFSymbolData &MSD = UndefinedSymbolData[i];
483 MCSymbolData &Data = *MSD.SymbolData;
Matt Fleming3565a062010-08-16 18:57:57 +0000484 WriteSymbol(F, MSD, Layout);
Rafael Espindolae15eb4e2010-09-23 19:55:14 +0000485 if (GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming3565a062010-08-16 18:57:57 +0000486 LastLocalSymbolIndex++;
487 }
488}
489
Benjamin Kramere5b57342010-08-17 18:20:28 +0000490// FIXME: this is currently X86/X86_64 only
Matt Fleming3565a062010-08-16 18:57:57 +0000491void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
492 const MCAsmLayout &Layout,
493 const MCFragment *Fragment,
494 const MCFixup &Fixup,
495 MCValue Target,
496 uint64_t &FixedValue) {
Matt Fleming3565a062010-08-16 18:57:57 +0000497 int64_t Addend = 0;
498 unsigned Index = 0;
Benjamin Kramer95c602a2010-08-27 10:38:39 +0000499 int64_t Value = Target.getConstant();
Matt Fleming3565a062010-08-16 18:57:57 +0000500
Rafael Espindola00074892010-09-17 22:34:41 +0000501 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
Benjamin Kramer81cfb852010-08-17 19:45:05 +0000502 if (!Target.isAbsolute()) {
Matt Fleming3565a062010-08-16 18:57:57 +0000503 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
504 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
505 const MCSymbolData *Base = Asm.getAtom(Layout, &SD);
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000506 MCFragment *F = SD.getFragment();
Matt Fleming3565a062010-08-16 18:57:57 +0000507
Rafael Espindola00074892010-09-17 22:34:41 +0000508 // Avoid relocations for cases like jumps and calls in the same file.
509 if (Symbol->isDefined() && !SD.isExternal() &&
510 IsPCRel &&
511 &Fragment->getParent()->getSection() == &Symbol->getSection()) {
512 uint64_t FixupAddr = Layout.getFragmentAddress(Fragment) + Fixup.getOffset();
513 FixedValue = Layout.getSymbolAddress(&SD) + Target.getConstant() - FixupAddr;
514 return;
515 }
516
Matt Fleming3565a062010-08-16 18:57:57 +0000517 if (Base) {
Rafael Espindolacd4b20a2010-09-24 18:48:08 +0000518 if (F && (!Symbol->isInSection() || SD.isCommon()) && !SD.isExternal()) {
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000519 Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
Rafael Espindolacd4b20a2010-09-24 18:48:08 +0000520 Value += Layout.getSymbolAddress(&SD);
Benjamin Kramerbcf2db62010-08-23 19:05:46 +0000521 } else
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000522 Index = getSymbolIndexInSymbolTable(Asm, Symbol);
Matt Fleming3565a062010-08-16 18:57:57 +0000523 if (Base != &SD)
524 Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
525 Addend = Value;
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000526 // Compensate for the addend on i386.
Benjamin Kramer4ba1b302010-08-26 18:12:04 +0000527 if (Is64Bit)
528 Value = 0;
Matt Fleming3565a062010-08-16 18:57:57 +0000529 } else {
Matt Fleming3565a062010-08-16 18:57:57 +0000530 if (F) {
531 // Index of the section in .symtab against this symbol
532 // is being relocated + 2 (empty section + abs. symbols).
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000533 Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
Matt Fleming3565a062010-08-16 18:57:57 +0000534
535 MCSectionData *FSD = F->getParent();
536 // Offset of the symbol in the section
537 Addend = Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
538 } else {
539 FixedValue = Value;
540 return;
541 }
542 }
543 }
544
Benjamin Kramer95c602a2010-08-27 10:38:39 +0000545 FixedValue = Value;
546
Matt Fleming3565a062010-08-16 18:57:57 +0000547 // determine the type of the relocation
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000548 unsigned Type;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000549 if (Is64Bit) {
550 if (IsPCRel) {
551 Type = ELF::R_X86_64_PC32;
552 } else {
553 switch ((unsigned)Fixup.getKind()) {
554 default: llvm_unreachable("invalid fixup kind!");
555 case FK_Data_8: Type = ELF::R_X86_64_64; break;
556 case X86::reloc_pcrel_4byte:
557 case FK_Data_4:
558 // check that the offset fits within a signed long
Rafael Espindola43779dc2010-09-20 19:20:47 +0000559 if (Target.getConstant() < 0) {
560 assert(isInt<32>(Target.getConstant()));
Benjamin Kramere5b57342010-08-17 18:20:28 +0000561 Type = ELF::R_X86_64_32S;
Rafael Espindola43779dc2010-09-20 19:20:47 +0000562 } else {
563 assert(isUInt<32>(Target.getConstant()));
Benjamin Kramere5b57342010-08-17 18:20:28 +0000564 Type = ELF::R_X86_64_32;
Rafael Espindola43779dc2010-09-20 19:20:47 +0000565 }
Benjamin Kramere5b57342010-08-17 18:20:28 +0000566 break;
567 case FK_Data_2: Type = ELF::R_X86_64_16; break;
568 case X86::reloc_pcrel_1byte:
569 case FK_Data_1: Type = ELF::R_X86_64_8; break;
570 }
571 }
Matt Fleming3565a062010-08-16 18:57:57 +0000572 } else {
Benjamin Kramere5b57342010-08-17 18:20:28 +0000573 if (IsPCRel) {
574 Type = ELF::R_386_PC32;
575 } else {
576 switch ((unsigned)Fixup.getKind()) {
577 default: llvm_unreachable("invalid fixup kind!");
578 case X86::reloc_pcrel_4byte:
579 case FK_Data_4: Type = ELF::R_386_32; break;
580 case FK_Data_2: Type = ELF::R_386_16; break;
581 case X86::reloc_pcrel_1byte:
582 case FK_Data_1: Type = ELF::R_386_8; break;
583 }
Matt Fleming3565a062010-08-16 18:57:57 +0000584 }
585 }
586
Benjamin Kramere5b57342010-08-17 18:20:28 +0000587 ELFRelocationEntry ERE;
588
589 if (Is64Bit) {
590 struct ELF::Elf64_Rela ERE64;
591 ERE64.setSymbolAndType(Index, Type);
592 ERE.r_info = ERE64.r_info;
593 } else {
594 struct ELF::Elf32_Rela ERE32;
595 ERE32.setSymbolAndType(Index, Type);
596 ERE.r_info = ERE32.r_info;
597 }
Matt Fleming3565a062010-08-16 18:57:57 +0000598
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000599 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
Benjamin Kramere5b57342010-08-17 18:20:28 +0000600
Matt Fleming3565a062010-08-16 18:57:57 +0000601 if (HasRelocationAddend)
602 ERE.r_addend = Addend;
Benjamin Kramer172d7d62010-08-17 00:33:24 +0000603 else
604 ERE.r_addend = 0; // Silence compiler warning.
Matt Fleming3565a062010-08-16 18:57:57 +0000605
606 Relocations[Fragment->getParent()].push_back(ERE);
607}
608
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000609uint64_t
610ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
611 const MCSymbol *S) {
Benjamin Kramer7b83c262010-08-25 20:09:43 +0000612 MCSymbolData &SD = Asm.getSymbolData(*S);
Eli Friedmanf8020a32010-08-16 19:15:06 +0000613
Benjamin Kramer7b83c262010-08-25 20:09:43 +0000614 // Local symbol.
615 if (!SD.isExternal() && !S->isUndefined())
616 return SD.getIndex() + /* empty symbol */ 1;
617
618 // External or undefined symbol.
619 return SD.getIndex() + Asm.size() + /* empty symbol */ 1;
Matt Fleming3565a062010-08-16 18:57:57 +0000620}
621
622void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
623 // Build section lookup table.
624 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
625 unsigned Index = 1;
626 for (MCAssembler::iterator it = Asm.begin(),
627 ie = Asm.end(); it != ie; ++it, ++Index)
628 SectionIndexMap[&it->getSection()] = Index;
629
630 // Index 0 is always the empty string.
631 StringMap<uint64_t> StringIndexMap;
632 StringTable += '\x00';
633
634 // Add the data for local symbols.
635 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
636 ie = Asm.symbol_end(); it != ie; ++it) {
637 const MCSymbol &Symbol = it->getSymbol();
638
639 // Ignore non-linker visible symbols.
640 if (!Asm.isSymbolLinkerVisible(Symbol))
641 continue;
642
643 if (it->isExternal() || Symbol.isUndefined())
644 continue;
645
646 uint64_t &Entry = StringIndexMap[Symbol.getName()];
647 if (!Entry) {
648 Entry = StringTable.size();
649 StringTable += Symbol.getName();
650 StringTable += '\x00';
651 }
652
653 ELFSymbolData MSD;
654 MSD.SymbolData = it;
655 MSD.StringIndex = Entry;
656
657 if (Symbol.isAbsolute()) {
658 MSD.SectionIndex = ELF::SHN_ABS;
659 LocalSymbolData.push_back(MSD);
660 } else {
661 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
662 assert(MSD.SectionIndex && "Invalid section index!");
663 LocalSymbolData.push_back(MSD);
664 }
665 }
666
667 // Now add non-local symbols.
668 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
669 ie = Asm.symbol_end(); it != ie; ++it) {
670 const MCSymbol &Symbol = it->getSymbol();
671
672 // Ignore non-linker visible symbols.
673 if (!Asm.isSymbolLinkerVisible(Symbol))
674 continue;
675
676 if (!it->isExternal() && !Symbol.isUndefined())
677 continue;
678
679 uint64_t &Entry = StringIndexMap[Symbol.getName()];
680 if (!Entry) {
681 Entry = StringTable.size();
682 StringTable += Symbol.getName();
683 StringTable += '\x00';
684 }
685
686 ELFSymbolData MSD;
687 MSD.SymbolData = it;
688 MSD.StringIndex = Entry;
689
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000690 if (it->isCommon()) {
691 MSD.SectionIndex = ELF::SHN_COMMON;
692 ExternalSymbolData.push_back(MSD);
693 } else if (Symbol.isUndefined()) {
Matt Fleming3565a062010-08-16 18:57:57 +0000694 MSD.SectionIndex = ELF::SHN_UNDEF;
Rafael Espindolae15eb4e2010-09-23 19:55:14 +0000695 // FIXME: Undefined symbols are global, but this is the first place we
696 // are able to set it.
697 if (GetBinding(*it) == ELF::STB_LOCAL)
698 SetBinding(*it, ELF::STB_GLOBAL);
Matt Fleming3565a062010-08-16 18:57:57 +0000699 UndefinedSymbolData.push_back(MSD);
700 } else if (Symbol.isAbsolute()) {
701 MSD.SectionIndex = ELF::SHN_ABS;
702 ExternalSymbolData.push_back(MSD);
Matt Fleming3565a062010-08-16 18:57:57 +0000703 } else {
704 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
705 assert(MSD.SectionIndex && "Invalid section index!");
706 ExternalSymbolData.push_back(MSD);
707 }
708 }
709
710 // Symbols are required to be in lexicographic order.
711 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
712 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
713 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
714
715 // Set the symbol indices. Local symbols must come before all other
716 // symbols with non-local bindings.
717 Index = 0;
718 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
719 LocalSymbolData[i].SymbolData->setIndex(Index++);
720 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
721 ExternalSymbolData[i].SymbolData->setIndex(Index++);
722 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
723 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
724}
725
726void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
727 const MCSectionData &SD) {
728 if (!Relocations[&SD].empty()) {
729 MCContext &Ctx = Asm.getContext();
730 const MCSection *RelaSection;
731 const MCSectionELF &Section =
732 static_cast<const MCSectionELF&>(SD.getSection());
733
734 const StringRef SectionName = Section.getSectionName();
Benjamin Kramer377a5722010-08-17 17:30:07 +0000735 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
Matt Fleming3565a062010-08-16 18:57:57 +0000736 RelaSectionName += SectionName;
Benjamin Kramer299fbe32010-08-17 17:56:13 +0000737
738 unsigned EntrySize;
739 if (HasRelocationAddend)
740 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
741 else
742 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming3565a062010-08-16 18:57:57 +0000743
Benjamin Kramer377a5722010-08-17 17:30:07 +0000744 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
745 ELF::SHT_RELA : ELF::SHT_REL, 0,
Matt Fleming3565a062010-08-16 18:57:57 +0000746 SectionKind::getReadOnly(),
747 false, EntrySize);
748
749 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000750 RelaSD.setAlignment(Is64Bit ? 8 : 4);
Matt Fleming3565a062010-08-16 18:57:57 +0000751
752 MCDataFragment *F = new MCDataFragment(&RelaSD);
753
754 WriteRelocationsFragment(Asm, F, &SD);
755
756 Asm.AddSectionToTheEnd(RelaSD, Layout);
757 }
758}
759
760void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
761 uint64_t Flags, uint64_t Address,
762 uint64_t Offset, uint64_t Size,
763 uint32_t Link, uint32_t Info,
764 uint64_t Alignment,
765 uint64_t EntrySize) {
766 Write32(Name); // sh_name: index into string table
767 Write32(Type); // sh_type
768 WriteWord(Flags); // sh_flags
769 WriteWord(Address); // sh_addr
770 WriteWord(Offset); // sh_offset
771 WriteWord(Size); // sh_size
772 Write32(Link); // sh_link
773 Write32(Info); // sh_info
774 WriteWord(Alignment); // sh_addralign
775 WriteWord(EntrySize); // sh_entsize
776}
777
778void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
779 MCDataFragment *F,
780 const MCSectionData *SD) {
781 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
782 // sort by the r_offset just like gnu as does
783 array_pod_sort(Relocs.begin(), Relocs.end());
784
785 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
786 ELFRelocationEntry entry = Relocs[e - i - 1];
787
Benjamin Kramer5e492e82010-09-09 18:01:29 +0000788 if (Is64Bit) {
789 char buf[8];
Matt Fleming3565a062010-08-16 18:57:57 +0000790
Benjamin Kramer5e492e82010-09-09 18:01:29 +0000791 String64(buf, entry.r_offset);
792 F->getContents() += StringRef(buf, 8);
793
794 String64(buf, entry.r_info);
795 F->getContents() += StringRef(buf, 8);
796
797 if (HasRelocationAddend) {
798 String64(buf, entry.r_addend);
799 F->getContents() += StringRef(buf, 8);
800 }
801 } else {
802 char buf[4];
803
804 String32(buf, entry.r_offset);
805 F->getContents() += StringRef(buf, 4);
806
807 String32(buf, entry.r_info);
808 F->getContents() += StringRef(buf, 4);
809
810 if (HasRelocationAddend) {
811 String32(buf, entry.r_addend);
812 F->getContents() += StringRef(buf, 4);
813 }
814 }
Matt Fleming3565a062010-08-16 18:57:57 +0000815 }
816}
817
818void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
819 MCAsmLayout &Layout) {
820 MCContext &Ctx = Asm.getContext();
821 MCDataFragment *F;
822
823 WriteRelocations(Asm, Layout);
824
825 const MCSection *SymtabSection;
826 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
827
Rafael Espindola71859c62010-09-16 19:46:31 +0000828 unsigned NumRegularSections = Asm.size();
829
Rafael Espindola38738bf2010-09-22 19:04:41 +0000830 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola71859c62010-09-16 19:46:31 +0000831 const MCSection *ShstrtabSection;
832 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
833 SectionKind::getReadOnly(), false);
834 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
835 ShstrtabSD.setAlignment(1);
836 ShstrtabIndex = Asm.size();
837
Matt Fleming3565a062010-08-16 18:57:57 +0000838 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
839 SectionKind::getReadOnly(),
840 false, EntrySize);
Matt Fleming3565a062010-08-16 18:57:57 +0000841 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Matt Fleming3565a062010-08-16 18:57:57 +0000842 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
843
Matt Fleming3565a062010-08-16 18:57:57 +0000844 const MCSection *StrtabSection;
845 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
846 SectionKind::getReadOnly(), false);
Matt Fleming3565a062010-08-16 18:57:57 +0000847 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
848 StrtabSD.setAlignment(1);
Matt Fleming3565a062010-08-16 18:57:57 +0000849 StringTableIndex = Asm.size();
850
Rafael Espindola71859c62010-09-16 19:46:31 +0000851
852 // Symbol table
853 F = new MCDataFragment(&SymtabSD);
854 WriteSymbolTable(F, Asm, Layout, NumRegularSections);
855 Asm.AddSectionToTheEnd(SymtabSD, Layout);
856
Matt Fleming3565a062010-08-16 18:57:57 +0000857 F = new MCDataFragment(&StrtabSD);
858 F->getContents().append(StringTable.begin(), StringTable.end());
859 Asm.AddSectionToTheEnd(StrtabSD, Layout);
860
Matt Fleming3565a062010-08-16 18:57:57 +0000861 F = new MCDataFragment(&ShstrtabSD);
862
Matt Fleming3565a062010-08-16 18:57:57 +0000863 // Section header string table.
864 //
865 // The first entry of a string table holds a null character so skip
866 // section 0.
867 uint64_t Index = 1;
868 F->getContents() += '\x00';
869
870 for (MCAssembler::const_iterator it = Asm.begin(),
871 ie = Asm.end(); it != ie; ++it) {
Matt Fleming3565a062010-08-16 18:57:57 +0000872 const MCSectionELF &Section =
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000873 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola51efe7a2010-09-23 14:14:56 +0000874 // FIXME: We could merge suffixes like in .text and .rela.text.
Matt Fleming3565a062010-08-16 18:57:57 +0000875
876 // Remember the index into the string table so we can write it
877 // into the sh_name field of the section header table.
878 SectionStringTableIndex[&it->getSection()] = Index;
879
880 Index += Section.getSectionName().size() + 1;
881 F->getContents() += Section.getSectionName();
882 F->getContents() += '\x00';
883 }
884
885 Asm.AddSectionToTheEnd(ShstrtabSD, Layout);
886}
887
888void ELFObjectWriterImpl::WriteObject(const MCAssembler &Asm,
889 const MCAsmLayout &Layout) {
Matt Fleming3565a062010-08-16 18:57:57 +0000890 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
891 const_cast<MCAsmLayout&>(Layout));
892
893 // Add 1 for the null section.
894 unsigned NumSections = Asm.size() + 1;
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000895 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
896 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
897 uint64_t FileOff = HeaderSize;
Matt Fleming3565a062010-08-16 18:57:57 +0000898
899 for (MCAssembler::const_iterator it = Asm.begin(),
900 ie = Asm.end(); it != ie; ++it) {
901 const MCSectionData &SD = *it;
Matt Fleming3565a062010-08-16 18:57:57 +0000902
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000903 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
904
Matt Fleming3565a062010-08-16 18:57:57 +0000905 // Get the size of the section in the output file (including padding).
906 uint64_t Size = Layout.getSectionFileSize(&SD);
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000907
908 FileOff += Size;
Matt Fleming3565a062010-08-16 18:57:57 +0000909 }
910
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000911 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
912
Matt Fleming3565a062010-08-16 18:57:57 +0000913 // Write out the ELF header ...
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000914 WriteHeader(FileOff - HeaderSize, NumSections);
915
916 FileOff = HeaderSize;
Matt Fleming3565a062010-08-16 18:57:57 +0000917
918 // ... then all of the sections ...
919 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
920
Benjamin Kramer44cbde82010-08-19 13:44:49 +0000921 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
922
923 unsigned Index = 1;
Matt Fleming3565a062010-08-16 18:57:57 +0000924 for (MCAssembler::const_iterator it = Asm.begin(),
925 ie = Asm.end(); it != ie; ++it) {
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000926 const MCSectionData &SD = *it;
927
928 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
929 WriteZeros(Padding);
930 FileOff += Padding;
931
Matt Fleming3565a062010-08-16 18:57:57 +0000932 // Remember the offset into the file for this section.
933 SectionOffsetMap[&it->getSection()] = FileOff;
Benjamin Kramer44cbde82010-08-19 13:44:49 +0000934 SectionIndexMap[&it->getSection()] = Index++;
935
Matt Fleming3565a062010-08-16 18:57:57 +0000936 FileOff += Layout.getSectionFileSize(&SD);
937
938 Asm.WriteSectionData(it, Layout, Writer);
939 }
940
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000941 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
942 WriteZeros(Padding);
943 FileOff += Padding;
944
Matt Fleming3565a062010-08-16 18:57:57 +0000945 // ... and then the section header table.
946 // Should we align the section header table?
947 //
948 // Null section first.
949 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
950
951 for (MCAssembler::const_iterator it = Asm.begin(),
952 ie = Asm.end(); it != ie; ++it) {
953 const MCSectionData &SD = *it;
954 const MCSectionELF &Section =
955 static_cast<const MCSectionELF&>(SD.getSection());
956
957 uint64_t sh_link = 0;
958 uint64_t sh_info = 0;
959
960 switch(Section.getType()) {
961 case ELF::SHT_DYNAMIC:
962 sh_link = SectionStringTableIndex[&it->getSection()];
963 sh_info = 0;
964 break;
965
966 case ELF::SHT_REL:
Eli Friedmanf8020a32010-08-16 19:15:06 +0000967 case ELF::SHT_RELA: {
Matt Fleming3565a062010-08-16 18:57:57 +0000968 const MCSection *SymtabSection;
969 const MCSection *InfoSection;
Matt Fleming3565a062010-08-16 18:57:57 +0000970
971 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
972 SectionKind::getReadOnly(),
Eli Friedmanf8020a32010-08-16 19:15:06 +0000973 false);
Benjamin Kramer44cbde82010-08-19 13:44:49 +0000974 sh_link = SectionIndexMap[SymtabSection];
Matt Fleming3565a062010-08-16 18:57:57 +0000975
Benjamin Kramer377a5722010-08-17 17:30:07 +0000976 // Remove ".rel" and ".rela" prefixes.
977 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
978 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
979
Eli Friedmanf8020a32010-08-16 19:15:06 +0000980 InfoSection = Asm.getContext().getELFSection(SectionName,
Matt Fleming3565a062010-08-16 18:57:57 +0000981 ELF::SHT_PROGBITS, 0,
Eli Friedmanf8020a32010-08-16 19:15:06 +0000982 SectionKind::getReadOnly(),
983 false);
Benjamin Kramer44cbde82010-08-19 13:44:49 +0000984 sh_info = SectionIndexMap[InfoSection];
Matt Fleming3565a062010-08-16 18:57:57 +0000985 break;
Eli Friedmanf8020a32010-08-16 19:15:06 +0000986 }
Matt Fleming3565a062010-08-16 18:57:57 +0000987
988 case ELF::SHT_SYMTAB:
989 case ELF::SHT_DYNSYM:
990 sh_link = StringTableIndex;
991 sh_info = LastLocalSymbolIndex;
992 break;
993
994 case ELF::SHT_PROGBITS:
995 case ELF::SHT_STRTAB:
996 case ELF::SHT_NOBITS:
Benjamin Kramer19dc7fa2010-08-31 17:03:33 +0000997 case ELF::SHT_NULL:
Matt Fleming3565a062010-08-16 18:57:57 +0000998 // Nothing to do.
999 break;
1000
1001 case ELF::SHT_HASH:
1002 case ELF::SHT_GROUP:
1003 case ELF::SHT_SYMTAB_SHNDX:
1004 default:
1005 assert(0 && "FIXME: sh_type value not supported!");
1006 break;
1007 }
1008
1009 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
1010 Section.getType(), Section.getFlags(),
Rafael Espindola71859c62010-09-16 19:46:31 +00001011 0,
Matt Fleming3565a062010-08-16 18:57:57 +00001012 SectionOffsetMap.lookup(&SD.getSection()),
1013 Layout.getSectionSize(&SD), sh_link,
1014 sh_info, SD.getAlignment(),
1015 Section.getEntrySize());
1016 }
1017}
1018
1019ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1020 bool Is64Bit,
Roman Divacky5baf79e2010-09-09 17:57:50 +00001021 Triple::OSType OSType,
Matt Fleming3565a062010-08-16 18:57:57 +00001022 bool IsLittleEndian,
1023 bool HasRelocationAddend)
1024 : MCObjectWriter(OS, IsLittleEndian)
1025{
Roman Divacky5baf79e2010-09-09 17:57:50 +00001026 Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend, OSType);
Matt Fleming3565a062010-08-16 18:57:57 +00001027}
1028
1029ELFObjectWriter::~ELFObjectWriter() {
1030 delete (ELFObjectWriterImpl*) Impl;
1031}
1032
1033void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1034 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1035}
1036
1037void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1038 const MCAsmLayout &Layout,
1039 const MCFragment *Fragment,
1040 const MCFixup &Fixup, MCValue Target,
1041 uint64_t &FixedValue) {
1042 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1043 Target, FixedValue);
1044}
1045
1046void ELFObjectWriter::WriteObject(const MCAssembler &Asm,
1047 const MCAsmLayout &Layout) {
1048 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);
1049}