blob: 8fb6ff60f8909d9af5d85f7ed602f5e33361a85b [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
37namespace {
38
39 class ELFObjectWriterImpl {
40 static bool isFixupKindX86PCRel(unsigned Kind) {
41 switch (Kind) {
42 default:
43 return false;
44 case X86::reloc_pcrel_1byte:
45 case X86::reloc_pcrel_4byte:
46 case X86::reloc_riprel_4byte:
47 case X86::reloc_riprel_4byte_movq_load:
48 return true;
49 }
50 }
51
52 static bool isFixupKindX86RIPRel(unsigned Kind) {
53 return Kind == X86::reloc_riprel_4byte ||
54 Kind == X86::reloc_riprel_4byte_movq_load;
55 }
56
57
58 /// ELFSymbolData - Helper struct for containing some precomputed information
59 /// on symbols.
60 struct ELFSymbolData {
61 MCSymbolData *SymbolData;
62 uint64_t StringIndex;
63 uint32_t SectionIndex;
64
65 // Support lexicographic sorting.
66 bool operator<(const ELFSymbolData &RHS) const {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +000067 return SymbolData->getSymbol().getName() <
68 RHS.SymbolData->getSymbol().getName();
Matt Fleming3565a062010-08-16 18:57:57 +000069 }
70 };
71
72 /// @name Relocation Data
73 /// @{
74
75 struct ELFRelocationEntry {
76 // Make these big enough for both 32-bit and 64-bit
77 uint64_t r_offset;
78 uint64_t r_info;
79 uint64_t r_addend;
80
81 // Support lexicographic sorting.
82 bool operator<(const ELFRelocationEntry &RE) const {
83 return RE.r_offset < r_offset;
84 }
85 };
86
87 llvm::DenseMap<const MCSectionData*,
88 std::vector<ELFRelocationEntry> > Relocations;
89 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
90
91 /// @}
92 /// @name Symbol Table Data
93 /// @{
94
95 SmallString<256> StringTable;
96 std::vector<ELFSymbolData> LocalSymbolData;
97 std::vector<ELFSymbolData> ExternalSymbolData;
98 std::vector<ELFSymbolData> UndefinedSymbolData;
99
100 /// @}
101
102 ELFObjectWriter *Writer;
103
104 raw_ostream &OS;
105
106 // This holds the current offset into the object file.
107 size_t FileOff;
108
109 unsigned Is64Bit : 1;
110
111 bool HasRelocationAddend;
112
113 // This holds the symbol table index of the last local symbol.
114 unsigned LastLocalSymbolIndex;
115 // This holds the .strtab section index.
116 unsigned StringTableIndex;
117
118 unsigned ShstrtabIndex;
119
120 public:
121 ELFObjectWriterImpl(ELFObjectWriter *_Writer, bool _Is64Bit,
122 bool _HasRelAddend)
123 : Writer(_Writer), OS(Writer->getStream()), FileOff(0),
124 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend) {
125 }
126
127 void Write8(uint8_t Value) { Writer->Write8(Value); }
128 void Write16(uint16_t Value) { Writer->Write16(Value); }
129 void Write32(uint32_t Value) { Writer->Write32(Value); }
130 void Write64(uint64_t Value) { Writer->Write64(Value); }
131 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
132 void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
133 Writer->WriteBytes(Str, ZeroFillSize);
134 }
135
136 void WriteWord(uint64_t W) {
137 if (Is64Bit) {
138 Writer->Write64(W);
139 } else {
140 Writer->Write32(W);
141 }
142 }
143
144 void String8(char *buf, uint8_t Value) {
145 buf[0] = Value;
146 }
147
148 void StringLE16(char *buf, uint16_t Value) {
149 buf[0] = char(Value >> 0);
150 buf[1] = char(Value >> 8);
151 }
152
153 void StringLE32(char *buf, uint32_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000154 StringLE16(buf, uint16_t(Value >> 0));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000155 StringLE16(buf + 2, uint16_t(Value >> 16));
Matt Fleming3565a062010-08-16 18:57:57 +0000156 }
157
158 void StringLE64(char *buf, uint64_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000159 StringLE32(buf, uint32_t(Value >> 0));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000160 StringLE32(buf + 4, uint32_t(Value >> 32));
Matt Fleming3565a062010-08-16 18:57:57 +0000161 }
162
163 void StringBE16(char *buf ,uint16_t Value) {
164 buf[0] = char(Value >> 8);
165 buf[1] = char(Value >> 0);
166 }
167
168 void StringBE32(char *buf, uint32_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000169 StringBE16(buf, uint16_t(Value >> 16));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000170 StringBE16(buf + 2, uint16_t(Value >> 0));
Matt Fleming3565a062010-08-16 18:57:57 +0000171 }
172
173 void StringBE64(char *buf, uint64_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000174 StringBE32(buf, uint32_t(Value >> 32));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000175 StringBE32(buf + 4, uint32_t(Value >> 0));
Matt Fleming3565a062010-08-16 18:57:57 +0000176 }
177
178 void String16(char *buf, uint16_t Value) {
179 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000180 StringLE16(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000181 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000182 StringBE16(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000183 }
184
185 void String32(char *buf, uint32_t Value) {
186 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000187 StringLE32(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000188 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000189 StringBE32(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000190 }
191
192 void String64(char *buf, uint64_t Value) {
193 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000194 StringLE64(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000195 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000196 StringBE64(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000197 }
198
199 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
200
201 void WriteSymbolEntry(MCDataFragment *F, uint64_t name, uint8_t info,
202 uint64_t value, uint64_t size,
203 uint8_t other, uint16_t shndx);
204
205 void WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
206 const MCAsmLayout &Layout);
207
208 void WriteSymbolTable(MCDataFragment *F, const MCAssembler &Asm,
209 const MCAsmLayout &Layout);
210
211 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
212 const MCFragment *Fragment, const MCFixup &Fixup,
213 MCValue Target, uint64_t &FixedValue);
214
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000215 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
216 const MCSymbol *S);
Matt Fleming3565a062010-08-16 18:57:57 +0000217
218 /// ComputeSymbolTable - Compute the symbol table data
219 ///
220 /// \param StringTable [out] - The string table data.
221 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
222 /// string table.
223 void ComputeSymbolTable(MCAssembler &Asm);
224
225 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
226 const MCSectionData &SD);
227
228 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
229 for (MCAssembler::const_iterator it = Asm.begin(),
230 ie = Asm.end(); it != ie; ++it) {
231 WriteRelocation(Asm, Layout, *it);
232 }
233 }
234
235 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
236
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000237 void ExecutePostLayoutBinding(MCAssembler &Asm) {
238 // Compute symbol table information.
239 ComputeSymbolTable(Asm);
240 }
Matt Fleming3565a062010-08-16 18:57:57 +0000241
242 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
243 uint64_t Address, uint64_t Offset,
244 uint64_t Size, uint32_t Link, uint32_t Info,
245 uint64_t Alignment, uint64_t EntrySize);
246
247 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
248 const MCSectionData *SD);
249
250 void WriteObject(const MCAssembler &Asm, const MCAsmLayout &Layout);
251 };
252
253}
254
255// Emit the ELF header.
256void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
257 unsigned NumberOfSections) {
258 // ELF Header
259 // ----------
260 //
261 // Note
262 // ----
263 // emitWord method behaves differently for ELF32 and ELF64, writing
264 // 4 bytes in the former and 8 in the latter.
265
266 Write8(0x7f); // e_ident[EI_MAG0]
267 Write8('E'); // e_ident[EI_MAG1]
268 Write8('L'); // e_ident[EI_MAG2]
269 Write8('F'); // e_ident[EI_MAG3]
270
271 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
272
273 // e_ident[EI_DATA]
274 Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
275
276 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
277 Write8(ELF::ELFOSABI_LINUX); // e_ident[EI_OSABI]
278 Write8(0); // e_ident[EI_ABIVERSION]
279
280 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
281
282 Write16(ELF::ET_REL); // e_type
283
284 // FIXME: Make this configurable
Benjamin Kramereb976772010-08-17 17:02:29 +0000285 Write16(Is64Bit ? ELF::EM_X86_64 : ELF::EM_386); // e_machine = target
Matt Fleming3565a062010-08-16 18:57:57 +0000286
287 Write32(ELF::EV_CURRENT); // e_version
288 WriteWord(0); // e_entry, no entry point in .o file
289 WriteWord(0); // e_phoff, no program header for .o
Benjamin Kramereb976772010-08-17 17:02:29 +0000290 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
291 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
Matt Fleming3565a062010-08-16 18:57:57 +0000292
293 // FIXME: Make this configurable.
294 Write32(0); // e_flags = whatever the target wants
295
296 // e_ehsize = ELF header size
297 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
298
299 Write16(0); // e_phentsize = prog header entry size
300 Write16(0); // e_phnum = # prog header entries = 0
301
302 // e_shentsize = Section header entry size
303 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
304
305 // e_shnum = # of section header ents
306 Write16(NumberOfSections);
307
308 // e_shstrndx = Section # of '.shstrtab'
309 Write16(ShstrtabIndex);
310}
311
312void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
313 uint8_t info, uint64_t value,
314 uint64_t size, uint8_t other,
315 uint16_t shndx) {
316 if (Is64Bit) {
317 char buf[8];
318
319 String32(buf, name);
320 F->getContents() += StringRef(buf, 4); // st_name
321
322 String8(buf, info);
323 F->getContents() += StringRef(buf, 1); // st_info
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000324
Matt Fleming3565a062010-08-16 18:57:57 +0000325 String8(buf, other);
326 F->getContents() += StringRef(buf, 1); // st_other
327
328 String16(buf, shndx);
329 F->getContents() += StringRef(buf, 2); // st_shndx
330
331 String64(buf, value);
332 F->getContents() += StringRef(buf, 8); // st_value
333
334 String64(buf, size);
335 F->getContents() += StringRef(buf, 8); // st_size
336 } else {
337 char buf[4];
338
339 String32(buf, name);
340 F->getContents() += StringRef(buf, 4); // st_name
341
342 String32(buf, value);
343 F->getContents() += StringRef(buf, 4); // st_value
344
345 String32(buf, size);
346 F->getContents() += StringRef(buf, 4); // st_size
347
348 String8(buf, info);
349 F->getContents() += StringRef(buf, 1); // st_info
350
351 String8(buf, other);
352 F->getContents() += StringRef(buf, 1); // st_other
353
354 String16(buf, shndx);
355 F->getContents() += StringRef(buf, 2); // st_shndx
356 }
357}
358
359void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
360 const MCAsmLayout &Layout) {
361 MCSymbolData &Data = *MSD.SymbolData;
Matt Fleming3565a062010-08-16 18:57:57 +0000362 uint8_t Info = (Data.getFlags() & 0xff);
363 uint8_t Other = ((Data.getFlags() & 0xf00) >> ELF_STV_Shift);
364 uint64_t Value = 0;
365 uint64_t Size = 0;
366 const MCExpr *ESize;
367
368 if (Data.isCommon() && Data.isExternal())
369 Value = Data.getCommonAlignment();
370
371 ESize = Data.getSize();
372 if (Data.getSize()) {
373 MCValue Res;
374 if (ESize->getKind() == MCExpr::Binary) {
375 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
376
377 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
378 MCSymbolData &A =
379 Layout.getAssembler().getSymbolData(Res.getSymA()->getSymbol());
380 MCSymbolData &B =
381 Layout.getAssembler().getSymbolData(Res.getSymB()->getSymbol());
382
383 Size = Layout.getSymbolAddress(&A) - Layout.getSymbolAddress(&B);
384 Value = Layout.getSymbolAddress(&Data);
385 }
386 } else if (ESize->getKind() == MCExpr::Constant) {
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000387 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
Matt Fleming3565a062010-08-16 18:57:57 +0000388 } else {
389 assert(0 && "Unsupported size expression");
390 }
391 }
392
393 // Write out the symbol table entry
394 WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
395 Size, Other, MSD.SectionIndex);
396}
397
398void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
399 const MCAssembler &Asm,
400 const MCAsmLayout &Layout) {
401 // The string table must be emitted first because we need the index
402 // into the string table for all the symbol names.
403 assert(StringTable.size() && "Missing string table");
404
405 // FIXME: Make sure the start of the symbol table is aligned.
406
407 // The first entry is the undefined symbol entry.
408 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000409 F->getContents().append(EntrySize, '\x00');
Matt Fleming3565a062010-08-16 18:57:57 +0000410
411 // Write the symbol table entries.
412 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
413 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
414 ELFSymbolData &MSD = LocalSymbolData[i];
415 WriteSymbol(F, MSD, Layout);
416 }
417
418 // Write out a symbol table entry for each section.
Eli Friedmana44fa242010-08-16 21:17:09 +0000419 // leaving out the just added .symtab which is at
420 // the very end
421 unsigned Index = 1;
422 for (MCAssembler::const_iterator it = Asm.begin(),
423 ie = Asm.end(); it != ie; ++it, ++Index) {
Eli Friedmana44fa242010-08-16 21:17:09 +0000424 const MCSectionELF &Section =
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000425 static_cast<const MCSectionELF&>(it->getSection());
Eli Friedmana44fa242010-08-16 21:17:09 +0000426 // Leave out relocations so we don't have indexes within
427 // the relocations messed up
Benjamin Kramer377a5722010-08-17 17:30:07 +0000428 if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
Eli Friedmana44fa242010-08-16 21:17:09 +0000429 continue;
430 if (Index == Asm.size())
431 continue;
Matt Fleming3565a062010-08-16 18:57:57 +0000432 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
Eli Friedmana44fa242010-08-16 21:17:09 +0000433 LastLocalSymbolIndex++;
434 }
Matt Fleming3565a062010-08-16 18:57:57 +0000435
436 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
437 ELFSymbolData &MSD = ExternalSymbolData[i];
438 MCSymbolData &Data = *MSD.SymbolData;
439 assert((Data.getFlags() & ELF_STB_Global) &&
440 "External symbol requires STB_GLOBAL flag");
441 WriteSymbol(F, MSD, Layout);
442 if (Data.getFlags() & ELF_STB_Local)
443 LastLocalSymbolIndex++;
444 }
445
446 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
447 ELFSymbolData &MSD = UndefinedSymbolData[i];
448 MCSymbolData &Data = *MSD.SymbolData;
449 Data.setFlags(Data.getFlags() | ELF_STB_Global);
450 WriteSymbol(F, MSD, Layout);
451 if (Data.getFlags() & ELF_STB_Local)
452 LastLocalSymbolIndex++;
453 }
454}
455
Benjamin Kramere5b57342010-08-17 18:20:28 +0000456// FIXME: this is currently X86/X86_64 only
Matt Fleming3565a062010-08-16 18:57:57 +0000457void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
458 const MCAsmLayout &Layout,
459 const MCFragment *Fragment,
460 const MCFixup &Fixup,
461 MCValue Target,
462 uint64_t &FixedValue) {
463 unsigned IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
Matt Fleming3565a062010-08-16 18:57:57 +0000464
465 uint64_t FixupOffset =
466 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
467 int64_t Value;
468 int64_t Addend = 0;
469 unsigned Index = 0;
470 unsigned Type;
471
472 Value = Target.getConstant();
473
Benjamin Kramer81cfb852010-08-17 19:45:05 +0000474 if (!Target.isAbsolute()) {
Matt Fleming3565a062010-08-16 18:57:57 +0000475 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
476 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
477 const MCSymbolData *Base = Asm.getAtom(Layout, &SD);
478
479 if (Base) {
Benjamin Kramer2f6e0e62010-08-24 17:34:39 +0000480 MCFragment *F = SD.getFragment();
481 if (F && (!Symbol->isInSection() || SD.isCommon())) {
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000482 Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
Benjamin Kramerbcf2db62010-08-23 19:05:46 +0000483 Value += Layout.getSymbolAddress(&SD);
484 } else
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000485 Index = getSymbolIndexInSymbolTable(Asm, Symbol);
Matt Fleming3565a062010-08-16 18:57:57 +0000486 if (Base != &SD)
487 Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
488 Addend = Value;
489 Value = 0;
490 } else {
491 MCFragment *F = SD.getFragment();
492 if (F) {
493 // Index of the section in .symtab against this symbol
494 // is being relocated + 2 (empty section + abs. symbols).
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000495 Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
Matt Fleming3565a062010-08-16 18:57:57 +0000496
497 MCSectionData *FSD = F->getParent();
498 // Offset of the symbol in the section
499 Addend = Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
500 } else {
501 FixedValue = Value;
502 return;
503 }
504 }
505 }
506
507 // determine the type of the relocation
Benjamin Kramere5b57342010-08-17 18:20:28 +0000508 if (Is64Bit) {
509 if (IsPCRel) {
510 Type = ELF::R_X86_64_PC32;
511 } else {
512 switch ((unsigned)Fixup.getKind()) {
513 default: llvm_unreachable("invalid fixup kind!");
514 case FK_Data_8: Type = ELF::R_X86_64_64; break;
515 case X86::reloc_pcrel_4byte:
516 case FK_Data_4:
517 // check that the offset fits within a signed long
518 if (isInt<32>(Target.getConstant()))
519 Type = ELF::R_X86_64_32S;
520 else
521 Type = ELF::R_X86_64_32;
522 break;
523 case FK_Data_2: Type = ELF::R_X86_64_16; break;
524 case X86::reloc_pcrel_1byte:
525 case FK_Data_1: Type = ELF::R_X86_64_8; break;
526 }
527 }
Matt Fleming3565a062010-08-16 18:57:57 +0000528 } else {
Benjamin Kramere5b57342010-08-17 18:20:28 +0000529 if (IsPCRel) {
530 Type = ELF::R_386_PC32;
531 } else {
532 switch ((unsigned)Fixup.getKind()) {
533 default: llvm_unreachable("invalid fixup kind!");
534 case X86::reloc_pcrel_4byte:
535 case FK_Data_4: Type = ELF::R_386_32; break;
536 case FK_Data_2: Type = ELF::R_386_16; break;
537 case X86::reloc_pcrel_1byte:
538 case FK_Data_1: Type = ELF::R_386_8; break;
539 }
Matt Fleming3565a062010-08-16 18:57:57 +0000540 }
541 }
542
543 FixedValue = Value;
544
Benjamin Kramere5b57342010-08-17 18:20:28 +0000545 ELFRelocationEntry ERE;
546
547 if (Is64Bit) {
548 struct ELF::Elf64_Rela ERE64;
549 ERE64.setSymbolAndType(Index, Type);
550 ERE.r_info = ERE64.r_info;
551 } else {
552 struct ELF::Elf32_Rela ERE32;
553 ERE32.setSymbolAndType(Index, Type);
554 ERE.r_info = ERE32.r_info;
555 }
Matt Fleming3565a062010-08-16 18:57:57 +0000556
557 ERE.r_offset = FixupOffset;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000558
Matt Fleming3565a062010-08-16 18:57:57 +0000559 if (HasRelocationAddend)
560 ERE.r_addend = Addend;
Benjamin Kramer172d7d62010-08-17 00:33:24 +0000561 else
562 ERE.r_addend = 0; // Silence compiler warning.
Matt Fleming3565a062010-08-16 18:57:57 +0000563
564 Relocations[Fragment->getParent()].push_back(ERE);
565}
566
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000567uint64_t
568ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
569 const MCSymbol *S) {
570 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
571 if (&LocalSymbolData[i].SymbolData->getSymbol() == S)
Matt Fleming3565a062010-08-16 18:57:57 +0000572 return i + /* empty symbol */ 1;
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000573 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
574 if (&ExternalSymbolData[i].SymbolData->getSymbol() == S)
575 return i + LocalSymbolData.size() + Asm.size() + /* empty symbol */ 1;
576 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
577 if (&UndefinedSymbolData[i].SymbolData->getSymbol() == S)
578 return i + LocalSymbolData.size() + ExternalSymbolData.size() +
579 Asm.size() + /* empty symbol */ 1;
Eli Friedmanf8020a32010-08-16 19:15:06 +0000580
581 llvm_unreachable("Cannot find symbol which should exist!");
Matt Fleming3565a062010-08-16 18:57:57 +0000582}
583
584void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
585 // Build section lookup table.
586 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
587 unsigned Index = 1;
588 for (MCAssembler::iterator it = Asm.begin(),
589 ie = Asm.end(); it != ie; ++it, ++Index)
590 SectionIndexMap[&it->getSection()] = Index;
591
592 // Index 0 is always the empty string.
593 StringMap<uint64_t> StringIndexMap;
594 StringTable += '\x00';
595
596 // Add the data for local symbols.
597 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
598 ie = Asm.symbol_end(); it != ie; ++it) {
599 const MCSymbol &Symbol = it->getSymbol();
600
601 // Ignore non-linker visible symbols.
602 if (!Asm.isSymbolLinkerVisible(Symbol))
603 continue;
604
605 if (it->isExternal() || Symbol.isUndefined())
606 continue;
607
608 uint64_t &Entry = StringIndexMap[Symbol.getName()];
609 if (!Entry) {
610 Entry = StringTable.size();
611 StringTable += Symbol.getName();
612 StringTable += '\x00';
613 }
614
615 ELFSymbolData MSD;
616 MSD.SymbolData = it;
617 MSD.StringIndex = Entry;
618
619 if (Symbol.isAbsolute()) {
620 MSD.SectionIndex = ELF::SHN_ABS;
621 LocalSymbolData.push_back(MSD);
622 } else {
623 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
624 assert(MSD.SectionIndex && "Invalid section index!");
625 LocalSymbolData.push_back(MSD);
626 }
627 }
628
629 // Now add non-local symbols.
630 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
631 ie = Asm.symbol_end(); it != ie; ++it) {
632 const MCSymbol &Symbol = it->getSymbol();
633
634 // Ignore non-linker visible symbols.
635 if (!Asm.isSymbolLinkerVisible(Symbol))
636 continue;
637
638 if (!it->isExternal() && !Symbol.isUndefined())
639 continue;
640
641 uint64_t &Entry = StringIndexMap[Symbol.getName()];
642 if (!Entry) {
643 Entry = StringTable.size();
644 StringTable += Symbol.getName();
645 StringTable += '\x00';
646 }
647
648 ELFSymbolData MSD;
649 MSD.SymbolData = it;
650 MSD.StringIndex = Entry;
651
652 if (Symbol.isUndefined()) {
653 MSD.SectionIndex = ELF::SHN_UNDEF;
654 // XXX: for some reason we dont Emit* this
655 it->setFlags(it->getFlags() | ELF_STB_Global);
656 UndefinedSymbolData.push_back(MSD);
657 } else if (Symbol.isAbsolute()) {
658 MSD.SectionIndex = ELF::SHN_ABS;
659 ExternalSymbolData.push_back(MSD);
660 } else if (it->isCommon()) {
661 MSD.SectionIndex = ELF::SHN_COMMON;
662 ExternalSymbolData.push_back(MSD);
663 } else {
664 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
665 assert(MSD.SectionIndex && "Invalid section index!");
666 ExternalSymbolData.push_back(MSD);
667 }
668 }
669
670 // Symbols are required to be in lexicographic order.
671 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
672 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
673 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
674
675 // Set the symbol indices. Local symbols must come before all other
676 // symbols with non-local bindings.
677 Index = 0;
678 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
679 LocalSymbolData[i].SymbolData->setIndex(Index++);
680 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
681 ExternalSymbolData[i].SymbolData->setIndex(Index++);
682 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
683 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
684}
685
686void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
687 const MCSectionData &SD) {
688 if (!Relocations[&SD].empty()) {
689 MCContext &Ctx = Asm.getContext();
690 const MCSection *RelaSection;
691 const MCSectionELF &Section =
692 static_cast<const MCSectionELF&>(SD.getSection());
693
694 const StringRef SectionName = Section.getSectionName();
Benjamin Kramer377a5722010-08-17 17:30:07 +0000695 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
Matt Fleming3565a062010-08-16 18:57:57 +0000696 RelaSectionName += SectionName;
Benjamin Kramer299fbe32010-08-17 17:56:13 +0000697
698 unsigned EntrySize;
699 if (HasRelocationAddend)
700 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
701 else
702 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming3565a062010-08-16 18:57:57 +0000703
Benjamin Kramer377a5722010-08-17 17:30:07 +0000704 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
705 ELF::SHT_RELA : ELF::SHT_REL, 0,
Matt Fleming3565a062010-08-16 18:57:57 +0000706 SectionKind::getReadOnly(),
707 false, EntrySize);
708
709 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
710 RelaSD.setAlignment(1);
711
712 MCDataFragment *F = new MCDataFragment(&RelaSD);
713
714 WriteRelocationsFragment(Asm, F, &SD);
715
716 Asm.AddSectionToTheEnd(RelaSD, Layout);
717 }
718}
719
720void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
721 uint64_t Flags, uint64_t Address,
722 uint64_t Offset, uint64_t Size,
723 uint32_t Link, uint32_t Info,
724 uint64_t Alignment,
725 uint64_t EntrySize) {
726 Write32(Name); // sh_name: index into string table
727 Write32(Type); // sh_type
728 WriteWord(Flags); // sh_flags
729 WriteWord(Address); // sh_addr
730 WriteWord(Offset); // sh_offset
731 WriteWord(Size); // sh_size
732 Write32(Link); // sh_link
733 Write32(Info); // sh_info
734 WriteWord(Alignment); // sh_addralign
735 WriteWord(EntrySize); // sh_entsize
736}
737
738void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
739 MCDataFragment *F,
740 const MCSectionData *SD) {
741 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
742 // sort by the r_offset just like gnu as does
743 array_pod_sort(Relocs.begin(), Relocs.end());
744
745 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
746 ELFRelocationEntry entry = Relocs[e - i - 1];
747
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000748 unsigned WordSize = Is64Bit ? 8 : 4;
749 F->getContents() += StringRef((const char *)&entry.r_offset, WordSize);
750 F->getContents() += StringRef((const char *)&entry.r_info, WordSize);
Matt Fleming3565a062010-08-16 18:57:57 +0000751
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000752 if (HasRelocationAddend)
753 F->getContents() += StringRef((const char *)&entry.r_addend, WordSize);
Matt Fleming3565a062010-08-16 18:57:57 +0000754 }
755}
756
757void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
758 MCAsmLayout &Layout) {
759 MCContext &Ctx = Asm.getContext();
760 MCDataFragment *F;
761
762 WriteRelocations(Asm, Layout);
763
764 const MCSection *SymtabSection;
765 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
766
767 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
768 SectionKind::getReadOnly(),
769 false, EntrySize);
770
771 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
772
773 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
774
775 F = new MCDataFragment(&SymtabSD);
776
777 // Symbol table
778 WriteSymbolTable(F, Asm, Layout);
779 Asm.AddSectionToTheEnd(SymtabSD, Layout);
780
781 const MCSection *StrtabSection;
782 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
783 SectionKind::getReadOnly(), false);
784
785 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
786 StrtabSD.setAlignment(1);
787
788 // FIXME: This isn't right. If the sections get rearranged this will
789 // be wrong. We need a proper lookup.
790 StringTableIndex = Asm.size();
791
792 F = new MCDataFragment(&StrtabSD);
793 F->getContents().append(StringTable.begin(), StringTable.end());
794 Asm.AddSectionToTheEnd(StrtabSD, Layout);
795
796 const MCSection *ShstrtabSection;
797 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
798 SectionKind::getReadOnly(), false);
799
800 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
801 ShstrtabSD.setAlignment(1);
802
803 F = new MCDataFragment(&ShstrtabSD);
804
805 // FIXME: This isn't right. If the sections get rearranged this will
806 // be wrong. We need a proper lookup.
807 ShstrtabIndex = Asm.size();
808
809 // Section header string table.
810 //
811 // The first entry of a string table holds a null character so skip
812 // section 0.
813 uint64_t Index = 1;
814 F->getContents() += '\x00';
815
816 for (MCAssembler::const_iterator it = Asm.begin(),
817 ie = Asm.end(); it != ie; ++it) {
Matt Fleming3565a062010-08-16 18:57:57 +0000818 const MCSectionELF &Section =
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000819 static_cast<const MCSectionELF&>(it->getSection());
Matt Fleming3565a062010-08-16 18:57:57 +0000820
821 // Remember the index into the string table so we can write it
822 // into the sh_name field of the section header table.
823 SectionStringTableIndex[&it->getSection()] = Index;
824
825 Index += Section.getSectionName().size() + 1;
826 F->getContents() += Section.getSectionName();
827 F->getContents() += '\x00';
828 }
829
830 Asm.AddSectionToTheEnd(ShstrtabSD, Layout);
831}
832
833void ELFObjectWriterImpl::WriteObject(const MCAssembler &Asm,
834 const MCAsmLayout &Layout) {
Matt Fleming3565a062010-08-16 18:57:57 +0000835 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
836 const_cast<MCAsmLayout&>(Layout));
837
838 // Add 1 for the null section.
839 unsigned NumSections = Asm.size() + 1;
840
841 uint64_t SectionDataSize = 0;
842
843 for (MCAssembler::const_iterator it = Asm.begin(),
844 ie = Asm.end(); it != ie; ++it) {
845 const MCSectionData &SD = *it;
Matt Fleming3565a062010-08-16 18:57:57 +0000846
847 // Get the size of the section in the output file (including padding).
848 uint64_t Size = Layout.getSectionFileSize(&SD);
849 SectionDataSize += Size;
850 }
851
852 // Write out the ELF header ...
853 WriteHeader(SectionDataSize, NumSections);
854 FileOff = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
855
856 // ... then all of the sections ...
857 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
858
Benjamin Kramer44cbde82010-08-19 13:44:49 +0000859 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
860
861 unsigned Index = 1;
Matt Fleming3565a062010-08-16 18:57:57 +0000862 for (MCAssembler::const_iterator it = Asm.begin(),
863 ie = Asm.end(); it != ie; ++it) {
864 // Remember the offset into the file for this section.
865 SectionOffsetMap[&it->getSection()] = FileOff;
866
Benjamin Kramer44cbde82010-08-19 13:44:49 +0000867 SectionIndexMap[&it->getSection()] = Index++;
868
Matt Fleming3565a062010-08-16 18:57:57 +0000869 const MCSectionData &SD = *it;
870 FileOff += Layout.getSectionFileSize(&SD);
871
872 Asm.WriteSectionData(it, Layout, Writer);
873 }
874
875 // ... and then the section header table.
876 // Should we align the section header table?
877 //
878 // Null section first.
879 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
880
881 for (MCAssembler::const_iterator it = Asm.begin(),
882 ie = Asm.end(); it != ie; ++it) {
883 const MCSectionData &SD = *it;
884 const MCSectionELF &Section =
885 static_cast<const MCSectionELF&>(SD.getSection());
886
887 uint64_t sh_link = 0;
888 uint64_t sh_info = 0;
889
890 switch(Section.getType()) {
891 case ELF::SHT_DYNAMIC:
892 sh_link = SectionStringTableIndex[&it->getSection()];
893 sh_info = 0;
894 break;
895
896 case ELF::SHT_REL:
Eli Friedmanf8020a32010-08-16 19:15:06 +0000897 case ELF::SHT_RELA: {
Matt Fleming3565a062010-08-16 18:57:57 +0000898 const MCSection *SymtabSection;
899 const MCSection *InfoSection;
Matt Fleming3565a062010-08-16 18:57:57 +0000900
901 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
902 SectionKind::getReadOnly(),
Eli Friedmanf8020a32010-08-16 19:15:06 +0000903 false);
Benjamin Kramer44cbde82010-08-19 13:44:49 +0000904 sh_link = SectionIndexMap[SymtabSection];
Matt Fleming3565a062010-08-16 18:57:57 +0000905
Benjamin Kramer377a5722010-08-17 17:30:07 +0000906 // Remove ".rel" and ".rela" prefixes.
907 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
908 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
909
Eli Friedmanf8020a32010-08-16 19:15:06 +0000910 InfoSection = Asm.getContext().getELFSection(SectionName,
Matt Fleming3565a062010-08-16 18:57:57 +0000911 ELF::SHT_PROGBITS, 0,
Eli Friedmanf8020a32010-08-16 19:15:06 +0000912 SectionKind::getReadOnly(),
913 false);
Benjamin Kramer44cbde82010-08-19 13:44:49 +0000914 sh_info = SectionIndexMap[InfoSection];
Matt Fleming3565a062010-08-16 18:57:57 +0000915 break;
Eli Friedmanf8020a32010-08-16 19:15:06 +0000916 }
Matt Fleming3565a062010-08-16 18:57:57 +0000917
918 case ELF::SHT_SYMTAB:
919 case ELF::SHT_DYNSYM:
920 sh_link = StringTableIndex;
921 sh_info = LastLocalSymbolIndex;
922 break;
923
924 case ELF::SHT_PROGBITS:
925 case ELF::SHT_STRTAB:
926 case ELF::SHT_NOBITS:
927 // Nothing to do.
928 break;
929
930 case ELF::SHT_HASH:
931 case ELF::SHT_GROUP:
932 case ELF::SHT_SYMTAB_SHNDX:
933 default:
934 assert(0 && "FIXME: sh_type value not supported!");
935 break;
936 }
937
938 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
939 Section.getType(), Section.getFlags(),
940 Layout.getSectionAddress(&SD),
941 SectionOffsetMap.lookup(&SD.getSection()),
942 Layout.getSectionSize(&SD), sh_link,
943 sh_info, SD.getAlignment(),
944 Section.getEntrySize());
945 }
946}
947
948ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
949 bool Is64Bit,
950 bool IsLittleEndian,
951 bool HasRelocationAddend)
952 : MCObjectWriter(OS, IsLittleEndian)
953{
954 Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend);
955}
956
957ELFObjectWriter::~ELFObjectWriter() {
958 delete (ELFObjectWriterImpl*) Impl;
959}
960
961void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
962 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
963}
964
965void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
966 const MCAsmLayout &Layout,
967 const MCFragment *Fragment,
968 const MCFixup &Fixup, MCValue Target,
969 uint64_t &FixedValue) {
970 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
971 Target, FixedValue);
972}
973
974void ELFObjectWriter::WriteObject(const MCAssembler &Asm,
975 const MCAsmLayout &Layout) {
976 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);
977}