blob: 1704fb023d4650798056f57b7bfc25c92a26e13a [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
Chris Lattnerb188a372010-08-28 03:21:03 +000052 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
Matt Fleming3565a062010-08-16 18:57:57 +000053 return Kind == X86::reloc_riprel_4byte ||
54 Kind == X86::reloc_riprel_4byte_movq_load;
Chris Lattnerb188a372010-08-28 03:21:03 +000055 }*/
Matt Fleming3565a062010-08-16 18:57:57 +000056
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); }
Chris Lattnerb188a372010-08-28 03:21:03 +0000130 //void Write64(uint64_t Value) { Writer->Write64(Value); }
Matt Fleming3565a062010-08-16 18:57:57 +0000131 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
Chris Lattnerb188a372010-08-28 03:21:03 +0000132 //void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
133 // Writer->WriteBytes(Str, ZeroFillSize);
134 //}
Matt Fleming3565a062010-08-16 18:57:57 +0000135
136 void WriteWord(uint64_t W) {
Chris Lattnerb188a372010-08-28 03:21:03 +0000137 if (Is64Bit)
Matt Fleming3565a062010-08-16 18:57:57 +0000138 Writer->Write64(W);
Chris Lattnerb188a372010-08-28 03:21:03 +0000139 else
Matt Fleming3565a062010-08-16 18:57:57 +0000140 Writer->Write32(W);
Matt Fleming3565a062010-08-16 18:57:57 +0000141 }
142
143 void String8(char *buf, uint8_t Value) {
144 buf[0] = Value;
145 }
146
147 void StringLE16(char *buf, uint16_t Value) {
148 buf[0] = char(Value >> 0);
149 buf[1] = char(Value >> 8);
150 }
151
152 void StringLE32(char *buf, uint32_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000153 StringLE16(buf, uint16_t(Value >> 0));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000154 StringLE16(buf + 2, uint16_t(Value >> 16));
Matt Fleming3565a062010-08-16 18:57:57 +0000155 }
156
157 void StringLE64(char *buf, uint64_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000158 StringLE32(buf, uint32_t(Value >> 0));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000159 StringLE32(buf + 4, uint32_t(Value >> 32));
Matt Fleming3565a062010-08-16 18:57:57 +0000160 }
161
162 void StringBE16(char *buf ,uint16_t Value) {
163 buf[0] = char(Value >> 8);
164 buf[1] = char(Value >> 0);
165 }
166
167 void StringBE32(char *buf, uint32_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000168 StringBE16(buf, uint16_t(Value >> 16));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000169 StringBE16(buf + 2, uint16_t(Value >> 0));
Matt Fleming3565a062010-08-16 18:57:57 +0000170 }
171
172 void StringBE64(char *buf, uint64_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000173 StringBE32(buf, uint32_t(Value >> 32));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000174 StringBE32(buf + 4, uint32_t(Value >> 0));
Matt Fleming3565a062010-08-16 18:57:57 +0000175 }
176
177 void String16(char *buf, uint16_t Value) {
178 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000179 StringLE16(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000180 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000181 StringBE16(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000182 }
183
184 void String32(char *buf, uint32_t Value) {
185 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000186 StringLE32(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000187 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000188 StringBE32(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000189 }
190
191 void String64(char *buf, uint64_t Value) {
192 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000193 StringLE64(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000194 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000195 StringBE64(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000196 }
197
198 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
199
200 void WriteSymbolEntry(MCDataFragment *F, uint64_t name, uint8_t info,
201 uint64_t value, uint64_t size,
202 uint8_t other, uint16_t shndx);
203
204 void WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
205 const MCAsmLayout &Layout);
206
207 void WriteSymbolTable(MCDataFragment *F, const MCAssembler &Asm,
208 const MCAsmLayout &Layout);
209
210 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
211 const MCFragment *Fragment, const MCFixup &Fixup,
212 MCValue Target, uint64_t &FixedValue);
213
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000214 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
215 const MCSymbol *S);
Matt Fleming3565a062010-08-16 18:57:57 +0000216
217 /// ComputeSymbolTable - Compute the symbol table data
218 ///
219 /// \param StringTable [out] - The string table data.
220 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
221 /// string table.
222 void ComputeSymbolTable(MCAssembler &Asm);
223
224 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
225 const MCSectionData &SD);
226
227 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
228 for (MCAssembler::const_iterator it = Asm.begin(),
229 ie = Asm.end(); it != ie; ++it) {
230 WriteRelocation(Asm, Layout, *it);
231 }
232 }
233
234 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
235
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000236 void ExecutePostLayoutBinding(MCAssembler &Asm) {
237 // Compute symbol table information.
238 ComputeSymbolTable(Asm);
239 }
Matt Fleming3565a062010-08-16 18:57:57 +0000240
241 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
242 uint64_t Address, uint64_t Offset,
243 uint64_t Size, uint32_t Link, uint32_t Info,
244 uint64_t Alignment, uint64_t EntrySize);
245
246 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
247 const MCSectionData *SD);
248
249 void WriteObject(const MCAssembler &Asm, const MCAsmLayout &Layout);
250 };
251
252}
253
254// Emit the ELF header.
255void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
256 unsigned NumberOfSections) {
257 // ELF Header
258 // ----------
259 //
260 // Note
261 // ----
262 // emitWord method behaves differently for ELF32 and ELF64, writing
263 // 4 bytes in the former and 8 in the latter.
264
265 Write8(0x7f); // e_ident[EI_MAG0]
266 Write8('E'); // e_ident[EI_MAG1]
267 Write8('L'); // e_ident[EI_MAG2]
268 Write8('F'); // e_ident[EI_MAG3]
269
270 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
271
272 // e_ident[EI_DATA]
273 Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
274
275 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
276 Write8(ELF::ELFOSABI_LINUX); // e_ident[EI_OSABI]
277 Write8(0); // e_ident[EI_ABIVERSION]
278
279 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
280
281 Write16(ELF::ET_REL); // e_type
282
283 // FIXME: Make this configurable
Benjamin Kramereb976772010-08-17 17:02:29 +0000284 Write16(Is64Bit ? ELF::EM_X86_64 : ELF::EM_386); // e_machine = target
Matt Fleming3565a062010-08-16 18:57:57 +0000285
286 Write32(ELF::EV_CURRENT); // e_version
287 WriteWord(0); // e_entry, no entry point in .o file
288 WriteWord(0); // e_phoff, no program header for .o
Benjamin Kramereb976772010-08-17 17:02:29 +0000289 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
290 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
Matt Fleming3565a062010-08-16 18:57:57 +0000291
292 // FIXME: Make this configurable.
293 Write32(0); // e_flags = whatever the target wants
294
295 // e_ehsize = ELF header size
296 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
297
298 Write16(0); // e_phentsize = prog header entry size
299 Write16(0); // e_phnum = # prog header entries = 0
300
301 // e_shentsize = Section header entry size
302 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
303
304 // e_shnum = # of section header ents
305 Write16(NumberOfSections);
306
307 // e_shstrndx = Section # of '.shstrtab'
308 Write16(ShstrtabIndex);
309}
310
311void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
312 uint8_t info, uint64_t value,
313 uint64_t size, uint8_t other,
314 uint16_t shndx) {
315 if (Is64Bit) {
316 char buf[8];
317
318 String32(buf, name);
319 F->getContents() += StringRef(buf, 4); // st_name
320
321 String8(buf, info);
322 F->getContents() += StringRef(buf, 1); // st_info
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000323
Matt Fleming3565a062010-08-16 18:57:57 +0000324 String8(buf, other);
325 F->getContents() += StringRef(buf, 1); // st_other
326
327 String16(buf, shndx);
328 F->getContents() += StringRef(buf, 2); // st_shndx
329
330 String64(buf, value);
331 F->getContents() += StringRef(buf, 8); // st_value
332
333 String64(buf, size);
334 F->getContents() += StringRef(buf, 8); // st_size
335 } else {
336 char buf[4];
337
338 String32(buf, name);
339 F->getContents() += StringRef(buf, 4); // st_name
340
341 String32(buf, value);
342 F->getContents() += StringRef(buf, 4); // st_value
343
344 String32(buf, size);
345 F->getContents() += StringRef(buf, 4); // st_size
346
347 String8(buf, info);
348 F->getContents() += StringRef(buf, 1); // st_info
349
350 String8(buf, other);
351 F->getContents() += StringRef(buf, 1); // st_other
352
353 String16(buf, shndx);
354 F->getContents() += StringRef(buf, 2); // st_shndx
355 }
356}
357
358void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
359 const MCAsmLayout &Layout) {
360 MCSymbolData &Data = *MSD.SymbolData;
Matt Fleming3565a062010-08-16 18:57:57 +0000361 uint8_t Info = (Data.getFlags() & 0xff);
362 uint8_t Other = ((Data.getFlags() & 0xf00) >> ELF_STV_Shift);
363 uint64_t Value = 0;
364 uint64_t Size = 0;
365 const MCExpr *ESize;
366
367 if (Data.isCommon() && Data.isExternal())
368 Value = Data.getCommonAlignment();
369
370 ESize = Data.getSize();
371 if (Data.getSize()) {
372 MCValue Res;
373 if (ESize->getKind() == MCExpr::Binary) {
374 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
375
376 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
377 MCSymbolData &A =
378 Layout.getAssembler().getSymbolData(Res.getSymA()->getSymbol());
379 MCSymbolData &B =
380 Layout.getAssembler().getSymbolData(Res.getSymB()->getSymbol());
381
382 Size = Layout.getSymbolAddress(&A) - Layout.getSymbolAddress(&B);
383 Value = Layout.getSymbolAddress(&Data);
384 }
385 } else if (ESize->getKind() == MCExpr::Constant) {
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000386 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
Matt Fleming3565a062010-08-16 18:57:57 +0000387 } else {
388 assert(0 && "Unsupported size expression");
389 }
390 }
391
392 // Write out the symbol table entry
393 WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
394 Size, Other, MSD.SectionIndex);
395}
396
397void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
398 const MCAssembler &Asm,
399 const MCAsmLayout &Layout) {
400 // The string table must be emitted first because we need the index
401 // into the string table for all the symbol names.
402 assert(StringTable.size() && "Missing string table");
403
404 // FIXME: Make sure the start of the symbol table is aligned.
405
406 // The first entry is the undefined symbol entry.
407 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000408 F->getContents().append(EntrySize, '\x00');
Matt Fleming3565a062010-08-16 18:57:57 +0000409
410 // Write the symbol table entries.
411 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
412 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
413 ELFSymbolData &MSD = LocalSymbolData[i];
414 WriteSymbol(F, MSD, Layout);
415 }
416
417 // Write out a symbol table entry for each section.
Eli Friedmana44fa242010-08-16 21:17:09 +0000418 // leaving out the just added .symtab which is at
419 // the very end
420 unsigned Index = 1;
421 for (MCAssembler::const_iterator it = Asm.begin(),
422 ie = Asm.end(); it != ie; ++it, ++Index) {
Eli Friedmana44fa242010-08-16 21:17:09 +0000423 const MCSectionELF &Section =
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000424 static_cast<const MCSectionELF&>(it->getSection());
Eli Friedmana44fa242010-08-16 21:17:09 +0000425 // Leave out relocations so we don't have indexes within
426 // the relocations messed up
Benjamin Kramer377a5722010-08-17 17:30:07 +0000427 if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
Eli Friedmana44fa242010-08-16 21:17:09 +0000428 continue;
429 if (Index == Asm.size())
430 continue;
Matt Fleming3565a062010-08-16 18:57:57 +0000431 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
Eli Friedmana44fa242010-08-16 21:17:09 +0000432 LastLocalSymbolIndex++;
433 }
Matt Fleming3565a062010-08-16 18:57:57 +0000434
435 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
436 ELFSymbolData &MSD = ExternalSymbolData[i];
437 MCSymbolData &Data = *MSD.SymbolData;
438 assert((Data.getFlags() & ELF_STB_Global) &&
439 "External symbol requires STB_GLOBAL flag");
440 WriteSymbol(F, MSD, Layout);
441 if (Data.getFlags() & ELF_STB_Local)
442 LastLocalSymbolIndex++;
443 }
444
445 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
446 ELFSymbolData &MSD = UndefinedSymbolData[i];
447 MCSymbolData &Data = *MSD.SymbolData;
448 Data.setFlags(Data.getFlags() | ELF_STB_Global);
449 WriteSymbol(F, MSD, Layout);
450 if (Data.getFlags() & ELF_STB_Local)
451 LastLocalSymbolIndex++;
452 }
453}
454
Benjamin Kramere5b57342010-08-17 18:20:28 +0000455// FIXME: this is currently X86/X86_64 only
Matt Fleming3565a062010-08-16 18:57:57 +0000456void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
457 const MCAsmLayout &Layout,
458 const MCFragment *Fragment,
459 const MCFixup &Fixup,
460 MCValue Target,
461 uint64_t &FixedValue) {
Matt Fleming3565a062010-08-16 18:57:57 +0000462 int64_t Addend = 0;
463 unsigned Index = 0;
Benjamin Kramer95c602a2010-08-27 10:38:39 +0000464 int64_t Value = Target.getConstant();
Matt Fleming3565a062010-08-16 18:57:57 +0000465
Benjamin Kramer81cfb852010-08-17 19:45:05 +0000466 if (!Target.isAbsolute()) {
Matt Fleming3565a062010-08-16 18:57:57 +0000467 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
468 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
469 const MCSymbolData *Base = Asm.getAtom(Layout, &SD);
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000470 MCFragment *F = SD.getFragment();
Matt Fleming3565a062010-08-16 18:57:57 +0000471
472 if (Base) {
Benjamin Kramer2f6e0e62010-08-24 17:34:39 +0000473 if (F && (!Symbol->isInSection() || SD.isCommon())) {
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000474 Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
Benjamin Kramerbcf2db62010-08-23 19:05:46 +0000475 Value += Layout.getSymbolAddress(&SD);
476 } else
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000477 Index = getSymbolIndexInSymbolTable(Asm, Symbol);
Matt Fleming3565a062010-08-16 18:57:57 +0000478 if (Base != &SD)
479 Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
480 Addend = Value;
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000481 // Compensate for the addend on i386.
Benjamin Kramer4ba1b302010-08-26 18:12:04 +0000482 if (Is64Bit)
483 Value = 0;
Matt Fleming3565a062010-08-16 18:57:57 +0000484 } else {
Matt Fleming3565a062010-08-16 18:57:57 +0000485 if (F) {
486 // Index of the section in .symtab against this symbol
487 // is being relocated + 2 (empty section + abs. symbols).
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000488 Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
Matt Fleming3565a062010-08-16 18:57:57 +0000489
490 MCSectionData *FSD = F->getParent();
491 // Offset of the symbol in the section
492 Addend = Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
493 } else {
494 FixedValue = Value;
495 return;
496 }
497 }
498 }
499
Benjamin Kramer95c602a2010-08-27 10:38:39 +0000500 FixedValue = Value;
501
Matt Fleming3565a062010-08-16 18:57:57 +0000502 // determine the type of the relocation
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000503 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
504 unsigned Type;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000505 if (Is64Bit) {
506 if (IsPCRel) {
507 Type = ELF::R_X86_64_PC32;
508 } else {
509 switch ((unsigned)Fixup.getKind()) {
510 default: llvm_unreachable("invalid fixup kind!");
511 case FK_Data_8: Type = ELF::R_X86_64_64; break;
512 case X86::reloc_pcrel_4byte:
513 case FK_Data_4:
514 // check that the offset fits within a signed long
515 if (isInt<32>(Target.getConstant()))
516 Type = ELF::R_X86_64_32S;
517 else
518 Type = ELF::R_X86_64_32;
519 break;
520 case FK_Data_2: Type = ELF::R_X86_64_16; break;
521 case X86::reloc_pcrel_1byte:
522 case FK_Data_1: Type = ELF::R_X86_64_8; break;
523 }
524 }
Matt Fleming3565a062010-08-16 18:57:57 +0000525 } else {
Benjamin Kramere5b57342010-08-17 18:20:28 +0000526 if (IsPCRel) {
527 Type = ELF::R_386_PC32;
528 } else {
529 switch ((unsigned)Fixup.getKind()) {
530 default: llvm_unreachable("invalid fixup kind!");
531 case X86::reloc_pcrel_4byte:
532 case FK_Data_4: Type = ELF::R_386_32; break;
533 case FK_Data_2: Type = ELF::R_386_16; break;
534 case X86::reloc_pcrel_1byte:
535 case FK_Data_1: Type = ELF::R_386_8; break;
536 }
Matt Fleming3565a062010-08-16 18:57:57 +0000537 }
538 }
539
Benjamin Kramere5b57342010-08-17 18:20:28 +0000540 ELFRelocationEntry ERE;
541
542 if (Is64Bit) {
543 struct ELF::Elf64_Rela ERE64;
544 ERE64.setSymbolAndType(Index, Type);
545 ERE.r_info = ERE64.r_info;
546 } else {
547 struct ELF::Elf32_Rela ERE32;
548 ERE32.setSymbolAndType(Index, Type);
549 ERE.r_info = ERE32.r_info;
550 }
Matt Fleming3565a062010-08-16 18:57:57 +0000551
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000552 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
Benjamin Kramere5b57342010-08-17 18:20:28 +0000553
Matt Fleming3565a062010-08-16 18:57:57 +0000554 if (HasRelocationAddend)
555 ERE.r_addend = Addend;
Benjamin Kramer172d7d62010-08-17 00:33:24 +0000556 else
557 ERE.r_addend = 0; // Silence compiler warning.
Matt Fleming3565a062010-08-16 18:57:57 +0000558
559 Relocations[Fragment->getParent()].push_back(ERE);
560}
561
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000562uint64_t
563ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
564 const MCSymbol *S) {
Benjamin Kramer7b83c262010-08-25 20:09:43 +0000565 MCSymbolData &SD = Asm.getSymbolData(*S);
Eli Friedmanf8020a32010-08-16 19:15:06 +0000566
Benjamin Kramer7b83c262010-08-25 20:09:43 +0000567 // Local symbol.
568 if (!SD.isExternal() && !S->isUndefined())
569 return SD.getIndex() + /* empty symbol */ 1;
570
571 // External or undefined symbol.
572 return SD.getIndex() + Asm.size() + /* empty symbol */ 1;
Matt Fleming3565a062010-08-16 18:57:57 +0000573}
574
575void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
576 // Build section lookup table.
577 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
578 unsigned Index = 1;
579 for (MCAssembler::iterator it = Asm.begin(),
580 ie = Asm.end(); it != ie; ++it, ++Index)
581 SectionIndexMap[&it->getSection()] = Index;
582
583 // Index 0 is always the empty string.
584 StringMap<uint64_t> StringIndexMap;
585 StringTable += '\x00';
586
587 // Add the data for local symbols.
588 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
589 ie = Asm.symbol_end(); it != ie; ++it) {
590 const MCSymbol &Symbol = it->getSymbol();
591
592 // Ignore non-linker visible symbols.
593 if (!Asm.isSymbolLinkerVisible(Symbol))
594 continue;
595
596 if (it->isExternal() || Symbol.isUndefined())
597 continue;
598
599 uint64_t &Entry = StringIndexMap[Symbol.getName()];
600 if (!Entry) {
601 Entry = StringTable.size();
602 StringTable += Symbol.getName();
603 StringTable += '\x00';
604 }
605
606 ELFSymbolData MSD;
607 MSD.SymbolData = it;
608 MSD.StringIndex = Entry;
609
610 if (Symbol.isAbsolute()) {
611 MSD.SectionIndex = ELF::SHN_ABS;
612 LocalSymbolData.push_back(MSD);
613 } else {
614 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
615 assert(MSD.SectionIndex && "Invalid section index!");
616 LocalSymbolData.push_back(MSD);
617 }
618 }
619
620 // Now add non-local symbols.
621 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
622 ie = Asm.symbol_end(); it != ie; ++it) {
623 const MCSymbol &Symbol = it->getSymbol();
624
625 // Ignore non-linker visible symbols.
626 if (!Asm.isSymbolLinkerVisible(Symbol))
627 continue;
628
629 if (!it->isExternal() && !Symbol.isUndefined())
630 continue;
631
632 uint64_t &Entry = StringIndexMap[Symbol.getName()];
633 if (!Entry) {
634 Entry = StringTable.size();
635 StringTable += Symbol.getName();
636 StringTable += '\x00';
637 }
638
639 ELFSymbolData MSD;
640 MSD.SymbolData = it;
641 MSD.StringIndex = Entry;
642
643 if (Symbol.isUndefined()) {
644 MSD.SectionIndex = ELF::SHN_UNDEF;
645 // XXX: for some reason we dont Emit* this
646 it->setFlags(it->getFlags() | ELF_STB_Global);
647 UndefinedSymbolData.push_back(MSD);
648 } else if (Symbol.isAbsolute()) {
649 MSD.SectionIndex = ELF::SHN_ABS;
650 ExternalSymbolData.push_back(MSD);
651 } else if (it->isCommon()) {
652 MSD.SectionIndex = ELF::SHN_COMMON;
653 ExternalSymbolData.push_back(MSD);
654 } else {
655 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
656 assert(MSD.SectionIndex && "Invalid section index!");
657 ExternalSymbolData.push_back(MSD);
658 }
659 }
660
661 // Symbols are required to be in lexicographic order.
662 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
663 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
664 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
665
666 // Set the symbol indices. Local symbols must come before all other
667 // symbols with non-local bindings.
668 Index = 0;
669 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
670 LocalSymbolData[i].SymbolData->setIndex(Index++);
671 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
672 ExternalSymbolData[i].SymbolData->setIndex(Index++);
673 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
674 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
675}
676
677void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
678 const MCSectionData &SD) {
679 if (!Relocations[&SD].empty()) {
680 MCContext &Ctx = Asm.getContext();
681 const MCSection *RelaSection;
682 const MCSectionELF &Section =
683 static_cast<const MCSectionELF&>(SD.getSection());
684
685 const StringRef SectionName = Section.getSectionName();
Benjamin Kramer377a5722010-08-17 17:30:07 +0000686 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
Matt Fleming3565a062010-08-16 18:57:57 +0000687 RelaSectionName += SectionName;
Benjamin Kramer299fbe32010-08-17 17:56:13 +0000688
689 unsigned EntrySize;
690 if (HasRelocationAddend)
691 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
692 else
693 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming3565a062010-08-16 18:57:57 +0000694
Benjamin Kramer377a5722010-08-17 17:30:07 +0000695 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
696 ELF::SHT_RELA : ELF::SHT_REL, 0,
Matt Fleming3565a062010-08-16 18:57:57 +0000697 SectionKind::getReadOnly(),
698 false, EntrySize);
699
700 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
701 RelaSD.setAlignment(1);
702
703 MCDataFragment *F = new MCDataFragment(&RelaSD);
704
705 WriteRelocationsFragment(Asm, F, &SD);
706
707 Asm.AddSectionToTheEnd(RelaSD, Layout);
708 }
709}
710
711void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
712 uint64_t Flags, uint64_t Address,
713 uint64_t Offset, uint64_t Size,
714 uint32_t Link, uint32_t Info,
715 uint64_t Alignment,
716 uint64_t EntrySize) {
717 Write32(Name); // sh_name: index into string table
718 Write32(Type); // sh_type
719 WriteWord(Flags); // sh_flags
720 WriteWord(Address); // sh_addr
721 WriteWord(Offset); // sh_offset
722 WriteWord(Size); // sh_size
723 Write32(Link); // sh_link
724 Write32(Info); // sh_info
725 WriteWord(Alignment); // sh_addralign
726 WriteWord(EntrySize); // sh_entsize
727}
728
729void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
730 MCDataFragment *F,
731 const MCSectionData *SD) {
732 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
733 // sort by the r_offset just like gnu as does
734 array_pod_sort(Relocs.begin(), Relocs.end());
735
736 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
737 ELFRelocationEntry entry = Relocs[e - i - 1];
738
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000739 unsigned WordSize = Is64Bit ? 8 : 4;
740 F->getContents() += StringRef((const char *)&entry.r_offset, WordSize);
741 F->getContents() += StringRef((const char *)&entry.r_info, WordSize);
Matt Fleming3565a062010-08-16 18:57:57 +0000742
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000743 if (HasRelocationAddend)
744 F->getContents() += StringRef((const char *)&entry.r_addend, WordSize);
Matt Fleming3565a062010-08-16 18:57:57 +0000745 }
746}
747
748void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
749 MCAsmLayout &Layout) {
750 MCContext &Ctx = Asm.getContext();
751 MCDataFragment *F;
752
753 WriteRelocations(Asm, Layout);
754
755 const MCSection *SymtabSection;
756 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
757
758 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
759 SectionKind::getReadOnly(),
760 false, EntrySize);
761
762 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
763
764 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
765
766 F = new MCDataFragment(&SymtabSD);
767
768 // Symbol table
769 WriteSymbolTable(F, Asm, Layout);
770 Asm.AddSectionToTheEnd(SymtabSD, Layout);
771
772 const MCSection *StrtabSection;
773 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
774 SectionKind::getReadOnly(), false);
775
776 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
777 StrtabSD.setAlignment(1);
778
779 // FIXME: This isn't right. If the sections get rearranged this will
780 // be wrong. We need a proper lookup.
781 StringTableIndex = Asm.size();
782
783 F = new MCDataFragment(&StrtabSD);
784 F->getContents().append(StringTable.begin(), StringTable.end());
785 Asm.AddSectionToTheEnd(StrtabSD, Layout);
786
787 const MCSection *ShstrtabSection;
788 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
789 SectionKind::getReadOnly(), false);
790
791 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
792 ShstrtabSD.setAlignment(1);
793
794 F = new MCDataFragment(&ShstrtabSD);
795
796 // FIXME: This isn't right. If the sections get rearranged this will
797 // be wrong. We need a proper lookup.
798 ShstrtabIndex = Asm.size();
799
800 // Section header string table.
801 //
802 // The first entry of a string table holds a null character so skip
803 // section 0.
804 uint64_t Index = 1;
805 F->getContents() += '\x00';
806
807 for (MCAssembler::const_iterator it = Asm.begin(),
808 ie = Asm.end(); it != ie; ++it) {
Matt Fleming3565a062010-08-16 18:57:57 +0000809 const MCSectionELF &Section =
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000810 static_cast<const MCSectionELF&>(it->getSection());
Matt Fleming3565a062010-08-16 18:57:57 +0000811
812 // Remember the index into the string table so we can write it
813 // into the sh_name field of the section header table.
814 SectionStringTableIndex[&it->getSection()] = Index;
815
816 Index += Section.getSectionName().size() + 1;
817 F->getContents() += Section.getSectionName();
818 F->getContents() += '\x00';
819 }
820
821 Asm.AddSectionToTheEnd(ShstrtabSD, Layout);
822}
823
824void ELFObjectWriterImpl::WriteObject(const MCAssembler &Asm,
825 const MCAsmLayout &Layout) {
Matt Fleming3565a062010-08-16 18:57:57 +0000826 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
827 const_cast<MCAsmLayout&>(Layout));
828
829 // Add 1 for the null section.
830 unsigned NumSections = Asm.size() + 1;
831
832 uint64_t SectionDataSize = 0;
833
834 for (MCAssembler::const_iterator it = Asm.begin(),
835 ie = Asm.end(); it != ie; ++it) {
836 const MCSectionData &SD = *it;
Matt Fleming3565a062010-08-16 18:57:57 +0000837
838 // Get the size of the section in the output file (including padding).
839 uint64_t Size = Layout.getSectionFileSize(&SD);
840 SectionDataSize += Size;
841 }
842
843 // Write out the ELF header ...
844 WriteHeader(SectionDataSize, NumSections);
845 FileOff = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
846
847 // ... then all of the sections ...
848 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
849
Benjamin Kramer44cbde82010-08-19 13:44:49 +0000850 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
851
852 unsigned Index = 1;
Matt Fleming3565a062010-08-16 18:57:57 +0000853 for (MCAssembler::const_iterator it = Asm.begin(),
854 ie = Asm.end(); it != ie; ++it) {
855 // Remember the offset into the file for this section.
856 SectionOffsetMap[&it->getSection()] = FileOff;
857
Benjamin Kramer44cbde82010-08-19 13:44:49 +0000858 SectionIndexMap[&it->getSection()] = Index++;
859
Matt Fleming3565a062010-08-16 18:57:57 +0000860 const MCSectionData &SD = *it;
861 FileOff += Layout.getSectionFileSize(&SD);
862
863 Asm.WriteSectionData(it, Layout, Writer);
864 }
865
866 // ... and then the section header table.
867 // Should we align the section header table?
868 //
869 // Null section first.
870 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
871
872 for (MCAssembler::const_iterator it = Asm.begin(),
873 ie = Asm.end(); it != ie; ++it) {
874 const MCSectionData &SD = *it;
875 const MCSectionELF &Section =
876 static_cast<const MCSectionELF&>(SD.getSection());
877
878 uint64_t sh_link = 0;
879 uint64_t sh_info = 0;
880
881 switch(Section.getType()) {
882 case ELF::SHT_DYNAMIC:
883 sh_link = SectionStringTableIndex[&it->getSection()];
884 sh_info = 0;
885 break;
886
887 case ELF::SHT_REL:
Eli Friedmanf8020a32010-08-16 19:15:06 +0000888 case ELF::SHT_RELA: {
Matt Fleming3565a062010-08-16 18:57:57 +0000889 const MCSection *SymtabSection;
890 const MCSection *InfoSection;
Matt Fleming3565a062010-08-16 18:57:57 +0000891
892 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
893 SectionKind::getReadOnly(),
Eli Friedmanf8020a32010-08-16 19:15:06 +0000894 false);
Benjamin Kramer44cbde82010-08-19 13:44:49 +0000895 sh_link = SectionIndexMap[SymtabSection];
Matt Fleming3565a062010-08-16 18:57:57 +0000896
Benjamin Kramer377a5722010-08-17 17:30:07 +0000897 // Remove ".rel" and ".rela" prefixes.
898 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
899 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
900
Eli Friedmanf8020a32010-08-16 19:15:06 +0000901 InfoSection = Asm.getContext().getELFSection(SectionName,
Matt Fleming3565a062010-08-16 18:57:57 +0000902 ELF::SHT_PROGBITS, 0,
Eli Friedmanf8020a32010-08-16 19:15:06 +0000903 SectionKind::getReadOnly(),
904 false);
Benjamin Kramer44cbde82010-08-19 13:44:49 +0000905 sh_info = SectionIndexMap[InfoSection];
Matt Fleming3565a062010-08-16 18:57:57 +0000906 break;
Eli Friedmanf8020a32010-08-16 19:15:06 +0000907 }
Matt Fleming3565a062010-08-16 18:57:57 +0000908
909 case ELF::SHT_SYMTAB:
910 case ELF::SHT_DYNSYM:
911 sh_link = StringTableIndex;
912 sh_info = LastLocalSymbolIndex;
913 break;
914
915 case ELF::SHT_PROGBITS:
916 case ELF::SHT_STRTAB:
917 case ELF::SHT_NOBITS:
918 // Nothing to do.
919 break;
920
921 case ELF::SHT_HASH:
922 case ELF::SHT_GROUP:
923 case ELF::SHT_SYMTAB_SHNDX:
924 default:
925 assert(0 && "FIXME: sh_type value not supported!");
926 break;
927 }
928
929 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
930 Section.getType(), Section.getFlags(),
931 Layout.getSectionAddress(&SD),
932 SectionOffsetMap.lookup(&SD.getSection()),
933 Layout.getSectionSize(&SD), sh_link,
934 sh_info, SD.getAlignment(),
935 Section.getEntrySize());
936 }
937}
938
939ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
940 bool Is64Bit,
941 bool IsLittleEndian,
942 bool HasRelocationAddend)
943 : MCObjectWriter(OS, IsLittleEndian)
944{
945 Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend);
946}
947
948ELFObjectWriter::~ELFObjectWriter() {
949 delete (ELFObjectWriterImpl*) Impl;
950}
951
952void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
953 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
954}
955
956void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
957 const MCAsmLayout &Layout,
958 const MCFragment *Fragment,
959 const MCFixup &Fixup, MCValue Target,
960 uint64_t &FixedValue) {
961 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
962 Target, FixedValue);
963}
964
965void ELFObjectWriter::WriteObject(const MCAssembler &Asm,
966 const MCAsmLayout &Layout) {
967 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);
968}