blob: 9b399eb29eb503ed8b7e82ce33d6bab008b73a73 [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
490// FIXME: this is currently X86_64 only
491void 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());
498 ELFRelocationEntry ERE;
499 struct ELF::Elf64_Rela ERE64;
500
501 uint64_t FixupOffset =
502 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
503 int64_t Value;
504 int64_t Addend = 0;
505 unsigned Index = 0;
506 unsigned Type;
507
508 Value = Target.getConstant();
509
510 if (Target.isAbsolute()) {
511 Type = ELF::R_X86_64_NONE;
512 Index = 0;
513 } else {
514 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
515 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
516 const MCSymbolData *Base = Asm.getAtom(Layout, &SD);
517
518 if (Base) {
519 Index = getSymbolIndexInSymbolTable(const_cast<MCAssembler &>(Asm), &Base->getSymbol());
520 if (Base != &SD)
521 Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
522 Addend = Value;
523 Value = 0;
524 } else {
525 MCFragment *F = SD.getFragment();
526 if (F) {
527 // Index of the section in .symtab against this symbol
528 // is being relocated + 2 (empty section + abs. symbols).
529 Index = SD.getFragment()->getParent()->getOrdinal() +
530 getNumOfLocalSymbols(Asm) + 1;
531
532 MCSectionData *FSD = F->getParent();
533 // Offset of the symbol in the section
534 Addend = Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
535 } else {
536 FixedValue = Value;
537 return;
538 }
539 }
540 }
541
542 // determine the type of the relocation
543 if (IsPCRel) {
544 Type = ELF::R_X86_64_PC32;
545 } else {
Benjamin Kramer1f8aa7b2010-08-16 23:00:12 +0000546 switch ((unsigned)Fixup.getKind()) {
547 default: llvm_unreachable("invalid fixup kind!");
Matt Fleming3565a062010-08-16 18:57:57 +0000548 case FK_Data_8: Type = ELF::R_X86_64_64; break;
549 case X86::reloc_pcrel_4byte:
550 case FK_Data_4:
Matt Fleming3565a062010-08-16 18:57:57 +0000551 // check that the offset fits within a signed long
Benjamin Kramer1f8aa7b2010-08-16 23:00:12 +0000552 if (isInt<32>(Target.getConstant()))
Matt Fleming3565a062010-08-16 18:57:57 +0000553 Type = ELF::R_X86_64_32S;
554 else
555 Type = ELF::R_X86_64_32;
556 break;
557 case FK_Data_2: Type = ELF::R_X86_64_16; break;
558 case X86::reloc_pcrel_1byte:
559 case FK_Data_1:
560 Type = ELF::R_X86_64_8;
561 break;
562 }
563 }
564
565 FixedValue = Value;
566
567 ERE64.setSymbolAndType(Index, Type);
568
569 ERE.r_offset = FixupOffset;
570 ERE.r_info = ERE64.r_info;
571 if (HasRelocationAddend)
572 ERE.r_addend = Addend;
Benjamin Kramer172d7d62010-08-17 00:33:24 +0000573 else
574 ERE.r_addend = 0; // Silence compiler warning.
Matt Fleming3565a062010-08-16 18:57:57 +0000575
576 Relocations[Fragment->getParent()].push_back(ERE);
577}
578
579// XXX-PERF: this should be cached
580uint64_t ELFObjectWriterImpl::getSymbolIndexInSymbolTable(MCAssembler &Asm,
581 const MCSymbol *S) {
582 std::vector<ELFSymbolData> Local;
583 std::vector<ELFSymbolData> External;
584 std::vector<ELFSymbolData> Undefined;
585
586 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
587 ie = Asm.symbol_end(); it != ie; ++it) {
588 const MCSymbol &Symbol = it->getSymbol();
589
590 // Ignore non-linker visible symbols.
591 if (!Asm.isSymbolLinkerVisible(Symbol))
592 continue;
593
594 if (it->isExternal() || Symbol.isUndefined())
595 continue;
596
597 ELFSymbolData MSD;
598 MSD.SymbolData = it;
599
600 Local.push_back(MSD);
601 }
602 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
603 ie = Asm.symbol_end(); it != ie; ++it) {
604 const MCSymbol &Symbol = it->getSymbol();
605
606 // Ignore non-linker visible symbols.
607 if (!Asm.isSymbolLinkerVisible(Symbol))
608 continue;
609
610 if (!it->isExternal() && !Symbol.isUndefined())
611 continue;
612
613 ELFSymbolData MSD;
614 MSD.SymbolData = it;
615
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000616 if (Symbol.isUndefined())
Matt Fleming3565a062010-08-16 18:57:57 +0000617 Undefined.push_back(MSD);
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000618 else
Matt Fleming3565a062010-08-16 18:57:57 +0000619 External.push_back(MSD);
Matt Fleming3565a062010-08-16 18:57:57 +0000620 }
621
622 array_pod_sort(Local.begin(), Local.end());
623 array_pod_sort(External.begin(), External.end());
624 array_pod_sort(Undefined.begin(), Undefined.end());
625
626 for (unsigned i = 0, e = Local.size(); i != e; ++i)
627 if (&Local[i].SymbolData->getSymbol() == S)
628 return i + /* empty symbol */ 1;
629 for (unsigned i = 0, e = External.size(); i != e; ++i)
630 if (&External[i].SymbolData->getSymbol() == S)
Eli Friedmana44fa242010-08-16 21:17:09 +0000631 return i + Local.size() + Asm.size() + /* empty symbol */ 1;
Matt Fleming3565a062010-08-16 18:57:57 +0000632 for (unsigned i = 0, e = Undefined.size(); i != e; ++i)
633 if (&Undefined[i].SymbolData->getSymbol() == S)
Eli Friedmana44fa242010-08-16 21:17:09 +0000634 return i + Local.size() + External.size() + Asm.size() + /* empty symbol */ 1;
Eli Friedmanf8020a32010-08-16 19:15:06 +0000635
636 llvm_unreachable("Cannot find symbol which should exist!");
Matt Fleming3565a062010-08-16 18:57:57 +0000637}
638
639void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
640 // Build section lookup table.
641 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
642 unsigned Index = 1;
643 for (MCAssembler::iterator it = Asm.begin(),
644 ie = Asm.end(); it != ie; ++it, ++Index)
645 SectionIndexMap[&it->getSection()] = Index;
646
647 // Index 0 is always the empty string.
648 StringMap<uint64_t> StringIndexMap;
649 StringTable += '\x00';
650
651 // Add the data for local symbols.
652 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
653 ie = Asm.symbol_end(); it != ie; ++it) {
654 const MCSymbol &Symbol = it->getSymbol();
655
656 // Ignore non-linker visible symbols.
657 if (!Asm.isSymbolLinkerVisible(Symbol))
658 continue;
659
660 if (it->isExternal() || Symbol.isUndefined())
661 continue;
662
663 uint64_t &Entry = StringIndexMap[Symbol.getName()];
664 if (!Entry) {
665 Entry = StringTable.size();
666 StringTable += Symbol.getName();
667 StringTable += '\x00';
668 }
669
670 ELFSymbolData MSD;
671 MSD.SymbolData = it;
672 MSD.StringIndex = Entry;
673
674 if (Symbol.isAbsolute()) {
675 MSD.SectionIndex = ELF::SHN_ABS;
676 LocalSymbolData.push_back(MSD);
677 } else {
678 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
679 assert(MSD.SectionIndex && "Invalid section index!");
680 LocalSymbolData.push_back(MSD);
681 }
682 }
683
684 // Now add non-local symbols.
685 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
686 ie = Asm.symbol_end(); it != ie; ++it) {
687 const MCSymbol &Symbol = it->getSymbol();
688
689 // Ignore non-linker visible symbols.
690 if (!Asm.isSymbolLinkerVisible(Symbol))
691 continue;
692
693 if (!it->isExternal() && !Symbol.isUndefined())
694 continue;
695
696 uint64_t &Entry = StringIndexMap[Symbol.getName()];
697 if (!Entry) {
698 Entry = StringTable.size();
699 StringTable += Symbol.getName();
700 StringTable += '\x00';
701 }
702
703 ELFSymbolData MSD;
704 MSD.SymbolData = it;
705 MSD.StringIndex = Entry;
706
707 if (Symbol.isUndefined()) {
708 MSD.SectionIndex = ELF::SHN_UNDEF;
709 // XXX: for some reason we dont Emit* this
710 it->setFlags(it->getFlags() | ELF_STB_Global);
711 UndefinedSymbolData.push_back(MSD);
712 } else if (Symbol.isAbsolute()) {
713 MSD.SectionIndex = ELF::SHN_ABS;
714 ExternalSymbolData.push_back(MSD);
715 } else if (it->isCommon()) {
716 MSD.SectionIndex = ELF::SHN_COMMON;
717 ExternalSymbolData.push_back(MSD);
718 } else {
719 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
720 assert(MSD.SectionIndex && "Invalid section index!");
721 ExternalSymbolData.push_back(MSD);
722 }
723 }
724
725 // Symbols are required to be in lexicographic order.
726 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
727 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
728 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
729
730 // Set the symbol indices. Local symbols must come before all other
731 // symbols with non-local bindings.
732 Index = 0;
733 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
734 LocalSymbolData[i].SymbolData->setIndex(Index++);
735 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
736 ExternalSymbolData[i].SymbolData->setIndex(Index++);
737 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
738 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
739}
740
741void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
742 const MCSectionData &SD) {
743 if (!Relocations[&SD].empty()) {
744 MCContext &Ctx = Asm.getContext();
745 const MCSection *RelaSection;
746 const MCSectionELF &Section =
747 static_cast<const MCSectionELF&>(SD.getSection());
748
749 const StringRef SectionName = Section.getSectionName();
Benjamin Kramer377a5722010-08-17 17:30:07 +0000750 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
Matt Fleming3565a062010-08-16 18:57:57 +0000751
752 RelaSectionName += SectionName;
753 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
754
Benjamin Kramer377a5722010-08-17 17:30:07 +0000755 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
756 ELF::SHT_RELA : ELF::SHT_REL, 0,
Matt Fleming3565a062010-08-16 18:57:57 +0000757 SectionKind::getReadOnly(),
758 false, EntrySize);
759
760 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
761 RelaSD.setAlignment(1);
762
763 MCDataFragment *F = new MCDataFragment(&RelaSD);
764
765 WriteRelocationsFragment(Asm, F, &SD);
766
767 Asm.AddSectionToTheEnd(RelaSD, Layout);
768 }
769}
770
771void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
772 uint64_t Flags, uint64_t Address,
773 uint64_t Offset, uint64_t Size,
774 uint32_t Link, uint32_t Info,
775 uint64_t Alignment,
776 uint64_t EntrySize) {
777 Write32(Name); // sh_name: index into string table
778 Write32(Type); // sh_type
779 WriteWord(Flags); // sh_flags
780 WriteWord(Address); // sh_addr
781 WriteWord(Offset); // sh_offset
782 WriteWord(Size); // sh_size
783 Write32(Link); // sh_link
784 Write32(Info); // sh_info
785 WriteWord(Alignment); // sh_addralign
786 WriteWord(EntrySize); // sh_entsize
787}
788
789void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
790 MCDataFragment *F,
791 const MCSectionData *SD) {
792 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
793 // sort by the r_offset just like gnu as does
794 array_pod_sort(Relocs.begin(), Relocs.end());
795
796 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
797 ELFRelocationEntry entry = Relocs[e - i - 1];
798
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000799 unsigned WordSize = Is64Bit ? 8 : 4;
800 F->getContents() += StringRef((const char *)&entry.r_offset, WordSize);
801 F->getContents() += StringRef((const char *)&entry.r_info, WordSize);
Matt Fleming3565a062010-08-16 18:57:57 +0000802
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000803 if (HasRelocationAddend)
804 F->getContents() += StringRef((const char *)&entry.r_addend, WordSize);
Matt Fleming3565a062010-08-16 18:57:57 +0000805 }
806}
807
808void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
809 MCAsmLayout &Layout) {
810 MCContext &Ctx = Asm.getContext();
811 MCDataFragment *F;
812
813 WriteRelocations(Asm, Layout);
814
815 const MCSection *SymtabSection;
816 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
817
818 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
819 SectionKind::getReadOnly(),
820 false, EntrySize);
821
822 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
823
824 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
825
826 F = new MCDataFragment(&SymtabSD);
827
828 // Symbol table
829 WriteSymbolTable(F, Asm, Layout);
830 Asm.AddSectionToTheEnd(SymtabSD, Layout);
831
832 const MCSection *StrtabSection;
833 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
834 SectionKind::getReadOnly(), false);
835
836 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
837 StrtabSD.setAlignment(1);
838
839 // FIXME: This isn't right. If the sections get rearranged this will
840 // be wrong. We need a proper lookup.
841 StringTableIndex = Asm.size();
842
843 F = new MCDataFragment(&StrtabSD);
844 F->getContents().append(StringTable.begin(), StringTable.end());
845 Asm.AddSectionToTheEnd(StrtabSD, Layout);
846
847 const MCSection *ShstrtabSection;
848 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
849 SectionKind::getReadOnly(), false);
850
851 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
852 ShstrtabSD.setAlignment(1);
853
854 F = new MCDataFragment(&ShstrtabSD);
855
856 // FIXME: This isn't right. If the sections get rearranged this will
857 // be wrong. We need a proper lookup.
858 ShstrtabIndex = Asm.size();
859
860 // Section header string table.
861 //
862 // The first entry of a string table holds a null character so skip
863 // section 0.
864 uint64_t Index = 1;
865 F->getContents() += '\x00';
866
867 for (MCAssembler::const_iterator it = Asm.begin(),
868 ie = Asm.end(); it != ie; ++it) {
Matt Fleming3565a062010-08-16 18:57:57 +0000869 const MCSectionELF &Section =
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000870 static_cast<const MCSectionELF&>(it->getSection());
Matt Fleming3565a062010-08-16 18:57:57 +0000871
872 // Remember the index into the string table so we can write it
873 // into the sh_name field of the section header table.
874 SectionStringTableIndex[&it->getSection()] = Index;
875
876 Index += Section.getSectionName().size() + 1;
877 F->getContents() += Section.getSectionName();
878 F->getContents() += '\x00';
879 }
880
881 Asm.AddSectionToTheEnd(ShstrtabSD, Layout);
882}
883
884void ELFObjectWriterImpl::WriteObject(const MCAssembler &Asm,
885 const MCAsmLayout &Layout) {
886 // Compute symbol table information.
887 ComputeSymbolTable(const_cast<MCAssembler&>(Asm));
888
889 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
890 const_cast<MCAsmLayout&>(Layout));
891
892 // Add 1 for the null section.
893 unsigned NumSections = Asm.size() + 1;
894
895 uint64_t SectionDataSize = 0;
896
897 for (MCAssembler::const_iterator it = Asm.begin(),
898 ie = Asm.end(); it != ie; ++it) {
899 const MCSectionData &SD = *it;
Matt Fleming3565a062010-08-16 18:57:57 +0000900
901 // Get the size of the section in the output file (including padding).
902 uint64_t Size = Layout.getSectionFileSize(&SD);
903 SectionDataSize += Size;
904 }
905
906 // Write out the ELF header ...
907 WriteHeader(SectionDataSize, NumSections);
908 FileOff = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
909
910 // ... then all of the sections ...
911 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
912
913 for (MCAssembler::const_iterator it = Asm.begin(),
914 ie = Asm.end(); it != ie; ++it) {
915 // Remember the offset into the file for this section.
916 SectionOffsetMap[&it->getSection()] = FileOff;
917
918 const MCSectionData &SD = *it;
919 FileOff += Layout.getSectionFileSize(&SD);
920
921 Asm.WriteSectionData(it, Layout, Writer);
922 }
923
924 // ... and then the section header table.
925 // Should we align the section header table?
926 //
927 // Null section first.
928 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
929
930 for (MCAssembler::const_iterator it = Asm.begin(),
931 ie = Asm.end(); it != ie; ++it) {
932 const MCSectionData &SD = *it;
933 const MCSectionELF &Section =
934 static_cast<const MCSectionELF&>(SD.getSection());
935
936 uint64_t sh_link = 0;
937 uint64_t sh_info = 0;
938
939 switch(Section.getType()) {
940 case ELF::SHT_DYNAMIC:
941 sh_link = SectionStringTableIndex[&it->getSection()];
942 sh_info = 0;
943 break;
944
945 case ELF::SHT_REL:
Eli Friedmanf8020a32010-08-16 19:15:06 +0000946 case ELF::SHT_RELA: {
Matt Fleming3565a062010-08-16 18:57:57 +0000947 const MCSection *SymtabSection;
948 const MCSection *InfoSection;
Matt Fleming3565a062010-08-16 18:57:57 +0000949 const MCSectionData *SymtabSD;
950 const MCSectionData *InfoSD;
951
952 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
953 SectionKind::getReadOnly(),
Eli Friedmanf8020a32010-08-16 19:15:06 +0000954 false);
Matt Fleming3565a062010-08-16 18:57:57 +0000955 SymtabSD = &Asm.getSectionData(*SymtabSection);
956 // we have to count the empty section in too
957 sh_link = SymtabSD->getLayoutOrder() + 1;
958
Benjamin Kramer377a5722010-08-17 17:30:07 +0000959 // Remove ".rel" and ".rela" prefixes.
960 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
961 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
962
Eli Friedmanf8020a32010-08-16 19:15:06 +0000963 InfoSection = Asm.getContext().getELFSection(SectionName,
Matt Fleming3565a062010-08-16 18:57:57 +0000964 ELF::SHT_PROGBITS, 0,
Eli Friedmanf8020a32010-08-16 19:15:06 +0000965 SectionKind::getReadOnly(),
966 false);
Matt Fleming3565a062010-08-16 18:57:57 +0000967 InfoSD = &Asm.getSectionData(*InfoSection);
968 sh_info = InfoSD->getLayoutOrder() + 1;
969 break;
Eli Friedmanf8020a32010-08-16 19:15:06 +0000970 }
Matt Fleming3565a062010-08-16 18:57:57 +0000971
972 case ELF::SHT_SYMTAB:
973 case ELF::SHT_DYNSYM:
974 sh_link = StringTableIndex;
975 sh_info = LastLocalSymbolIndex;
976 break;
977
978 case ELF::SHT_PROGBITS:
979 case ELF::SHT_STRTAB:
980 case ELF::SHT_NOBITS:
981 // Nothing to do.
982 break;
983
984 case ELF::SHT_HASH:
985 case ELF::SHT_GROUP:
986 case ELF::SHT_SYMTAB_SHNDX:
987 default:
988 assert(0 && "FIXME: sh_type value not supported!");
989 break;
990 }
991
992 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
993 Section.getType(), Section.getFlags(),
994 Layout.getSectionAddress(&SD),
995 SectionOffsetMap.lookup(&SD.getSection()),
996 Layout.getSectionSize(&SD), sh_link,
997 sh_info, SD.getAlignment(),
998 Section.getEntrySize());
999 }
1000}
1001
1002ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1003 bool Is64Bit,
1004 bool IsLittleEndian,
1005 bool HasRelocationAddend)
1006 : MCObjectWriter(OS, IsLittleEndian)
1007{
1008 Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend);
1009}
1010
1011ELFObjectWriter::~ELFObjectWriter() {
1012 delete (ELFObjectWriterImpl*) Impl;
1013}
1014
1015void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1016 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1017}
1018
1019void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1020 const MCAsmLayout &Layout,
1021 const MCFragment *Fragment,
1022 const MCFixup &Fixup, MCValue Target,
1023 uint64_t &FixedValue) {
1024 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1025 Target, FixedValue);
1026}
1027
1028void ELFObjectWriter::WriteObject(const MCAssembler &Asm,
1029 const MCAsmLayout &Layout) {
1030 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);
1031}