blob: c7b862f3928ab074e4e3b15931846409f97a5d4a [file] [log] [blame]
Matt Fleming3565a062010-08-16 18:57:57 +00001//===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements ELF object file writer information.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/MC/ELFObjectWriter.h"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/StringMap.h"
17#include "llvm/ADT/Twine.h"
18#include "llvm/MC/MCAssembler.h"
19#include "llvm/MC/MCAsmLayout.h"
20#include "llvm/MC/MCContext.h"
21#include "llvm/MC/MCELFSymbolFlags.h"
22#include "llvm/MC/MCExpr.h"
23#include "llvm/MC/MCObjectWriter.h"
24#include "llvm/MC/MCSectionELF.h"
25#include "llvm/MC/MCSymbol.h"
26#include "llvm/MC/MCValue.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/ELF.h"
30#include "llvm/Target/TargetAsmBackend.h"
31
32#include "../Target/X86/X86FixupKinds.h"
33
34#include <vector>
35using namespace llvm;
36
Rafael Espindolaad49cf52010-09-18 15:03:21 +000037static unsigned GetType(const MCSymbolData &SD) {
38 uint32_t Type = (SD.getFlags() & (0xf << ELF_STT_Shift)) >> ELF_STT_Shift;
39 assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
40 Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
41 Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
42 Type == ELF::STT_TLS);
43 return Type;
44}
45
Rafael Espindolae15eb4e2010-09-23 19:55:14 +000046static unsigned GetBinding(const MCSymbolData &SD) {
47 uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
48 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
49 Binding == ELF::STB_WEAK);
50 return Binding;
51}
52
53static void SetBinding(MCSymbolData &SD, unsigned Binding) {
54 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
55 Binding == ELF::STB_WEAK);
56 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
57 SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
58}
59
Matt Fleming3565a062010-08-16 18:57:57 +000060namespace {
61
62 class ELFObjectWriterImpl {
63 static bool isFixupKindX86PCRel(unsigned Kind) {
64 switch (Kind) {
65 default:
66 return false;
67 case X86::reloc_pcrel_1byte:
68 case X86::reloc_pcrel_4byte:
69 case X86::reloc_riprel_4byte:
70 case X86::reloc_riprel_4byte_movq_load:
71 return true;
72 }
73 }
74
Chris Lattnerb188a372010-08-28 03:21:03 +000075 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
Matt Fleming3565a062010-08-16 18:57:57 +000076 return Kind == X86::reloc_riprel_4byte ||
77 Kind == X86::reloc_riprel_4byte_movq_load;
Chris Lattnerb188a372010-08-28 03:21:03 +000078 }*/
Matt Fleming3565a062010-08-16 18:57:57 +000079
80
81 /// ELFSymbolData - Helper struct for containing some precomputed information
82 /// on symbols.
83 struct ELFSymbolData {
84 MCSymbolData *SymbolData;
85 uint64_t StringIndex;
86 uint32_t SectionIndex;
87
88 // Support lexicographic sorting.
89 bool operator<(const ELFSymbolData &RHS) const {
Rafael Espindolaad49cf52010-09-18 15:03:21 +000090 if (GetType(*SymbolData) == ELF::STT_FILE)
91 return true;
92 if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
93 return false;
Benjamin Kramer36c6dc22010-08-23 21:23:52 +000094 return SymbolData->getSymbol().getName() <
95 RHS.SymbolData->getSymbol().getName();
Matt Fleming3565a062010-08-16 18:57:57 +000096 }
97 };
98
99 /// @name Relocation Data
100 /// @{
101
102 struct ELFRelocationEntry {
103 // Make these big enough for both 32-bit and 64-bit
104 uint64_t r_offset;
105 uint64_t r_info;
106 uint64_t r_addend;
107
108 // Support lexicographic sorting.
109 bool operator<(const ELFRelocationEntry &RE) const {
110 return RE.r_offset < r_offset;
111 }
112 };
113
114 llvm::DenseMap<const MCSectionData*,
115 std::vector<ELFRelocationEntry> > Relocations;
116 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
117
118 /// @}
119 /// @name Symbol Table Data
120 /// @{
121
122 SmallString<256> StringTable;
123 std::vector<ELFSymbolData> LocalSymbolData;
124 std::vector<ELFSymbolData> ExternalSymbolData;
125 std::vector<ELFSymbolData> UndefinedSymbolData;
126
127 /// @}
128
129 ELFObjectWriter *Writer;
130
131 raw_ostream &OS;
132
Matt Fleming3565a062010-08-16 18:57:57 +0000133 unsigned Is64Bit : 1;
134
135 bool HasRelocationAddend;
136
Roman Divacky5baf79e2010-09-09 17:57:50 +0000137 Triple::OSType OSType;
138
Matt Fleming3565a062010-08-16 18:57:57 +0000139 // This holds the symbol table index of the last local symbol.
140 unsigned LastLocalSymbolIndex;
141 // This holds the .strtab section index.
142 unsigned StringTableIndex;
143
144 unsigned ShstrtabIndex;
145
146 public:
147 ELFObjectWriterImpl(ELFObjectWriter *_Writer, bool _Is64Bit,
Roman Divacky5baf79e2010-09-09 17:57:50 +0000148 bool _HasRelAddend, Triple::OSType _OSType)
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000149 : Writer(_Writer), OS(Writer->getStream()),
Roman Divacky5baf79e2010-09-09 17:57:50 +0000150 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
151 OSType(_OSType) {
Matt Fleming3565a062010-08-16 18:57:57 +0000152 }
153
154 void Write8(uint8_t Value) { Writer->Write8(Value); }
155 void Write16(uint16_t Value) { Writer->Write16(Value); }
156 void Write32(uint32_t Value) { Writer->Write32(Value); }
Chris Lattnerb188a372010-08-28 03:21:03 +0000157 //void Write64(uint64_t Value) { Writer->Write64(Value); }
Matt Fleming3565a062010-08-16 18:57:57 +0000158 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
Chris Lattnerb188a372010-08-28 03:21:03 +0000159 //void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
160 // Writer->WriteBytes(Str, ZeroFillSize);
161 //}
Matt Fleming3565a062010-08-16 18:57:57 +0000162
163 void WriteWord(uint64_t W) {
Chris Lattnerb188a372010-08-28 03:21:03 +0000164 if (Is64Bit)
Matt Fleming3565a062010-08-16 18:57:57 +0000165 Writer->Write64(W);
Chris Lattnerb188a372010-08-28 03:21:03 +0000166 else
Matt Fleming3565a062010-08-16 18:57:57 +0000167 Writer->Write32(W);
Matt Fleming3565a062010-08-16 18:57:57 +0000168 }
169
170 void String8(char *buf, uint8_t Value) {
171 buf[0] = Value;
172 }
173
174 void StringLE16(char *buf, uint16_t Value) {
175 buf[0] = char(Value >> 0);
176 buf[1] = char(Value >> 8);
177 }
178
179 void StringLE32(char *buf, uint32_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000180 StringLE16(buf, uint16_t(Value >> 0));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000181 StringLE16(buf + 2, uint16_t(Value >> 16));
Matt Fleming3565a062010-08-16 18:57:57 +0000182 }
183
184 void StringLE64(char *buf, uint64_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000185 StringLE32(buf, uint32_t(Value >> 0));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000186 StringLE32(buf + 4, uint32_t(Value >> 32));
Matt Fleming3565a062010-08-16 18:57:57 +0000187 }
188
189 void StringBE16(char *buf ,uint16_t Value) {
190 buf[0] = char(Value >> 8);
191 buf[1] = char(Value >> 0);
192 }
193
194 void StringBE32(char *buf, uint32_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000195 StringBE16(buf, uint16_t(Value >> 16));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000196 StringBE16(buf + 2, uint16_t(Value >> 0));
Matt Fleming3565a062010-08-16 18:57:57 +0000197 }
198
199 void StringBE64(char *buf, uint64_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000200 StringBE32(buf, uint32_t(Value >> 32));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000201 StringBE32(buf + 4, uint32_t(Value >> 0));
Matt Fleming3565a062010-08-16 18:57:57 +0000202 }
203
204 void String16(char *buf, uint16_t Value) {
205 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000206 StringLE16(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000207 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000208 StringBE16(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000209 }
210
211 void String32(char *buf, uint32_t Value) {
212 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000213 StringLE32(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000214 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000215 StringBE32(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000216 }
217
218 void String64(char *buf, uint64_t Value) {
219 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000220 StringLE64(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000221 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000222 StringBE64(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000223 }
224
225 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
226
227 void WriteSymbolEntry(MCDataFragment *F, uint64_t name, uint8_t info,
228 uint64_t value, uint64_t size,
229 uint8_t other, uint16_t shndx);
230
231 void WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
232 const MCAsmLayout &Layout);
233
234 void WriteSymbolTable(MCDataFragment *F, const MCAssembler &Asm,
Rafael Espindola71859c62010-09-16 19:46:31 +0000235 const MCAsmLayout &Layout,
236 unsigned NumRegularSections);
Matt Fleming3565a062010-08-16 18:57:57 +0000237
238 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
239 const MCFragment *Fragment, const MCFixup &Fixup,
240 MCValue Target, uint64_t &FixedValue);
241
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000242 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
243 const MCSymbol *S);
Matt Fleming3565a062010-08-16 18:57:57 +0000244
245 /// ComputeSymbolTable - Compute the symbol table data
246 ///
247 /// \param StringTable [out] - The string table data.
248 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
249 /// string table.
250 void ComputeSymbolTable(MCAssembler &Asm);
251
252 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
253 const MCSectionData &SD);
254
255 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
256 for (MCAssembler::const_iterator it = Asm.begin(),
257 ie = Asm.end(); it != ie; ++it) {
258 WriteRelocation(Asm, Layout, *it);
259 }
260 }
261
262 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
263
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000264 void ExecutePostLayoutBinding(MCAssembler &Asm) {
265 // Compute symbol table information.
266 ComputeSymbolTable(Asm);
267 }
Matt Fleming3565a062010-08-16 18:57:57 +0000268
269 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
270 uint64_t Address, uint64_t Offset,
271 uint64_t Size, uint32_t Link, uint32_t Info,
272 uint64_t Alignment, uint64_t EntrySize);
273
274 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
275 const MCSectionData *SD);
276
Rafael Espindola70703872010-09-30 02:22:20 +0000277 bool IsFixupFullyResolved(const MCAssembler &Asm,
278 const MCValue Target,
279 bool IsPCRel,
280 const MCFragment *DF) const;
281
Matt Fleming3565a062010-08-16 18:57:57 +0000282 void WriteObject(const MCAssembler &Asm, const MCAsmLayout &Layout);
283 };
284
285}
286
287// Emit the ELF header.
288void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
289 unsigned NumberOfSections) {
290 // ELF Header
291 // ----------
292 //
293 // Note
294 // ----
295 // emitWord method behaves differently for ELF32 and ELF64, writing
296 // 4 bytes in the former and 8 in the latter.
297
298 Write8(0x7f); // e_ident[EI_MAG0]
299 Write8('E'); // e_ident[EI_MAG1]
300 Write8('L'); // e_ident[EI_MAG2]
301 Write8('F'); // e_ident[EI_MAG3]
302
303 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
304
305 // e_ident[EI_DATA]
306 Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
307
308 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky5baf79e2010-09-09 17:57:50 +0000309 // e_ident[EI_OSABI]
310 switch (OSType) {
311 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
312 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
313 default: Write8(ELF::ELFOSABI_NONE); break;
314 }
Matt Fleming3565a062010-08-16 18:57:57 +0000315 Write8(0); // e_ident[EI_ABIVERSION]
316
317 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
318
319 Write16(ELF::ET_REL); // e_type
320
321 // FIXME: Make this configurable
Benjamin Kramereb976772010-08-17 17:02:29 +0000322 Write16(Is64Bit ? ELF::EM_X86_64 : ELF::EM_386); // e_machine = target
Matt Fleming3565a062010-08-16 18:57:57 +0000323
324 Write32(ELF::EV_CURRENT); // e_version
325 WriteWord(0); // e_entry, no entry point in .o file
326 WriteWord(0); // e_phoff, no program header for .o
Benjamin Kramereb976772010-08-17 17:02:29 +0000327 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
328 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
Matt Fleming3565a062010-08-16 18:57:57 +0000329
330 // FIXME: Make this configurable.
331 Write32(0); // e_flags = whatever the target wants
332
333 // e_ehsize = ELF header size
334 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
335
336 Write16(0); // e_phentsize = prog header entry size
337 Write16(0); // e_phnum = # prog header entries = 0
338
339 // e_shentsize = Section header entry size
340 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
341
342 // e_shnum = # of section header ents
343 Write16(NumberOfSections);
344
345 // e_shstrndx = Section # of '.shstrtab'
346 Write16(ShstrtabIndex);
347}
348
349void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
350 uint8_t info, uint64_t value,
351 uint64_t size, uint8_t other,
352 uint16_t shndx) {
353 if (Is64Bit) {
354 char buf[8];
355
356 String32(buf, name);
357 F->getContents() += StringRef(buf, 4); // st_name
358
359 String8(buf, info);
360 F->getContents() += StringRef(buf, 1); // st_info
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000361
Matt Fleming3565a062010-08-16 18:57:57 +0000362 String8(buf, other);
363 F->getContents() += StringRef(buf, 1); // st_other
364
365 String16(buf, shndx);
366 F->getContents() += StringRef(buf, 2); // st_shndx
367
368 String64(buf, value);
369 F->getContents() += StringRef(buf, 8); // st_value
370
371 String64(buf, size);
372 F->getContents() += StringRef(buf, 8); // st_size
373 } else {
374 char buf[4];
375
376 String32(buf, name);
377 F->getContents() += StringRef(buf, 4); // st_name
378
379 String32(buf, value);
380 F->getContents() += StringRef(buf, 4); // st_value
381
382 String32(buf, size);
383 F->getContents() += StringRef(buf, 4); // st_size
384
385 String8(buf, info);
386 F->getContents() += StringRef(buf, 1); // st_info
387
388 String8(buf, other);
389 F->getContents() += StringRef(buf, 1); // st_other
390
391 String16(buf, shndx);
392 F->getContents() += StringRef(buf, 2); // st_shndx
393 }
394}
395
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000396static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
397 if (Data.isCommon() && Data.isExternal())
398 return Data.getCommonAlignment();
399
400 const MCSymbol &Symbol = Data.getSymbol();
401 if (!Symbol.isInSection())
402 return 0;
403
404 if (!Data.isCommon() && !(Data.getFlags() & ELF_STB_Weak))
405 if (MCFragment *FF = Data.getFragment())
406 return Layout.getSymbolAddress(&Data) -
407 Layout.getSectionAddress(FF->getParent());
408
409 return 0;
410}
411
Matt Fleming3565a062010-08-16 18:57:57 +0000412void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
413 const MCAsmLayout &Layout) {
414 MCSymbolData &Data = *MSD.SymbolData;
Matt Fleming3565a062010-08-16 18:57:57 +0000415 uint8_t Info = (Data.getFlags() & 0xff);
416 uint8_t Other = ((Data.getFlags() & 0xf00) >> ELF_STV_Shift);
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000417 uint64_t Value = SymbolValue(Data, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000418 uint64_t Size = 0;
419 const MCExpr *ESize;
420
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000421 assert(!(Data.isCommon() && !Data.isExternal()));
422
Matt Fleming3565a062010-08-16 18:57:57 +0000423 ESize = Data.getSize();
424 if (Data.getSize()) {
425 MCValue Res;
426 if (ESize->getKind() == MCExpr::Binary) {
427 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
428
429 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
430 MCSymbolData &A =
431 Layout.getAssembler().getSymbolData(Res.getSymA()->getSymbol());
432 MCSymbolData &B =
433 Layout.getAssembler().getSymbolData(Res.getSymB()->getSymbol());
434
435 Size = Layout.getSymbolAddress(&A) - Layout.getSymbolAddress(&B);
Matt Fleming3565a062010-08-16 18:57:57 +0000436 }
437 } else if (ESize->getKind() == MCExpr::Constant) {
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000438 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
Matt Fleming3565a062010-08-16 18:57:57 +0000439 } else {
440 assert(0 && "Unsupported size expression");
441 }
442 }
443
444 // Write out the symbol table entry
445 WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
446 Size, Other, MSD.SectionIndex);
447}
448
449void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
450 const MCAssembler &Asm,
Rafael Espindola71859c62010-09-16 19:46:31 +0000451 const MCAsmLayout &Layout,
452 unsigned NumRegularSections) {
Matt Fleming3565a062010-08-16 18:57:57 +0000453 // The string table must be emitted first because we need the index
454 // into the string table for all the symbol names.
455 assert(StringTable.size() && "Missing string table");
456
457 // FIXME: Make sure the start of the symbol table is aligned.
458
459 // The first entry is the undefined symbol entry.
460 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000461 F->getContents().append(EntrySize, '\x00');
Matt Fleming3565a062010-08-16 18:57:57 +0000462
463 // Write the symbol table entries.
464 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
465 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
466 ELFSymbolData &MSD = LocalSymbolData[i];
467 WriteSymbol(F, MSD, Layout);
468 }
469
Rafael Espindola71859c62010-09-16 19:46:31 +0000470 // Write out a symbol table entry for each regular section.
Eli Friedmana44fa242010-08-16 21:17:09 +0000471 unsigned Index = 1;
Rafael Espindola71859c62010-09-16 19:46:31 +0000472 for (MCAssembler::const_iterator it = Asm.begin();
473 Index <= NumRegularSections; ++it, ++Index) {
Eli Friedmana44fa242010-08-16 21:17:09 +0000474 const MCSectionELF &Section =
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000475 static_cast<const MCSectionELF&>(it->getSection());
Eli Friedmana44fa242010-08-16 21:17:09 +0000476 // Leave out relocations so we don't have indexes within
477 // the relocations messed up
Benjamin Kramer377a5722010-08-17 17:30:07 +0000478 if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
Eli Friedmana44fa242010-08-16 21:17:09 +0000479 continue;
Matt Fleming3565a062010-08-16 18:57:57 +0000480 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
Eli Friedmana44fa242010-08-16 21:17:09 +0000481 LastLocalSymbolIndex++;
482 }
Matt Fleming3565a062010-08-16 18:57:57 +0000483
484 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
485 ELFSymbolData &MSD = ExternalSymbolData[i];
486 MCSymbolData &Data = *MSD.SymbolData;
487 assert((Data.getFlags() & ELF_STB_Global) &&
488 "External symbol requires STB_GLOBAL flag");
489 WriteSymbol(F, MSD, Layout);
Rafael Espindolae15eb4e2010-09-23 19:55:14 +0000490 if (GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming3565a062010-08-16 18:57:57 +0000491 LastLocalSymbolIndex++;
492 }
493
494 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
495 ELFSymbolData &MSD = UndefinedSymbolData[i];
496 MCSymbolData &Data = *MSD.SymbolData;
Matt Fleming3565a062010-08-16 18:57:57 +0000497 WriteSymbol(F, MSD, Layout);
Rafael Espindolae15eb4e2010-09-23 19:55:14 +0000498 if (GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming3565a062010-08-16 18:57:57 +0000499 LastLocalSymbolIndex++;
500 }
501}
502
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000503static bool ShouldRelocOnSymbol(const MCSymbolData &SD,
504 const MCValue &Target) {
505 const MCSymbol &Symbol = SD.getSymbol();
506 if (Symbol.isUndefined())
507 return true;
Rafael Espindola73ffea42010-09-25 05:42:19 +0000508
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000509 const MCSectionELF &Section =
510 static_cast<const MCSectionELF&>(Symbol.getSection());
511
512 if (Section.getFlags() & MCSectionELF::SHF_MERGE)
513 return Target.getConstant() != 0;
514
515 if (SD.isExternal())
516 return true;
517
518 return false;
Rafael Espindola73ffea42010-09-25 05:42:19 +0000519}
520
Benjamin Kramere5b57342010-08-17 18:20:28 +0000521// FIXME: this is currently X86/X86_64 only
Matt Fleming3565a062010-08-16 18:57:57 +0000522void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
523 const MCAsmLayout &Layout,
524 const MCFragment *Fragment,
525 const MCFixup &Fixup,
526 MCValue Target,
527 uint64_t &FixedValue) {
Matt Fleming3565a062010-08-16 18:57:57 +0000528 int64_t Addend = 0;
529 unsigned Index = 0;
Benjamin Kramer95c602a2010-08-27 10:38:39 +0000530 int64_t Value = Target.getConstant();
Matt Fleming3565a062010-08-16 18:57:57 +0000531
Rafael Espindola00074892010-09-17 22:34:41 +0000532 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
Benjamin Kramer81cfb852010-08-17 19:45:05 +0000533 if (!Target.isAbsolute()) {
Matt Fleming3565a062010-08-16 18:57:57 +0000534 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
535 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000536 MCFragment *F = SD.getFragment();
Matt Fleming3565a062010-08-16 18:57:57 +0000537
Rafael Espindola9d8b7552010-10-03 00:46:57 +0000538 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
539 const MCSymbol &SymbolB = RefB->getSymbol();
540 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
541 IsPCRel = true;
Rafael Espindola55fb1022010-10-04 15:59:01 +0000542 MCSectionData *Sec = Fragment->getParent();
543
544 // Offset of the symbol in the section
545 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
546
547 // Ofeset of the relocation in the section
548 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
549 Value += b - a;
Rafael Espindola9d8b7552010-10-03 00:46:57 +0000550 }
551
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000552 // Check that this case has already been fully resolved before we get
553 // here.
Rafael Espindola00074892010-09-17 22:34:41 +0000554 if (Symbol->isDefined() && !SD.isExternal() &&
555 IsPCRel &&
556 &Fragment->getParent()->getSection() == &Symbol->getSection()) {
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000557 llvm_unreachable("We don't need a relocation in this case.");
Rafael Espindola00074892010-09-17 22:34:41 +0000558 return;
559 }
560
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000561 bool RelocOnSymbol = ShouldRelocOnSymbol(SD, Target);
562 if (!RelocOnSymbol) {
563 Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
Rafael Espindolaa6489182010-09-24 21:19:03 +0000564
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000565 MCSectionData *FSD = F->getParent();
566 // Offset of the symbol in the section
567 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
568 } else
569 Index = getSymbolIndexInSymbolTable(Asm, Symbol);
570 Addend = Value;
571 // Compensate for the addend on i386.
572 if (Is64Bit)
573 Value = 0;
Matt Fleming3565a062010-08-16 18:57:57 +0000574 }
575
Benjamin Kramer95c602a2010-08-27 10:38:39 +0000576 FixedValue = Value;
577
Matt Fleming3565a062010-08-16 18:57:57 +0000578 // determine the type of the relocation
Rafael Espindola28f9ac82010-10-04 18:44:25 +0000579
580 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000581 unsigned Type;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000582 if (Is64Bit) {
583 if (IsPCRel) {
584 Type = ELF::R_X86_64_PC32;
585 } else {
586 switch ((unsigned)Fixup.getKind()) {
587 default: llvm_unreachable("invalid fixup kind!");
588 case FK_Data_8: Type = ELF::R_X86_64_64; break;
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000589 case X86::reloc_signed_4byte:
Benjamin Kramere5b57342010-08-17 18:20:28 +0000590 case X86::reloc_pcrel_4byte:
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000591 assert(isInt<32>(Target.getConstant()));
Rafael Espindola28f9ac82010-10-04 18:44:25 +0000592 switch (Modifier) {
593 case MCSymbolRefExpr::VK_None:
594 Type = ELF::R_X86_64_32S;
595 break;
596 case MCSymbolRefExpr::VK_GOT:
597 Type = ELF::R_X86_64_GOT32;
598 break;
599 default:
600 llvm_unreachable("Unimplemented");
601 }
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000602 break;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000603 case FK_Data_4:
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000604 Type = ELF::R_X86_64_32;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000605 break;
606 case FK_Data_2: Type = ELF::R_X86_64_16; break;
607 case X86::reloc_pcrel_1byte:
608 case FK_Data_1: Type = ELF::R_X86_64_8; break;
609 }
610 }
Matt Fleming3565a062010-08-16 18:57:57 +0000611 } else {
Benjamin Kramere5b57342010-08-17 18:20:28 +0000612 if (IsPCRel) {
613 Type = ELF::R_386_PC32;
614 } else {
615 switch ((unsigned)Fixup.getKind()) {
616 default: llvm_unreachable("invalid fixup kind!");
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000617
618 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
619 // instead?
620 case X86::reloc_signed_4byte:
Benjamin Kramere5b57342010-08-17 18:20:28 +0000621 case X86::reloc_pcrel_4byte:
622 case FK_Data_4: Type = ELF::R_386_32; break;
623 case FK_Data_2: Type = ELF::R_386_16; break;
624 case X86::reloc_pcrel_1byte:
625 case FK_Data_1: Type = ELF::R_386_8; break;
626 }
Matt Fleming3565a062010-08-16 18:57:57 +0000627 }
628 }
629
Benjamin Kramere5b57342010-08-17 18:20:28 +0000630 ELFRelocationEntry ERE;
631
632 if (Is64Bit) {
633 struct ELF::Elf64_Rela ERE64;
634 ERE64.setSymbolAndType(Index, Type);
635 ERE.r_info = ERE64.r_info;
636 } else {
637 struct ELF::Elf32_Rela ERE32;
638 ERE32.setSymbolAndType(Index, Type);
639 ERE.r_info = ERE32.r_info;
640 }
Matt Fleming3565a062010-08-16 18:57:57 +0000641
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000642 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
Benjamin Kramere5b57342010-08-17 18:20:28 +0000643
Matt Fleming3565a062010-08-16 18:57:57 +0000644 if (HasRelocationAddend)
645 ERE.r_addend = Addend;
Benjamin Kramer172d7d62010-08-17 00:33:24 +0000646 else
647 ERE.r_addend = 0; // Silence compiler warning.
Matt Fleming3565a062010-08-16 18:57:57 +0000648
649 Relocations[Fragment->getParent()].push_back(ERE);
650}
651
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000652uint64_t
653ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
654 const MCSymbol *S) {
Benjamin Kramer7b83c262010-08-25 20:09:43 +0000655 MCSymbolData &SD = Asm.getSymbolData(*S);
Eli Friedmanf8020a32010-08-16 19:15:06 +0000656
Benjamin Kramer7b83c262010-08-25 20:09:43 +0000657 // Local symbol.
658 if (!SD.isExternal() && !S->isUndefined())
659 return SD.getIndex() + /* empty symbol */ 1;
660
661 // External or undefined symbol.
662 return SD.getIndex() + Asm.size() + /* empty symbol */ 1;
Matt Fleming3565a062010-08-16 18:57:57 +0000663}
664
665void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
666 // Build section lookup table.
667 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
668 unsigned Index = 1;
669 for (MCAssembler::iterator it = Asm.begin(),
670 ie = Asm.end(); it != ie; ++it, ++Index)
671 SectionIndexMap[&it->getSection()] = Index;
672
673 // Index 0 is always the empty string.
674 StringMap<uint64_t> StringIndexMap;
675 StringTable += '\x00';
676
677 // Add the data for local symbols.
678 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
679 ie = Asm.symbol_end(); it != ie; ++it) {
680 const MCSymbol &Symbol = it->getSymbol();
681
682 // Ignore non-linker visible symbols.
683 if (!Asm.isSymbolLinkerVisible(Symbol))
684 continue;
685
686 if (it->isExternal() || Symbol.isUndefined())
687 continue;
688
689 uint64_t &Entry = StringIndexMap[Symbol.getName()];
690 if (!Entry) {
691 Entry = StringTable.size();
692 StringTable += Symbol.getName();
693 StringTable += '\x00';
694 }
695
696 ELFSymbolData MSD;
697 MSD.SymbolData = it;
698 MSD.StringIndex = Entry;
699
700 if (Symbol.isAbsolute()) {
701 MSD.SectionIndex = ELF::SHN_ABS;
702 LocalSymbolData.push_back(MSD);
703 } else {
704 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
705 assert(MSD.SectionIndex && "Invalid section index!");
706 LocalSymbolData.push_back(MSD);
707 }
708 }
709
710 // Now add non-local symbols.
711 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
712 ie = Asm.symbol_end(); it != ie; ++it) {
713 const MCSymbol &Symbol = it->getSymbol();
714
715 // Ignore non-linker visible symbols.
Rafael Espindola53725bc2010-09-28 16:19:11 +0000716 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
Matt Fleming3565a062010-08-16 18:57:57 +0000717 continue;
718
719 if (!it->isExternal() && !Symbol.isUndefined())
720 continue;
721
Rafael Espindola53725bc2010-09-28 16:19:11 +0000722 if (Symbol.isVariable())
723 continue;
724
Matt Fleming3565a062010-08-16 18:57:57 +0000725 uint64_t &Entry = StringIndexMap[Symbol.getName()];
726 if (!Entry) {
727 Entry = StringTable.size();
728 StringTable += Symbol.getName();
729 StringTable += '\x00';
730 }
731
732 ELFSymbolData MSD;
733 MSD.SymbolData = it;
734 MSD.StringIndex = Entry;
735
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000736 if (it->isCommon()) {
737 MSD.SectionIndex = ELF::SHN_COMMON;
738 ExternalSymbolData.push_back(MSD);
739 } else if (Symbol.isUndefined()) {
Matt Fleming3565a062010-08-16 18:57:57 +0000740 MSD.SectionIndex = ELF::SHN_UNDEF;
Rafael Espindolae15eb4e2010-09-23 19:55:14 +0000741 // FIXME: Undefined symbols are global, but this is the first place we
742 // are able to set it.
743 if (GetBinding(*it) == ELF::STB_LOCAL)
744 SetBinding(*it, ELF::STB_GLOBAL);
Matt Fleming3565a062010-08-16 18:57:57 +0000745 UndefinedSymbolData.push_back(MSD);
746 } else if (Symbol.isAbsolute()) {
747 MSD.SectionIndex = ELF::SHN_ABS;
748 ExternalSymbolData.push_back(MSD);
Matt Fleming3565a062010-08-16 18:57:57 +0000749 } else {
750 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
751 assert(MSD.SectionIndex && "Invalid section index!");
752 ExternalSymbolData.push_back(MSD);
753 }
754 }
755
756 // Symbols are required to be in lexicographic order.
757 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
758 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
759 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
760
761 // Set the symbol indices. Local symbols must come before all other
762 // symbols with non-local bindings.
763 Index = 0;
764 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
765 LocalSymbolData[i].SymbolData->setIndex(Index++);
766 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
767 ExternalSymbolData[i].SymbolData->setIndex(Index++);
768 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
769 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
770}
771
772void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
773 const MCSectionData &SD) {
774 if (!Relocations[&SD].empty()) {
775 MCContext &Ctx = Asm.getContext();
776 const MCSection *RelaSection;
777 const MCSectionELF &Section =
778 static_cast<const MCSectionELF&>(SD.getSection());
779
780 const StringRef SectionName = Section.getSectionName();
Benjamin Kramer377a5722010-08-17 17:30:07 +0000781 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
Matt Fleming3565a062010-08-16 18:57:57 +0000782 RelaSectionName += SectionName;
Benjamin Kramer299fbe32010-08-17 17:56:13 +0000783
784 unsigned EntrySize;
785 if (HasRelocationAddend)
786 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
787 else
788 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming3565a062010-08-16 18:57:57 +0000789
Benjamin Kramer377a5722010-08-17 17:30:07 +0000790 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
791 ELF::SHT_RELA : ELF::SHT_REL, 0,
Matt Fleming3565a062010-08-16 18:57:57 +0000792 SectionKind::getReadOnly(),
793 false, EntrySize);
794
795 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000796 RelaSD.setAlignment(Is64Bit ? 8 : 4);
Matt Fleming3565a062010-08-16 18:57:57 +0000797
798 MCDataFragment *F = new MCDataFragment(&RelaSD);
799
800 WriteRelocationsFragment(Asm, F, &SD);
801
Rafael Espindola70703872010-09-30 02:22:20 +0000802 Asm.AddSectionToTheEnd(*Writer, RelaSD, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000803 }
804}
805
806void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
807 uint64_t Flags, uint64_t Address,
808 uint64_t Offset, uint64_t Size,
809 uint32_t Link, uint32_t Info,
810 uint64_t Alignment,
811 uint64_t EntrySize) {
812 Write32(Name); // sh_name: index into string table
813 Write32(Type); // sh_type
814 WriteWord(Flags); // sh_flags
815 WriteWord(Address); // sh_addr
816 WriteWord(Offset); // sh_offset
817 WriteWord(Size); // sh_size
818 Write32(Link); // sh_link
819 Write32(Info); // sh_info
820 WriteWord(Alignment); // sh_addralign
821 WriteWord(EntrySize); // sh_entsize
822}
823
824void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
825 MCDataFragment *F,
826 const MCSectionData *SD) {
827 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
828 // sort by the r_offset just like gnu as does
829 array_pod_sort(Relocs.begin(), Relocs.end());
830
831 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
832 ELFRelocationEntry entry = Relocs[e - i - 1];
833
Benjamin Kramer5e492e82010-09-09 18:01:29 +0000834 if (Is64Bit) {
835 char buf[8];
Matt Fleming3565a062010-08-16 18:57:57 +0000836
Benjamin Kramer5e492e82010-09-09 18:01:29 +0000837 String64(buf, entry.r_offset);
838 F->getContents() += StringRef(buf, 8);
839
840 String64(buf, entry.r_info);
841 F->getContents() += StringRef(buf, 8);
842
843 if (HasRelocationAddend) {
844 String64(buf, entry.r_addend);
845 F->getContents() += StringRef(buf, 8);
846 }
847 } else {
848 char buf[4];
849
850 String32(buf, entry.r_offset);
851 F->getContents() += StringRef(buf, 4);
852
853 String32(buf, entry.r_info);
854 F->getContents() += StringRef(buf, 4);
855
856 if (HasRelocationAddend) {
857 String32(buf, entry.r_addend);
858 F->getContents() += StringRef(buf, 4);
859 }
860 }
Matt Fleming3565a062010-08-16 18:57:57 +0000861 }
862}
863
864void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
865 MCAsmLayout &Layout) {
866 MCContext &Ctx = Asm.getContext();
867 MCDataFragment *F;
868
Matt Fleming3565a062010-08-16 18:57:57 +0000869 const MCSection *SymtabSection;
870 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
871
Rafael Espindola71859c62010-09-16 19:46:31 +0000872 unsigned NumRegularSections = Asm.size();
873
Rafael Espindola38738bf2010-09-22 19:04:41 +0000874 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola71859c62010-09-16 19:46:31 +0000875 const MCSection *ShstrtabSection;
876 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
877 SectionKind::getReadOnly(), false);
878 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
879 ShstrtabSD.setAlignment(1);
880 ShstrtabIndex = Asm.size();
881
Matt Fleming3565a062010-08-16 18:57:57 +0000882 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
883 SectionKind::getReadOnly(),
884 false, EntrySize);
Matt Fleming3565a062010-08-16 18:57:57 +0000885 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Matt Fleming3565a062010-08-16 18:57:57 +0000886 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
887
Matt Fleming3565a062010-08-16 18:57:57 +0000888 const MCSection *StrtabSection;
889 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
890 SectionKind::getReadOnly(), false);
Matt Fleming3565a062010-08-16 18:57:57 +0000891 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
892 StrtabSD.setAlignment(1);
Matt Fleming3565a062010-08-16 18:57:57 +0000893 StringTableIndex = Asm.size();
894
Rafael Espindolac3c413f2010-09-27 22:04:54 +0000895 WriteRelocations(Asm, Layout);
Rafael Espindola71859c62010-09-16 19:46:31 +0000896
897 // Symbol table
898 F = new MCDataFragment(&SymtabSD);
899 WriteSymbolTable(F, Asm, Layout, NumRegularSections);
Rafael Espindola70703872010-09-30 02:22:20 +0000900 Asm.AddSectionToTheEnd(*Writer, SymtabSD, Layout);
Rafael Espindola71859c62010-09-16 19:46:31 +0000901
Matt Fleming3565a062010-08-16 18:57:57 +0000902 F = new MCDataFragment(&StrtabSD);
903 F->getContents().append(StringTable.begin(), StringTable.end());
Rafael Espindola70703872010-09-30 02:22:20 +0000904 Asm.AddSectionToTheEnd(*Writer, StrtabSD, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000905
Matt Fleming3565a062010-08-16 18:57:57 +0000906 F = new MCDataFragment(&ShstrtabSD);
907
Matt Fleming3565a062010-08-16 18:57:57 +0000908 // Section header string table.
909 //
910 // The first entry of a string table holds a null character so skip
911 // section 0.
912 uint64_t Index = 1;
913 F->getContents() += '\x00';
914
915 for (MCAssembler::const_iterator it = Asm.begin(),
916 ie = Asm.end(); it != ie; ++it) {
Matt Fleming3565a062010-08-16 18:57:57 +0000917 const MCSectionELF &Section =
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000918 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola51efe7a2010-09-23 14:14:56 +0000919 // FIXME: We could merge suffixes like in .text and .rela.text.
Matt Fleming3565a062010-08-16 18:57:57 +0000920
921 // Remember the index into the string table so we can write it
922 // into the sh_name field of the section header table.
923 SectionStringTableIndex[&it->getSection()] = Index;
924
925 Index += Section.getSectionName().size() + 1;
926 F->getContents() += Section.getSectionName();
927 F->getContents() += '\x00';
928 }
929
Rafael Espindola70703872010-09-30 02:22:20 +0000930 Asm.AddSectionToTheEnd(*Writer, ShstrtabSD, Layout);
931}
932
933bool ELFObjectWriterImpl::IsFixupFullyResolved(const MCAssembler &Asm,
934 const MCValue Target,
935 bool IsPCRel,
936 const MCFragment *DF) const {
937 // If this is a PCrel relocation, find the section this fixup value is
938 // relative to.
939 const MCSection *BaseSection = 0;
940 if (IsPCRel) {
941 BaseSection = &DF->getParent()->getSection();
942 assert(BaseSection);
943 }
944
945 const MCSection *SectionA = 0;
946 const MCSymbol *SymbolA = 0;
947 if (const MCSymbolRefExpr *A = Target.getSymA()) {
948 SymbolA = &A->getSymbol();
949 SectionA = &SymbolA->getSection();
950 }
951
952 const MCSection *SectionB = 0;
953 if (const MCSymbolRefExpr *B = Target.getSymB()) {
954 SectionB = &B->getSymbol().getSection();
955 }
956
957 if (!BaseSection)
958 return SectionA == SectionB;
959
960 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
961 if (DataA.isExternal())
962 return false;
963
964 return !SectionB && BaseSection == SectionA;
Matt Fleming3565a062010-08-16 18:57:57 +0000965}
966
967void ELFObjectWriterImpl::WriteObject(const MCAssembler &Asm,
968 const MCAsmLayout &Layout) {
Matt Fleming3565a062010-08-16 18:57:57 +0000969 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
970 const_cast<MCAsmLayout&>(Layout));
971
972 // Add 1 for the null section.
973 unsigned NumSections = Asm.size() + 1;
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000974 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
975 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
976 uint64_t FileOff = HeaderSize;
Matt Fleming3565a062010-08-16 18:57:57 +0000977
978 for (MCAssembler::const_iterator it = Asm.begin(),
979 ie = Asm.end(); it != ie; ++it) {
980 const MCSectionData &SD = *it;
Matt Fleming3565a062010-08-16 18:57:57 +0000981
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000982 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
983
Matt Fleming3565a062010-08-16 18:57:57 +0000984 // Get the size of the section in the output file (including padding).
985 uint64_t Size = Layout.getSectionFileSize(&SD);
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000986
987 FileOff += Size;
Matt Fleming3565a062010-08-16 18:57:57 +0000988 }
989
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000990 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
991
Matt Fleming3565a062010-08-16 18:57:57 +0000992 // Write out the ELF header ...
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000993 WriteHeader(FileOff - HeaderSize, NumSections);
994
995 FileOff = HeaderSize;
Matt Fleming3565a062010-08-16 18:57:57 +0000996
997 // ... then all of the sections ...
998 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
999
Benjamin Kramer44cbde82010-08-19 13:44:49 +00001000 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
1001
1002 unsigned Index = 1;
Matt Fleming3565a062010-08-16 18:57:57 +00001003 for (MCAssembler::const_iterator it = Asm.begin(),
1004 ie = Asm.end(); it != ie; ++it) {
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001005 const MCSectionData &SD = *it;
1006
1007 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1008 WriteZeros(Padding);
1009 FileOff += Padding;
1010
Matt Fleming3565a062010-08-16 18:57:57 +00001011 // Remember the offset into the file for this section.
1012 SectionOffsetMap[&it->getSection()] = FileOff;
Benjamin Kramer44cbde82010-08-19 13:44:49 +00001013 SectionIndexMap[&it->getSection()] = Index++;
1014
Matt Fleming3565a062010-08-16 18:57:57 +00001015 FileOff += Layout.getSectionFileSize(&SD);
1016
1017 Asm.WriteSectionData(it, Layout, Writer);
1018 }
1019
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001020 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1021 WriteZeros(Padding);
1022 FileOff += Padding;
1023
Matt Fleming3565a062010-08-16 18:57:57 +00001024 // ... and then the section header table.
1025 // Should we align the section header table?
1026 //
1027 // Null section first.
1028 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1029
1030 for (MCAssembler::const_iterator it = Asm.begin(),
1031 ie = Asm.end(); it != ie; ++it) {
1032 const MCSectionData &SD = *it;
1033 const MCSectionELF &Section =
1034 static_cast<const MCSectionELF&>(SD.getSection());
1035
1036 uint64_t sh_link = 0;
1037 uint64_t sh_info = 0;
1038
1039 switch(Section.getType()) {
1040 case ELF::SHT_DYNAMIC:
1041 sh_link = SectionStringTableIndex[&it->getSection()];
1042 sh_info = 0;
1043 break;
1044
1045 case ELF::SHT_REL:
Eli Friedmanf8020a32010-08-16 19:15:06 +00001046 case ELF::SHT_RELA: {
Matt Fleming3565a062010-08-16 18:57:57 +00001047 const MCSection *SymtabSection;
1048 const MCSection *InfoSection;
Matt Fleming3565a062010-08-16 18:57:57 +00001049
1050 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1051 SectionKind::getReadOnly(),
Eli Friedmanf8020a32010-08-16 19:15:06 +00001052 false);
Benjamin Kramer44cbde82010-08-19 13:44:49 +00001053 sh_link = SectionIndexMap[SymtabSection];
Matt Fleming3565a062010-08-16 18:57:57 +00001054
Benjamin Kramer377a5722010-08-17 17:30:07 +00001055 // Remove ".rel" and ".rela" prefixes.
1056 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1057 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1058
Eli Friedmanf8020a32010-08-16 19:15:06 +00001059 InfoSection = Asm.getContext().getELFSection(SectionName,
Matt Fleming3565a062010-08-16 18:57:57 +00001060 ELF::SHT_PROGBITS, 0,
Eli Friedmanf8020a32010-08-16 19:15:06 +00001061 SectionKind::getReadOnly(),
1062 false);
Benjamin Kramer44cbde82010-08-19 13:44:49 +00001063 sh_info = SectionIndexMap[InfoSection];
Matt Fleming3565a062010-08-16 18:57:57 +00001064 break;
Eli Friedmanf8020a32010-08-16 19:15:06 +00001065 }
Matt Fleming3565a062010-08-16 18:57:57 +00001066
1067 case ELF::SHT_SYMTAB:
1068 case ELF::SHT_DYNSYM:
1069 sh_link = StringTableIndex;
1070 sh_info = LastLocalSymbolIndex;
1071 break;
1072
1073 case ELF::SHT_PROGBITS:
1074 case ELF::SHT_STRTAB:
1075 case ELF::SHT_NOBITS:
Benjamin Kramer19dc7fa2010-08-31 17:03:33 +00001076 case ELF::SHT_NULL:
Matt Fleming3565a062010-08-16 18:57:57 +00001077 // Nothing to do.
1078 break;
1079
1080 case ELF::SHT_HASH:
1081 case ELF::SHT_GROUP:
1082 case ELF::SHT_SYMTAB_SHNDX:
1083 default:
1084 assert(0 && "FIXME: sh_type value not supported!");
1085 break;
1086 }
1087
1088 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
1089 Section.getType(), Section.getFlags(),
Rafael Espindola71859c62010-09-16 19:46:31 +00001090 0,
Matt Fleming3565a062010-08-16 18:57:57 +00001091 SectionOffsetMap.lookup(&SD.getSection()),
1092 Layout.getSectionSize(&SD), sh_link,
1093 sh_info, SD.getAlignment(),
1094 Section.getEntrySize());
1095 }
1096}
1097
1098ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1099 bool Is64Bit,
Roman Divacky5baf79e2010-09-09 17:57:50 +00001100 Triple::OSType OSType,
Matt Fleming3565a062010-08-16 18:57:57 +00001101 bool IsLittleEndian,
1102 bool HasRelocationAddend)
1103 : MCObjectWriter(OS, IsLittleEndian)
1104{
Roman Divacky5baf79e2010-09-09 17:57:50 +00001105 Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend, OSType);
Matt Fleming3565a062010-08-16 18:57:57 +00001106}
1107
1108ELFObjectWriter::~ELFObjectWriter() {
1109 delete (ELFObjectWriterImpl*) Impl;
1110}
1111
1112void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1113 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1114}
1115
1116void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1117 const MCAsmLayout &Layout,
1118 const MCFragment *Fragment,
1119 const MCFixup &Fixup, MCValue Target,
1120 uint64_t &FixedValue) {
1121 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1122 Target, FixedValue);
1123}
1124
Rafael Espindola70703872010-09-30 02:22:20 +00001125bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1126 const MCValue Target,
1127 bool IsPCRel,
1128 const MCFragment *DF) const {
1129 return ((ELFObjectWriterImpl*) Impl)->IsFixupFullyResolved(Asm, Target,
1130 IsPCRel, DF);
1131}
1132
Matt Fleming3565a062010-08-16 18:57:57 +00001133void ELFObjectWriter::WriteObject(const MCAssembler &Asm,
1134 const MCAsmLayout &Layout) {
1135 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);
1136}