blob: b33b04703081d43a193ecde9e215095453903bf6 [file] [log] [blame]
Matt Fleming3565a062010-08-16 18:57:57 +00001//===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements ELF object file writer information.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/MC/ELFObjectWriter.h"
Rafael Espindola8f413fa2010-10-05 15:11:03 +000015#include "llvm/ADT/SmallPtrSet.h"
Matt Fleming3565a062010-08-16 18:57:57 +000016#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/StringMap.h"
18#include "llvm/ADT/Twine.h"
19#include "llvm/MC/MCAssembler.h"
20#include "llvm/MC/MCAsmLayout.h"
21#include "llvm/MC/MCContext.h"
22#include "llvm/MC/MCELFSymbolFlags.h"
23#include "llvm/MC/MCExpr.h"
24#include "llvm/MC/MCObjectWriter.h"
25#include "llvm/MC/MCSectionELF.h"
26#include "llvm/MC/MCSymbol.h"
27#include "llvm/MC/MCValue.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/ELF.h"
31#include "llvm/Target/TargetAsmBackend.h"
32
33#include "../Target/X86/X86FixupKinds.h"
34
35#include <vector>
36using namespace llvm;
37
Rafael Espindolaad49cf52010-09-18 15:03:21 +000038static unsigned GetType(const MCSymbolData &SD) {
39 uint32_t Type = (SD.getFlags() & (0xf << ELF_STT_Shift)) >> ELF_STT_Shift;
40 assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
41 Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
42 Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
43 Type == ELF::STT_TLS);
44 return Type;
45}
46
Rafael Espindolae15eb4e2010-09-23 19:55:14 +000047static unsigned GetBinding(const MCSymbolData &SD) {
48 uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
49 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
50 Binding == ELF::STB_WEAK);
51 return Binding;
52}
53
54static void SetBinding(MCSymbolData &SD, unsigned Binding) {
55 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
56 Binding == ELF::STB_WEAK);
57 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
58 SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
59}
60
Rafael Espindolacebdc012010-10-04 19:46:28 +000061static bool isFixupKindX86PCRel(unsigned Kind) {
62 switch (Kind) {
63 default:
64 return false;
65 case X86::reloc_pcrel_1byte:
66 case X86::reloc_pcrel_4byte:
67 case X86::reloc_riprel_4byte:
68 case X86::reloc_riprel_4byte_movq_load:
69 return true;
70 }
71}
72
Rafael Espindola5c77c162010-10-05 15:48:37 +000073static bool RelocNeedsGOT(unsigned Type) {
74 switch (Type) {
75 default:
76 return false;
77 case ELF::R_X86_64_GOT32:
78 case ELF::R_X86_64_PLT32:
79 case ELF::R_X86_64_GOTPCREL:
80 return true;
81 }
82}
83
Matt Fleming3565a062010-08-16 18:57:57 +000084namespace {
85
86 class ELFObjectWriterImpl {
Chris Lattnerb188a372010-08-28 03:21:03 +000087 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
Matt Fleming3565a062010-08-16 18:57:57 +000088 return Kind == X86::reloc_riprel_4byte ||
89 Kind == X86::reloc_riprel_4byte_movq_load;
Chris Lattnerb188a372010-08-28 03:21:03 +000090 }*/
Matt Fleming3565a062010-08-16 18:57:57 +000091
92
93 /// ELFSymbolData - Helper struct for containing some precomputed information
94 /// on symbols.
95 struct ELFSymbolData {
96 MCSymbolData *SymbolData;
97 uint64_t StringIndex;
98 uint32_t SectionIndex;
99
100 // Support lexicographic sorting.
101 bool operator<(const ELFSymbolData &RHS) const {
Rafael Espindolaad49cf52010-09-18 15:03:21 +0000102 if (GetType(*SymbolData) == ELF::STT_FILE)
103 return true;
104 if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
105 return false;
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000106 return SymbolData->getSymbol().getName() <
107 RHS.SymbolData->getSymbol().getName();
Matt Fleming3565a062010-08-16 18:57:57 +0000108 }
109 };
110
111 /// @name Relocation Data
112 /// @{
113
114 struct ELFRelocationEntry {
115 // Make these big enough for both 32-bit and 64-bit
116 uint64_t r_offset;
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000117 int Index;
118 unsigned Type;
119 const MCSymbol *Symbol;
Matt Fleming3565a062010-08-16 18:57:57 +0000120 uint64_t r_addend;
121
122 // Support lexicographic sorting.
123 bool operator<(const ELFRelocationEntry &RE) const {
124 return RE.r_offset < r_offset;
125 }
126 };
127
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000128 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
129
Matt Fleming3565a062010-08-16 18:57:57 +0000130 llvm::DenseMap<const MCSectionData*,
131 std::vector<ELFRelocationEntry> > Relocations;
132 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
133
134 /// @}
135 /// @name Symbol Table Data
136 /// @{
137
138 SmallString<256> StringTable;
139 std::vector<ELFSymbolData> LocalSymbolData;
140 std::vector<ELFSymbolData> ExternalSymbolData;
141 std::vector<ELFSymbolData> UndefinedSymbolData;
142
143 /// @}
144
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000145 int NumRegularSections;
146
Rafael Espindola5c77c162010-10-05 15:48:37 +0000147 bool NeedsGOT;
148
Matt Fleming3565a062010-08-16 18:57:57 +0000149 ELFObjectWriter *Writer;
150
151 raw_ostream &OS;
152
Matt Fleming3565a062010-08-16 18:57:57 +0000153 unsigned Is64Bit : 1;
154
155 bool HasRelocationAddend;
156
Roman Divacky5baf79e2010-09-09 17:57:50 +0000157 Triple::OSType OSType;
158
Matt Fleming3565a062010-08-16 18:57:57 +0000159 // This holds the symbol table index of the last local symbol.
160 unsigned LastLocalSymbolIndex;
161 // This holds the .strtab section index.
162 unsigned StringTableIndex;
163
164 unsigned ShstrtabIndex;
165
166 public:
167 ELFObjectWriterImpl(ELFObjectWriter *_Writer, bool _Is64Bit,
Roman Divacky5baf79e2010-09-09 17:57:50 +0000168 bool _HasRelAddend, Triple::OSType _OSType)
Rafael Espindola5c77c162010-10-05 15:48:37 +0000169 : NeedsGOT(false), Writer(_Writer), OS(Writer->getStream()),
Roman Divacky5baf79e2010-09-09 17:57:50 +0000170 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
171 OSType(_OSType) {
Matt Fleming3565a062010-08-16 18:57:57 +0000172 }
173
174 void Write8(uint8_t Value) { Writer->Write8(Value); }
175 void Write16(uint16_t Value) { Writer->Write16(Value); }
176 void Write32(uint32_t Value) { Writer->Write32(Value); }
Chris Lattnerb188a372010-08-28 03:21:03 +0000177 //void Write64(uint64_t Value) { Writer->Write64(Value); }
Matt Fleming3565a062010-08-16 18:57:57 +0000178 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
Chris Lattnerb188a372010-08-28 03:21:03 +0000179 //void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
180 // Writer->WriteBytes(Str, ZeroFillSize);
181 //}
Matt Fleming3565a062010-08-16 18:57:57 +0000182
183 void WriteWord(uint64_t W) {
Chris Lattnerb188a372010-08-28 03:21:03 +0000184 if (Is64Bit)
Matt Fleming3565a062010-08-16 18:57:57 +0000185 Writer->Write64(W);
Chris Lattnerb188a372010-08-28 03:21:03 +0000186 else
Matt Fleming3565a062010-08-16 18:57:57 +0000187 Writer->Write32(W);
Matt Fleming3565a062010-08-16 18:57:57 +0000188 }
189
190 void String8(char *buf, uint8_t Value) {
191 buf[0] = Value;
192 }
193
194 void StringLE16(char *buf, uint16_t Value) {
195 buf[0] = char(Value >> 0);
196 buf[1] = char(Value >> 8);
197 }
198
199 void StringLE32(char *buf, uint32_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000200 StringLE16(buf, uint16_t(Value >> 0));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000201 StringLE16(buf + 2, uint16_t(Value >> 16));
Matt Fleming3565a062010-08-16 18:57:57 +0000202 }
203
204 void StringLE64(char *buf, uint64_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000205 StringLE32(buf, uint32_t(Value >> 0));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000206 StringLE32(buf + 4, uint32_t(Value >> 32));
Matt Fleming3565a062010-08-16 18:57:57 +0000207 }
208
209 void StringBE16(char *buf ,uint16_t Value) {
210 buf[0] = char(Value >> 8);
211 buf[1] = char(Value >> 0);
212 }
213
214 void StringBE32(char *buf, uint32_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000215 StringBE16(buf, uint16_t(Value >> 16));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000216 StringBE16(buf + 2, uint16_t(Value >> 0));
Matt Fleming3565a062010-08-16 18:57:57 +0000217 }
218
219 void StringBE64(char *buf, uint64_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000220 StringBE32(buf, uint32_t(Value >> 32));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000221 StringBE32(buf + 4, uint32_t(Value >> 0));
Matt Fleming3565a062010-08-16 18:57:57 +0000222 }
223
224 void String16(char *buf, uint16_t Value) {
225 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000226 StringLE16(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000227 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000228 StringBE16(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000229 }
230
231 void String32(char *buf, uint32_t Value) {
232 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000233 StringLE32(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000234 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000235 StringBE32(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000236 }
237
238 void String64(char *buf, uint64_t Value) {
239 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000240 StringLE64(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000241 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000242 StringBE64(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000243 }
244
245 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
246
247 void WriteSymbolEntry(MCDataFragment *F, uint64_t name, uint8_t info,
248 uint64_t value, uint64_t size,
249 uint8_t other, uint16_t shndx);
250
251 void WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
252 const MCAsmLayout &Layout);
253
254 void WriteSymbolTable(MCDataFragment *F, const MCAssembler &Asm,
Rafael Espindola71859c62010-09-16 19:46:31 +0000255 const MCAsmLayout &Layout,
256 unsigned NumRegularSections);
Matt Fleming3565a062010-08-16 18:57:57 +0000257
258 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
259 const MCFragment *Fragment, const MCFixup &Fixup,
260 MCValue Target, uint64_t &FixedValue);
261
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000262 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
263 const MCSymbol *S);
Matt Fleming3565a062010-08-16 18:57:57 +0000264
265 /// ComputeSymbolTable - Compute the symbol table data
266 ///
267 /// \param StringTable [out] - The string table data.
268 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
269 /// string table.
270 void ComputeSymbolTable(MCAssembler &Asm);
271
272 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
273 const MCSectionData &SD);
274
275 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
276 for (MCAssembler::const_iterator it = Asm.begin(),
277 ie = Asm.end(); it != ie; ++it) {
278 WriteRelocation(Asm, Layout, *it);
279 }
280 }
281
282 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
283
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000284 void ExecutePostLayoutBinding(MCAssembler &Asm) {
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000285 }
Matt Fleming3565a062010-08-16 18:57:57 +0000286
287 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
288 uint64_t Address, uint64_t Offset,
289 uint64_t Size, uint32_t Link, uint32_t Info,
290 uint64_t Alignment, uint64_t EntrySize);
291
292 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
293 const MCSectionData *SD);
294
Rafael Espindola70703872010-09-30 02:22:20 +0000295 bool IsFixupFullyResolved(const MCAssembler &Asm,
296 const MCValue Target,
297 bool IsPCRel,
298 const MCFragment *DF) const;
299
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000300 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000301 };
302
303}
304
305// Emit the ELF header.
306void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
307 unsigned NumberOfSections) {
308 // ELF Header
309 // ----------
310 //
311 // Note
312 // ----
313 // emitWord method behaves differently for ELF32 and ELF64, writing
314 // 4 bytes in the former and 8 in the latter.
315
316 Write8(0x7f); // e_ident[EI_MAG0]
317 Write8('E'); // e_ident[EI_MAG1]
318 Write8('L'); // e_ident[EI_MAG2]
319 Write8('F'); // e_ident[EI_MAG3]
320
321 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
322
323 // e_ident[EI_DATA]
324 Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
325
326 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky5baf79e2010-09-09 17:57:50 +0000327 // e_ident[EI_OSABI]
328 switch (OSType) {
329 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
330 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
331 default: Write8(ELF::ELFOSABI_NONE); break;
332 }
Matt Fleming3565a062010-08-16 18:57:57 +0000333 Write8(0); // e_ident[EI_ABIVERSION]
334
335 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
336
337 Write16(ELF::ET_REL); // e_type
338
339 // FIXME: Make this configurable
Benjamin Kramereb976772010-08-17 17:02:29 +0000340 Write16(Is64Bit ? ELF::EM_X86_64 : ELF::EM_386); // e_machine = target
Matt Fleming3565a062010-08-16 18:57:57 +0000341
342 Write32(ELF::EV_CURRENT); // e_version
343 WriteWord(0); // e_entry, no entry point in .o file
344 WriteWord(0); // e_phoff, no program header for .o
Benjamin Kramereb976772010-08-17 17:02:29 +0000345 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
346 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
Matt Fleming3565a062010-08-16 18:57:57 +0000347
348 // FIXME: Make this configurable.
349 Write32(0); // e_flags = whatever the target wants
350
351 // e_ehsize = ELF header size
352 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
353
354 Write16(0); // e_phentsize = prog header entry size
355 Write16(0); // e_phnum = # prog header entries = 0
356
357 // e_shentsize = Section header entry size
358 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
359
360 // e_shnum = # of section header ents
361 Write16(NumberOfSections);
362
363 // e_shstrndx = Section # of '.shstrtab'
364 Write16(ShstrtabIndex);
365}
366
367void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
368 uint8_t info, uint64_t value,
369 uint64_t size, uint8_t other,
370 uint16_t shndx) {
371 if (Is64Bit) {
372 char buf[8];
373
374 String32(buf, name);
375 F->getContents() += StringRef(buf, 4); // st_name
376
377 String8(buf, info);
378 F->getContents() += StringRef(buf, 1); // st_info
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000379
Matt Fleming3565a062010-08-16 18:57:57 +0000380 String8(buf, other);
381 F->getContents() += StringRef(buf, 1); // st_other
382
383 String16(buf, shndx);
384 F->getContents() += StringRef(buf, 2); // st_shndx
385
386 String64(buf, value);
387 F->getContents() += StringRef(buf, 8); // st_value
388
389 String64(buf, size);
390 F->getContents() += StringRef(buf, 8); // st_size
391 } else {
392 char buf[4];
393
394 String32(buf, name);
395 F->getContents() += StringRef(buf, 4); // st_name
396
397 String32(buf, value);
398 F->getContents() += StringRef(buf, 4); // st_value
399
400 String32(buf, size);
401 F->getContents() += StringRef(buf, 4); // st_size
402
403 String8(buf, info);
404 F->getContents() += StringRef(buf, 1); // st_info
405
406 String8(buf, other);
407 F->getContents() += StringRef(buf, 1); // st_other
408
409 String16(buf, shndx);
410 F->getContents() += StringRef(buf, 2); // st_shndx
411 }
412}
413
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000414static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
415 if (Data.isCommon() && Data.isExternal())
416 return Data.getCommonAlignment();
417
418 const MCSymbol &Symbol = Data.getSymbol();
419 if (!Symbol.isInSection())
420 return 0;
421
422 if (!Data.isCommon() && !(Data.getFlags() & ELF_STB_Weak))
423 if (MCFragment *FF = Data.getFragment())
424 return Layout.getSymbolAddress(&Data) -
425 Layout.getSectionAddress(FF->getParent());
426
427 return 0;
428}
429
Matt Fleming3565a062010-08-16 18:57:57 +0000430void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
431 const MCAsmLayout &Layout) {
432 MCSymbolData &Data = *MSD.SymbolData;
Matt Fleming3565a062010-08-16 18:57:57 +0000433 uint8_t Info = (Data.getFlags() & 0xff);
434 uint8_t Other = ((Data.getFlags() & 0xf00) >> ELF_STV_Shift);
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000435 uint64_t Value = SymbolValue(Data, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000436 uint64_t Size = 0;
437 const MCExpr *ESize;
438
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000439 assert(!(Data.isCommon() && !Data.isExternal()));
440
Matt Fleming3565a062010-08-16 18:57:57 +0000441 ESize = Data.getSize();
442 if (Data.getSize()) {
443 MCValue Res;
444 if (ESize->getKind() == MCExpr::Binary) {
445 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
446
447 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
448 MCSymbolData &A =
449 Layout.getAssembler().getSymbolData(Res.getSymA()->getSymbol());
450 MCSymbolData &B =
451 Layout.getAssembler().getSymbolData(Res.getSymB()->getSymbol());
452
453 Size = Layout.getSymbolAddress(&A) - Layout.getSymbolAddress(&B);
Matt Fleming3565a062010-08-16 18:57:57 +0000454 }
455 } else if (ESize->getKind() == MCExpr::Constant) {
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000456 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
Matt Fleming3565a062010-08-16 18:57:57 +0000457 } else {
458 assert(0 && "Unsupported size expression");
459 }
460 }
461
462 // Write out the symbol table entry
463 WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
464 Size, Other, MSD.SectionIndex);
465}
466
467void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
468 const MCAssembler &Asm,
Rafael Espindola71859c62010-09-16 19:46:31 +0000469 const MCAsmLayout &Layout,
470 unsigned NumRegularSections) {
Matt Fleming3565a062010-08-16 18:57:57 +0000471 // The string table must be emitted first because we need the index
472 // into the string table for all the symbol names.
473 assert(StringTable.size() && "Missing string table");
474
475 // FIXME: Make sure the start of the symbol table is aligned.
476
477 // The first entry is the undefined symbol entry.
478 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000479 F->getContents().append(EntrySize, '\x00');
Matt Fleming3565a062010-08-16 18:57:57 +0000480
481 // Write the symbol table entries.
482 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
483 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
484 ELFSymbolData &MSD = LocalSymbolData[i];
485 WriteSymbol(F, MSD, Layout);
486 }
487
Rafael Espindola71859c62010-09-16 19:46:31 +0000488 // Write out a symbol table entry for each regular section.
Eli Friedmana44fa242010-08-16 21:17:09 +0000489 unsigned Index = 1;
Rafael Espindola71859c62010-09-16 19:46:31 +0000490 for (MCAssembler::const_iterator it = Asm.begin();
491 Index <= NumRegularSections; ++it, ++Index) {
Eli Friedmana44fa242010-08-16 21:17:09 +0000492 const MCSectionELF &Section =
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000493 static_cast<const MCSectionELF&>(it->getSection());
Eli Friedmana44fa242010-08-16 21:17:09 +0000494 // Leave out relocations so we don't have indexes within
495 // the relocations messed up
Benjamin Kramer377a5722010-08-17 17:30:07 +0000496 if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
Eli Friedmana44fa242010-08-16 21:17:09 +0000497 continue;
Matt Fleming3565a062010-08-16 18:57:57 +0000498 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
Eli Friedmana44fa242010-08-16 21:17:09 +0000499 LastLocalSymbolIndex++;
500 }
Matt Fleming3565a062010-08-16 18:57:57 +0000501
502 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
503 ELFSymbolData &MSD = ExternalSymbolData[i];
504 MCSymbolData &Data = *MSD.SymbolData;
505 assert((Data.getFlags() & ELF_STB_Global) &&
506 "External symbol requires STB_GLOBAL flag");
507 WriteSymbol(F, MSD, Layout);
Rafael Espindolae15eb4e2010-09-23 19:55:14 +0000508 if (GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming3565a062010-08-16 18:57:57 +0000509 LastLocalSymbolIndex++;
510 }
511
512 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
513 ELFSymbolData &MSD = UndefinedSymbolData[i];
514 MCSymbolData &Data = *MSD.SymbolData;
Matt Fleming3565a062010-08-16 18:57:57 +0000515 WriteSymbol(F, MSD, Layout);
Rafael Espindolae15eb4e2010-09-23 19:55:14 +0000516 if (GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming3565a062010-08-16 18:57:57 +0000517 LastLocalSymbolIndex++;
518 }
519}
520
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000521static bool ShouldRelocOnSymbol(const MCSymbolData &SD,
522 const MCValue &Target) {
523 const MCSymbol &Symbol = SD.getSymbol();
524 if (Symbol.isUndefined())
525 return true;
Rafael Espindola73ffea42010-09-25 05:42:19 +0000526
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000527 const MCSectionELF &Section =
528 static_cast<const MCSectionELF&>(Symbol.getSection());
529
530 if (Section.getFlags() & MCSectionELF::SHF_MERGE)
531 return Target.getConstant() != 0;
532
533 if (SD.isExternal())
534 return true;
535
536 return false;
Rafael Espindola73ffea42010-09-25 05:42:19 +0000537}
538
Benjamin Kramere5b57342010-08-17 18:20:28 +0000539// FIXME: this is currently X86/X86_64 only
Matt Fleming3565a062010-08-16 18:57:57 +0000540void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
541 const MCAsmLayout &Layout,
542 const MCFragment *Fragment,
543 const MCFixup &Fixup,
544 MCValue Target,
545 uint64_t &FixedValue) {
Matt Fleming3565a062010-08-16 18:57:57 +0000546 int64_t Addend = 0;
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000547 int Index = 0;
Benjamin Kramer95c602a2010-08-27 10:38:39 +0000548 int64_t Value = Target.getConstant();
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000549 const MCSymbol *Symbol = 0;
Matt Fleming3565a062010-08-16 18:57:57 +0000550
Rafael Espindola00074892010-09-17 22:34:41 +0000551 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
Benjamin Kramer81cfb852010-08-17 19:45:05 +0000552 if (!Target.isAbsolute()) {
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000553 Symbol = &Target.getSymA()->getSymbol();
Matt Fleming3565a062010-08-16 18:57:57 +0000554 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000555 MCFragment *F = SD.getFragment();
Matt Fleming3565a062010-08-16 18:57:57 +0000556
Rafael Espindola9d8b7552010-10-03 00:46:57 +0000557 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
558 const MCSymbol &SymbolB = RefB->getSymbol();
559 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
560 IsPCRel = true;
Rafael Espindola55fb1022010-10-04 15:59:01 +0000561 MCSectionData *Sec = Fragment->getParent();
562
563 // Offset of the symbol in the section
564 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
565
566 // Ofeset of the relocation in the section
567 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
568 Value += b - a;
Rafael Espindola9d8b7552010-10-03 00:46:57 +0000569 }
570
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000571 // Check that this case has already been fully resolved before we get
572 // here.
Rafael Espindola00074892010-09-17 22:34:41 +0000573 if (Symbol->isDefined() && !SD.isExternal() &&
574 IsPCRel &&
575 &Fragment->getParent()->getSection() == &Symbol->getSection()) {
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000576 llvm_unreachable("We don't need a relocation in this case.");
Rafael Espindola00074892010-09-17 22:34:41 +0000577 return;
578 }
579
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000580 bool RelocOnSymbol = ShouldRelocOnSymbol(SD, Target);
581 if (!RelocOnSymbol) {
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000582 Index = F->getParent()->getOrdinal();
Rafael Espindolaa6489182010-09-24 21:19:03 +0000583
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000584 MCSectionData *FSD = F->getParent();
585 // Offset of the symbol in the section
586 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000587 } else {
588 UsedInReloc.insert(Symbol);
589 Index = -1;
590 }
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000591 Addend = Value;
592 // Compensate for the addend on i386.
593 if (Is64Bit)
594 Value = 0;
Matt Fleming3565a062010-08-16 18:57:57 +0000595 }
596
Benjamin Kramer95c602a2010-08-27 10:38:39 +0000597 FixedValue = Value;
598
Matt Fleming3565a062010-08-16 18:57:57 +0000599 // determine the type of the relocation
Rafael Espindola28f9ac82010-10-04 18:44:25 +0000600
601 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000602 unsigned Type;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000603 if (Is64Bit) {
604 if (IsPCRel) {
Rafael Espindola92bf6682010-10-04 19:04:13 +0000605 switch (Modifier) {
606 case MCSymbolRefExpr::VK_None:
607 Type = ELF::R_X86_64_PC32;
608 break;
609 case MCSymbolRefExpr::VK_PLT:
610 Type = ELF::R_X86_64_PLT32;
611 break;
Rafael Espindola607d1f62010-10-04 19:51:39 +0000612 case llvm::MCSymbolRefExpr::VK_GOTPCREL:
613 Type = ELF::R_X86_64_GOTPCREL;
614 break;
Rafael Espindola92bf6682010-10-04 19:04:13 +0000615 default:
616 llvm_unreachable("Unimplemented");
617 }
Benjamin Kramere5b57342010-08-17 18:20:28 +0000618 } else {
619 switch ((unsigned)Fixup.getKind()) {
620 default: llvm_unreachable("invalid fixup kind!");
621 case FK_Data_8: Type = ELF::R_X86_64_64; break;
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000622 case X86::reloc_signed_4byte:
Benjamin Kramere5b57342010-08-17 18:20:28 +0000623 case X86::reloc_pcrel_4byte:
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000624 assert(isInt<32>(Target.getConstant()));
Rafael Espindola28f9ac82010-10-04 18:44:25 +0000625 switch (Modifier) {
626 case MCSymbolRefExpr::VK_None:
627 Type = ELF::R_X86_64_32S;
628 break;
629 case MCSymbolRefExpr::VK_GOT:
630 Type = ELF::R_X86_64_GOT32;
631 break;
632 default:
633 llvm_unreachable("Unimplemented");
634 }
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000635 break;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000636 case FK_Data_4:
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000637 Type = ELF::R_X86_64_32;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000638 break;
639 case FK_Data_2: Type = ELF::R_X86_64_16; break;
640 case X86::reloc_pcrel_1byte:
641 case FK_Data_1: Type = ELF::R_X86_64_8; break;
642 }
643 }
Matt Fleming3565a062010-08-16 18:57:57 +0000644 } else {
Benjamin Kramere5b57342010-08-17 18:20:28 +0000645 if (IsPCRel) {
646 Type = ELF::R_386_PC32;
647 } else {
648 switch ((unsigned)Fixup.getKind()) {
649 default: llvm_unreachable("invalid fixup kind!");
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000650
651 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
652 // instead?
653 case X86::reloc_signed_4byte:
Benjamin Kramere5b57342010-08-17 18:20:28 +0000654 case X86::reloc_pcrel_4byte:
655 case FK_Data_4: Type = ELF::R_386_32; break;
656 case FK_Data_2: Type = ELF::R_386_16; break;
657 case X86::reloc_pcrel_1byte:
658 case FK_Data_1: Type = ELF::R_386_8; break;
659 }
Matt Fleming3565a062010-08-16 18:57:57 +0000660 }
661 }
662
Rafael Espindola5c77c162010-10-05 15:48:37 +0000663 if (RelocNeedsGOT(Type))
664 NeedsGOT = true;
665
Benjamin Kramere5b57342010-08-17 18:20:28 +0000666 ELFRelocationEntry ERE;
667
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000668 ERE.Index = Index;
669 ERE.Type = Type;
670 ERE.Symbol = Symbol;
Matt Fleming3565a062010-08-16 18:57:57 +0000671
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000672 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
Benjamin Kramere5b57342010-08-17 18:20:28 +0000673
Matt Fleming3565a062010-08-16 18:57:57 +0000674 if (HasRelocationAddend)
675 ERE.r_addend = Addend;
Benjamin Kramer172d7d62010-08-17 00:33:24 +0000676 else
677 ERE.r_addend = 0; // Silence compiler warning.
Matt Fleming3565a062010-08-16 18:57:57 +0000678
679 Relocations[Fragment->getParent()].push_back(ERE);
680}
681
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000682uint64_t
683ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
684 const MCSymbol *S) {
Benjamin Kramer7b83c262010-08-25 20:09:43 +0000685 MCSymbolData &SD = Asm.getSymbolData(*S);
Eli Friedmanf8020a32010-08-16 19:15:06 +0000686
Benjamin Kramer7b83c262010-08-25 20:09:43 +0000687 // Local symbol.
688 if (!SD.isExternal() && !S->isUndefined())
689 return SD.getIndex() + /* empty symbol */ 1;
690
691 // External or undefined symbol.
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000692 return SD.getIndex() + NumRegularSections + /* empty symbol */ 1;
Matt Fleming3565a062010-08-16 18:57:57 +0000693}
694
695void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
Rafael Espindola5c77c162010-10-05 15:48:37 +0000696 // FIXME: Is this the correct place to do this?
697 if (NeedsGOT) {
698 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
699 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
700 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
701 Data.setExternal(true);
702 }
703
Matt Fleming3565a062010-08-16 18:57:57 +0000704 // Build section lookup table.
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000705 NumRegularSections = Asm.size();
Matt Fleming3565a062010-08-16 18:57:57 +0000706 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
707 unsigned Index = 1;
708 for (MCAssembler::iterator it = Asm.begin(),
709 ie = Asm.end(); it != ie; ++it, ++Index)
710 SectionIndexMap[&it->getSection()] = Index;
711
712 // Index 0 is always the empty string.
713 StringMap<uint64_t> StringIndexMap;
714 StringTable += '\x00';
715
716 // Add the data for local symbols.
717 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
718 ie = Asm.symbol_end(); it != ie; ++it) {
719 const MCSymbol &Symbol = it->getSymbol();
720
721 // Ignore non-linker visible symbols.
722 if (!Asm.isSymbolLinkerVisible(Symbol))
723 continue;
724
725 if (it->isExternal() || Symbol.isUndefined())
726 continue;
727
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000728 if (Symbol.isTemporary() && !UsedInReloc.count(&Symbol))
729 continue;
730
Matt Fleming3565a062010-08-16 18:57:57 +0000731 uint64_t &Entry = StringIndexMap[Symbol.getName()];
732 if (!Entry) {
733 Entry = StringTable.size();
734 StringTable += Symbol.getName();
735 StringTable += '\x00';
736 }
737
738 ELFSymbolData MSD;
739 MSD.SymbolData = it;
740 MSD.StringIndex = Entry;
741
742 if (Symbol.isAbsolute()) {
743 MSD.SectionIndex = ELF::SHN_ABS;
744 LocalSymbolData.push_back(MSD);
745 } else {
746 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
747 assert(MSD.SectionIndex && "Invalid section index!");
748 LocalSymbolData.push_back(MSD);
749 }
750 }
751
752 // Now add non-local symbols.
753 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
754 ie = Asm.symbol_end(); it != ie; ++it) {
755 const MCSymbol &Symbol = it->getSymbol();
756
757 // Ignore non-linker visible symbols.
Rafael Espindola53725bc2010-09-28 16:19:11 +0000758 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
Matt Fleming3565a062010-08-16 18:57:57 +0000759 continue;
760
761 if (!it->isExternal() && !Symbol.isUndefined())
762 continue;
763
Rafael Espindola53725bc2010-09-28 16:19:11 +0000764 if (Symbol.isVariable())
765 continue;
766
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000767 if (Symbol.isUndefined() && !UsedInReloc.count(&Symbol)
768 && Symbol.isTemporary())
769 continue;
770
Matt Fleming3565a062010-08-16 18:57:57 +0000771 uint64_t &Entry = StringIndexMap[Symbol.getName()];
772 if (!Entry) {
773 Entry = StringTable.size();
774 StringTable += Symbol.getName();
775 StringTable += '\x00';
776 }
777
778 ELFSymbolData MSD;
779 MSD.SymbolData = it;
780 MSD.StringIndex = Entry;
781
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000782 if (it->isCommon()) {
783 MSD.SectionIndex = ELF::SHN_COMMON;
784 ExternalSymbolData.push_back(MSD);
785 } else if (Symbol.isUndefined()) {
Matt Fleming3565a062010-08-16 18:57:57 +0000786 MSD.SectionIndex = ELF::SHN_UNDEF;
Rafael Espindolae15eb4e2010-09-23 19:55:14 +0000787 // FIXME: Undefined symbols are global, but this is the first place we
788 // are able to set it.
789 if (GetBinding(*it) == ELF::STB_LOCAL)
790 SetBinding(*it, ELF::STB_GLOBAL);
Matt Fleming3565a062010-08-16 18:57:57 +0000791 UndefinedSymbolData.push_back(MSD);
792 } else if (Symbol.isAbsolute()) {
793 MSD.SectionIndex = ELF::SHN_ABS;
794 ExternalSymbolData.push_back(MSD);
Matt Fleming3565a062010-08-16 18:57:57 +0000795 } else {
796 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
797 assert(MSD.SectionIndex && "Invalid section index!");
798 ExternalSymbolData.push_back(MSD);
799 }
800 }
801
802 // Symbols are required to be in lexicographic order.
803 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
804 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
805 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
806
807 // Set the symbol indices. Local symbols must come before all other
808 // symbols with non-local bindings.
809 Index = 0;
810 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
811 LocalSymbolData[i].SymbolData->setIndex(Index++);
812 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
813 ExternalSymbolData[i].SymbolData->setIndex(Index++);
814 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
815 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
816}
817
818void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
819 const MCSectionData &SD) {
820 if (!Relocations[&SD].empty()) {
821 MCContext &Ctx = Asm.getContext();
822 const MCSection *RelaSection;
823 const MCSectionELF &Section =
824 static_cast<const MCSectionELF&>(SD.getSection());
825
826 const StringRef SectionName = Section.getSectionName();
Benjamin Kramer377a5722010-08-17 17:30:07 +0000827 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
Matt Fleming3565a062010-08-16 18:57:57 +0000828 RelaSectionName += SectionName;
Benjamin Kramer299fbe32010-08-17 17:56:13 +0000829
830 unsigned EntrySize;
831 if (HasRelocationAddend)
832 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
833 else
834 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming3565a062010-08-16 18:57:57 +0000835
Benjamin Kramer377a5722010-08-17 17:30:07 +0000836 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
837 ELF::SHT_RELA : ELF::SHT_REL, 0,
Matt Fleming3565a062010-08-16 18:57:57 +0000838 SectionKind::getReadOnly(),
839 false, EntrySize);
840
841 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000842 RelaSD.setAlignment(Is64Bit ? 8 : 4);
Matt Fleming3565a062010-08-16 18:57:57 +0000843
844 MCDataFragment *F = new MCDataFragment(&RelaSD);
845
846 WriteRelocationsFragment(Asm, F, &SD);
847
Rafael Espindola70703872010-09-30 02:22:20 +0000848 Asm.AddSectionToTheEnd(*Writer, RelaSD, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000849 }
850}
851
852void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
853 uint64_t Flags, uint64_t Address,
854 uint64_t Offset, uint64_t Size,
855 uint32_t Link, uint32_t Info,
856 uint64_t Alignment,
857 uint64_t EntrySize) {
858 Write32(Name); // sh_name: index into string table
859 Write32(Type); // sh_type
860 WriteWord(Flags); // sh_flags
861 WriteWord(Address); // sh_addr
862 WriteWord(Offset); // sh_offset
863 WriteWord(Size); // sh_size
864 Write32(Link); // sh_link
865 Write32(Info); // sh_info
866 WriteWord(Alignment); // sh_addralign
867 WriteWord(EntrySize); // sh_entsize
868}
869
870void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
871 MCDataFragment *F,
872 const MCSectionData *SD) {
873 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
874 // sort by the r_offset just like gnu as does
875 array_pod_sort(Relocs.begin(), Relocs.end());
876
877 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
878 ELFRelocationEntry entry = Relocs[e - i - 1];
879
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000880 if (entry.Index < 0)
881 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
882 else
883 entry.Index += LocalSymbolData.size() + 1;
Benjamin Kramer5e492e82010-09-09 18:01:29 +0000884 if (Is64Bit) {
885 char buf[8];
Matt Fleming3565a062010-08-16 18:57:57 +0000886
Benjamin Kramer5e492e82010-09-09 18:01:29 +0000887 String64(buf, entry.r_offset);
888 F->getContents() += StringRef(buf, 8);
889
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000890 struct ELF::Elf64_Rela ERE64;
891 ERE64.setSymbolAndType(entry.Index, entry.Type);
892 String64(buf, ERE64.r_info);
Benjamin Kramer5e492e82010-09-09 18:01:29 +0000893 F->getContents() += StringRef(buf, 8);
894
895 if (HasRelocationAddend) {
896 String64(buf, entry.r_addend);
897 F->getContents() += StringRef(buf, 8);
898 }
899 } else {
900 char buf[4];
901
902 String32(buf, entry.r_offset);
903 F->getContents() += StringRef(buf, 4);
904
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000905 struct ELF::Elf32_Rela ERE32;
906 ERE32.setSymbolAndType(entry.Index, entry.Type);
907 String32(buf, ERE32.r_info);
Benjamin Kramer5e492e82010-09-09 18:01:29 +0000908 F->getContents() += StringRef(buf, 4);
909
910 if (HasRelocationAddend) {
911 String32(buf, entry.r_addend);
912 F->getContents() += StringRef(buf, 4);
913 }
914 }
Matt Fleming3565a062010-08-16 18:57:57 +0000915 }
916}
917
918void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
919 MCAsmLayout &Layout) {
920 MCContext &Ctx = Asm.getContext();
921 MCDataFragment *F;
922
Matt Fleming3565a062010-08-16 18:57:57 +0000923 const MCSection *SymtabSection;
924 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
925
Rafael Espindola71859c62010-09-16 19:46:31 +0000926 unsigned NumRegularSections = Asm.size();
927
Rafael Espindola38738bf2010-09-22 19:04:41 +0000928 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola71859c62010-09-16 19:46:31 +0000929 const MCSection *ShstrtabSection;
930 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
931 SectionKind::getReadOnly(), false);
932 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
933 ShstrtabSD.setAlignment(1);
934 ShstrtabIndex = Asm.size();
935
Matt Fleming3565a062010-08-16 18:57:57 +0000936 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
937 SectionKind::getReadOnly(),
938 false, EntrySize);
Matt Fleming3565a062010-08-16 18:57:57 +0000939 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Matt Fleming3565a062010-08-16 18:57:57 +0000940 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
941
Matt Fleming3565a062010-08-16 18:57:57 +0000942 const MCSection *StrtabSection;
943 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
944 SectionKind::getReadOnly(), false);
Matt Fleming3565a062010-08-16 18:57:57 +0000945 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
946 StrtabSD.setAlignment(1);
Matt Fleming3565a062010-08-16 18:57:57 +0000947 StringTableIndex = Asm.size();
948
Rafael Espindolac3c413f2010-09-27 22:04:54 +0000949 WriteRelocations(Asm, Layout);
Rafael Espindola71859c62010-09-16 19:46:31 +0000950
951 // Symbol table
952 F = new MCDataFragment(&SymtabSD);
953 WriteSymbolTable(F, Asm, Layout, NumRegularSections);
Rafael Espindola70703872010-09-30 02:22:20 +0000954 Asm.AddSectionToTheEnd(*Writer, SymtabSD, Layout);
Rafael Espindola71859c62010-09-16 19:46:31 +0000955
Matt Fleming3565a062010-08-16 18:57:57 +0000956 F = new MCDataFragment(&StrtabSD);
957 F->getContents().append(StringTable.begin(), StringTable.end());
Rafael Espindola70703872010-09-30 02:22:20 +0000958 Asm.AddSectionToTheEnd(*Writer, StrtabSD, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000959
Matt Fleming3565a062010-08-16 18:57:57 +0000960 F = new MCDataFragment(&ShstrtabSD);
961
Matt Fleming3565a062010-08-16 18:57:57 +0000962 // Section header string table.
963 //
964 // The first entry of a string table holds a null character so skip
965 // section 0.
966 uint64_t Index = 1;
967 F->getContents() += '\x00';
968
969 for (MCAssembler::const_iterator it = Asm.begin(),
970 ie = Asm.end(); it != ie; ++it) {
Matt Fleming3565a062010-08-16 18:57:57 +0000971 const MCSectionELF &Section =
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000972 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola51efe7a2010-09-23 14:14:56 +0000973 // FIXME: We could merge suffixes like in .text and .rela.text.
Matt Fleming3565a062010-08-16 18:57:57 +0000974
975 // Remember the index into the string table so we can write it
976 // into the sh_name field of the section header table.
977 SectionStringTableIndex[&it->getSection()] = Index;
978
979 Index += Section.getSectionName().size() + 1;
980 F->getContents() += Section.getSectionName();
981 F->getContents() += '\x00';
982 }
983
Rafael Espindola70703872010-09-30 02:22:20 +0000984 Asm.AddSectionToTheEnd(*Writer, ShstrtabSD, Layout);
985}
986
987bool ELFObjectWriterImpl::IsFixupFullyResolved(const MCAssembler &Asm,
988 const MCValue Target,
989 bool IsPCRel,
990 const MCFragment *DF) const {
991 // If this is a PCrel relocation, find the section this fixup value is
992 // relative to.
993 const MCSection *BaseSection = 0;
994 if (IsPCRel) {
995 BaseSection = &DF->getParent()->getSection();
996 assert(BaseSection);
997 }
998
999 const MCSection *SectionA = 0;
1000 const MCSymbol *SymbolA = 0;
1001 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1002 SymbolA = &A->getSymbol();
1003 SectionA = &SymbolA->getSection();
1004 }
1005
1006 const MCSection *SectionB = 0;
1007 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1008 SectionB = &B->getSymbol().getSection();
1009 }
1010
1011 if (!BaseSection)
1012 return SectionA == SectionB;
1013
1014 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1015 if (DataA.isExternal())
1016 return false;
1017
1018 return !SectionB && BaseSection == SectionA;
Matt Fleming3565a062010-08-16 18:57:57 +00001019}
1020
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001021void ELFObjectWriterImpl::WriteObject(MCAssembler &Asm,
Matt Fleming3565a062010-08-16 18:57:57 +00001022 const MCAsmLayout &Layout) {
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001023 // Compute symbol table information.
1024 ComputeSymbolTable(Asm);
1025
Matt Fleming3565a062010-08-16 18:57:57 +00001026 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1027 const_cast<MCAsmLayout&>(Layout));
1028
1029 // Add 1 for the null section.
1030 unsigned NumSections = Asm.size() + 1;
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001031 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1032 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1033 uint64_t FileOff = HeaderSize;
Matt Fleming3565a062010-08-16 18:57:57 +00001034
1035 for (MCAssembler::const_iterator it = Asm.begin(),
1036 ie = Asm.end(); it != ie; ++it) {
1037 const MCSectionData &SD = *it;
Matt Fleming3565a062010-08-16 18:57:57 +00001038
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001039 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1040
Matt Fleming3565a062010-08-16 18:57:57 +00001041 // Get the size of the section in the output file (including padding).
1042 uint64_t Size = Layout.getSectionFileSize(&SD);
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001043
1044 FileOff += Size;
Matt Fleming3565a062010-08-16 18:57:57 +00001045 }
1046
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001047 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1048
Matt Fleming3565a062010-08-16 18:57:57 +00001049 // Write out the ELF header ...
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001050 WriteHeader(FileOff - HeaderSize, NumSections);
1051
1052 FileOff = HeaderSize;
Matt Fleming3565a062010-08-16 18:57:57 +00001053
1054 // ... then all of the sections ...
1055 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1056
Benjamin Kramer44cbde82010-08-19 13:44:49 +00001057 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
1058
1059 unsigned Index = 1;
Matt Fleming3565a062010-08-16 18:57:57 +00001060 for (MCAssembler::const_iterator it = Asm.begin(),
1061 ie = Asm.end(); it != ie; ++it) {
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001062 const MCSectionData &SD = *it;
1063
1064 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1065 WriteZeros(Padding);
1066 FileOff += Padding;
1067
Matt Fleming3565a062010-08-16 18:57:57 +00001068 // Remember the offset into the file for this section.
1069 SectionOffsetMap[&it->getSection()] = FileOff;
Benjamin Kramer44cbde82010-08-19 13:44:49 +00001070 SectionIndexMap[&it->getSection()] = Index++;
1071
Matt Fleming3565a062010-08-16 18:57:57 +00001072 FileOff += Layout.getSectionFileSize(&SD);
1073
1074 Asm.WriteSectionData(it, Layout, Writer);
1075 }
1076
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001077 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1078 WriteZeros(Padding);
1079 FileOff += Padding;
1080
Matt Fleming3565a062010-08-16 18:57:57 +00001081 // ... and then the section header table.
1082 // Should we align the section header table?
1083 //
1084 // Null section first.
1085 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1086
1087 for (MCAssembler::const_iterator it = Asm.begin(),
1088 ie = Asm.end(); it != ie; ++it) {
1089 const MCSectionData &SD = *it;
1090 const MCSectionELF &Section =
1091 static_cast<const MCSectionELF&>(SD.getSection());
1092
1093 uint64_t sh_link = 0;
1094 uint64_t sh_info = 0;
1095
1096 switch(Section.getType()) {
1097 case ELF::SHT_DYNAMIC:
1098 sh_link = SectionStringTableIndex[&it->getSection()];
1099 sh_info = 0;
1100 break;
1101
1102 case ELF::SHT_REL:
Eli Friedmanf8020a32010-08-16 19:15:06 +00001103 case ELF::SHT_RELA: {
Matt Fleming3565a062010-08-16 18:57:57 +00001104 const MCSection *SymtabSection;
1105 const MCSection *InfoSection;
Matt Fleming3565a062010-08-16 18:57:57 +00001106
1107 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1108 SectionKind::getReadOnly(),
Eli Friedmanf8020a32010-08-16 19:15:06 +00001109 false);
Benjamin Kramer44cbde82010-08-19 13:44:49 +00001110 sh_link = SectionIndexMap[SymtabSection];
Matt Fleming3565a062010-08-16 18:57:57 +00001111
Benjamin Kramer377a5722010-08-17 17:30:07 +00001112 // Remove ".rel" and ".rela" prefixes.
1113 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1114 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1115
Eli Friedmanf8020a32010-08-16 19:15:06 +00001116 InfoSection = Asm.getContext().getELFSection(SectionName,
Matt Fleming3565a062010-08-16 18:57:57 +00001117 ELF::SHT_PROGBITS, 0,
Eli Friedmanf8020a32010-08-16 19:15:06 +00001118 SectionKind::getReadOnly(),
1119 false);
Benjamin Kramer44cbde82010-08-19 13:44:49 +00001120 sh_info = SectionIndexMap[InfoSection];
Matt Fleming3565a062010-08-16 18:57:57 +00001121 break;
Eli Friedmanf8020a32010-08-16 19:15:06 +00001122 }
Matt Fleming3565a062010-08-16 18:57:57 +00001123
1124 case ELF::SHT_SYMTAB:
1125 case ELF::SHT_DYNSYM:
1126 sh_link = StringTableIndex;
1127 sh_info = LastLocalSymbolIndex;
1128 break;
1129
1130 case ELF::SHT_PROGBITS:
1131 case ELF::SHT_STRTAB:
1132 case ELF::SHT_NOBITS:
Benjamin Kramer19dc7fa2010-08-31 17:03:33 +00001133 case ELF::SHT_NULL:
Matt Fleming3565a062010-08-16 18:57:57 +00001134 // Nothing to do.
1135 break;
1136
1137 case ELF::SHT_HASH:
1138 case ELF::SHT_GROUP:
1139 case ELF::SHT_SYMTAB_SHNDX:
1140 default:
1141 assert(0 && "FIXME: sh_type value not supported!");
1142 break;
1143 }
1144
1145 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
1146 Section.getType(), Section.getFlags(),
Rafael Espindola71859c62010-09-16 19:46:31 +00001147 0,
Matt Fleming3565a062010-08-16 18:57:57 +00001148 SectionOffsetMap.lookup(&SD.getSection()),
1149 Layout.getSectionSize(&SD), sh_link,
1150 sh_info, SD.getAlignment(),
1151 Section.getEntrySize());
1152 }
1153}
1154
1155ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1156 bool Is64Bit,
Roman Divacky5baf79e2010-09-09 17:57:50 +00001157 Triple::OSType OSType,
Matt Fleming3565a062010-08-16 18:57:57 +00001158 bool IsLittleEndian,
1159 bool HasRelocationAddend)
1160 : MCObjectWriter(OS, IsLittleEndian)
1161{
Roman Divacky5baf79e2010-09-09 17:57:50 +00001162 Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend, OSType);
Matt Fleming3565a062010-08-16 18:57:57 +00001163}
1164
1165ELFObjectWriter::~ELFObjectWriter() {
1166 delete (ELFObjectWriterImpl*) Impl;
1167}
1168
1169void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1170 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1171}
1172
1173void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1174 const MCAsmLayout &Layout,
1175 const MCFragment *Fragment,
1176 const MCFixup &Fixup, MCValue Target,
1177 uint64_t &FixedValue) {
1178 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1179 Target, FixedValue);
1180}
1181
Rafael Espindola70703872010-09-30 02:22:20 +00001182bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1183 const MCValue Target,
1184 bool IsPCRel,
1185 const MCFragment *DF) const {
1186 return ((ELFObjectWriterImpl*) Impl)->IsFixupFullyResolved(Asm, Target,
1187 IsPCRel, DF);
1188}
1189
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001190void ELFObjectWriter::WriteObject(MCAssembler &Asm,
Matt Fleming3565a062010-08-16 18:57:57 +00001191 const MCAsmLayout &Layout) {
1192 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);
1193}