blob: f4b68c4e481778722672d6bea4dcb322c7528c8c [file] [log] [blame]
Matt Fleming3565a062010-08-16 18:57:57 +00001//===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements ELF object file writer information.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/MC/ELFObjectWriter.h"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/StringMap.h"
17#include "llvm/ADT/Twine.h"
18#include "llvm/MC/MCAssembler.h"
19#include "llvm/MC/MCAsmLayout.h"
20#include "llvm/MC/MCContext.h"
21#include "llvm/MC/MCELFSymbolFlags.h"
22#include "llvm/MC/MCExpr.h"
23#include "llvm/MC/MCObjectWriter.h"
24#include "llvm/MC/MCSectionELF.h"
25#include "llvm/MC/MCSymbol.h"
26#include "llvm/MC/MCValue.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/ELF.h"
30#include "llvm/Target/TargetAsmBackend.h"
31
32#include "../Target/X86/X86FixupKinds.h"
33
34#include <vector>
35using namespace llvm;
36
37namespace {
38
39 class ELFObjectWriterImpl {
40 static bool isFixupKindX86PCRel(unsigned Kind) {
41 switch (Kind) {
42 default:
43 return false;
44 case X86::reloc_pcrel_1byte:
45 case X86::reloc_pcrel_4byte:
46 case X86::reloc_riprel_4byte:
47 case X86::reloc_riprel_4byte_movq_load:
48 return true;
49 }
50 }
51
52 static bool isFixupKindX86RIPRel(unsigned Kind) {
53 return Kind == X86::reloc_riprel_4byte ||
54 Kind == X86::reloc_riprel_4byte_movq_load;
55 }
56
57
58 /// ELFSymbolData - Helper struct for containing some precomputed information
59 /// on symbols.
60 struct ELFSymbolData {
61 MCSymbolData *SymbolData;
62 uint64_t StringIndex;
63 uint32_t SectionIndex;
64
65 // Support lexicographic sorting.
66 bool operator<(const ELFSymbolData &RHS) const {
67 const std::string &Name = SymbolData->getSymbol().getName();
68 return Name < RHS.SymbolData->getSymbol().getName();
69 }
70 };
71
72 /// @name Relocation Data
73 /// @{
74
75 struct ELFRelocationEntry {
76 // Make these big enough for both 32-bit and 64-bit
77 uint64_t r_offset;
78 uint64_t r_info;
79 uint64_t r_addend;
80
81 // Support lexicographic sorting.
82 bool operator<(const ELFRelocationEntry &RE) const {
83 return RE.r_offset < r_offset;
84 }
85 };
86
87 llvm::DenseMap<const MCSectionData*,
88 std::vector<ELFRelocationEntry> > Relocations;
89 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
90
91 /// @}
92 /// @name Symbol Table Data
93 /// @{
94
95 SmallString<256> StringTable;
96 std::vector<ELFSymbolData> LocalSymbolData;
97 std::vector<ELFSymbolData> ExternalSymbolData;
98 std::vector<ELFSymbolData> UndefinedSymbolData;
99
100 /// @}
101
102 ELFObjectWriter *Writer;
103
104 raw_ostream &OS;
105
106 // This holds the current offset into the object file.
107 size_t FileOff;
108
109 unsigned Is64Bit : 1;
110
111 bool HasRelocationAddend;
112
113 // This holds the symbol table index of the last local symbol.
114 unsigned LastLocalSymbolIndex;
115 // This holds the .strtab section index.
116 unsigned StringTableIndex;
117
118 unsigned ShstrtabIndex;
119
120 public:
121 ELFObjectWriterImpl(ELFObjectWriter *_Writer, bool _Is64Bit,
122 bool _HasRelAddend)
123 : Writer(_Writer), OS(Writer->getStream()), FileOff(0),
124 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend) {
125 }
126
127 void Write8(uint8_t Value) { Writer->Write8(Value); }
128 void Write16(uint16_t Value) { Writer->Write16(Value); }
129 void Write32(uint32_t Value) { Writer->Write32(Value); }
130 void Write64(uint64_t Value) { Writer->Write64(Value); }
131 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
132 void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
133 Writer->WriteBytes(Str, ZeroFillSize);
134 }
135
136 void WriteWord(uint64_t W) {
137 if (Is64Bit) {
138 Writer->Write64(W);
139 } else {
140 Writer->Write32(W);
141 }
142 }
143
144 void String8(char *buf, uint8_t Value) {
145 buf[0] = Value;
146 }
147
148 void StringLE16(char *buf, uint16_t Value) {
149 buf[0] = char(Value >> 0);
150 buf[1] = char(Value >> 8);
151 }
152
153 void StringLE32(char *buf, uint32_t Value) {
154 buf[0] = char(Value >> 0);
155 buf[1] = char(Value >> 8);
156 buf[2] = char(Value >> 16);
157 buf[3] = char(Value >> 24);
158 }
159
160 void StringLE64(char *buf, uint64_t Value) {
161 buf[0] = char(Value >> 0);
162 buf[1] = char(Value >> 8);
163 buf[2] = char(Value >> 16);
164 buf[3] = char(Value >> 24);
165 buf[4] = char(Value >> 32);
166 buf[5] = char(Value >> 40);
167 buf[6] = char(Value >> 48);
168 buf[7] = char(Value >> 56);
169 }
170
171 void StringBE16(char *buf ,uint16_t Value) {
172 buf[0] = char(Value >> 8);
173 buf[1] = char(Value >> 0);
174 }
175
176 void StringBE32(char *buf, uint32_t Value) {
177 buf[0] = char(Value >> 24);
178 buf[1] = char(Value >> 16);
179 buf[2] = char(Value >> 8);
180 buf[3] = char(Value >> 0);
181 }
182
183 void StringBE64(char *buf, uint64_t Value) {
184 buf[0] = char(Value >> 56);
185 buf[1] = char(Value >> 48);
186 buf[2] = char(Value >> 40);
187 buf[3] = char(Value >> 32);
188 buf[4] = char(Value >> 24);
189 buf[5] = char(Value >> 16);
190 buf[6] = char(Value >> 8);
191 buf[7] = char(Value >> 0);
192 }
193
194 void String16(char *buf, uint16_t Value) {
195 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000196 StringLE16(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000197 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000198 StringBE16(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000199 }
200
201 void String32(char *buf, uint32_t Value) {
202 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000203 StringLE32(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000204 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000205 StringBE32(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000206 }
207
208 void String64(char *buf, uint64_t Value) {
209 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000210 StringLE64(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000211 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000212 StringBE64(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000213 }
214
215 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
216
217 void WriteSymbolEntry(MCDataFragment *F, uint64_t name, uint8_t info,
218 uint64_t value, uint64_t size,
219 uint8_t other, uint16_t shndx);
220
221 void WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
222 const MCAsmLayout &Layout);
223
224 void WriteSymbolTable(MCDataFragment *F, const MCAssembler &Asm,
225 const MCAsmLayout &Layout);
226
227 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
228 const MCFragment *Fragment, const MCFixup &Fixup,
229 MCValue Target, uint64_t &FixedValue);
230
231 // XXX-PERF: this should be cached
232 uint64_t getNumOfLocalSymbols(const MCAssembler &Asm) {
233 std::vector<const MCSymbol*> Local;
234
235 uint64_t Index = 0;
236 for (MCAssembler::const_symbol_iterator it = Asm.symbol_begin(),
237 ie = Asm.symbol_end(); it != ie; ++it) {
238 const MCSymbol &Symbol = it->getSymbol();
239
240 // Ignore non-linker visible symbols.
241 if (!Asm.isSymbolLinkerVisible(Symbol))
242 continue;
243
244 if (it->isExternal() || Symbol.isUndefined())
245 continue;
246
247 Index++;
248 }
249
250 return Index;
251 }
252
253 uint64_t getSymbolIndexInSymbolTable(MCAssembler &Asm, const MCSymbol *S);
254
255 /// ComputeSymbolTable - Compute the symbol table data
256 ///
257 /// \param StringTable [out] - The string table data.
258 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
259 /// string table.
260 void ComputeSymbolTable(MCAssembler &Asm);
261
262 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
263 const MCSectionData &SD);
264
265 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
266 for (MCAssembler::const_iterator it = Asm.begin(),
267 ie = Asm.end(); it != ie; ++it) {
268 WriteRelocation(Asm, Layout, *it);
269 }
270 }
271
272 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
273
274 void ExecutePostLayoutBinding(MCAssembler &Asm) {}
275
276 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
277 uint64_t Address, uint64_t Offset,
278 uint64_t Size, uint32_t Link, uint32_t Info,
279 uint64_t Alignment, uint64_t EntrySize);
280
281 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
282 const MCSectionData *SD);
283
284 void WriteObject(const MCAssembler &Asm, const MCAsmLayout &Layout);
285 };
286
287}
288
289// Emit the ELF header.
290void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
291 unsigned NumberOfSections) {
292 // ELF Header
293 // ----------
294 //
295 // Note
296 // ----
297 // emitWord method behaves differently for ELF32 and ELF64, writing
298 // 4 bytes in the former and 8 in the latter.
299
300 Write8(0x7f); // e_ident[EI_MAG0]
301 Write8('E'); // e_ident[EI_MAG1]
302 Write8('L'); // e_ident[EI_MAG2]
303 Write8('F'); // e_ident[EI_MAG3]
304
305 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
306
307 // e_ident[EI_DATA]
308 Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
309
310 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
311 Write8(ELF::ELFOSABI_LINUX); // e_ident[EI_OSABI]
312 Write8(0); // e_ident[EI_ABIVERSION]
313
314 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
315
316 Write16(ELF::ET_REL); // e_type
317
318 // FIXME: Make this configurable
Benjamin Kramereb976772010-08-17 17:02:29 +0000319 Write16(Is64Bit ? ELF::EM_X86_64 : ELF::EM_386); // e_machine = target
Matt Fleming3565a062010-08-16 18:57:57 +0000320
321 Write32(ELF::EV_CURRENT); // e_version
322 WriteWord(0); // e_entry, no entry point in .o file
323 WriteWord(0); // e_phoff, no program header for .o
Benjamin Kramereb976772010-08-17 17:02:29 +0000324 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
325 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
Matt Fleming3565a062010-08-16 18:57:57 +0000326
327 // FIXME: Make this configurable.
328 Write32(0); // e_flags = whatever the target wants
329
330 // e_ehsize = ELF header size
331 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
332
333 Write16(0); // e_phentsize = prog header entry size
334 Write16(0); // e_phnum = # prog header entries = 0
335
336 // e_shentsize = Section header entry size
337 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
338
339 // e_shnum = # of section header ents
340 Write16(NumberOfSections);
341
342 // e_shstrndx = Section # of '.shstrtab'
343 Write16(ShstrtabIndex);
344}
345
346void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
347 uint8_t info, uint64_t value,
348 uint64_t size, uint8_t other,
349 uint16_t shndx) {
350 if (Is64Bit) {
351 char buf[8];
352
353 String32(buf, name);
354 F->getContents() += StringRef(buf, 4); // st_name
355
356 String8(buf, info);
357 F->getContents() += StringRef(buf, 1); // st_info
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000358
Matt Fleming3565a062010-08-16 18:57:57 +0000359 String8(buf, other);
360 F->getContents() += StringRef(buf, 1); // st_other
361
362 String16(buf, shndx);
363 F->getContents() += StringRef(buf, 2); // st_shndx
364
365 String64(buf, value);
366 F->getContents() += StringRef(buf, 8); // st_value
367
368 String64(buf, size);
369 F->getContents() += StringRef(buf, 8); // st_size
370 } else {
371 char buf[4];
372
373 String32(buf, name);
374 F->getContents() += StringRef(buf, 4); // st_name
375
376 String32(buf, value);
377 F->getContents() += StringRef(buf, 4); // st_value
378
379 String32(buf, size);
380 F->getContents() += StringRef(buf, 4); // st_size
381
382 String8(buf, info);
383 F->getContents() += StringRef(buf, 1); // st_info
384
385 String8(buf, other);
386 F->getContents() += StringRef(buf, 1); // st_other
387
388 String16(buf, shndx);
389 F->getContents() += StringRef(buf, 2); // st_shndx
390 }
391}
392
393void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
394 const MCAsmLayout &Layout) {
395 MCSymbolData &Data = *MSD.SymbolData;
Matt Fleming3565a062010-08-16 18:57:57 +0000396 uint8_t Info = (Data.getFlags() & 0xff);
397 uint8_t Other = ((Data.getFlags() & 0xf00) >> ELF_STV_Shift);
398 uint64_t Value = 0;
399 uint64_t Size = 0;
400 const MCExpr *ESize;
401
402 if (Data.isCommon() && Data.isExternal())
403 Value = Data.getCommonAlignment();
404
405 ESize = Data.getSize();
406 if (Data.getSize()) {
407 MCValue Res;
408 if (ESize->getKind() == MCExpr::Binary) {
409 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
410
411 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
412 MCSymbolData &A =
413 Layout.getAssembler().getSymbolData(Res.getSymA()->getSymbol());
414 MCSymbolData &B =
415 Layout.getAssembler().getSymbolData(Res.getSymB()->getSymbol());
416
417 Size = Layout.getSymbolAddress(&A) - Layout.getSymbolAddress(&B);
418 Value = Layout.getSymbolAddress(&Data);
419 }
420 } else if (ESize->getKind() == MCExpr::Constant) {
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000421 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
Matt Fleming3565a062010-08-16 18:57:57 +0000422 } else {
423 assert(0 && "Unsupported size expression");
424 }
425 }
426
427 // Write out the symbol table entry
428 WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
429 Size, Other, MSD.SectionIndex);
430}
431
432void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
433 const MCAssembler &Asm,
434 const MCAsmLayout &Layout) {
435 // The string table must be emitted first because we need the index
436 // into the string table for all the symbol names.
437 assert(StringTable.size() && "Missing string table");
438
439 // FIXME: Make sure the start of the symbol table is aligned.
440
441 // The first entry is the undefined symbol entry.
442 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000443 F->getContents().append(EntrySize, '\x00');
Matt Fleming3565a062010-08-16 18:57:57 +0000444
445 // Write the symbol table entries.
446 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
447 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
448 ELFSymbolData &MSD = LocalSymbolData[i];
449 WriteSymbol(F, MSD, Layout);
450 }
451
452 // Write out a symbol table entry for each section.
Eli Friedmana44fa242010-08-16 21:17:09 +0000453 // leaving out the just added .symtab which is at
454 // the very end
455 unsigned Index = 1;
456 for (MCAssembler::const_iterator it = Asm.begin(),
457 ie = Asm.end(); it != ie; ++it, ++Index) {
Eli Friedmana44fa242010-08-16 21:17:09 +0000458 const MCSectionELF &Section =
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000459 static_cast<const MCSectionELF&>(it->getSection());
Eli Friedmana44fa242010-08-16 21:17:09 +0000460 // Leave out relocations so we don't have indexes within
461 // the relocations messed up
Benjamin Kramer377a5722010-08-17 17:30:07 +0000462 if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
Eli Friedmana44fa242010-08-16 21:17:09 +0000463 continue;
464 if (Index == Asm.size())
465 continue;
Matt Fleming3565a062010-08-16 18:57:57 +0000466 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
Eli Friedmana44fa242010-08-16 21:17:09 +0000467 LastLocalSymbolIndex++;
468 }
Matt Fleming3565a062010-08-16 18:57:57 +0000469
470 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
471 ELFSymbolData &MSD = ExternalSymbolData[i];
472 MCSymbolData &Data = *MSD.SymbolData;
473 assert((Data.getFlags() & ELF_STB_Global) &&
474 "External symbol requires STB_GLOBAL flag");
475 WriteSymbol(F, MSD, Layout);
476 if (Data.getFlags() & ELF_STB_Local)
477 LastLocalSymbolIndex++;
478 }
479
480 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
481 ELFSymbolData &MSD = UndefinedSymbolData[i];
482 MCSymbolData &Data = *MSD.SymbolData;
483 Data.setFlags(Data.getFlags() | ELF_STB_Global);
484 WriteSymbol(F, MSD, Layout);
485 if (Data.getFlags() & ELF_STB_Local)
486 LastLocalSymbolIndex++;
487 }
488}
489
Benjamin Kramere5b57342010-08-17 18:20:28 +0000490// FIXME: this is currently X86/X86_64 only
Matt Fleming3565a062010-08-16 18:57:57 +0000491void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
492 const MCAsmLayout &Layout,
493 const MCFragment *Fragment,
494 const MCFixup &Fixup,
495 MCValue Target,
496 uint64_t &FixedValue) {
497 unsigned IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
Matt Fleming3565a062010-08-16 18:57:57 +0000498
499 uint64_t FixupOffset =
500 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
501 int64_t Value;
502 int64_t Addend = 0;
503 unsigned Index = 0;
504 unsigned Type;
505
506 Value = Target.getConstant();
507
Benjamin Kramer81cfb852010-08-17 19:45:05 +0000508 if (!Target.isAbsolute()) {
Matt Fleming3565a062010-08-16 18:57:57 +0000509 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
510 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
511 const MCSymbolData *Base = Asm.getAtom(Layout, &SD);
512
513 if (Base) {
514 Index = getSymbolIndexInSymbolTable(const_cast<MCAssembler &>(Asm), &Base->getSymbol());
515 if (Base != &SD)
516 Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
517 Addend = Value;
518 Value = 0;
519 } else {
520 MCFragment *F = SD.getFragment();
521 if (F) {
522 // Index of the section in .symtab against this symbol
523 // is being relocated + 2 (empty section + abs. symbols).
524 Index = SD.getFragment()->getParent()->getOrdinal() +
525 getNumOfLocalSymbols(Asm) + 1;
526
527 MCSectionData *FSD = F->getParent();
528 // Offset of the symbol in the section
529 Addend = Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
530 } else {
531 FixedValue = Value;
532 return;
533 }
534 }
535 }
536
537 // determine the type of the relocation
Benjamin Kramere5b57342010-08-17 18:20:28 +0000538 if (Is64Bit) {
539 if (IsPCRel) {
540 Type = ELF::R_X86_64_PC32;
541 } else {
542 switch ((unsigned)Fixup.getKind()) {
543 default: llvm_unreachable("invalid fixup kind!");
544 case FK_Data_8: Type = ELF::R_X86_64_64; break;
545 case X86::reloc_pcrel_4byte:
546 case FK_Data_4:
547 // check that the offset fits within a signed long
548 if (isInt<32>(Target.getConstant()))
549 Type = ELF::R_X86_64_32S;
550 else
551 Type = ELF::R_X86_64_32;
552 break;
553 case FK_Data_2: Type = ELF::R_X86_64_16; break;
554 case X86::reloc_pcrel_1byte:
555 case FK_Data_1: Type = ELF::R_X86_64_8; break;
556 }
557 }
Matt Fleming3565a062010-08-16 18:57:57 +0000558 } else {
Benjamin Kramere5b57342010-08-17 18:20:28 +0000559 if (IsPCRel) {
560 Type = ELF::R_386_PC32;
561 } else {
562 switch ((unsigned)Fixup.getKind()) {
563 default: llvm_unreachable("invalid fixup kind!");
564 case X86::reloc_pcrel_4byte:
565 case FK_Data_4: Type = ELF::R_386_32; break;
566 case FK_Data_2: Type = ELF::R_386_16; break;
567 case X86::reloc_pcrel_1byte:
568 case FK_Data_1: Type = ELF::R_386_8; break;
569 }
Matt Fleming3565a062010-08-16 18:57:57 +0000570 }
571 }
572
573 FixedValue = Value;
574
Benjamin Kramere5b57342010-08-17 18:20:28 +0000575 ELFRelocationEntry ERE;
576
577 if (Is64Bit) {
578 struct ELF::Elf64_Rela ERE64;
579 ERE64.setSymbolAndType(Index, Type);
580 ERE.r_info = ERE64.r_info;
581 } else {
582 struct ELF::Elf32_Rela ERE32;
583 ERE32.setSymbolAndType(Index, Type);
584 ERE.r_info = ERE32.r_info;
585 }
Matt Fleming3565a062010-08-16 18:57:57 +0000586
587 ERE.r_offset = FixupOffset;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000588
Matt Fleming3565a062010-08-16 18:57:57 +0000589 if (HasRelocationAddend)
590 ERE.r_addend = Addend;
Benjamin Kramer172d7d62010-08-17 00:33:24 +0000591 else
592 ERE.r_addend = 0; // Silence compiler warning.
Matt Fleming3565a062010-08-16 18:57:57 +0000593
594 Relocations[Fragment->getParent()].push_back(ERE);
595}
596
597// XXX-PERF: this should be cached
598uint64_t ELFObjectWriterImpl::getSymbolIndexInSymbolTable(MCAssembler &Asm,
599 const MCSymbol *S) {
600 std::vector<ELFSymbolData> Local;
601 std::vector<ELFSymbolData> External;
602 std::vector<ELFSymbolData> Undefined;
603
604 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
605 ie = Asm.symbol_end(); it != ie; ++it) {
606 const MCSymbol &Symbol = it->getSymbol();
607
608 // Ignore non-linker visible symbols.
609 if (!Asm.isSymbolLinkerVisible(Symbol))
610 continue;
611
612 if (it->isExternal() || Symbol.isUndefined())
613 continue;
614
615 ELFSymbolData MSD;
616 MSD.SymbolData = it;
617
618 Local.push_back(MSD);
619 }
620 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
621 ie = Asm.symbol_end(); it != ie; ++it) {
622 const MCSymbol &Symbol = it->getSymbol();
623
624 // Ignore non-linker visible symbols.
625 if (!Asm.isSymbolLinkerVisible(Symbol))
626 continue;
627
628 if (!it->isExternal() && !Symbol.isUndefined())
629 continue;
630
631 ELFSymbolData MSD;
632 MSD.SymbolData = it;
633
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000634 if (Symbol.isUndefined())
Matt Fleming3565a062010-08-16 18:57:57 +0000635 Undefined.push_back(MSD);
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000636 else
Matt Fleming3565a062010-08-16 18:57:57 +0000637 External.push_back(MSD);
Matt Fleming3565a062010-08-16 18:57:57 +0000638 }
639
640 array_pod_sort(Local.begin(), Local.end());
641 array_pod_sort(External.begin(), External.end());
642 array_pod_sort(Undefined.begin(), Undefined.end());
643
644 for (unsigned i = 0, e = Local.size(); i != e; ++i)
645 if (&Local[i].SymbolData->getSymbol() == S)
646 return i + /* empty symbol */ 1;
647 for (unsigned i = 0, e = External.size(); i != e; ++i)
648 if (&External[i].SymbolData->getSymbol() == S)
Eli Friedmana44fa242010-08-16 21:17:09 +0000649 return i + Local.size() + Asm.size() + /* empty symbol */ 1;
Matt Fleming3565a062010-08-16 18:57:57 +0000650 for (unsigned i = 0, e = Undefined.size(); i != e; ++i)
651 if (&Undefined[i].SymbolData->getSymbol() == S)
Eli Friedmana44fa242010-08-16 21:17:09 +0000652 return i + Local.size() + External.size() + Asm.size() + /* empty symbol */ 1;
Eli Friedmanf8020a32010-08-16 19:15:06 +0000653
654 llvm_unreachable("Cannot find symbol which should exist!");
Matt Fleming3565a062010-08-16 18:57:57 +0000655}
656
657void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
658 // Build section lookup table.
659 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
660 unsigned Index = 1;
661 for (MCAssembler::iterator it = Asm.begin(),
662 ie = Asm.end(); it != ie; ++it, ++Index)
663 SectionIndexMap[&it->getSection()] = Index;
664
665 // Index 0 is always the empty string.
666 StringMap<uint64_t> StringIndexMap;
667 StringTable += '\x00';
668
669 // Add the data for local symbols.
670 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
671 ie = Asm.symbol_end(); it != ie; ++it) {
672 const MCSymbol &Symbol = it->getSymbol();
673
674 // Ignore non-linker visible symbols.
675 if (!Asm.isSymbolLinkerVisible(Symbol))
676 continue;
677
678 if (it->isExternal() || Symbol.isUndefined())
679 continue;
680
681 uint64_t &Entry = StringIndexMap[Symbol.getName()];
682 if (!Entry) {
683 Entry = StringTable.size();
684 StringTable += Symbol.getName();
685 StringTable += '\x00';
686 }
687
688 ELFSymbolData MSD;
689 MSD.SymbolData = it;
690 MSD.StringIndex = Entry;
691
692 if (Symbol.isAbsolute()) {
693 MSD.SectionIndex = ELF::SHN_ABS;
694 LocalSymbolData.push_back(MSD);
695 } else {
696 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
697 assert(MSD.SectionIndex && "Invalid section index!");
698 LocalSymbolData.push_back(MSD);
699 }
700 }
701
702 // Now add non-local symbols.
703 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
704 ie = Asm.symbol_end(); it != ie; ++it) {
705 const MCSymbol &Symbol = it->getSymbol();
706
707 // Ignore non-linker visible symbols.
708 if (!Asm.isSymbolLinkerVisible(Symbol))
709 continue;
710
711 if (!it->isExternal() && !Symbol.isUndefined())
712 continue;
713
714 uint64_t &Entry = StringIndexMap[Symbol.getName()];
715 if (!Entry) {
716 Entry = StringTable.size();
717 StringTable += Symbol.getName();
718 StringTable += '\x00';
719 }
720
721 ELFSymbolData MSD;
722 MSD.SymbolData = it;
723 MSD.StringIndex = Entry;
724
725 if (Symbol.isUndefined()) {
726 MSD.SectionIndex = ELF::SHN_UNDEF;
727 // XXX: for some reason we dont Emit* this
728 it->setFlags(it->getFlags() | ELF_STB_Global);
729 UndefinedSymbolData.push_back(MSD);
730 } else if (Symbol.isAbsolute()) {
731 MSD.SectionIndex = ELF::SHN_ABS;
732 ExternalSymbolData.push_back(MSD);
733 } else if (it->isCommon()) {
734 MSD.SectionIndex = ELF::SHN_COMMON;
735 ExternalSymbolData.push_back(MSD);
736 } else {
737 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
738 assert(MSD.SectionIndex && "Invalid section index!");
739 ExternalSymbolData.push_back(MSD);
740 }
741 }
742
743 // Symbols are required to be in lexicographic order.
744 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
745 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
746 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
747
748 // Set the symbol indices. Local symbols must come before all other
749 // symbols with non-local bindings.
750 Index = 0;
751 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
752 LocalSymbolData[i].SymbolData->setIndex(Index++);
753 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
754 ExternalSymbolData[i].SymbolData->setIndex(Index++);
755 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
756 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
757}
758
759void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
760 const MCSectionData &SD) {
761 if (!Relocations[&SD].empty()) {
762 MCContext &Ctx = Asm.getContext();
763 const MCSection *RelaSection;
764 const MCSectionELF &Section =
765 static_cast<const MCSectionELF&>(SD.getSection());
766
767 const StringRef SectionName = Section.getSectionName();
Benjamin Kramer377a5722010-08-17 17:30:07 +0000768 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
Matt Fleming3565a062010-08-16 18:57:57 +0000769 RelaSectionName += SectionName;
Benjamin Kramer299fbe32010-08-17 17:56:13 +0000770
771 unsigned EntrySize;
772 if (HasRelocationAddend)
773 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
774 else
775 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming3565a062010-08-16 18:57:57 +0000776
Benjamin Kramer377a5722010-08-17 17:30:07 +0000777 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
778 ELF::SHT_RELA : ELF::SHT_REL, 0,
Matt Fleming3565a062010-08-16 18:57:57 +0000779 SectionKind::getReadOnly(),
780 false, EntrySize);
781
782 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
783 RelaSD.setAlignment(1);
784
785 MCDataFragment *F = new MCDataFragment(&RelaSD);
786
787 WriteRelocationsFragment(Asm, F, &SD);
788
789 Asm.AddSectionToTheEnd(RelaSD, Layout);
790 }
791}
792
793void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
794 uint64_t Flags, uint64_t Address,
795 uint64_t Offset, uint64_t Size,
796 uint32_t Link, uint32_t Info,
797 uint64_t Alignment,
798 uint64_t EntrySize) {
799 Write32(Name); // sh_name: index into string table
800 Write32(Type); // sh_type
801 WriteWord(Flags); // sh_flags
802 WriteWord(Address); // sh_addr
803 WriteWord(Offset); // sh_offset
804 WriteWord(Size); // sh_size
805 Write32(Link); // sh_link
806 Write32(Info); // sh_info
807 WriteWord(Alignment); // sh_addralign
808 WriteWord(EntrySize); // sh_entsize
809}
810
811void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
812 MCDataFragment *F,
813 const MCSectionData *SD) {
814 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
815 // sort by the r_offset just like gnu as does
816 array_pod_sort(Relocs.begin(), Relocs.end());
817
818 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
819 ELFRelocationEntry entry = Relocs[e - i - 1];
820
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000821 unsigned WordSize = Is64Bit ? 8 : 4;
822 F->getContents() += StringRef((const char *)&entry.r_offset, WordSize);
823 F->getContents() += StringRef((const char *)&entry.r_info, WordSize);
Matt Fleming3565a062010-08-16 18:57:57 +0000824
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000825 if (HasRelocationAddend)
826 F->getContents() += StringRef((const char *)&entry.r_addend, WordSize);
Matt Fleming3565a062010-08-16 18:57:57 +0000827 }
828}
829
830void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
831 MCAsmLayout &Layout) {
832 MCContext &Ctx = Asm.getContext();
833 MCDataFragment *F;
834
835 WriteRelocations(Asm, Layout);
836
837 const MCSection *SymtabSection;
838 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
839
840 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
841 SectionKind::getReadOnly(),
842 false, EntrySize);
843
844 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
845
846 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
847
848 F = new MCDataFragment(&SymtabSD);
849
850 // Symbol table
851 WriteSymbolTable(F, Asm, Layout);
852 Asm.AddSectionToTheEnd(SymtabSD, Layout);
853
854 const MCSection *StrtabSection;
855 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
856 SectionKind::getReadOnly(), false);
857
858 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
859 StrtabSD.setAlignment(1);
860
861 // FIXME: This isn't right. If the sections get rearranged this will
862 // be wrong. We need a proper lookup.
863 StringTableIndex = Asm.size();
864
865 F = new MCDataFragment(&StrtabSD);
866 F->getContents().append(StringTable.begin(), StringTable.end());
867 Asm.AddSectionToTheEnd(StrtabSD, Layout);
868
869 const MCSection *ShstrtabSection;
870 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
871 SectionKind::getReadOnly(), false);
872
873 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
874 ShstrtabSD.setAlignment(1);
875
876 F = new MCDataFragment(&ShstrtabSD);
877
878 // FIXME: This isn't right. If the sections get rearranged this will
879 // be wrong. We need a proper lookup.
880 ShstrtabIndex = Asm.size();
881
882 // Section header string table.
883 //
884 // The first entry of a string table holds a null character so skip
885 // section 0.
886 uint64_t Index = 1;
887 F->getContents() += '\x00';
888
889 for (MCAssembler::const_iterator it = Asm.begin(),
890 ie = Asm.end(); it != ie; ++it) {
Matt Fleming3565a062010-08-16 18:57:57 +0000891 const MCSectionELF &Section =
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000892 static_cast<const MCSectionELF&>(it->getSection());
Matt Fleming3565a062010-08-16 18:57:57 +0000893
894 // Remember the index into the string table so we can write it
895 // into the sh_name field of the section header table.
896 SectionStringTableIndex[&it->getSection()] = Index;
897
898 Index += Section.getSectionName().size() + 1;
899 F->getContents() += Section.getSectionName();
900 F->getContents() += '\x00';
901 }
902
903 Asm.AddSectionToTheEnd(ShstrtabSD, Layout);
904}
905
906void ELFObjectWriterImpl::WriteObject(const MCAssembler &Asm,
907 const MCAsmLayout &Layout) {
908 // Compute symbol table information.
909 ComputeSymbolTable(const_cast<MCAssembler&>(Asm));
910
911 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
912 const_cast<MCAsmLayout&>(Layout));
913
914 // Add 1 for the null section.
915 unsigned NumSections = Asm.size() + 1;
916
917 uint64_t SectionDataSize = 0;
918
919 for (MCAssembler::const_iterator it = Asm.begin(),
920 ie = Asm.end(); it != ie; ++it) {
921 const MCSectionData &SD = *it;
Matt Fleming3565a062010-08-16 18:57:57 +0000922
923 // Get the size of the section in the output file (including padding).
924 uint64_t Size = Layout.getSectionFileSize(&SD);
925 SectionDataSize += Size;
926 }
927
928 // Write out the ELF header ...
929 WriteHeader(SectionDataSize, NumSections);
930 FileOff = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
931
932 // ... then all of the sections ...
933 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
934
Benjamin Kramer44cbde82010-08-19 13:44:49 +0000935 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
936
937 unsigned Index = 1;
Matt Fleming3565a062010-08-16 18:57:57 +0000938 for (MCAssembler::const_iterator it = Asm.begin(),
939 ie = Asm.end(); it != ie; ++it) {
940 // Remember the offset into the file for this section.
941 SectionOffsetMap[&it->getSection()] = FileOff;
942
Benjamin Kramer44cbde82010-08-19 13:44:49 +0000943 SectionIndexMap[&it->getSection()] = Index++;
944
Matt Fleming3565a062010-08-16 18:57:57 +0000945 const MCSectionData &SD = *it;
946 FileOff += Layout.getSectionFileSize(&SD);
947
948 Asm.WriteSectionData(it, Layout, Writer);
949 }
950
951 // ... and then the section header table.
952 // Should we align the section header table?
953 //
954 // Null section first.
955 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
956
957 for (MCAssembler::const_iterator it = Asm.begin(),
958 ie = Asm.end(); it != ie; ++it) {
959 const MCSectionData &SD = *it;
960 const MCSectionELF &Section =
961 static_cast<const MCSectionELF&>(SD.getSection());
962
963 uint64_t sh_link = 0;
964 uint64_t sh_info = 0;
965
966 switch(Section.getType()) {
967 case ELF::SHT_DYNAMIC:
968 sh_link = SectionStringTableIndex[&it->getSection()];
969 sh_info = 0;
970 break;
971
972 case ELF::SHT_REL:
Eli Friedmanf8020a32010-08-16 19:15:06 +0000973 case ELF::SHT_RELA: {
Matt Fleming3565a062010-08-16 18:57:57 +0000974 const MCSection *SymtabSection;
975 const MCSection *InfoSection;
Matt Fleming3565a062010-08-16 18:57:57 +0000976
977 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
978 SectionKind::getReadOnly(),
Eli Friedmanf8020a32010-08-16 19:15:06 +0000979 false);
Benjamin Kramer44cbde82010-08-19 13:44:49 +0000980 sh_link = SectionIndexMap[SymtabSection];
Matt Fleming3565a062010-08-16 18:57:57 +0000981
Benjamin Kramer377a5722010-08-17 17:30:07 +0000982 // Remove ".rel" and ".rela" prefixes.
983 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
984 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
985
Eli Friedmanf8020a32010-08-16 19:15:06 +0000986 InfoSection = Asm.getContext().getELFSection(SectionName,
Matt Fleming3565a062010-08-16 18:57:57 +0000987 ELF::SHT_PROGBITS, 0,
Eli Friedmanf8020a32010-08-16 19:15:06 +0000988 SectionKind::getReadOnly(),
989 false);
Benjamin Kramer44cbde82010-08-19 13:44:49 +0000990 sh_info = SectionIndexMap[InfoSection];
Matt Fleming3565a062010-08-16 18:57:57 +0000991 break;
Eli Friedmanf8020a32010-08-16 19:15:06 +0000992 }
Matt Fleming3565a062010-08-16 18:57:57 +0000993
994 case ELF::SHT_SYMTAB:
995 case ELF::SHT_DYNSYM:
996 sh_link = StringTableIndex;
997 sh_info = LastLocalSymbolIndex;
998 break;
999
1000 case ELF::SHT_PROGBITS:
1001 case ELF::SHT_STRTAB:
1002 case ELF::SHT_NOBITS:
1003 // Nothing to do.
1004 break;
1005
1006 case ELF::SHT_HASH:
1007 case ELF::SHT_GROUP:
1008 case ELF::SHT_SYMTAB_SHNDX:
1009 default:
1010 assert(0 && "FIXME: sh_type value not supported!");
1011 break;
1012 }
1013
1014 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
1015 Section.getType(), Section.getFlags(),
1016 Layout.getSectionAddress(&SD),
1017 SectionOffsetMap.lookup(&SD.getSection()),
1018 Layout.getSectionSize(&SD), sh_link,
1019 sh_info, SD.getAlignment(),
1020 Section.getEntrySize());
1021 }
1022}
1023
1024ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1025 bool Is64Bit,
1026 bool IsLittleEndian,
1027 bool HasRelocationAddend)
1028 : MCObjectWriter(OS, IsLittleEndian)
1029{
1030 Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend);
1031}
1032
1033ELFObjectWriter::~ELFObjectWriter() {
1034 delete (ELFObjectWriterImpl*) Impl;
1035}
1036
1037void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1038 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1039}
1040
1041void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1042 const MCAsmLayout &Layout,
1043 const MCFragment *Fragment,
1044 const MCFixup &Fixup, MCValue Target,
1045 uint64_t &FixedValue) {
1046 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1047 Target, FixedValue);
1048}
1049
1050void ELFObjectWriter::WriteObject(const MCAssembler &Asm,
1051 const MCAsmLayout &Layout) {
1052 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);
1053}