blob: b9d2acea4612fb74d880eebc289f1baf3b3d022f [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
Matt Fleming3565a062010-08-16 18:57:57 +000073namespace {
74
75 class ELFObjectWriterImpl {
Chris Lattnerb188a372010-08-28 03:21:03 +000076 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
Matt Fleming3565a062010-08-16 18:57:57 +000077 return Kind == X86::reloc_riprel_4byte ||
78 Kind == X86::reloc_riprel_4byte_movq_load;
Chris Lattnerb188a372010-08-28 03:21:03 +000079 }*/
Matt Fleming3565a062010-08-16 18:57:57 +000080
81
82 /// ELFSymbolData - Helper struct for containing some precomputed information
83 /// on symbols.
84 struct ELFSymbolData {
85 MCSymbolData *SymbolData;
86 uint64_t StringIndex;
87 uint32_t SectionIndex;
88
89 // Support lexicographic sorting.
90 bool operator<(const ELFSymbolData &RHS) const {
Rafael Espindolaad49cf52010-09-18 15:03:21 +000091 if (GetType(*SymbolData) == ELF::STT_FILE)
92 return true;
93 if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
94 return false;
Benjamin Kramer36c6dc22010-08-23 21:23:52 +000095 return SymbolData->getSymbol().getName() <
96 RHS.SymbolData->getSymbol().getName();
Matt Fleming3565a062010-08-16 18:57:57 +000097 }
98 };
99
100 /// @name Relocation Data
101 /// @{
102
103 struct ELFRelocationEntry {
104 // Make these big enough for both 32-bit and 64-bit
105 uint64_t r_offset;
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000106 int Index;
107 unsigned Type;
108 const MCSymbol *Symbol;
Matt Fleming3565a062010-08-16 18:57:57 +0000109 uint64_t r_addend;
110
111 // Support lexicographic sorting.
112 bool operator<(const ELFRelocationEntry &RE) const {
113 return RE.r_offset < r_offset;
114 }
115 };
116
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000117 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
118
Matt Fleming3565a062010-08-16 18:57:57 +0000119 llvm::DenseMap<const MCSectionData*,
120 std::vector<ELFRelocationEntry> > Relocations;
121 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
122
123 /// @}
124 /// @name Symbol Table Data
125 /// @{
126
127 SmallString<256> StringTable;
128 std::vector<ELFSymbolData> LocalSymbolData;
129 std::vector<ELFSymbolData> ExternalSymbolData;
130 std::vector<ELFSymbolData> UndefinedSymbolData;
131
132 /// @}
133
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000134 int NumRegularSections;
135
Matt Fleming3565a062010-08-16 18:57:57 +0000136 ELFObjectWriter *Writer;
137
138 raw_ostream &OS;
139
Matt Fleming3565a062010-08-16 18:57:57 +0000140 unsigned Is64Bit : 1;
141
142 bool HasRelocationAddend;
143
Roman Divacky5baf79e2010-09-09 17:57:50 +0000144 Triple::OSType OSType;
145
Matt Fleming3565a062010-08-16 18:57:57 +0000146 // This holds the symbol table index of the last local symbol.
147 unsigned LastLocalSymbolIndex;
148 // This holds the .strtab section index.
149 unsigned StringTableIndex;
150
151 unsigned ShstrtabIndex;
152
153 public:
154 ELFObjectWriterImpl(ELFObjectWriter *_Writer, bool _Is64Bit,
Roman Divacky5baf79e2010-09-09 17:57:50 +0000155 bool _HasRelAddend, Triple::OSType _OSType)
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000156 : Writer(_Writer), OS(Writer->getStream()),
Roman Divacky5baf79e2010-09-09 17:57:50 +0000157 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
158 OSType(_OSType) {
Matt Fleming3565a062010-08-16 18:57:57 +0000159 }
160
161 void Write8(uint8_t Value) { Writer->Write8(Value); }
162 void Write16(uint16_t Value) { Writer->Write16(Value); }
163 void Write32(uint32_t Value) { Writer->Write32(Value); }
Chris Lattnerb188a372010-08-28 03:21:03 +0000164 //void Write64(uint64_t Value) { Writer->Write64(Value); }
Matt Fleming3565a062010-08-16 18:57:57 +0000165 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
Chris Lattnerb188a372010-08-28 03:21:03 +0000166 //void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
167 // Writer->WriteBytes(Str, ZeroFillSize);
168 //}
Matt Fleming3565a062010-08-16 18:57:57 +0000169
170 void WriteWord(uint64_t W) {
Chris Lattnerb188a372010-08-28 03:21:03 +0000171 if (Is64Bit)
Matt Fleming3565a062010-08-16 18:57:57 +0000172 Writer->Write64(W);
Chris Lattnerb188a372010-08-28 03:21:03 +0000173 else
Matt Fleming3565a062010-08-16 18:57:57 +0000174 Writer->Write32(W);
Matt Fleming3565a062010-08-16 18:57:57 +0000175 }
176
177 void String8(char *buf, uint8_t Value) {
178 buf[0] = Value;
179 }
180
181 void StringLE16(char *buf, uint16_t Value) {
182 buf[0] = char(Value >> 0);
183 buf[1] = char(Value >> 8);
184 }
185
186 void StringLE32(char *buf, uint32_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000187 StringLE16(buf, uint16_t(Value >> 0));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000188 StringLE16(buf + 2, uint16_t(Value >> 16));
Matt Fleming3565a062010-08-16 18:57:57 +0000189 }
190
191 void StringLE64(char *buf, uint64_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000192 StringLE32(buf, uint32_t(Value >> 0));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000193 StringLE32(buf + 4, uint32_t(Value >> 32));
Matt Fleming3565a062010-08-16 18:57:57 +0000194 }
195
196 void StringBE16(char *buf ,uint16_t Value) {
197 buf[0] = char(Value >> 8);
198 buf[1] = char(Value >> 0);
199 }
200
201 void StringBE32(char *buf, uint32_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000202 StringBE16(buf, uint16_t(Value >> 16));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000203 StringBE16(buf + 2, uint16_t(Value >> 0));
Matt Fleming3565a062010-08-16 18:57:57 +0000204 }
205
206 void StringBE64(char *buf, uint64_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000207 StringBE32(buf, uint32_t(Value >> 32));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000208 StringBE32(buf + 4, uint32_t(Value >> 0));
Matt Fleming3565a062010-08-16 18:57:57 +0000209 }
210
211 void String16(char *buf, uint16_t Value) {
212 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000213 StringLE16(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000214 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000215 StringBE16(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000216 }
217
218 void String32(char *buf, uint32_t Value) {
219 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000220 StringLE32(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000221 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000222 StringBE32(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000223 }
224
225 void String64(char *buf, uint64_t Value) {
226 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000227 StringLE64(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000228 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000229 StringBE64(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000230 }
231
232 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
233
234 void WriteSymbolEntry(MCDataFragment *F, uint64_t name, uint8_t info,
235 uint64_t value, uint64_t size,
236 uint8_t other, uint16_t shndx);
237
238 void WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
239 const MCAsmLayout &Layout);
240
241 void WriteSymbolTable(MCDataFragment *F, const MCAssembler &Asm,
Rafael Espindola71859c62010-09-16 19:46:31 +0000242 const MCAsmLayout &Layout,
243 unsigned NumRegularSections);
Matt Fleming3565a062010-08-16 18:57:57 +0000244
245 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
246 const MCFragment *Fragment, const MCFixup &Fixup,
247 MCValue Target, uint64_t &FixedValue);
248
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000249 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
250 const MCSymbol *S);
Matt Fleming3565a062010-08-16 18:57:57 +0000251
252 /// ComputeSymbolTable - Compute the symbol table data
253 ///
254 /// \param StringTable [out] - The string table data.
255 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
256 /// string table.
257 void ComputeSymbolTable(MCAssembler &Asm);
258
259 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
260 const MCSectionData &SD);
261
262 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
263 for (MCAssembler::const_iterator it = Asm.begin(),
264 ie = Asm.end(); it != ie; ++it) {
265 WriteRelocation(Asm, Layout, *it);
266 }
267 }
268
269 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
270
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000271 void ExecutePostLayoutBinding(MCAssembler &Asm) {
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000272 }
Matt Fleming3565a062010-08-16 18:57:57 +0000273
274 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
275 uint64_t Address, uint64_t Offset,
276 uint64_t Size, uint32_t Link, uint32_t Info,
277 uint64_t Alignment, uint64_t EntrySize);
278
279 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
280 const MCSectionData *SD);
281
Rafael Espindola70703872010-09-30 02:22:20 +0000282 bool IsFixupFullyResolved(const MCAssembler &Asm,
283 const MCValue Target,
284 bool IsPCRel,
285 const MCFragment *DF) const;
286
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000287 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000288 };
289
290}
291
292// Emit the ELF header.
293void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
294 unsigned NumberOfSections) {
295 // ELF Header
296 // ----------
297 //
298 // Note
299 // ----
300 // emitWord method behaves differently for ELF32 and ELF64, writing
301 // 4 bytes in the former and 8 in the latter.
302
303 Write8(0x7f); // e_ident[EI_MAG0]
304 Write8('E'); // e_ident[EI_MAG1]
305 Write8('L'); // e_ident[EI_MAG2]
306 Write8('F'); // e_ident[EI_MAG3]
307
308 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
309
310 // e_ident[EI_DATA]
311 Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
312
313 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky5baf79e2010-09-09 17:57:50 +0000314 // e_ident[EI_OSABI]
315 switch (OSType) {
316 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
317 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
318 default: Write8(ELF::ELFOSABI_NONE); break;
319 }
Matt Fleming3565a062010-08-16 18:57:57 +0000320 Write8(0); // e_ident[EI_ABIVERSION]
321
322 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
323
324 Write16(ELF::ET_REL); // e_type
325
326 // FIXME: Make this configurable
Benjamin Kramereb976772010-08-17 17:02:29 +0000327 Write16(Is64Bit ? ELF::EM_X86_64 : ELF::EM_386); // e_machine = target
Matt Fleming3565a062010-08-16 18:57:57 +0000328
329 Write32(ELF::EV_CURRENT); // e_version
330 WriteWord(0); // e_entry, no entry point in .o file
331 WriteWord(0); // e_phoff, no program header for .o
Benjamin Kramereb976772010-08-17 17:02:29 +0000332 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
333 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
Matt Fleming3565a062010-08-16 18:57:57 +0000334
335 // FIXME: Make this configurable.
336 Write32(0); // e_flags = whatever the target wants
337
338 // e_ehsize = ELF header size
339 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
340
341 Write16(0); // e_phentsize = prog header entry size
342 Write16(0); // e_phnum = # prog header entries = 0
343
344 // e_shentsize = Section header entry size
345 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
346
347 // e_shnum = # of section header ents
348 Write16(NumberOfSections);
349
350 // e_shstrndx = Section # of '.shstrtab'
351 Write16(ShstrtabIndex);
352}
353
354void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
355 uint8_t info, uint64_t value,
356 uint64_t size, uint8_t other,
357 uint16_t shndx) {
358 if (Is64Bit) {
359 char buf[8];
360
361 String32(buf, name);
362 F->getContents() += StringRef(buf, 4); // st_name
363
364 String8(buf, info);
365 F->getContents() += StringRef(buf, 1); // st_info
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000366
Matt Fleming3565a062010-08-16 18:57:57 +0000367 String8(buf, other);
368 F->getContents() += StringRef(buf, 1); // st_other
369
370 String16(buf, shndx);
371 F->getContents() += StringRef(buf, 2); // st_shndx
372
373 String64(buf, value);
374 F->getContents() += StringRef(buf, 8); // st_value
375
376 String64(buf, size);
377 F->getContents() += StringRef(buf, 8); // st_size
378 } else {
379 char buf[4];
380
381 String32(buf, name);
382 F->getContents() += StringRef(buf, 4); // st_name
383
384 String32(buf, value);
385 F->getContents() += StringRef(buf, 4); // st_value
386
387 String32(buf, size);
388 F->getContents() += StringRef(buf, 4); // st_size
389
390 String8(buf, info);
391 F->getContents() += StringRef(buf, 1); // st_info
392
393 String8(buf, other);
394 F->getContents() += StringRef(buf, 1); // st_other
395
396 String16(buf, shndx);
397 F->getContents() += StringRef(buf, 2); // st_shndx
398 }
399}
400
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000401static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
402 if (Data.isCommon() && Data.isExternal())
403 return Data.getCommonAlignment();
404
405 const MCSymbol &Symbol = Data.getSymbol();
406 if (!Symbol.isInSection())
407 return 0;
408
409 if (!Data.isCommon() && !(Data.getFlags() & ELF_STB_Weak))
410 if (MCFragment *FF = Data.getFragment())
411 return Layout.getSymbolAddress(&Data) -
412 Layout.getSectionAddress(FF->getParent());
413
414 return 0;
415}
416
Matt Fleming3565a062010-08-16 18:57:57 +0000417void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
418 const MCAsmLayout &Layout) {
419 MCSymbolData &Data = *MSD.SymbolData;
Matt Fleming3565a062010-08-16 18:57:57 +0000420 uint8_t Info = (Data.getFlags() & 0xff);
421 uint8_t Other = ((Data.getFlags() & 0xf00) >> ELF_STV_Shift);
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000422 uint64_t Value = SymbolValue(Data, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000423 uint64_t Size = 0;
424 const MCExpr *ESize;
425
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000426 assert(!(Data.isCommon() && !Data.isExternal()));
427
Matt Fleming3565a062010-08-16 18:57:57 +0000428 ESize = Data.getSize();
429 if (Data.getSize()) {
430 MCValue Res;
431 if (ESize->getKind() == MCExpr::Binary) {
432 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
433
434 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
435 MCSymbolData &A =
436 Layout.getAssembler().getSymbolData(Res.getSymA()->getSymbol());
437 MCSymbolData &B =
438 Layout.getAssembler().getSymbolData(Res.getSymB()->getSymbol());
439
440 Size = Layout.getSymbolAddress(&A) - Layout.getSymbolAddress(&B);
Matt Fleming3565a062010-08-16 18:57:57 +0000441 }
442 } else if (ESize->getKind() == MCExpr::Constant) {
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000443 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
Matt Fleming3565a062010-08-16 18:57:57 +0000444 } else {
445 assert(0 && "Unsupported size expression");
446 }
447 }
448
449 // Write out the symbol table entry
450 WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
451 Size, Other, MSD.SectionIndex);
452}
453
454void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
455 const MCAssembler &Asm,
Rafael Espindola71859c62010-09-16 19:46:31 +0000456 const MCAsmLayout &Layout,
457 unsigned NumRegularSections) {
Matt Fleming3565a062010-08-16 18:57:57 +0000458 // The string table must be emitted first because we need the index
459 // into the string table for all the symbol names.
460 assert(StringTable.size() && "Missing string table");
461
462 // FIXME: Make sure the start of the symbol table is aligned.
463
464 // The first entry is the undefined symbol entry.
465 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000466 F->getContents().append(EntrySize, '\x00');
Matt Fleming3565a062010-08-16 18:57:57 +0000467
468 // Write the symbol table entries.
469 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
470 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
471 ELFSymbolData &MSD = LocalSymbolData[i];
472 WriteSymbol(F, MSD, Layout);
473 }
474
Rafael Espindola71859c62010-09-16 19:46:31 +0000475 // Write out a symbol table entry for each regular section.
Eli Friedmana44fa242010-08-16 21:17:09 +0000476 unsigned Index = 1;
Rafael Espindola71859c62010-09-16 19:46:31 +0000477 for (MCAssembler::const_iterator it = Asm.begin();
478 Index <= NumRegularSections; ++it, ++Index) {
Eli Friedmana44fa242010-08-16 21:17:09 +0000479 const MCSectionELF &Section =
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000480 static_cast<const MCSectionELF&>(it->getSection());
Eli Friedmana44fa242010-08-16 21:17:09 +0000481 // Leave out relocations so we don't have indexes within
482 // the relocations messed up
Benjamin Kramer377a5722010-08-17 17:30:07 +0000483 if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
Eli Friedmana44fa242010-08-16 21:17:09 +0000484 continue;
Matt Fleming3565a062010-08-16 18:57:57 +0000485 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
Eli Friedmana44fa242010-08-16 21:17:09 +0000486 LastLocalSymbolIndex++;
487 }
Matt Fleming3565a062010-08-16 18:57:57 +0000488
489 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
490 ELFSymbolData &MSD = ExternalSymbolData[i];
491 MCSymbolData &Data = *MSD.SymbolData;
492 assert((Data.getFlags() & ELF_STB_Global) &&
493 "External symbol requires STB_GLOBAL flag");
494 WriteSymbol(F, MSD, Layout);
Rafael Espindolae15eb4e2010-09-23 19:55:14 +0000495 if (GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming3565a062010-08-16 18:57:57 +0000496 LastLocalSymbolIndex++;
497 }
498
499 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
500 ELFSymbolData &MSD = UndefinedSymbolData[i];
501 MCSymbolData &Data = *MSD.SymbolData;
Matt Fleming3565a062010-08-16 18:57:57 +0000502 WriteSymbol(F, MSD, Layout);
Rafael Espindolae15eb4e2010-09-23 19:55:14 +0000503 if (GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming3565a062010-08-16 18:57:57 +0000504 LastLocalSymbolIndex++;
505 }
506}
507
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000508static bool ShouldRelocOnSymbol(const MCSymbolData &SD,
509 const MCValue &Target) {
510 const MCSymbol &Symbol = SD.getSymbol();
511 if (Symbol.isUndefined())
512 return true;
Rafael Espindola73ffea42010-09-25 05:42:19 +0000513
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000514 const MCSectionELF &Section =
515 static_cast<const MCSectionELF&>(Symbol.getSection());
516
517 if (Section.getFlags() & MCSectionELF::SHF_MERGE)
518 return Target.getConstant() != 0;
519
520 if (SD.isExternal())
521 return true;
522
523 return false;
Rafael Espindola73ffea42010-09-25 05:42:19 +0000524}
525
Benjamin Kramere5b57342010-08-17 18:20:28 +0000526// FIXME: this is currently X86/X86_64 only
Matt Fleming3565a062010-08-16 18:57:57 +0000527void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
528 const MCAsmLayout &Layout,
529 const MCFragment *Fragment,
530 const MCFixup &Fixup,
531 MCValue Target,
532 uint64_t &FixedValue) {
Matt Fleming3565a062010-08-16 18:57:57 +0000533 int64_t Addend = 0;
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000534 int Index = 0;
Benjamin Kramer95c602a2010-08-27 10:38:39 +0000535 int64_t Value = Target.getConstant();
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000536 const MCSymbol *Symbol = 0;
Matt Fleming3565a062010-08-16 18:57:57 +0000537
Rafael Espindola00074892010-09-17 22:34:41 +0000538 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
Benjamin Kramer81cfb852010-08-17 19:45:05 +0000539 if (!Target.isAbsolute()) {
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000540 Symbol = &Target.getSymA()->getSymbol();
Matt Fleming3565a062010-08-16 18:57:57 +0000541 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000542 MCFragment *F = SD.getFragment();
Matt Fleming3565a062010-08-16 18:57:57 +0000543
Rafael Espindola9d8b7552010-10-03 00:46:57 +0000544 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
545 const MCSymbol &SymbolB = RefB->getSymbol();
546 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
547 IsPCRel = true;
Rafael Espindola55fb1022010-10-04 15:59:01 +0000548 MCSectionData *Sec = Fragment->getParent();
549
550 // Offset of the symbol in the section
551 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
552
553 // Ofeset of the relocation in the section
554 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
555 Value += b - a;
Rafael Espindola9d8b7552010-10-03 00:46:57 +0000556 }
557
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000558 // Check that this case has already been fully resolved before we get
559 // here.
Rafael Espindola00074892010-09-17 22:34:41 +0000560 if (Symbol->isDefined() && !SD.isExternal() &&
561 IsPCRel &&
562 &Fragment->getParent()->getSection() == &Symbol->getSection()) {
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000563 llvm_unreachable("We don't need a relocation in this case.");
Rafael Espindola00074892010-09-17 22:34:41 +0000564 return;
565 }
566
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000567 bool RelocOnSymbol = ShouldRelocOnSymbol(SD, Target);
568 if (!RelocOnSymbol) {
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000569 Index = F->getParent()->getOrdinal();
Rafael Espindolaa6489182010-09-24 21:19:03 +0000570
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000571 MCSectionData *FSD = F->getParent();
572 // Offset of the symbol in the section
573 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000574 } else {
575 UsedInReloc.insert(Symbol);
576 Index = -1;
577 }
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000578 Addend = Value;
579 // Compensate for the addend on i386.
580 if (Is64Bit)
581 Value = 0;
Matt Fleming3565a062010-08-16 18:57:57 +0000582 }
583
Benjamin Kramer95c602a2010-08-27 10:38:39 +0000584 FixedValue = Value;
585
Matt Fleming3565a062010-08-16 18:57:57 +0000586 // determine the type of the relocation
Rafael Espindola28f9ac82010-10-04 18:44:25 +0000587
588 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000589 unsigned Type;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000590 if (Is64Bit) {
591 if (IsPCRel) {
Rafael Espindola92bf6682010-10-04 19:04:13 +0000592 switch (Modifier) {
593 case MCSymbolRefExpr::VK_None:
594 Type = ELF::R_X86_64_PC32;
595 break;
596 case MCSymbolRefExpr::VK_PLT:
597 Type = ELF::R_X86_64_PLT32;
598 break;
Rafael Espindola607d1f62010-10-04 19:51:39 +0000599 case llvm::MCSymbolRefExpr::VK_GOTPCREL:
600 Type = ELF::R_X86_64_GOTPCREL;
601 break;
Rafael Espindola92bf6682010-10-04 19:04:13 +0000602 default:
603 llvm_unreachable("Unimplemented");
604 }
Benjamin Kramere5b57342010-08-17 18:20:28 +0000605 } else {
606 switch ((unsigned)Fixup.getKind()) {
607 default: llvm_unreachable("invalid fixup kind!");
608 case FK_Data_8: Type = ELF::R_X86_64_64; break;
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000609 case X86::reloc_signed_4byte:
Benjamin Kramere5b57342010-08-17 18:20:28 +0000610 case X86::reloc_pcrel_4byte:
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000611 assert(isInt<32>(Target.getConstant()));
Rafael Espindola28f9ac82010-10-04 18:44:25 +0000612 switch (Modifier) {
613 case MCSymbolRefExpr::VK_None:
614 Type = ELF::R_X86_64_32S;
615 break;
616 case MCSymbolRefExpr::VK_GOT:
617 Type = ELF::R_X86_64_GOT32;
618 break;
619 default:
620 llvm_unreachable("Unimplemented");
621 }
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000622 break;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000623 case FK_Data_4:
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000624 Type = ELF::R_X86_64_32;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000625 break;
626 case FK_Data_2: Type = ELF::R_X86_64_16; break;
627 case X86::reloc_pcrel_1byte:
628 case FK_Data_1: Type = ELF::R_X86_64_8; break;
629 }
630 }
Matt Fleming3565a062010-08-16 18:57:57 +0000631 } else {
Benjamin Kramere5b57342010-08-17 18:20:28 +0000632 if (IsPCRel) {
633 Type = ELF::R_386_PC32;
634 } else {
635 switch ((unsigned)Fixup.getKind()) {
636 default: llvm_unreachable("invalid fixup kind!");
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000637
638 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
639 // instead?
640 case X86::reloc_signed_4byte:
Benjamin Kramere5b57342010-08-17 18:20:28 +0000641 case X86::reloc_pcrel_4byte:
642 case FK_Data_4: Type = ELF::R_386_32; break;
643 case FK_Data_2: Type = ELF::R_386_16; break;
644 case X86::reloc_pcrel_1byte:
645 case FK_Data_1: Type = ELF::R_386_8; break;
646 }
Matt Fleming3565a062010-08-16 18:57:57 +0000647 }
648 }
649
Benjamin Kramere5b57342010-08-17 18:20:28 +0000650 ELFRelocationEntry ERE;
651
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000652 ERE.Index = Index;
653 ERE.Type = Type;
654 ERE.Symbol = Symbol;
Matt Fleming3565a062010-08-16 18:57:57 +0000655
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000656 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
Benjamin Kramere5b57342010-08-17 18:20:28 +0000657
Matt Fleming3565a062010-08-16 18:57:57 +0000658 if (HasRelocationAddend)
659 ERE.r_addend = Addend;
Benjamin Kramer172d7d62010-08-17 00:33:24 +0000660 else
661 ERE.r_addend = 0; // Silence compiler warning.
Matt Fleming3565a062010-08-16 18:57:57 +0000662
663 Relocations[Fragment->getParent()].push_back(ERE);
664}
665
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000666uint64_t
667ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
668 const MCSymbol *S) {
Benjamin Kramer7b83c262010-08-25 20:09:43 +0000669 MCSymbolData &SD = Asm.getSymbolData(*S);
Eli Friedmanf8020a32010-08-16 19:15:06 +0000670
Benjamin Kramer7b83c262010-08-25 20:09:43 +0000671 // Local symbol.
672 if (!SD.isExternal() && !S->isUndefined())
673 return SD.getIndex() + /* empty symbol */ 1;
674
675 // External or undefined symbol.
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000676 return SD.getIndex() + NumRegularSections + /* empty symbol */ 1;
Matt Fleming3565a062010-08-16 18:57:57 +0000677}
678
679void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
680 // Build section lookup table.
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000681 NumRegularSections = Asm.size();
Matt Fleming3565a062010-08-16 18:57:57 +0000682 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
683 unsigned Index = 1;
684 for (MCAssembler::iterator it = Asm.begin(),
685 ie = Asm.end(); it != ie; ++it, ++Index)
686 SectionIndexMap[&it->getSection()] = Index;
687
688 // Index 0 is always the empty string.
689 StringMap<uint64_t> StringIndexMap;
690 StringTable += '\x00';
691
692 // Add the data for local symbols.
693 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
694 ie = Asm.symbol_end(); it != ie; ++it) {
695 const MCSymbol &Symbol = it->getSymbol();
696
697 // Ignore non-linker visible symbols.
698 if (!Asm.isSymbolLinkerVisible(Symbol))
699 continue;
700
701 if (it->isExternal() || Symbol.isUndefined())
702 continue;
703
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000704 if (Symbol.isTemporary() && !UsedInReloc.count(&Symbol))
705 continue;
706
Matt Fleming3565a062010-08-16 18:57:57 +0000707 uint64_t &Entry = StringIndexMap[Symbol.getName()];
708 if (!Entry) {
709 Entry = StringTable.size();
710 StringTable += Symbol.getName();
711 StringTable += '\x00';
712 }
713
714 ELFSymbolData MSD;
715 MSD.SymbolData = it;
716 MSD.StringIndex = Entry;
717
718 if (Symbol.isAbsolute()) {
719 MSD.SectionIndex = ELF::SHN_ABS;
720 LocalSymbolData.push_back(MSD);
721 } else {
722 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
723 assert(MSD.SectionIndex && "Invalid section index!");
724 LocalSymbolData.push_back(MSD);
725 }
726 }
727
728 // Now add non-local symbols.
729 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
730 ie = Asm.symbol_end(); it != ie; ++it) {
731 const MCSymbol &Symbol = it->getSymbol();
732
733 // Ignore non-linker visible symbols.
Rafael Espindola53725bc2010-09-28 16:19:11 +0000734 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
Matt Fleming3565a062010-08-16 18:57:57 +0000735 continue;
736
737 if (!it->isExternal() && !Symbol.isUndefined())
738 continue;
739
Rafael Espindola53725bc2010-09-28 16:19:11 +0000740 if (Symbol.isVariable())
741 continue;
742
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000743 if (Symbol.isUndefined() && !UsedInReloc.count(&Symbol)
744 && Symbol.isTemporary())
745 continue;
746
Matt Fleming3565a062010-08-16 18:57:57 +0000747 uint64_t &Entry = StringIndexMap[Symbol.getName()];
748 if (!Entry) {
749 Entry = StringTable.size();
750 StringTable += Symbol.getName();
751 StringTable += '\x00';
752 }
753
754 ELFSymbolData MSD;
755 MSD.SymbolData = it;
756 MSD.StringIndex = Entry;
757
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000758 if (it->isCommon()) {
759 MSD.SectionIndex = ELF::SHN_COMMON;
760 ExternalSymbolData.push_back(MSD);
761 } else if (Symbol.isUndefined()) {
Matt Fleming3565a062010-08-16 18:57:57 +0000762 MSD.SectionIndex = ELF::SHN_UNDEF;
Rafael Espindolae15eb4e2010-09-23 19:55:14 +0000763 // FIXME: Undefined symbols are global, but this is the first place we
764 // are able to set it.
765 if (GetBinding(*it) == ELF::STB_LOCAL)
766 SetBinding(*it, ELF::STB_GLOBAL);
Matt Fleming3565a062010-08-16 18:57:57 +0000767 UndefinedSymbolData.push_back(MSD);
768 } else if (Symbol.isAbsolute()) {
769 MSD.SectionIndex = ELF::SHN_ABS;
770 ExternalSymbolData.push_back(MSD);
Matt Fleming3565a062010-08-16 18:57:57 +0000771 } else {
772 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
773 assert(MSD.SectionIndex && "Invalid section index!");
774 ExternalSymbolData.push_back(MSD);
775 }
776 }
777
778 // Symbols are required to be in lexicographic order.
779 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
780 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
781 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
782
783 // Set the symbol indices. Local symbols must come before all other
784 // symbols with non-local bindings.
785 Index = 0;
786 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
787 LocalSymbolData[i].SymbolData->setIndex(Index++);
788 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
789 ExternalSymbolData[i].SymbolData->setIndex(Index++);
790 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
791 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
792}
793
794void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
795 const MCSectionData &SD) {
796 if (!Relocations[&SD].empty()) {
797 MCContext &Ctx = Asm.getContext();
798 const MCSection *RelaSection;
799 const MCSectionELF &Section =
800 static_cast<const MCSectionELF&>(SD.getSection());
801
802 const StringRef SectionName = Section.getSectionName();
Benjamin Kramer377a5722010-08-17 17:30:07 +0000803 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
Matt Fleming3565a062010-08-16 18:57:57 +0000804 RelaSectionName += SectionName;
Benjamin Kramer299fbe32010-08-17 17:56:13 +0000805
806 unsigned EntrySize;
807 if (HasRelocationAddend)
808 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
809 else
810 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming3565a062010-08-16 18:57:57 +0000811
Benjamin Kramer377a5722010-08-17 17:30:07 +0000812 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
813 ELF::SHT_RELA : ELF::SHT_REL, 0,
Matt Fleming3565a062010-08-16 18:57:57 +0000814 SectionKind::getReadOnly(),
815 false, EntrySize);
816
817 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000818 RelaSD.setAlignment(Is64Bit ? 8 : 4);
Matt Fleming3565a062010-08-16 18:57:57 +0000819
820 MCDataFragment *F = new MCDataFragment(&RelaSD);
821
822 WriteRelocationsFragment(Asm, F, &SD);
823
Rafael Espindola70703872010-09-30 02:22:20 +0000824 Asm.AddSectionToTheEnd(*Writer, RelaSD, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000825 }
826}
827
828void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
829 uint64_t Flags, uint64_t Address,
830 uint64_t Offset, uint64_t Size,
831 uint32_t Link, uint32_t Info,
832 uint64_t Alignment,
833 uint64_t EntrySize) {
834 Write32(Name); // sh_name: index into string table
835 Write32(Type); // sh_type
836 WriteWord(Flags); // sh_flags
837 WriteWord(Address); // sh_addr
838 WriteWord(Offset); // sh_offset
839 WriteWord(Size); // sh_size
840 Write32(Link); // sh_link
841 Write32(Info); // sh_info
842 WriteWord(Alignment); // sh_addralign
843 WriteWord(EntrySize); // sh_entsize
844}
845
846void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
847 MCDataFragment *F,
848 const MCSectionData *SD) {
849 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
850 // sort by the r_offset just like gnu as does
851 array_pod_sort(Relocs.begin(), Relocs.end());
852
853 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
854 ELFRelocationEntry entry = Relocs[e - i - 1];
855
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000856 if (entry.Index < 0)
857 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
858 else
859 entry.Index += LocalSymbolData.size() + 1;
Benjamin Kramer5e492e82010-09-09 18:01:29 +0000860 if (Is64Bit) {
861 char buf[8];
Matt Fleming3565a062010-08-16 18:57:57 +0000862
Benjamin Kramer5e492e82010-09-09 18:01:29 +0000863 String64(buf, entry.r_offset);
864 F->getContents() += StringRef(buf, 8);
865
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000866 struct ELF::Elf64_Rela ERE64;
867 ERE64.setSymbolAndType(entry.Index, entry.Type);
868 String64(buf, ERE64.r_info);
Benjamin Kramer5e492e82010-09-09 18:01:29 +0000869 F->getContents() += StringRef(buf, 8);
870
871 if (HasRelocationAddend) {
872 String64(buf, entry.r_addend);
873 F->getContents() += StringRef(buf, 8);
874 }
875 } else {
876 char buf[4];
877
878 String32(buf, entry.r_offset);
879 F->getContents() += StringRef(buf, 4);
880
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000881 struct ELF::Elf32_Rela ERE32;
882 ERE32.setSymbolAndType(entry.Index, entry.Type);
883 String32(buf, ERE32.r_info);
Benjamin Kramer5e492e82010-09-09 18:01:29 +0000884 F->getContents() += StringRef(buf, 4);
885
886 if (HasRelocationAddend) {
887 String32(buf, entry.r_addend);
888 F->getContents() += StringRef(buf, 4);
889 }
890 }
Matt Fleming3565a062010-08-16 18:57:57 +0000891 }
892}
893
894void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
895 MCAsmLayout &Layout) {
896 MCContext &Ctx = Asm.getContext();
897 MCDataFragment *F;
898
Matt Fleming3565a062010-08-16 18:57:57 +0000899 const MCSection *SymtabSection;
900 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
901
Rafael Espindola71859c62010-09-16 19:46:31 +0000902 unsigned NumRegularSections = Asm.size();
903
Rafael Espindola38738bf2010-09-22 19:04:41 +0000904 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola71859c62010-09-16 19:46:31 +0000905 const MCSection *ShstrtabSection;
906 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
907 SectionKind::getReadOnly(), false);
908 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
909 ShstrtabSD.setAlignment(1);
910 ShstrtabIndex = Asm.size();
911
Matt Fleming3565a062010-08-16 18:57:57 +0000912 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
913 SectionKind::getReadOnly(),
914 false, EntrySize);
Matt Fleming3565a062010-08-16 18:57:57 +0000915 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Matt Fleming3565a062010-08-16 18:57:57 +0000916 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
917
Matt Fleming3565a062010-08-16 18:57:57 +0000918 const MCSection *StrtabSection;
919 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
920 SectionKind::getReadOnly(), false);
Matt Fleming3565a062010-08-16 18:57:57 +0000921 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
922 StrtabSD.setAlignment(1);
Matt Fleming3565a062010-08-16 18:57:57 +0000923 StringTableIndex = Asm.size();
924
Rafael Espindolac3c413f2010-09-27 22:04:54 +0000925 WriteRelocations(Asm, Layout);
Rafael Espindola71859c62010-09-16 19:46:31 +0000926
927 // Symbol table
928 F = new MCDataFragment(&SymtabSD);
929 WriteSymbolTable(F, Asm, Layout, NumRegularSections);
Rafael Espindola70703872010-09-30 02:22:20 +0000930 Asm.AddSectionToTheEnd(*Writer, SymtabSD, Layout);
Rafael Espindola71859c62010-09-16 19:46:31 +0000931
Matt Fleming3565a062010-08-16 18:57:57 +0000932 F = new MCDataFragment(&StrtabSD);
933 F->getContents().append(StringTable.begin(), StringTable.end());
Rafael Espindola70703872010-09-30 02:22:20 +0000934 Asm.AddSectionToTheEnd(*Writer, StrtabSD, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000935
Matt Fleming3565a062010-08-16 18:57:57 +0000936 F = new MCDataFragment(&ShstrtabSD);
937
Matt Fleming3565a062010-08-16 18:57:57 +0000938 // Section header string table.
939 //
940 // The first entry of a string table holds a null character so skip
941 // section 0.
942 uint64_t Index = 1;
943 F->getContents() += '\x00';
944
945 for (MCAssembler::const_iterator it = Asm.begin(),
946 ie = Asm.end(); it != ie; ++it) {
Matt Fleming3565a062010-08-16 18:57:57 +0000947 const MCSectionELF &Section =
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000948 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola51efe7a2010-09-23 14:14:56 +0000949 // FIXME: We could merge suffixes like in .text and .rela.text.
Matt Fleming3565a062010-08-16 18:57:57 +0000950
951 // Remember the index into the string table so we can write it
952 // into the sh_name field of the section header table.
953 SectionStringTableIndex[&it->getSection()] = Index;
954
955 Index += Section.getSectionName().size() + 1;
956 F->getContents() += Section.getSectionName();
957 F->getContents() += '\x00';
958 }
959
Rafael Espindola70703872010-09-30 02:22:20 +0000960 Asm.AddSectionToTheEnd(*Writer, ShstrtabSD, Layout);
961}
962
963bool ELFObjectWriterImpl::IsFixupFullyResolved(const MCAssembler &Asm,
964 const MCValue Target,
965 bool IsPCRel,
966 const MCFragment *DF) const {
967 // If this is a PCrel relocation, find the section this fixup value is
968 // relative to.
969 const MCSection *BaseSection = 0;
970 if (IsPCRel) {
971 BaseSection = &DF->getParent()->getSection();
972 assert(BaseSection);
973 }
974
975 const MCSection *SectionA = 0;
976 const MCSymbol *SymbolA = 0;
977 if (const MCSymbolRefExpr *A = Target.getSymA()) {
978 SymbolA = &A->getSymbol();
979 SectionA = &SymbolA->getSection();
980 }
981
982 const MCSection *SectionB = 0;
983 if (const MCSymbolRefExpr *B = Target.getSymB()) {
984 SectionB = &B->getSymbol().getSection();
985 }
986
987 if (!BaseSection)
988 return SectionA == SectionB;
989
990 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
991 if (DataA.isExternal())
992 return false;
993
994 return !SectionB && BaseSection == SectionA;
Matt Fleming3565a062010-08-16 18:57:57 +0000995}
996
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000997void ELFObjectWriterImpl::WriteObject(MCAssembler &Asm,
Matt Fleming3565a062010-08-16 18:57:57 +0000998 const MCAsmLayout &Layout) {
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000999 // Compute symbol table information.
1000 ComputeSymbolTable(Asm);
1001
Matt Fleming3565a062010-08-16 18:57:57 +00001002 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1003 const_cast<MCAsmLayout&>(Layout));
1004
1005 // Add 1 for the null section.
1006 unsigned NumSections = Asm.size() + 1;
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001007 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1008 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1009 uint64_t FileOff = HeaderSize;
Matt Fleming3565a062010-08-16 18:57:57 +00001010
1011 for (MCAssembler::const_iterator it = Asm.begin(),
1012 ie = Asm.end(); it != ie; ++it) {
1013 const MCSectionData &SD = *it;
Matt Fleming3565a062010-08-16 18:57:57 +00001014
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001015 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1016
Matt Fleming3565a062010-08-16 18:57:57 +00001017 // Get the size of the section in the output file (including padding).
1018 uint64_t Size = Layout.getSectionFileSize(&SD);
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001019
1020 FileOff += Size;
Matt Fleming3565a062010-08-16 18:57:57 +00001021 }
1022
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001023 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1024
Matt Fleming3565a062010-08-16 18:57:57 +00001025 // Write out the ELF header ...
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001026 WriteHeader(FileOff - HeaderSize, NumSections);
1027
1028 FileOff = HeaderSize;
Matt Fleming3565a062010-08-16 18:57:57 +00001029
1030 // ... then all of the sections ...
1031 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1032
Benjamin Kramer44cbde82010-08-19 13:44:49 +00001033 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
1034
1035 unsigned Index = 1;
Matt Fleming3565a062010-08-16 18:57:57 +00001036 for (MCAssembler::const_iterator it = Asm.begin(),
1037 ie = Asm.end(); it != ie; ++it) {
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001038 const MCSectionData &SD = *it;
1039
1040 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1041 WriteZeros(Padding);
1042 FileOff += Padding;
1043
Matt Fleming3565a062010-08-16 18:57:57 +00001044 // Remember the offset into the file for this section.
1045 SectionOffsetMap[&it->getSection()] = FileOff;
Benjamin Kramer44cbde82010-08-19 13:44:49 +00001046 SectionIndexMap[&it->getSection()] = Index++;
1047
Matt Fleming3565a062010-08-16 18:57:57 +00001048 FileOff += Layout.getSectionFileSize(&SD);
1049
1050 Asm.WriteSectionData(it, Layout, Writer);
1051 }
1052
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001053 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1054 WriteZeros(Padding);
1055 FileOff += Padding;
1056
Matt Fleming3565a062010-08-16 18:57:57 +00001057 // ... and then the section header table.
1058 // Should we align the section header table?
1059 //
1060 // Null section first.
1061 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1062
1063 for (MCAssembler::const_iterator it = Asm.begin(),
1064 ie = Asm.end(); it != ie; ++it) {
1065 const MCSectionData &SD = *it;
1066 const MCSectionELF &Section =
1067 static_cast<const MCSectionELF&>(SD.getSection());
1068
1069 uint64_t sh_link = 0;
1070 uint64_t sh_info = 0;
1071
1072 switch(Section.getType()) {
1073 case ELF::SHT_DYNAMIC:
1074 sh_link = SectionStringTableIndex[&it->getSection()];
1075 sh_info = 0;
1076 break;
1077
1078 case ELF::SHT_REL:
Eli Friedmanf8020a32010-08-16 19:15:06 +00001079 case ELF::SHT_RELA: {
Matt Fleming3565a062010-08-16 18:57:57 +00001080 const MCSection *SymtabSection;
1081 const MCSection *InfoSection;
Matt Fleming3565a062010-08-16 18:57:57 +00001082
1083 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1084 SectionKind::getReadOnly(),
Eli Friedmanf8020a32010-08-16 19:15:06 +00001085 false);
Benjamin Kramer44cbde82010-08-19 13:44:49 +00001086 sh_link = SectionIndexMap[SymtabSection];
Matt Fleming3565a062010-08-16 18:57:57 +00001087
Benjamin Kramer377a5722010-08-17 17:30:07 +00001088 // Remove ".rel" and ".rela" prefixes.
1089 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1090 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1091
Eli Friedmanf8020a32010-08-16 19:15:06 +00001092 InfoSection = Asm.getContext().getELFSection(SectionName,
Matt Fleming3565a062010-08-16 18:57:57 +00001093 ELF::SHT_PROGBITS, 0,
Eli Friedmanf8020a32010-08-16 19:15:06 +00001094 SectionKind::getReadOnly(),
1095 false);
Benjamin Kramer44cbde82010-08-19 13:44:49 +00001096 sh_info = SectionIndexMap[InfoSection];
Matt Fleming3565a062010-08-16 18:57:57 +00001097 break;
Eli Friedmanf8020a32010-08-16 19:15:06 +00001098 }
Matt Fleming3565a062010-08-16 18:57:57 +00001099
1100 case ELF::SHT_SYMTAB:
1101 case ELF::SHT_DYNSYM:
1102 sh_link = StringTableIndex;
1103 sh_info = LastLocalSymbolIndex;
1104 break;
1105
1106 case ELF::SHT_PROGBITS:
1107 case ELF::SHT_STRTAB:
1108 case ELF::SHT_NOBITS:
Benjamin Kramer19dc7fa2010-08-31 17:03:33 +00001109 case ELF::SHT_NULL:
Matt Fleming3565a062010-08-16 18:57:57 +00001110 // Nothing to do.
1111 break;
1112
1113 case ELF::SHT_HASH:
1114 case ELF::SHT_GROUP:
1115 case ELF::SHT_SYMTAB_SHNDX:
1116 default:
1117 assert(0 && "FIXME: sh_type value not supported!");
1118 break;
1119 }
1120
1121 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
1122 Section.getType(), Section.getFlags(),
Rafael Espindola71859c62010-09-16 19:46:31 +00001123 0,
Matt Fleming3565a062010-08-16 18:57:57 +00001124 SectionOffsetMap.lookup(&SD.getSection()),
1125 Layout.getSectionSize(&SD), sh_link,
1126 sh_info, SD.getAlignment(),
1127 Section.getEntrySize());
1128 }
1129}
1130
1131ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1132 bool Is64Bit,
Roman Divacky5baf79e2010-09-09 17:57:50 +00001133 Triple::OSType OSType,
Matt Fleming3565a062010-08-16 18:57:57 +00001134 bool IsLittleEndian,
1135 bool HasRelocationAddend)
1136 : MCObjectWriter(OS, IsLittleEndian)
1137{
Roman Divacky5baf79e2010-09-09 17:57:50 +00001138 Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend, OSType);
Matt Fleming3565a062010-08-16 18:57:57 +00001139}
1140
1141ELFObjectWriter::~ELFObjectWriter() {
1142 delete (ELFObjectWriterImpl*) Impl;
1143}
1144
1145void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1146 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1147}
1148
1149void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1150 const MCAsmLayout &Layout,
1151 const MCFragment *Fragment,
1152 const MCFixup &Fixup, MCValue Target,
1153 uint64_t &FixedValue) {
1154 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1155 Target, FixedValue);
1156}
1157
Rafael Espindola70703872010-09-30 02:22:20 +00001158bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1159 const MCValue Target,
1160 bool IsPCRel,
1161 const MCFragment *DF) const {
1162 return ((ELFObjectWriterImpl*) Impl)->IsFixupFullyResolved(Asm, Target,
1163 IsPCRel, DF);
1164}
1165
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001166void ELFObjectWriter::WriteObject(MCAssembler &Asm,
Matt Fleming3565a062010-08-16 18:57:57 +00001167 const MCAsmLayout &Layout) {
1168 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);
1169}