blob: 7960a07499a7ad5a9b0389e11be9612d0fb5f68a [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
Matt Fleming3565a062010-08-16 18:57:57 +000046namespace {
47
48 class ELFObjectWriterImpl {
49 static bool isFixupKindX86PCRel(unsigned Kind) {
50 switch (Kind) {
51 default:
52 return false;
53 case X86::reloc_pcrel_1byte:
54 case X86::reloc_pcrel_4byte:
55 case X86::reloc_riprel_4byte:
56 case X86::reloc_riprel_4byte_movq_load:
57 return true;
58 }
59 }
60
Chris Lattnerb188a372010-08-28 03:21:03 +000061 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
Matt Fleming3565a062010-08-16 18:57:57 +000062 return Kind == X86::reloc_riprel_4byte ||
63 Kind == X86::reloc_riprel_4byte_movq_load;
Chris Lattnerb188a372010-08-28 03:21:03 +000064 }*/
Matt Fleming3565a062010-08-16 18:57:57 +000065
66
67 /// ELFSymbolData - Helper struct for containing some precomputed information
68 /// on symbols.
69 struct ELFSymbolData {
70 MCSymbolData *SymbolData;
71 uint64_t StringIndex;
72 uint32_t SectionIndex;
73
74 // Support lexicographic sorting.
75 bool operator<(const ELFSymbolData &RHS) const {
Rafael Espindolaad49cf52010-09-18 15:03:21 +000076 if (GetType(*SymbolData) == ELF::STT_FILE)
77 return true;
78 if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
79 return false;
Benjamin Kramer36c6dc22010-08-23 21:23:52 +000080 return SymbolData->getSymbol().getName() <
81 RHS.SymbolData->getSymbol().getName();
Matt Fleming3565a062010-08-16 18:57:57 +000082 }
83 };
84
85 /// @name Relocation Data
86 /// @{
87
88 struct ELFRelocationEntry {
89 // Make these big enough for both 32-bit and 64-bit
90 uint64_t r_offset;
91 uint64_t r_info;
92 uint64_t r_addend;
93
94 // Support lexicographic sorting.
95 bool operator<(const ELFRelocationEntry &RE) const {
96 return RE.r_offset < r_offset;
97 }
98 };
99
100 llvm::DenseMap<const MCSectionData*,
101 std::vector<ELFRelocationEntry> > Relocations;
102 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
103
104 /// @}
105 /// @name Symbol Table Data
106 /// @{
107
108 SmallString<256> StringTable;
109 std::vector<ELFSymbolData> LocalSymbolData;
110 std::vector<ELFSymbolData> ExternalSymbolData;
111 std::vector<ELFSymbolData> UndefinedSymbolData;
112
113 /// @}
114
115 ELFObjectWriter *Writer;
116
117 raw_ostream &OS;
118
Matt Fleming3565a062010-08-16 18:57:57 +0000119 unsigned Is64Bit : 1;
120
121 bool HasRelocationAddend;
122
Roman Divacky5baf79e2010-09-09 17:57:50 +0000123 Triple::OSType OSType;
124
Matt Fleming3565a062010-08-16 18:57:57 +0000125 // This holds the symbol table index of the last local symbol.
126 unsigned LastLocalSymbolIndex;
127 // This holds the .strtab section index.
128 unsigned StringTableIndex;
129
130 unsigned ShstrtabIndex;
131
132 public:
133 ELFObjectWriterImpl(ELFObjectWriter *_Writer, bool _Is64Bit,
Roman Divacky5baf79e2010-09-09 17:57:50 +0000134 bool _HasRelAddend, Triple::OSType _OSType)
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000135 : Writer(_Writer), OS(Writer->getStream()),
Roman Divacky5baf79e2010-09-09 17:57:50 +0000136 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
137 OSType(_OSType) {
Matt Fleming3565a062010-08-16 18:57:57 +0000138 }
139
140 void Write8(uint8_t Value) { Writer->Write8(Value); }
141 void Write16(uint16_t Value) { Writer->Write16(Value); }
142 void Write32(uint32_t Value) { Writer->Write32(Value); }
Chris Lattnerb188a372010-08-28 03:21:03 +0000143 //void Write64(uint64_t Value) { Writer->Write64(Value); }
Matt Fleming3565a062010-08-16 18:57:57 +0000144 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
Chris Lattnerb188a372010-08-28 03:21:03 +0000145 //void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
146 // Writer->WriteBytes(Str, ZeroFillSize);
147 //}
Matt Fleming3565a062010-08-16 18:57:57 +0000148
149 void WriteWord(uint64_t W) {
Chris Lattnerb188a372010-08-28 03:21:03 +0000150 if (Is64Bit)
Matt Fleming3565a062010-08-16 18:57:57 +0000151 Writer->Write64(W);
Chris Lattnerb188a372010-08-28 03:21:03 +0000152 else
Matt Fleming3565a062010-08-16 18:57:57 +0000153 Writer->Write32(W);
Matt Fleming3565a062010-08-16 18:57:57 +0000154 }
155
156 void String8(char *buf, uint8_t Value) {
157 buf[0] = Value;
158 }
159
160 void StringLE16(char *buf, uint16_t Value) {
161 buf[0] = char(Value >> 0);
162 buf[1] = char(Value >> 8);
163 }
164
165 void StringLE32(char *buf, uint32_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000166 StringLE16(buf, uint16_t(Value >> 0));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000167 StringLE16(buf + 2, uint16_t(Value >> 16));
Matt Fleming3565a062010-08-16 18:57:57 +0000168 }
169
170 void StringLE64(char *buf, uint64_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000171 StringLE32(buf, uint32_t(Value >> 0));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000172 StringLE32(buf + 4, uint32_t(Value >> 32));
Matt Fleming3565a062010-08-16 18:57:57 +0000173 }
174
175 void StringBE16(char *buf ,uint16_t Value) {
176 buf[0] = char(Value >> 8);
177 buf[1] = char(Value >> 0);
178 }
179
180 void StringBE32(char *buf, uint32_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000181 StringBE16(buf, uint16_t(Value >> 16));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000182 StringBE16(buf + 2, uint16_t(Value >> 0));
Matt Fleming3565a062010-08-16 18:57:57 +0000183 }
184
185 void StringBE64(char *buf, uint64_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000186 StringBE32(buf, uint32_t(Value >> 32));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000187 StringBE32(buf + 4, uint32_t(Value >> 0));
Matt Fleming3565a062010-08-16 18:57:57 +0000188 }
189
190 void String16(char *buf, uint16_t Value) {
191 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000192 StringLE16(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000193 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000194 StringBE16(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000195 }
196
197 void String32(char *buf, uint32_t Value) {
198 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000199 StringLE32(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000200 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000201 StringBE32(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000202 }
203
204 void String64(char *buf, uint64_t Value) {
205 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000206 StringLE64(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000207 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000208 StringBE64(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000209 }
210
211 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
212
213 void WriteSymbolEntry(MCDataFragment *F, uint64_t name, uint8_t info,
214 uint64_t value, uint64_t size,
215 uint8_t other, uint16_t shndx);
216
217 void WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
218 const MCAsmLayout &Layout);
219
220 void WriteSymbolTable(MCDataFragment *F, const MCAssembler &Asm,
Rafael Espindola71859c62010-09-16 19:46:31 +0000221 const MCAsmLayout &Layout,
222 unsigned NumRegularSections);
Matt Fleming3565a062010-08-16 18:57:57 +0000223
224 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
225 const MCFragment *Fragment, const MCFixup &Fixup,
226 MCValue Target, uint64_t &FixedValue);
227
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000228 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
229 const MCSymbol *S);
Matt Fleming3565a062010-08-16 18:57:57 +0000230
231 /// ComputeSymbolTable - Compute the symbol table data
232 ///
233 /// \param StringTable [out] - The string table data.
234 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
235 /// string table.
236 void ComputeSymbolTable(MCAssembler &Asm);
237
238 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
239 const MCSectionData &SD);
240
241 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
242 for (MCAssembler::const_iterator it = Asm.begin(),
243 ie = Asm.end(); it != ie; ++it) {
244 WriteRelocation(Asm, Layout, *it);
245 }
246 }
247
248 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
249
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000250 void ExecutePostLayoutBinding(MCAssembler &Asm) {
251 // Compute symbol table information.
252 ComputeSymbolTable(Asm);
253 }
Matt Fleming3565a062010-08-16 18:57:57 +0000254
255 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
256 uint64_t Address, uint64_t Offset,
257 uint64_t Size, uint32_t Link, uint32_t Info,
258 uint64_t Alignment, uint64_t EntrySize);
259
260 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
261 const MCSectionData *SD);
262
263 void WriteObject(const MCAssembler &Asm, const MCAsmLayout &Layout);
264 };
265
266}
267
268// Emit the ELF header.
269void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
270 unsigned NumberOfSections) {
271 // ELF Header
272 // ----------
273 //
274 // Note
275 // ----
276 // emitWord method behaves differently for ELF32 and ELF64, writing
277 // 4 bytes in the former and 8 in the latter.
278
279 Write8(0x7f); // e_ident[EI_MAG0]
280 Write8('E'); // e_ident[EI_MAG1]
281 Write8('L'); // e_ident[EI_MAG2]
282 Write8('F'); // e_ident[EI_MAG3]
283
284 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
285
286 // e_ident[EI_DATA]
287 Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
288
289 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky5baf79e2010-09-09 17:57:50 +0000290 // e_ident[EI_OSABI]
291 switch (OSType) {
292 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
293 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
294 default: Write8(ELF::ELFOSABI_NONE); break;
295 }
Matt Fleming3565a062010-08-16 18:57:57 +0000296 Write8(0); // e_ident[EI_ABIVERSION]
297
298 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
299
300 Write16(ELF::ET_REL); // e_type
301
302 // FIXME: Make this configurable
Benjamin Kramereb976772010-08-17 17:02:29 +0000303 Write16(Is64Bit ? ELF::EM_X86_64 : ELF::EM_386); // e_machine = target
Matt Fleming3565a062010-08-16 18:57:57 +0000304
305 Write32(ELF::EV_CURRENT); // e_version
306 WriteWord(0); // e_entry, no entry point in .o file
307 WriteWord(0); // e_phoff, no program header for .o
Benjamin Kramereb976772010-08-17 17:02:29 +0000308 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
309 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
Matt Fleming3565a062010-08-16 18:57:57 +0000310
311 // FIXME: Make this configurable.
312 Write32(0); // e_flags = whatever the target wants
313
314 // e_ehsize = ELF header size
315 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
316
317 Write16(0); // e_phentsize = prog header entry size
318 Write16(0); // e_phnum = # prog header entries = 0
319
320 // e_shentsize = Section header entry size
321 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
322
323 // e_shnum = # of section header ents
324 Write16(NumberOfSections);
325
326 // e_shstrndx = Section # of '.shstrtab'
327 Write16(ShstrtabIndex);
328}
329
330void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
331 uint8_t info, uint64_t value,
332 uint64_t size, uint8_t other,
333 uint16_t shndx) {
334 if (Is64Bit) {
335 char buf[8];
336
337 String32(buf, name);
338 F->getContents() += StringRef(buf, 4); // st_name
339
340 String8(buf, info);
341 F->getContents() += StringRef(buf, 1); // st_info
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000342
Matt Fleming3565a062010-08-16 18:57:57 +0000343 String8(buf, other);
344 F->getContents() += StringRef(buf, 1); // st_other
345
346 String16(buf, shndx);
347 F->getContents() += StringRef(buf, 2); // st_shndx
348
349 String64(buf, value);
350 F->getContents() += StringRef(buf, 8); // st_value
351
352 String64(buf, size);
353 F->getContents() += StringRef(buf, 8); // st_size
354 } else {
355 char buf[4];
356
357 String32(buf, name);
358 F->getContents() += StringRef(buf, 4); // st_name
359
360 String32(buf, value);
361 F->getContents() += StringRef(buf, 4); // st_value
362
363 String32(buf, size);
364 F->getContents() += StringRef(buf, 4); // st_size
365
366 String8(buf, info);
367 F->getContents() += StringRef(buf, 1); // st_info
368
369 String8(buf, other);
370 F->getContents() += StringRef(buf, 1); // st_other
371
372 String16(buf, shndx);
373 F->getContents() += StringRef(buf, 2); // st_shndx
374 }
375}
376
377void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
378 const MCAsmLayout &Layout) {
379 MCSymbolData &Data = *MSD.SymbolData;
Matt Fleming3565a062010-08-16 18:57:57 +0000380 uint8_t Info = (Data.getFlags() & 0xff);
381 uint8_t Other = ((Data.getFlags() & 0xf00) >> ELF_STV_Shift);
382 uint64_t Value = 0;
383 uint64_t Size = 0;
384 const MCExpr *ESize;
385
386 if (Data.isCommon() && Data.isExternal())
387 Value = Data.getCommonAlignment();
388
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000389 assert(!(Data.isCommon() && !Data.isExternal()));
390
Roman Divacky563b38a2010-09-08 14:29:45 +0000391 if (!Data.isCommon() && !(Data.getFlags() & ELF_STB_Weak))
Benjamin Kramer6cc53be2010-08-30 17:20:17 +0000392 if (MCFragment *FF = Data.getFragment())
393 Value = Layout.getSymbolAddress(&Data) -
394 Layout.getSectionAddress(FF->getParent());
395
Matt Fleming3565a062010-08-16 18:57:57 +0000396 ESize = Data.getSize();
397 if (Data.getSize()) {
398 MCValue Res;
399 if (ESize->getKind() == MCExpr::Binary) {
400 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
401
402 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
403 MCSymbolData &A =
404 Layout.getAssembler().getSymbolData(Res.getSymA()->getSymbol());
405 MCSymbolData &B =
406 Layout.getAssembler().getSymbolData(Res.getSymB()->getSymbol());
407
408 Size = Layout.getSymbolAddress(&A) - Layout.getSymbolAddress(&B);
Matt Fleming3565a062010-08-16 18:57:57 +0000409 }
410 } else if (ESize->getKind() == MCExpr::Constant) {
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000411 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
Matt Fleming3565a062010-08-16 18:57:57 +0000412 } else {
413 assert(0 && "Unsupported size expression");
414 }
415 }
416
417 // Write out the symbol table entry
418 WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
419 Size, Other, MSD.SectionIndex);
420}
421
422void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
423 const MCAssembler &Asm,
Rafael Espindola71859c62010-09-16 19:46:31 +0000424 const MCAsmLayout &Layout,
425 unsigned NumRegularSections) {
Matt Fleming3565a062010-08-16 18:57:57 +0000426 // The string table must be emitted first because we need the index
427 // into the string table for all the symbol names.
428 assert(StringTable.size() && "Missing string table");
429
430 // FIXME: Make sure the start of the symbol table is aligned.
431
432 // The first entry is the undefined symbol entry.
433 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000434 F->getContents().append(EntrySize, '\x00');
Matt Fleming3565a062010-08-16 18:57:57 +0000435
436 // Write the symbol table entries.
437 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
438 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
439 ELFSymbolData &MSD = LocalSymbolData[i];
440 WriteSymbol(F, MSD, Layout);
441 }
442
Rafael Espindola71859c62010-09-16 19:46:31 +0000443 // Write out a symbol table entry for each regular section.
Eli Friedmana44fa242010-08-16 21:17:09 +0000444 unsigned Index = 1;
Rafael Espindola71859c62010-09-16 19:46:31 +0000445 for (MCAssembler::const_iterator it = Asm.begin();
446 Index <= NumRegularSections; ++it, ++Index) {
Eli Friedmana44fa242010-08-16 21:17:09 +0000447 const MCSectionELF &Section =
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000448 static_cast<const MCSectionELF&>(it->getSection());
Eli Friedmana44fa242010-08-16 21:17:09 +0000449 // Leave out relocations so we don't have indexes within
450 // the relocations messed up
Benjamin Kramer377a5722010-08-17 17:30:07 +0000451 if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
Eli Friedmana44fa242010-08-16 21:17:09 +0000452 continue;
Matt Fleming3565a062010-08-16 18:57:57 +0000453 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
Eli Friedmana44fa242010-08-16 21:17:09 +0000454 LastLocalSymbolIndex++;
455 }
Matt Fleming3565a062010-08-16 18:57:57 +0000456
457 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
458 ELFSymbolData &MSD = ExternalSymbolData[i];
459 MCSymbolData &Data = *MSD.SymbolData;
460 assert((Data.getFlags() & ELF_STB_Global) &&
461 "External symbol requires STB_GLOBAL flag");
462 WriteSymbol(F, MSD, Layout);
Roman Divackyb629dcc2010-09-08 18:08:40 +0000463 if ((Data.getFlags() & (0xf << ELF_STB_Shift)) == ELF_STB_Local)
Matt Fleming3565a062010-08-16 18:57:57 +0000464 LastLocalSymbolIndex++;
465 }
466
467 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
468 ELFSymbolData &MSD = UndefinedSymbolData[i];
469 MCSymbolData &Data = *MSD.SymbolData;
470 Data.setFlags(Data.getFlags() | ELF_STB_Global);
471 WriteSymbol(F, MSD, Layout);
Roman Divackyb629dcc2010-09-08 18:08:40 +0000472 if ((Data.getFlags() & (0xf << ELF_STB_Shift)) == ELF_STB_Local)
Matt Fleming3565a062010-08-16 18:57:57 +0000473 LastLocalSymbolIndex++;
474 }
475}
476
Benjamin Kramere5b57342010-08-17 18:20:28 +0000477// FIXME: this is currently X86/X86_64 only
Matt Fleming3565a062010-08-16 18:57:57 +0000478void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
479 const MCAsmLayout &Layout,
480 const MCFragment *Fragment,
481 const MCFixup &Fixup,
482 MCValue Target,
483 uint64_t &FixedValue) {
Matt Fleming3565a062010-08-16 18:57:57 +0000484 int64_t Addend = 0;
485 unsigned Index = 0;
Benjamin Kramer95c602a2010-08-27 10:38:39 +0000486 int64_t Value = Target.getConstant();
Matt Fleming3565a062010-08-16 18:57:57 +0000487
Rafael Espindola00074892010-09-17 22:34:41 +0000488 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
Benjamin Kramer81cfb852010-08-17 19:45:05 +0000489 if (!Target.isAbsolute()) {
Matt Fleming3565a062010-08-16 18:57:57 +0000490 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
491 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
492 const MCSymbolData *Base = Asm.getAtom(Layout, &SD);
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000493 MCFragment *F = SD.getFragment();
Matt Fleming3565a062010-08-16 18:57:57 +0000494
Rafael Espindola00074892010-09-17 22:34:41 +0000495 // Avoid relocations for cases like jumps and calls in the same file.
496 if (Symbol->isDefined() && !SD.isExternal() &&
497 IsPCRel &&
498 &Fragment->getParent()->getSection() == &Symbol->getSection()) {
499 uint64_t FixupAddr = Layout.getFragmentAddress(Fragment) + Fixup.getOffset();
500 FixedValue = Layout.getSymbolAddress(&SD) + Target.getConstant() - FixupAddr;
501 return;
502 }
503
Matt Fleming3565a062010-08-16 18:57:57 +0000504 if (Base) {
Rafael Espindolab142bef2010-09-23 17:25:18 +0000505 if (F && !SD.isExternal()) {
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000506 Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
Rafael Espindolaaa359bd2010-09-21 00:40:19 +0000507 Value += Layout.getSymbolAddress(&SD);
Benjamin Kramerbcf2db62010-08-23 19:05:46 +0000508 } else
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000509 Index = getSymbolIndexInSymbolTable(Asm, Symbol);
Matt Fleming3565a062010-08-16 18:57:57 +0000510 if (Base != &SD)
511 Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
512 Addend = Value;
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000513 // Compensate for the addend on i386.
Benjamin Kramer4ba1b302010-08-26 18:12:04 +0000514 if (Is64Bit)
515 Value = 0;
Matt Fleming3565a062010-08-16 18:57:57 +0000516 } else {
Matt Fleming3565a062010-08-16 18:57:57 +0000517 if (F) {
518 // Index of the section in .symtab against this symbol
519 // is being relocated + 2 (empty section + abs. symbols).
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000520 Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
Matt Fleming3565a062010-08-16 18:57:57 +0000521
522 MCSectionData *FSD = F->getParent();
523 // Offset of the symbol in the section
524 Addend = Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
525 } else {
526 FixedValue = Value;
527 return;
528 }
529 }
530 }
531
Benjamin Kramer95c602a2010-08-27 10:38:39 +0000532 FixedValue = Value;
533
Matt Fleming3565a062010-08-16 18:57:57 +0000534 // determine the type of the relocation
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000535 unsigned Type;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000536 if (Is64Bit) {
537 if (IsPCRel) {
538 Type = ELF::R_X86_64_PC32;
539 } else {
540 switch ((unsigned)Fixup.getKind()) {
541 default: llvm_unreachable("invalid fixup kind!");
542 case FK_Data_8: Type = ELF::R_X86_64_64; break;
543 case X86::reloc_pcrel_4byte:
544 case FK_Data_4:
545 // check that the offset fits within a signed long
Rafael Espindola43779dc2010-09-20 19:20:47 +0000546 if (Target.getConstant() < 0) {
547 assert(isInt<32>(Target.getConstant()));
Benjamin Kramere5b57342010-08-17 18:20:28 +0000548 Type = ELF::R_X86_64_32S;
Rafael Espindola43779dc2010-09-20 19:20:47 +0000549 } else {
550 assert(isUInt<32>(Target.getConstant()));
Benjamin Kramere5b57342010-08-17 18:20:28 +0000551 Type = ELF::R_X86_64_32;
Rafael Espindola43779dc2010-09-20 19:20:47 +0000552 }
Benjamin Kramere5b57342010-08-17 18:20:28 +0000553 break;
554 case FK_Data_2: Type = ELF::R_X86_64_16; break;
555 case X86::reloc_pcrel_1byte:
556 case FK_Data_1: Type = ELF::R_X86_64_8; break;
557 }
558 }
Matt Fleming3565a062010-08-16 18:57:57 +0000559 } else {
Benjamin Kramere5b57342010-08-17 18:20:28 +0000560 if (IsPCRel) {
561 Type = ELF::R_386_PC32;
562 } else {
563 switch ((unsigned)Fixup.getKind()) {
564 default: llvm_unreachable("invalid fixup kind!");
565 case X86::reloc_pcrel_4byte:
566 case FK_Data_4: Type = ELF::R_386_32; break;
567 case FK_Data_2: Type = ELF::R_386_16; break;
568 case X86::reloc_pcrel_1byte:
569 case FK_Data_1: Type = ELF::R_386_8; break;
570 }
Matt Fleming3565a062010-08-16 18:57:57 +0000571 }
572 }
573
Benjamin Kramere5b57342010-08-17 18:20:28 +0000574 ELFRelocationEntry ERE;
575
576 if (Is64Bit) {
577 struct ELF::Elf64_Rela ERE64;
578 ERE64.setSymbolAndType(Index, Type);
579 ERE.r_info = ERE64.r_info;
580 } else {
581 struct ELF::Elf32_Rela ERE32;
582 ERE32.setSymbolAndType(Index, Type);
583 ERE.r_info = ERE32.r_info;
584 }
Matt Fleming3565a062010-08-16 18:57:57 +0000585
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000586 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
Benjamin Kramere5b57342010-08-17 18:20:28 +0000587
Matt Fleming3565a062010-08-16 18:57:57 +0000588 if (HasRelocationAddend)
589 ERE.r_addend = Addend;
Benjamin Kramer172d7d62010-08-17 00:33:24 +0000590 else
591 ERE.r_addend = 0; // Silence compiler warning.
Matt Fleming3565a062010-08-16 18:57:57 +0000592
593 Relocations[Fragment->getParent()].push_back(ERE);
594}
595
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000596uint64_t
597ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
598 const MCSymbol *S) {
Benjamin Kramer7b83c262010-08-25 20:09:43 +0000599 MCSymbolData &SD = Asm.getSymbolData(*S);
Eli Friedmanf8020a32010-08-16 19:15:06 +0000600
Benjamin Kramer7b83c262010-08-25 20:09:43 +0000601 // Local symbol.
602 if (!SD.isExternal() && !S->isUndefined())
603 return SD.getIndex() + /* empty symbol */ 1;
604
605 // External or undefined symbol.
606 return SD.getIndex() + Asm.size() + /* empty symbol */ 1;
Matt Fleming3565a062010-08-16 18:57:57 +0000607}
608
609void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
610 // Build section lookup table.
611 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
612 unsigned Index = 1;
613 for (MCAssembler::iterator it = Asm.begin(),
614 ie = Asm.end(); it != ie; ++it, ++Index)
615 SectionIndexMap[&it->getSection()] = Index;
616
617 // Index 0 is always the empty string.
618 StringMap<uint64_t> StringIndexMap;
619 StringTable += '\x00';
620
621 // Add the data for local symbols.
622 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
623 ie = Asm.symbol_end(); it != ie; ++it) {
624 const MCSymbol &Symbol = it->getSymbol();
625
626 // Ignore non-linker visible symbols.
627 if (!Asm.isSymbolLinkerVisible(Symbol))
628 continue;
629
630 if (it->isExternal() || Symbol.isUndefined())
631 continue;
632
633 uint64_t &Entry = StringIndexMap[Symbol.getName()];
634 if (!Entry) {
635 Entry = StringTable.size();
636 StringTable += Symbol.getName();
637 StringTable += '\x00';
638 }
639
640 ELFSymbolData MSD;
641 MSD.SymbolData = it;
642 MSD.StringIndex = Entry;
643
644 if (Symbol.isAbsolute()) {
645 MSD.SectionIndex = ELF::SHN_ABS;
646 LocalSymbolData.push_back(MSD);
647 } else {
648 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
649 assert(MSD.SectionIndex && "Invalid section index!");
650 LocalSymbolData.push_back(MSD);
651 }
652 }
653
654 // Now add non-local symbols.
655 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
656 ie = Asm.symbol_end(); it != ie; ++it) {
657 const MCSymbol &Symbol = it->getSymbol();
658
659 // Ignore non-linker visible symbols.
660 if (!Asm.isSymbolLinkerVisible(Symbol))
661 continue;
662
663 if (!it->isExternal() && !Symbol.isUndefined())
664 continue;
665
666 uint64_t &Entry = StringIndexMap[Symbol.getName()];
667 if (!Entry) {
668 Entry = StringTable.size();
669 StringTable += Symbol.getName();
670 StringTable += '\x00';
671 }
672
673 ELFSymbolData MSD;
674 MSD.SymbolData = it;
675 MSD.StringIndex = Entry;
676
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000677 if (it->isCommon()) {
678 MSD.SectionIndex = ELF::SHN_COMMON;
679 ExternalSymbolData.push_back(MSD);
680 } else if (Symbol.isUndefined()) {
Matt Fleming3565a062010-08-16 18:57:57 +0000681 MSD.SectionIndex = ELF::SHN_UNDEF;
682 // XXX: for some reason we dont Emit* this
683 it->setFlags(it->getFlags() | ELF_STB_Global);
684 UndefinedSymbolData.push_back(MSD);
685 } else if (Symbol.isAbsolute()) {
686 MSD.SectionIndex = ELF::SHN_ABS;
687 ExternalSymbolData.push_back(MSD);
Matt Fleming3565a062010-08-16 18:57:57 +0000688 } else {
689 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
690 assert(MSD.SectionIndex && "Invalid section index!");
691 ExternalSymbolData.push_back(MSD);
692 }
693 }
694
695 // Symbols are required to be in lexicographic order.
696 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
697 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
698 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
699
700 // Set the symbol indices. Local symbols must come before all other
701 // symbols with non-local bindings.
702 Index = 0;
703 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
704 LocalSymbolData[i].SymbolData->setIndex(Index++);
705 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
706 ExternalSymbolData[i].SymbolData->setIndex(Index++);
707 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
708 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
709}
710
711void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
712 const MCSectionData &SD) {
713 if (!Relocations[&SD].empty()) {
714 MCContext &Ctx = Asm.getContext();
715 const MCSection *RelaSection;
716 const MCSectionELF &Section =
717 static_cast<const MCSectionELF&>(SD.getSection());
718
719 const StringRef SectionName = Section.getSectionName();
Benjamin Kramer377a5722010-08-17 17:30:07 +0000720 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
Matt Fleming3565a062010-08-16 18:57:57 +0000721 RelaSectionName += SectionName;
Benjamin Kramer299fbe32010-08-17 17:56:13 +0000722
723 unsigned EntrySize;
724 if (HasRelocationAddend)
725 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
726 else
727 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming3565a062010-08-16 18:57:57 +0000728
Benjamin Kramer377a5722010-08-17 17:30:07 +0000729 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
730 ELF::SHT_RELA : ELF::SHT_REL, 0,
Matt Fleming3565a062010-08-16 18:57:57 +0000731 SectionKind::getReadOnly(),
732 false, EntrySize);
733
734 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000735 RelaSD.setAlignment(Is64Bit ? 8 : 4);
Matt Fleming3565a062010-08-16 18:57:57 +0000736
737 MCDataFragment *F = new MCDataFragment(&RelaSD);
738
739 WriteRelocationsFragment(Asm, F, &SD);
740
741 Asm.AddSectionToTheEnd(RelaSD, Layout);
742 }
743}
744
745void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
746 uint64_t Flags, uint64_t Address,
747 uint64_t Offset, uint64_t Size,
748 uint32_t Link, uint32_t Info,
749 uint64_t Alignment,
750 uint64_t EntrySize) {
751 Write32(Name); // sh_name: index into string table
752 Write32(Type); // sh_type
753 WriteWord(Flags); // sh_flags
754 WriteWord(Address); // sh_addr
755 WriteWord(Offset); // sh_offset
756 WriteWord(Size); // sh_size
757 Write32(Link); // sh_link
758 Write32(Info); // sh_info
759 WriteWord(Alignment); // sh_addralign
760 WriteWord(EntrySize); // sh_entsize
761}
762
763void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
764 MCDataFragment *F,
765 const MCSectionData *SD) {
766 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
767 // sort by the r_offset just like gnu as does
768 array_pod_sort(Relocs.begin(), Relocs.end());
769
770 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
771 ELFRelocationEntry entry = Relocs[e - i - 1];
772
Benjamin Kramer5e492e82010-09-09 18:01:29 +0000773 if (Is64Bit) {
774 char buf[8];
Matt Fleming3565a062010-08-16 18:57:57 +0000775
Benjamin Kramer5e492e82010-09-09 18:01:29 +0000776 String64(buf, entry.r_offset);
777 F->getContents() += StringRef(buf, 8);
778
779 String64(buf, entry.r_info);
780 F->getContents() += StringRef(buf, 8);
781
782 if (HasRelocationAddend) {
783 String64(buf, entry.r_addend);
784 F->getContents() += StringRef(buf, 8);
785 }
786 } else {
787 char buf[4];
788
789 String32(buf, entry.r_offset);
790 F->getContents() += StringRef(buf, 4);
791
792 String32(buf, entry.r_info);
793 F->getContents() += StringRef(buf, 4);
794
795 if (HasRelocationAddend) {
796 String32(buf, entry.r_addend);
797 F->getContents() += StringRef(buf, 4);
798 }
799 }
Matt Fleming3565a062010-08-16 18:57:57 +0000800 }
801}
802
803void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
804 MCAsmLayout &Layout) {
805 MCContext &Ctx = Asm.getContext();
806 MCDataFragment *F;
807
808 WriteRelocations(Asm, Layout);
809
810 const MCSection *SymtabSection;
811 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
812
Rafael Espindola71859c62010-09-16 19:46:31 +0000813 unsigned NumRegularSections = Asm.size();
814
Rafael Espindola38738bf2010-09-22 19:04:41 +0000815 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola71859c62010-09-16 19:46:31 +0000816 const MCSection *ShstrtabSection;
817 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
818 SectionKind::getReadOnly(), false);
819 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
820 ShstrtabSD.setAlignment(1);
821 ShstrtabIndex = Asm.size();
822
Matt Fleming3565a062010-08-16 18:57:57 +0000823 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
824 SectionKind::getReadOnly(),
825 false, EntrySize);
Matt Fleming3565a062010-08-16 18:57:57 +0000826 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Matt Fleming3565a062010-08-16 18:57:57 +0000827 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
828
Matt Fleming3565a062010-08-16 18:57:57 +0000829 const MCSection *StrtabSection;
830 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
831 SectionKind::getReadOnly(), false);
Matt Fleming3565a062010-08-16 18:57:57 +0000832 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
833 StrtabSD.setAlignment(1);
Matt Fleming3565a062010-08-16 18:57:57 +0000834 StringTableIndex = Asm.size();
835
Rafael Espindola71859c62010-09-16 19:46:31 +0000836
837 // Symbol table
838 F = new MCDataFragment(&SymtabSD);
839 WriteSymbolTable(F, Asm, Layout, NumRegularSections);
840 Asm.AddSectionToTheEnd(SymtabSD, Layout);
841
Matt Fleming3565a062010-08-16 18:57:57 +0000842 F = new MCDataFragment(&StrtabSD);
843 F->getContents().append(StringTable.begin(), StringTable.end());
844 Asm.AddSectionToTheEnd(StrtabSD, Layout);
845
Matt Fleming3565a062010-08-16 18:57:57 +0000846 F = new MCDataFragment(&ShstrtabSD);
847
Matt Fleming3565a062010-08-16 18:57:57 +0000848 // Section header string table.
849 //
850 // The first entry of a string table holds a null character so skip
851 // section 0.
852 uint64_t Index = 1;
853 F->getContents() += '\x00';
854
855 for (MCAssembler::const_iterator it = Asm.begin(),
856 ie = Asm.end(); it != ie; ++it) {
Matt Fleming3565a062010-08-16 18:57:57 +0000857 const MCSectionELF &Section =
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000858 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola51efe7a2010-09-23 14:14:56 +0000859 // FIXME: We could merge suffixes like in .text and .rela.text.
Matt Fleming3565a062010-08-16 18:57:57 +0000860
861 // Remember the index into the string table so we can write it
862 // into the sh_name field of the section header table.
863 SectionStringTableIndex[&it->getSection()] = Index;
864
865 Index += Section.getSectionName().size() + 1;
866 F->getContents() += Section.getSectionName();
867 F->getContents() += '\x00';
868 }
869
870 Asm.AddSectionToTheEnd(ShstrtabSD, Layout);
871}
872
873void ELFObjectWriterImpl::WriteObject(const MCAssembler &Asm,
874 const MCAsmLayout &Layout) {
Matt Fleming3565a062010-08-16 18:57:57 +0000875 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
876 const_cast<MCAsmLayout&>(Layout));
877
878 // Add 1 for the null section.
879 unsigned NumSections = Asm.size() + 1;
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000880 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
881 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
882 uint64_t FileOff = HeaderSize;
Matt Fleming3565a062010-08-16 18:57:57 +0000883
884 for (MCAssembler::const_iterator it = Asm.begin(),
885 ie = Asm.end(); it != ie; ++it) {
886 const MCSectionData &SD = *it;
Matt Fleming3565a062010-08-16 18:57:57 +0000887
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000888 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
889
Matt Fleming3565a062010-08-16 18:57:57 +0000890 // Get the size of the section in the output file (including padding).
891 uint64_t Size = Layout.getSectionFileSize(&SD);
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000892
893 FileOff += Size;
Matt Fleming3565a062010-08-16 18:57:57 +0000894 }
895
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000896 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
897
Matt Fleming3565a062010-08-16 18:57:57 +0000898 // Write out the ELF header ...
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000899 WriteHeader(FileOff - HeaderSize, NumSections);
900
901 FileOff = HeaderSize;
Matt Fleming3565a062010-08-16 18:57:57 +0000902
903 // ... then all of the sections ...
904 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
905
Benjamin Kramer44cbde82010-08-19 13:44:49 +0000906 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
907
908 unsigned Index = 1;
Matt Fleming3565a062010-08-16 18:57:57 +0000909 for (MCAssembler::const_iterator it = Asm.begin(),
910 ie = Asm.end(); it != ie; ++it) {
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000911 const MCSectionData &SD = *it;
912
913 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
914 WriteZeros(Padding);
915 FileOff += Padding;
916
Matt Fleming3565a062010-08-16 18:57:57 +0000917 // Remember the offset into the file for this section.
918 SectionOffsetMap[&it->getSection()] = FileOff;
Benjamin Kramer44cbde82010-08-19 13:44:49 +0000919 SectionIndexMap[&it->getSection()] = Index++;
920
Matt Fleming3565a062010-08-16 18:57:57 +0000921 FileOff += Layout.getSectionFileSize(&SD);
922
923 Asm.WriteSectionData(it, Layout, Writer);
924 }
925
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000926 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
927 WriteZeros(Padding);
928 FileOff += Padding;
929
Matt Fleming3565a062010-08-16 18:57:57 +0000930 // ... and then the section header table.
931 // Should we align the section header table?
932 //
933 // Null section first.
934 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
935
936 for (MCAssembler::const_iterator it = Asm.begin(),
937 ie = Asm.end(); it != ie; ++it) {
938 const MCSectionData &SD = *it;
939 const MCSectionELF &Section =
940 static_cast<const MCSectionELF&>(SD.getSection());
941
942 uint64_t sh_link = 0;
943 uint64_t sh_info = 0;
944
945 switch(Section.getType()) {
946 case ELF::SHT_DYNAMIC:
947 sh_link = SectionStringTableIndex[&it->getSection()];
948 sh_info = 0;
949 break;
950
951 case ELF::SHT_REL:
Eli Friedmanf8020a32010-08-16 19:15:06 +0000952 case ELF::SHT_RELA: {
Matt Fleming3565a062010-08-16 18:57:57 +0000953 const MCSection *SymtabSection;
954 const MCSection *InfoSection;
Matt Fleming3565a062010-08-16 18:57:57 +0000955
956 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
957 SectionKind::getReadOnly(),
Eli Friedmanf8020a32010-08-16 19:15:06 +0000958 false);
Benjamin Kramer44cbde82010-08-19 13:44:49 +0000959 sh_link = SectionIndexMap[SymtabSection];
Matt Fleming3565a062010-08-16 18:57:57 +0000960
Benjamin Kramer377a5722010-08-17 17:30:07 +0000961 // Remove ".rel" and ".rela" prefixes.
962 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
963 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
964
Eli Friedmanf8020a32010-08-16 19:15:06 +0000965 InfoSection = Asm.getContext().getELFSection(SectionName,
Matt Fleming3565a062010-08-16 18:57:57 +0000966 ELF::SHT_PROGBITS, 0,
Eli Friedmanf8020a32010-08-16 19:15:06 +0000967 SectionKind::getReadOnly(),
968 false);
Benjamin Kramer44cbde82010-08-19 13:44:49 +0000969 sh_info = SectionIndexMap[InfoSection];
Matt Fleming3565a062010-08-16 18:57:57 +0000970 break;
Eli Friedmanf8020a32010-08-16 19:15:06 +0000971 }
Matt Fleming3565a062010-08-16 18:57:57 +0000972
973 case ELF::SHT_SYMTAB:
974 case ELF::SHT_DYNSYM:
975 sh_link = StringTableIndex;
976 sh_info = LastLocalSymbolIndex;
977 break;
978
979 case ELF::SHT_PROGBITS:
980 case ELF::SHT_STRTAB:
981 case ELF::SHT_NOBITS:
Benjamin Kramer19dc7fa2010-08-31 17:03:33 +0000982 case ELF::SHT_NULL:
Matt Fleming3565a062010-08-16 18:57:57 +0000983 // Nothing to do.
984 break;
985
986 case ELF::SHT_HASH:
987 case ELF::SHT_GROUP:
988 case ELF::SHT_SYMTAB_SHNDX:
989 default:
990 assert(0 && "FIXME: sh_type value not supported!");
991 break;
992 }
993
994 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
995 Section.getType(), Section.getFlags(),
Rafael Espindola71859c62010-09-16 19:46:31 +0000996 0,
Matt Fleming3565a062010-08-16 18:57:57 +0000997 SectionOffsetMap.lookup(&SD.getSection()),
998 Layout.getSectionSize(&SD), sh_link,
999 sh_info, SD.getAlignment(),
1000 Section.getEntrySize());
1001 }
1002}
1003
1004ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1005 bool Is64Bit,
Roman Divacky5baf79e2010-09-09 17:57:50 +00001006 Triple::OSType OSType,
Matt Fleming3565a062010-08-16 18:57:57 +00001007 bool IsLittleEndian,
1008 bool HasRelocationAddend)
1009 : MCObjectWriter(OS, IsLittleEndian)
1010{
Roman Divacky5baf79e2010-09-09 17:57:50 +00001011 Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend, OSType);
Matt Fleming3565a062010-08-16 18:57:57 +00001012}
1013
1014ELFObjectWriter::~ELFObjectWriter() {
1015 delete (ELFObjectWriterImpl*) Impl;
1016}
1017
1018void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1019 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1020}
1021
1022void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1023 const MCAsmLayout &Layout,
1024 const MCFragment *Fragment,
1025 const MCFixup &Fixup, MCValue Target,
1026 uint64_t &FixedValue) {
1027 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1028 Target, FixedValue);
1029}
1030
1031void ELFObjectWriter::WriteObject(const MCAssembler &Asm,
1032 const MCAsmLayout &Layout) {
1033 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);
1034}