blob: 5f7ef1217d71042f60a3570cf7022b8cdba6131b [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
319 Write16(ELF::EM_X86_64); // e_machine = target
320
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
324 WriteWord(SectionDataSize + 64); // e_shoff = sec hdr table off in bytes
325
326 // FIXME: Make this configurable.
327 Write32(0); // e_flags = whatever the target wants
328
329 // e_ehsize = ELF header size
330 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
331
332 Write16(0); // e_phentsize = prog header entry size
333 Write16(0); // e_phnum = # prog header entries = 0
334
335 // e_shentsize = Section header entry size
336 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
337
338 // e_shnum = # of section header ents
339 Write16(NumberOfSections);
340
341 // e_shstrndx = Section # of '.shstrtab'
342 Write16(ShstrtabIndex);
343}
344
345void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
346 uint8_t info, uint64_t value,
347 uint64_t size, uint8_t other,
348 uint16_t shndx) {
349 if (Is64Bit) {
350 char buf[8];
351
352 String32(buf, name);
353 F->getContents() += StringRef(buf, 4); // st_name
354
355 String8(buf, info);
356 F->getContents() += StringRef(buf, 1); // st_info
357 String8(buf, other);
358 F->getContents() += StringRef(buf, 1); // st_other
359
360 String16(buf, shndx);
361 F->getContents() += StringRef(buf, 2); // st_shndx
362
363 String64(buf, value);
364 F->getContents() += StringRef(buf, 8); // st_value
365
366 String64(buf, size);
367 F->getContents() += StringRef(buf, 8); // st_size
368 } else {
369 char buf[4];
370
371 String32(buf, name);
372 F->getContents() += StringRef(buf, 4); // st_name
373
374 String32(buf, value);
375 F->getContents() += StringRef(buf, 4); // st_value
376
377 String32(buf, size);
378 F->getContents() += StringRef(buf, 4); // st_size
379
380 String8(buf, info);
381 F->getContents() += StringRef(buf, 1); // st_info
382
383 String8(buf, other);
384 F->getContents() += StringRef(buf, 1); // st_other
385
386 String16(buf, shndx);
387 F->getContents() += StringRef(buf, 2); // st_shndx
388 }
389}
390
391void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
392 const MCAsmLayout &Layout) {
393 MCSymbolData &Data = *MSD.SymbolData;
Matt Fleming3565a062010-08-16 18:57:57 +0000394 uint8_t Info = (Data.getFlags() & 0xff);
395 uint8_t Other = ((Data.getFlags() & 0xf00) >> ELF_STV_Shift);
396 uint64_t Value = 0;
397 uint64_t Size = 0;
398 const MCExpr *ESize;
399
400 if (Data.isCommon() && Data.isExternal())
401 Value = Data.getCommonAlignment();
402
403 ESize = Data.getSize();
404 if (Data.getSize()) {
405 MCValue Res;
406 if (ESize->getKind() == MCExpr::Binary) {
407 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
408
409 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
410 MCSymbolData &A =
411 Layout.getAssembler().getSymbolData(Res.getSymA()->getSymbol());
412 MCSymbolData &B =
413 Layout.getAssembler().getSymbolData(Res.getSymB()->getSymbol());
414
415 Size = Layout.getSymbolAddress(&A) - Layout.getSymbolAddress(&B);
416 Value = Layout.getSymbolAddress(&Data);
417 }
418 } else if (ESize->getKind() == MCExpr::Constant) {
419 const MCConstantExpr *CE;
420 CE = static_cast<const MCConstantExpr *>(ESize);
421 Size = CE->getValue();
422 } 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;
443 for (unsigned i = 0; i < EntrySize; ++i)
444 F->getContents() += '\x00';
445
446 // Write the symbol table entries.
447 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
448 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
449 ELFSymbolData &MSD = LocalSymbolData[i];
450 WriteSymbol(F, MSD, Layout);
451 }
452
453 // Write out a symbol table entry for each section.
Eli Friedmana44fa242010-08-16 21:17:09 +0000454 // leaving out the just added .symtab which is at
455 // the very end
456 unsigned Index = 1;
457 for (MCAssembler::const_iterator it = Asm.begin(),
458 ie = Asm.end(); it != ie; ++it, ++Index) {
459 const MCSectionData &SD = *it;
460 const MCSectionELF &Section =
461 static_cast<const MCSectionELF&>(SD.getSection());
462 // Leave out relocations so we don't have indexes within
463 // the relocations messed up
464 if (Section.getType() == ELF::SHT_RELA)
465 continue;
466 if (Index == Asm.size())
467 continue;
Matt Fleming3565a062010-08-16 18:57:57 +0000468 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
Eli Friedmana44fa242010-08-16 21:17:09 +0000469 LastLocalSymbolIndex++;
470 }
Matt Fleming3565a062010-08-16 18:57:57 +0000471
472 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
473 ELFSymbolData &MSD = ExternalSymbolData[i];
474 MCSymbolData &Data = *MSD.SymbolData;
475 assert((Data.getFlags() & ELF_STB_Global) &&
476 "External symbol requires STB_GLOBAL flag");
477 WriteSymbol(F, MSD, Layout);
478 if (Data.getFlags() & ELF_STB_Local)
479 LastLocalSymbolIndex++;
480 }
481
482 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
483 ELFSymbolData &MSD = UndefinedSymbolData[i];
484 MCSymbolData &Data = *MSD.SymbolData;
485 Data.setFlags(Data.getFlags() | ELF_STB_Global);
486 WriteSymbol(F, MSD, Layout);
487 if (Data.getFlags() & ELF_STB_Local)
488 LastLocalSymbolIndex++;
489 }
490}
491
492// FIXME: this is currently X86_64 only
493void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
494 const MCAsmLayout &Layout,
495 const MCFragment *Fragment,
496 const MCFixup &Fixup,
497 MCValue Target,
498 uint64_t &FixedValue) {
499 unsigned IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
500 ELFRelocationEntry ERE;
501 struct ELF::Elf64_Rela ERE64;
502
503 uint64_t FixupOffset =
504 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
505 int64_t Value;
506 int64_t Addend = 0;
507 unsigned Index = 0;
508 unsigned Type;
509
510 Value = Target.getConstant();
511
512 if (Target.isAbsolute()) {
513 Type = ELF::R_X86_64_NONE;
514 Index = 0;
515 } else {
516 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
517 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
518 const MCSymbolData *Base = Asm.getAtom(Layout, &SD);
519
520 if (Base) {
521 Index = getSymbolIndexInSymbolTable(const_cast<MCAssembler &>(Asm), &Base->getSymbol());
522 if (Base != &SD)
523 Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
524 Addend = Value;
525 Value = 0;
526 } else {
527 MCFragment *F = SD.getFragment();
528 if (F) {
529 // Index of the section in .symtab against this symbol
530 // is being relocated + 2 (empty section + abs. symbols).
531 Index = SD.getFragment()->getParent()->getOrdinal() +
532 getNumOfLocalSymbols(Asm) + 1;
533
534 MCSectionData *FSD = F->getParent();
535 // Offset of the symbol in the section
536 Addend = Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
537 } else {
538 FixedValue = Value;
539 return;
540 }
541 }
542 }
543
544 // determine the type of the relocation
545 if (IsPCRel) {
546 Type = ELF::R_X86_64_PC32;
547 } else {
548 switch (Fixup.getKind()) {
549 case FK_Data_8: Type = ELF::R_X86_64_64; break;
550 case X86::reloc_pcrel_4byte:
551 case FK_Data_4:
552 long Offset;
553 Offset = Target.getConstant();
554 // check that the offset fits within a signed long
555 if (!(((long) -1 << 31) & Offset) || (((long) -1 << 31) & Offset) == ((long) -1 << 31))
556 Type = ELF::R_X86_64_32S;
557 else
558 Type = ELF::R_X86_64_32;
559 break;
560 case FK_Data_2: Type = ELF::R_X86_64_16; break;
561 case X86::reloc_pcrel_1byte:
562 case FK_Data_1:
563 Type = ELF::R_X86_64_8;
564 break;
565 }
566 }
567
568 FixedValue = Value;
569
570 ERE64.setSymbolAndType(Index, Type);
571
572 ERE.r_offset = FixupOffset;
573 ERE.r_info = ERE64.r_info;
574 if (HasRelocationAddend)
575 ERE.r_addend = Addend;
576
577 Relocations[Fragment->getParent()].push_back(ERE);
578}
579
580// XXX-PERF: this should be cached
581uint64_t ELFObjectWriterImpl::getSymbolIndexInSymbolTable(MCAssembler &Asm,
582 const MCSymbol *S) {
583 std::vector<ELFSymbolData> Local;
584 std::vector<ELFSymbolData> External;
585 std::vector<ELFSymbolData> Undefined;
586
587 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
588 ie = Asm.symbol_end(); it != ie; ++it) {
589 const MCSymbol &Symbol = it->getSymbol();
590
591 // Ignore non-linker visible symbols.
592 if (!Asm.isSymbolLinkerVisible(Symbol))
593 continue;
594
595 if (it->isExternal() || Symbol.isUndefined())
596 continue;
597
598 ELFSymbolData MSD;
599 MSD.SymbolData = it;
600
601 Local.push_back(MSD);
602 }
603 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
604 ie = Asm.symbol_end(); it != ie; ++it) {
605 const MCSymbol &Symbol = it->getSymbol();
606
607 // Ignore non-linker visible symbols.
608 if (!Asm.isSymbolLinkerVisible(Symbol))
609 continue;
610
611 if (!it->isExternal() && !Symbol.isUndefined())
612 continue;
613
614 ELFSymbolData MSD;
615 MSD.SymbolData = it;
616
617 if (Symbol.isUndefined()) {
618 Undefined.push_back(MSD);
619 } else if (Symbol.isAbsolute()) {
620 External.push_back(MSD);
621 } else if (it->isCommon()) {
622 External.push_back(MSD);
623 } else {
624 External.push_back(MSD);
625 }
626 }
627
628 array_pod_sort(Local.begin(), Local.end());
629 array_pod_sort(External.begin(), External.end());
630 array_pod_sort(Undefined.begin(), Undefined.end());
631
632 for (unsigned i = 0, e = Local.size(); i != e; ++i)
633 if (&Local[i].SymbolData->getSymbol() == S)
634 return i + /* empty symbol */ 1;
635 for (unsigned i = 0, e = External.size(); i != e; ++i)
636 if (&External[i].SymbolData->getSymbol() == S)
Eli Friedmana44fa242010-08-16 21:17:09 +0000637 return i + Local.size() + Asm.size() + /* empty symbol */ 1;
Matt Fleming3565a062010-08-16 18:57:57 +0000638 for (unsigned i = 0, e = Undefined.size(); i != e; ++i)
639 if (&Undefined[i].SymbolData->getSymbol() == S)
Eli Friedmana44fa242010-08-16 21:17:09 +0000640 return i + Local.size() + External.size() + Asm.size() + /* empty symbol */ 1;
Eli Friedmanf8020a32010-08-16 19:15:06 +0000641
642 llvm_unreachable("Cannot find symbol which should exist!");
Matt Fleming3565a062010-08-16 18:57:57 +0000643}
644
645void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
646 // Build section lookup table.
647 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
648 unsigned Index = 1;
649 for (MCAssembler::iterator it = Asm.begin(),
650 ie = Asm.end(); it != ie; ++it, ++Index)
651 SectionIndexMap[&it->getSection()] = Index;
652
653 // Index 0 is always the empty string.
654 StringMap<uint64_t> StringIndexMap;
655 StringTable += '\x00';
656
657 // Add the data for local symbols.
658 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
659 ie = Asm.symbol_end(); it != ie; ++it) {
660 const MCSymbol &Symbol = it->getSymbol();
661
662 // Ignore non-linker visible symbols.
663 if (!Asm.isSymbolLinkerVisible(Symbol))
664 continue;
665
666 if (it->isExternal() || Symbol.isUndefined())
667 continue;
668
669 uint64_t &Entry = StringIndexMap[Symbol.getName()];
670 if (!Entry) {
671 Entry = StringTable.size();
672 StringTable += Symbol.getName();
673 StringTable += '\x00';
674 }
675
676 ELFSymbolData MSD;
677 MSD.SymbolData = it;
678 MSD.StringIndex = Entry;
679
680 if (Symbol.isAbsolute()) {
681 MSD.SectionIndex = ELF::SHN_ABS;
682 LocalSymbolData.push_back(MSD);
683 } else {
684 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
685 assert(MSD.SectionIndex && "Invalid section index!");
686 LocalSymbolData.push_back(MSD);
687 }
688 }
689
690 // Now add non-local symbols.
691 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
692 ie = Asm.symbol_end(); it != ie; ++it) {
693 const MCSymbol &Symbol = it->getSymbol();
694
695 // Ignore non-linker visible symbols.
696 if (!Asm.isSymbolLinkerVisible(Symbol))
697 continue;
698
699 if (!it->isExternal() && !Symbol.isUndefined())
700 continue;
701
702 uint64_t &Entry = StringIndexMap[Symbol.getName()];
703 if (!Entry) {
704 Entry = StringTable.size();
705 StringTable += Symbol.getName();
706 StringTable += '\x00';
707 }
708
709 ELFSymbolData MSD;
710 MSD.SymbolData = it;
711 MSD.StringIndex = Entry;
712
713 if (Symbol.isUndefined()) {
714 MSD.SectionIndex = ELF::SHN_UNDEF;
715 // XXX: for some reason we dont Emit* this
716 it->setFlags(it->getFlags() | ELF_STB_Global);
717 UndefinedSymbolData.push_back(MSD);
718 } else if (Symbol.isAbsolute()) {
719 MSD.SectionIndex = ELF::SHN_ABS;
720 ExternalSymbolData.push_back(MSD);
721 } else if (it->isCommon()) {
722 MSD.SectionIndex = ELF::SHN_COMMON;
723 ExternalSymbolData.push_back(MSD);
724 } else {
725 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
726 assert(MSD.SectionIndex && "Invalid section index!");
727 ExternalSymbolData.push_back(MSD);
728 }
729 }
730
731 // Symbols are required to be in lexicographic order.
732 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
733 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
734 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
735
736 // Set the symbol indices. Local symbols must come before all other
737 // symbols with non-local bindings.
738 Index = 0;
739 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
740 LocalSymbolData[i].SymbolData->setIndex(Index++);
741 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
742 ExternalSymbolData[i].SymbolData->setIndex(Index++);
743 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
744 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
745}
746
747void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
748 const MCSectionData &SD) {
749 if (!Relocations[&SD].empty()) {
750 MCContext &Ctx = Asm.getContext();
751 const MCSection *RelaSection;
752 const MCSectionELF &Section =
753 static_cast<const MCSectionELF&>(SD.getSection());
754
755 const StringRef SectionName = Section.getSectionName();
756 std::string RelaSectionName = ".rela";
757
758 RelaSectionName += SectionName;
759 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
760
761 RelaSection = Ctx.getELFSection(RelaSectionName, ELF::SHT_RELA, 0,
762 SectionKind::getReadOnly(),
763 false, EntrySize);
764
765 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
766 RelaSD.setAlignment(1);
767
768 MCDataFragment *F = new MCDataFragment(&RelaSD);
769
770 WriteRelocationsFragment(Asm, F, &SD);
771
772 Asm.AddSectionToTheEnd(RelaSD, Layout);
773 }
774}
775
776void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
777 uint64_t Flags, uint64_t Address,
778 uint64_t Offset, uint64_t Size,
779 uint32_t Link, uint32_t Info,
780 uint64_t Alignment,
781 uint64_t EntrySize) {
782 Write32(Name); // sh_name: index into string table
783 Write32(Type); // sh_type
784 WriteWord(Flags); // sh_flags
785 WriteWord(Address); // sh_addr
786 WriteWord(Offset); // sh_offset
787 WriteWord(Size); // sh_size
788 Write32(Link); // sh_link
789 Write32(Info); // sh_info
790 WriteWord(Alignment); // sh_addralign
791 WriteWord(EntrySize); // sh_entsize
792}
793
794void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
795 MCDataFragment *F,
796 const MCSectionData *SD) {
797 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
798 // sort by the r_offset just like gnu as does
799 array_pod_sort(Relocs.begin(), Relocs.end());
800
801 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
802 ELFRelocationEntry entry = Relocs[e - i - 1];
803
804 if (Is64Bit) {
805 F->getContents() += StringRef((const char *)&entry.r_offset, 8);
806 F->getContents() += StringRef((const char *)&entry.r_info, 8);
807
808 if (HasRelocationAddend)
809 F->getContents() += StringRef((const char *)&entry.r_addend, 8);
810 } else {
811 F->getContents() += StringRef((const char *)&entry.r_offset, 4);
812 F->getContents() += StringRef((const char *)&entry.r_info, 4);
813
814 if (HasRelocationAddend)
815 F->getContents() += StringRef((const char *)&entry.r_addend, 4);
816 }
817 }
818}
819
820void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
821 MCAsmLayout &Layout) {
822 MCContext &Ctx = Asm.getContext();
823 MCDataFragment *F;
824
825 WriteRelocations(Asm, Layout);
826
827 const MCSection *SymtabSection;
828 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
829
830 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
831 SectionKind::getReadOnly(),
832 false, EntrySize);
833
834 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
835
836 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
837
838 F = new MCDataFragment(&SymtabSD);
839
840 // Symbol table
841 WriteSymbolTable(F, Asm, Layout);
842 Asm.AddSectionToTheEnd(SymtabSD, Layout);
843
844 const MCSection *StrtabSection;
845 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
846 SectionKind::getReadOnly(), false);
847
848 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
849 StrtabSD.setAlignment(1);
850
851 // FIXME: This isn't right. If the sections get rearranged this will
852 // be wrong. We need a proper lookup.
853 StringTableIndex = Asm.size();
854
855 F = new MCDataFragment(&StrtabSD);
856 F->getContents().append(StringTable.begin(), StringTable.end());
857 Asm.AddSectionToTheEnd(StrtabSD, Layout);
858
859 const MCSection *ShstrtabSection;
860 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
861 SectionKind::getReadOnly(), false);
862
863 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
864 ShstrtabSD.setAlignment(1);
865
866 F = new MCDataFragment(&ShstrtabSD);
867
868 // FIXME: This isn't right. If the sections get rearranged this will
869 // be wrong. We need a proper lookup.
870 ShstrtabIndex = Asm.size();
871
872 // Section header string table.
873 //
874 // The first entry of a string table holds a null character so skip
875 // section 0.
876 uint64_t Index = 1;
877 F->getContents() += '\x00';
878
879 for (MCAssembler::const_iterator it = Asm.begin(),
880 ie = Asm.end(); it != ie; ++it) {
881 const MCSectionData &SD = *it;
882 const MCSectionELF &Section =
883 static_cast<const MCSectionELF&>(SD.getSection());
884
885
886 // Remember the index into the string table so we can write it
887 // into the sh_name field of the section header table.
888 SectionStringTableIndex[&it->getSection()] = Index;
889
890 Index += Section.getSectionName().size() + 1;
891 F->getContents() += Section.getSectionName();
892 F->getContents() += '\x00';
893 }
894
895 Asm.AddSectionToTheEnd(ShstrtabSD, Layout);
896}
897
898void ELFObjectWriterImpl::WriteObject(const MCAssembler &Asm,
899 const MCAsmLayout &Layout) {
900 // Compute symbol table information.
901 ComputeSymbolTable(const_cast<MCAssembler&>(Asm));
902
903 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
904 const_cast<MCAsmLayout&>(Layout));
905
906 // Add 1 for the null section.
907 unsigned NumSections = Asm.size() + 1;
908
909 uint64_t SectionDataSize = 0;
910
911 for (MCAssembler::const_iterator it = Asm.begin(),
912 ie = Asm.end(); it != ie; ++it) {
913 const MCSectionData &SD = *it;
Matt Fleming3565a062010-08-16 18:57:57 +0000914
915 // Get the size of the section in the output file (including padding).
916 uint64_t Size = Layout.getSectionFileSize(&SD);
917 SectionDataSize += Size;
918 }
919
920 // Write out the ELF header ...
921 WriteHeader(SectionDataSize, NumSections);
922 FileOff = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
923
924 // ... then all of the sections ...
925 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
926
927 for (MCAssembler::const_iterator it = Asm.begin(),
928 ie = Asm.end(); it != ie; ++it) {
929 // Remember the offset into the file for this section.
930 SectionOffsetMap[&it->getSection()] = FileOff;
931
932 const MCSectionData &SD = *it;
933 FileOff += Layout.getSectionFileSize(&SD);
934
935 Asm.WriteSectionData(it, Layout, Writer);
936 }
937
938 // ... and then the section header table.
939 // Should we align the section header table?
940 //
941 // Null section first.
942 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
943
944 for (MCAssembler::const_iterator it = Asm.begin(),
945 ie = Asm.end(); it != ie; ++it) {
946 const MCSectionData &SD = *it;
947 const MCSectionELF &Section =
948 static_cast<const MCSectionELF&>(SD.getSection());
949
950 uint64_t sh_link = 0;
951 uint64_t sh_info = 0;
952
953 switch(Section.getType()) {
954 case ELF::SHT_DYNAMIC:
955 sh_link = SectionStringTableIndex[&it->getSection()];
956 sh_info = 0;
957 break;
958
959 case ELF::SHT_REL:
Eli Friedmanf8020a32010-08-16 19:15:06 +0000960 case ELF::SHT_RELA: {
Matt Fleming3565a062010-08-16 18:57:57 +0000961 const MCSection *SymtabSection;
962 const MCSection *InfoSection;
Eli Friedmanf8020a32010-08-16 19:15:06 +0000963 StringRef SectionName;
Matt Fleming3565a062010-08-16 18:57:57 +0000964 const MCSectionData *SymtabSD;
965 const MCSectionData *InfoSD;
966
967 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
968 SectionKind::getReadOnly(),
Eli Friedmanf8020a32010-08-16 19:15:06 +0000969 false);
Matt Fleming3565a062010-08-16 18:57:57 +0000970 SymtabSD = &Asm.getSectionData(*SymtabSection);
971 // we have to count the empty section in too
972 sh_link = SymtabSD->getLayoutOrder() + 1;
973
Eli Friedmanf8020a32010-08-16 19:15:06 +0000974 SectionName = Section.getSectionName();
975 SectionName = SectionName.slice(5, SectionName.size());
976 InfoSection = Asm.getContext().getELFSection(SectionName,
Matt Fleming3565a062010-08-16 18:57:57 +0000977 ELF::SHT_PROGBITS, 0,
Eli Friedmanf8020a32010-08-16 19:15:06 +0000978 SectionKind::getReadOnly(),
979 false);
Matt Fleming3565a062010-08-16 18:57:57 +0000980 InfoSD = &Asm.getSectionData(*InfoSection);
981 sh_info = InfoSD->getLayoutOrder() + 1;
982 break;
Eli Friedmanf8020a32010-08-16 19:15:06 +0000983 }
Matt Fleming3565a062010-08-16 18:57:57 +0000984
985 case ELF::SHT_SYMTAB:
986 case ELF::SHT_DYNSYM:
987 sh_link = StringTableIndex;
988 sh_info = LastLocalSymbolIndex;
989 break;
990
991 case ELF::SHT_PROGBITS:
992 case ELF::SHT_STRTAB:
993 case ELF::SHT_NOBITS:
994 // Nothing to do.
995 break;
996
997 case ELF::SHT_HASH:
998 case ELF::SHT_GROUP:
999 case ELF::SHT_SYMTAB_SHNDX:
1000 default:
1001 assert(0 && "FIXME: sh_type value not supported!");
1002 break;
1003 }
1004
1005 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
1006 Section.getType(), Section.getFlags(),
1007 Layout.getSectionAddress(&SD),
1008 SectionOffsetMap.lookup(&SD.getSection()),
1009 Layout.getSectionSize(&SD), sh_link,
1010 sh_info, SD.getAlignment(),
1011 Section.getEntrySize());
1012 }
1013}
1014
1015ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1016 bool Is64Bit,
1017 bool IsLittleEndian,
1018 bool HasRelocationAddend)
1019 : MCObjectWriter(OS, IsLittleEndian)
1020{
1021 Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend);
1022}
1023
1024ELFObjectWriter::~ELFObjectWriter() {
1025 delete (ELFObjectWriterImpl*) Impl;
1026}
1027
1028void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1029 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1030}
1031
1032void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1033 const MCAsmLayout &Layout,
1034 const MCFragment *Fragment,
1035 const MCFixup &Fixup, MCValue Target,
1036 uint64_t &FixedValue) {
1037 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1038 Target, FixedValue);
1039}
1040
1041void ELFObjectWriter::WriteObject(const MCAssembler &Asm,
1042 const MCAsmLayout &Layout) {
1043 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);
1044}