dd2419fa051c90394d5c7acc8c1dae7a79576b68
[oota-llvm.git] / lib / MC / ELFObjectWriter.cpp
1 //===- 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>
35 using namespace llvm;
36
37 namespace {
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         return SymbolData->getSymbol().getName() <
68                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     void String8(char *buf, uint8_t Value) {
144       buf[0] = Value;
145     }
146
147     void StringLE16(char *buf, uint16_t Value) {
148       buf[0] = char(Value >> 0);
149       buf[1] = char(Value >> 8);
150     }
151
152     void StringLE32(char *buf, uint32_t Value) {
153       StringLE16(buf, uint16_t(Value >> 0));
154       StringLE16(buf + 2, uint16_t(Value >> 16));
155     }
156
157     void StringLE64(char *buf, uint64_t Value) {
158       StringLE32(buf, uint32_t(Value >> 0));
159       StringLE32(buf + 4, uint32_t(Value >> 32));
160     }
161
162     void StringBE16(char *buf ,uint16_t Value) {
163       buf[0] = char(Value >> 8);
164       buf[1] = char(Value >> 0);
165     }
166
167     void StringBE32(char *buf, uint32_t Value) {
168       StringBE16(buf, uint16_t(Value >> 16));
169       StringBE16(buf + 2, uint16_t(Value >> 0));
170     }
171
172     void StringBE64(char *buf, uint64_t Value) {
173       StringBE32(buf, uint32_t(Value >> 32));
174       StringBE32(buf + 4, uint32_t(Value >> 0));
175     }
176
177     void String16(char *buf, uint16_t Value) {
178       if (Writer->isLittleEndian())
179         StringLE16(buf, Value);
180       else
181         StringBE16(buf, Value);
182     }
183
184     void String32(char *buf, uint32_t Value) {
185       if (Writer->isLittleEndian())
186         StringLE32(buf, Value);
187       else
188         StringBE32(buf, Value);
189     }
190
191     void String64(char *buf, uint64_t Value) {
192       if (Writer->isLittleEndian())
193         StringLE64(buf, Value);
194       else
195         StringBE64(buf, Value);
196     }
197
198     void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
199
200     void WriteSymbolEntry(MCDataFragment *F, uint64_t name, uint8_t info,
201                           uint64_t value, uint64_t size,
202                           uint8_t other, uint16_t shndx);
203
204     void WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
205                      const MCAsmLayout &Layout);
206
207     void WriteSymbolTable(MCDataFragment *F, const MCAssembler &Asm,
208                           const MCAsmLayout &Layout);
209
210     void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
211                           const MCFragment *Fragment, const MCFixup &Fixup,
212                           MCValue Target, uint64_t &FixedValue);
213
214     uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
215                                          const MCSymbol *S);
216
217     /// ComputeSymbolTable - Compute the symbol table data
218     ///
219     /// \param StringTable [out] - The string table data.
220     /// \param StringIndexMap [out] - Map from symbol names to offsets in the
221     /// string table.
222     void ComputeSymbolTable(MCAssembler &Asm);
223
224     void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
225                          const MCSectionData &SD);
226
227     void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
228       for (MCAssembler::const_iterator it = Asm.begin(),
229              ie = Asm.end(); it != ie; ++it) {
230         WriteRelocation(Asm, Layout, *it);
231       }
232     }
233
234     void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
235
236     void ExecutePostLayoutBinding(MCAssembler &Asm) {
237       // Compute symbol table information.
238       ComputeSymbolTable(Asm);
239     }
240
241     void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
242                           uint64_t Address, uint64_t Offset,
243                           uint64_t Size, uint32_t Link, uint32_t Info,
244                           uint64_t Alignment, uint64_t EntrySize);
245
246     void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
247                                   const MCSectionData *SD);
248
249     void WriteObject(const MCAssembler &Asm, const MCAsmLayout &Layout);
250   };
251
252 }
253
254 // Emit the ELF header.
255 void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
256                                       unsigned NumberOfSections) {
257   // ELF Header
258   // ----------
259   //
260   // Note
261   // ----
262   // emitWord method behaves differently for ELF32 and ELF64, writing
263   // 4 bytes in the former and 8 in the latter.
264
265   Write8(0x7f); // e_ident[EI_MAG0]
266   Write8('E');  // e_ident[EI_MAG1]
267   Write8('L');  // e_ident[EI_MAG2]
268   Write8('F');  // e_ident[EI_MAG3]
269
270   Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
271
272   // e_ident[EI_DATA]
273   Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
274
275   Write8(ELF::EV_CURRENT);        // e_ident[EI_VERSION]
276   Write8(ELF::ELFOSABI_LINUX);    // e_ident[EI_OSABI]
277   Write8(0);                  // e_ident[EI_ABIVERSION]
278
279   WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
280
281   Write16(ELF::ET_REL);             // e_type
282
283   // FIXME: Make this configurable
284   Write16(Is64Bit ? ELF::EM_X86_64 : ELF::EM_386); // e_machine = target
285
286   Write32(ELF::EV_CURRENT);         // e_version
287   WriteWord(0);                    // e_entry, no entry point in .o file
288   WriteWord(0);                    // e_phoff, no program header for .o
289   WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
290             sizeof(ELF::Elf32_Ehdr)));  // e_shoff = sec hdr table off in bytes
291
292   // FIXME: Make this configurable.
293   Write32(0);   // e_flags = whatever the target wants
294
295   // e_ehsize = ELF header size
296   Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
297
298   Write16(0);                  // e_phentsize = prog header entry size
299   Write16(0);                  // e_phnum = # prog header entries = 0
300
301   // e_shentsize = Section header entry size
302   Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
303
304   // e_shnum     = # of section header ents
305   Write16(NumberOfSections);
306
307   // e_shstrndx  = Section # of '.shstrtab'
308   Write16(ShstrtabIndex);
309 }
310
311 void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
312                                            uint8_t info, uint64_t value,
313                                            uint64_t size, uint8_t other,
314                                            uint16_t shndx) {
315   if (Is64Bit) {
316     char buf[8];
317
318     String32(buf, name);
319     F->getContents() += StringRef(buf, 4); // st_name
320
321     String8(buf, info);
322     F->getContents() += StringRef(buf, 1);  // st_info
323
324     String8(buf, other);
325     F->getContents() += StringRef(buf, 1); // st_other
326
327     String16(buf, shndx);
328     F->getContents() += StringRef(buf, 2); // st_shndx
329
330     String64(buf, value);
331     F->getContents() += StringRef(buf, 8); // st_value
332
333     String64(buf, size);
334     F->getContents() += StringRef(buf, 8);  // st_size
335   } else {
336     char buf[4];
337
338     String32(buf, name);
339     F->getContents() += StringRef(buf, 4);  // st_name
340
341     String32(buf, value);
342     F->getContents() += StringRef(buf, 4); // st_value
343
344     String32(buf, size);
345     F->getContents() += StringRef(buf, 4);  // st_size
346
347     String8(buf, info);
348     F->getContents() += StringRef(buf, 1);  // st_info
349
350     String8(buf, other);
351     F->getContents() += StringRef(buf, 1); // st_other
352
353     String16(buf, shndx);
354     F->getContents() += StringRef(buf, 2); // st_shndx
355   }
356 }
357
358 void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
359                                       const MCAsmLayout &Layout) {
360   MCSymbolData &Data = *MSD.SymbolData;
361   uint8_t Info = (Data.getFlags() & 0xff);
362   uint8_t Other = ((Data.getFlags() & 0xf00) >> ELF_STV_Shift);
363   uint64_t Value = 0;
364   uint64_t Size = 0;
365   const MCExpr *ESize;
366
367   if (Data.isCommon() && Data.isExternal())
368     Value = Data.getCommonAlignment();
369
370   ESize = Data.getSize();
371   if (Data.getSize()) {
372     MCValue Res;
373     if (ESize->getKind() == MCExpr::Binary) {
374       const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
375
376       if (BE->EvaluateAsRelocatable(Res, &Layout)) {
377         MCSymbolData &A =
378           Layout.getAssembler().getSymbolData(Res.getSymA()->getSymbol());
379         MCSymbolData &B =
380           Layout.getAssembler().getSymbolData(Res.getSymB()->getSymbol());
381
382         Size = Layout.getSymbolAddress(&A) - Layout.getSymbolAddress(&B);
383         Value = Layout.getSymbolAddress(&Data);
384       }
385     } else if (ESize->getKind() == MCExpr::Constant) {
386       Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
387       MCFragment *F = Data.getFragment();
388       Value = Layout.getSymbolAddress(&Data) - Layout.getSectionAddress(F->getParent());
389     } else {
390       assert(0 && "Unsupported size expression");
391     }
392   }
393
394   // Write out the symbol table entry
395   WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
396                    Size, Other, MSD.SectionIndex);
397 }
398
399 void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
400                                            const MCAssembler &Asm,
401                                            const MCAsmLayout &Layout) {
402   // The string table must be emitted first because we need the index
403   // into the string table for all the symbol names.
404   assert(StringTable.size() && "Missing string table");
405
406   // FIXME: Make sure the start of the symbol table is aligned.
407
408   // The first entry is the undefined symbol entry.
409   unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
410   F->getContents().append(EntrySize, '\x00');
411
412   // Write the symbol table entries.
413   LastLocalSymbolIndex = LocalSymbolData.size() + 1;
414   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
415     ELFSymbolData &MSD = LocalSymbolData[i];
416     WriteSymbol(F, MSD, Layout);
417   }
418
419   // Write out a symbol table entry for each section.
420   // leaving out the just added .symtab which is at
421   // the very end
422   unsigned Index = 1;
423   for (MCAssembler::const_iterator it = Asm.begin(),
424        ie = Asm.end(); it != ie; ++it, ++Index) {
425     const MCSectionELF &Section =
426       static_cast<const MCSectionELF&>(it->getSection());
427     // Leave out relocations so we don't have indexes within
428     // the relocations messed up
429     if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
430       continue;
431     if (Index == Asm.size())
432       continue;
433     WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
434     LastLocalSymbolIndex++;
435   }
436
437   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
438     ELFSymbolData &MSD = ExternalSymbolData[i];
439     MCSymbolData &Data = *MSD.SymbolData;
440     assert((Data.getFlags() & ELF_STB_Global) &&
441            "External symbol requires STB_GLOBAL flag");
442     WriteSymbol(F, MSD, Layout);
443     if (Data.getFlags() & ELF_STB_Local)
444       LastLocalSymbolIndex++;
445   }
446
447   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
448     ELFSymbolData &MSD = UndefinedSymbolData[i];
449     MCSymbolData &Data = *MSD.SymbolData;
450     Data.setFlags(Data.getFlags() | ELF_STB_Global);
451     WriteSymbol(F, MSD, Layout);
452     if (Data.getFlags() & ELF_STB_Local)
453       LastLocalSymbolIndex++;
454   }
455 }
456
457 // FIXME: this is currently X86/X86_64 only
458 void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
459                                            const MCAsmLayout &Layout,
460                                            const MCFragment *Fragment,
461                                            const MCFixup &Fixup,
462                                            MCValue Target,
463                                            uint64_t &FixedValue) {
464   int64_t Addend = 0;
465   unsigned Index = 0;
466   int64_t Value = Target.getConstant();
467
468   if (!Target.isAbsolute()) {
469     const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
470     MCSymbolData &SD = Asm.getSymbolData(*Symbol);
471     const MCSymbolData *Base = Asm.getAtom(Layout, &SD);
472     MCFragment *F = SD.getFragment();
473
474     if (Base) {
475       if (F && (!Symbol->isInSection() || SD.isCommon()) && !SD.isExternal()) {
476         Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
477         Value += Layout.getSymbolAddress(&SD);
478       } else
479         Index = getSymbolIndexInSymbolTable(Asm, Symbol);
480       if (Base != &SD)
481         Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
482       Addend = Value;
483       // Compensate for the addend on i386.
484       if (Is64Bit)
485         Value = 0;
486     } else {
487       if (F) {
488         // Index of the section in .symtab against this symbol
489         // is being relocated + 2 (empty section + abs. symbols).
490         Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
491
492         MCSectionData *FSD = F->getParent();
493         // Offset of the symbol in the section
494         Addend = Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
495       } else {
496         FixedValue = Value;
497         return;
498       }
499     }
500   }
501
502   FixedValue = Value;
503
504   // determine the type of the relocation
505   bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
506   unsigned Type;
507   if (Is64Bit) {
508     if (IsPCRel) {
509       Type = ELF::R_X86_64_PC32;
510     } else {
511       switch ((unsigned)Fixup.getKind()) {
512       default: llvm_unreachable("invalid fixup kind!");
513       case FK_Data_8: Type = ELF::R_X86_64_64; break;
514       case X86::reloc_pcrel_4byte:
515       case FK_Data_4:
516         // check that the offset fits within a signed long
517         if (isInt<32>(Target.getConstant()))
518           Type = ELF::R_X86_64_32S;
519         else
520           Type = ELF::R_X86_64_32;
521         break;
522       case FK_Data_2: Type = ELF::R_X86_64_16; break;
523       case X86::reloc_pcrel_1byte:
524       case FK_Data_1: Type = ELF::R_X86_64_8; break;
525       }
526     }
527   } else {
528     if (IsPCRel) {
529       Type = ELF::R_386_PC32;
530     } else {
531       switch ((unsigned)Fixup.getKind()) {
532       default: llvm_unreachable("invalid fixup kind!");
533       case X86::reloc_pcrel_4byte:
534       case FK_Data_4: Type = ELF::R_386_32; break;
535       case FK_Data_2: Type = ELF::R_386_16; break;
536       case X86::reloc_pcrel_1byte:
537       case FK_Data_1: Type = ELF::R_386_8; break;
538       }
539     }
540   }
541
542   ELFRelocationEntry ERE;
543
544   if (Is64Bit) {
545     struct ELF::Elf64_Rela ERE64;
546     ERE64.setSymbolAndType(Index, Type);
547     ERE.r_info = ERE64.r_info;
548   } else {
549     struct ELF::Elf32_Rela ERE32;
550     ERE32.setSymbolAndType(Index, Type);
551     ERE.r_info = ERE32.r_info;
552   }
553
554   ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
555
556   if (HasRelocationAddend)
557     ERE.r_addend = Addend;
558   else
559     ERE.r_addend = 0; // Silence compiler warning.
560
561   Relocations[Fragment->getParent()].push_back(ERE);
562 }
563
564 uint64_t
565 ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
566                                                  const MCSymbol *S) {
567   MCSymbolData &SD = Asm.getSymbolData(*S);
568
569   // Local symbol.
570   if (!SD.isExternal() && !S->isUndefined())
571     return SD.getIndex() + /* empty symbol */ 1;
572
573   // External or undefined symbol.
574   return SD.getIndex() + Asm.size() + /* empty symbol */ 1;
575 }
576
577 void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
578   // Build section lookup table.
579   DenseMap<const MCSection*, uint8_t> SectionIndexMap;
580   unsigned Index = 1;
581   for (MCAssembler::iterator it = Asm.begin(),
582          ie = Asm.end(); it != ie; ++it, ++Index)
583     SectionIndexMap[&it->getSection()] = Index;
584
585   // Index 0 is always the empty string.
586   StringMap<uint64_t> StringIndexMap;
587   StringTable += '\x00';
588
589   // Add the data for local symbols.
590   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
591          ie = Asm.symbol_end(); it != ie; ++it) {
592     const MCSymbol &Symbol = it->getSymbol();
593
594     // Ignore non-linker visible symbols.
595     if (!Asm.isSymbolLinkerVisible(Symbol))
596       continue;
597
598     if (it->isExternal() || Symbol.isUndefined())
599       continue;
600
601     uint64_t &Entry = StringIndexMap[Symbol.getName()];
602     if (!Entry) {
603       Entry = StringTable.size();
604       StringTable += Symbol.getName();
605       StringTable += '\x00';
606     }
607
608     ELFSymbolData MSD;
609     MSD.SymbolData = it;
610     MSD.StringIndex = Entry;
611
612     if (Symbol.isAbsolute()) {
613       MSD.SectionIndex = ELF::SHN_ABS;
614       LocalSymbolData.push_back(MSD);
615     } else {
616       MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
617       assert(MSD.SectionIndex && "Invalid section index!");
618       LocalSymbolData.push_back(MSD);
619     }
620   }
621
622   // Now add non-local symbols.
623   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
624          ie = Asm.symbol_end(); it != ie; ++it) {
625     const MCSymbol &Symbol = it->getSymbol();
626
627     // Ignore non-linker visible symbols.
628     if (!Asm.isSymbolLinkerVisible(Symbol))
629       continue;
630
631     if (!it->isExternal() && !Symbol.isUndefined())
632       continue;
633
634     uint64_t &Entry = StringIndexMap[Symbol.getName()];
635     if (!Entry) {
636       Entry = StringTable.size();
637       StringTable += Symbol.getName();
638       StringTable += '\x00';
639     }
640
641     ELFSymbolData MSD;
642     MSD.SymbolData = it;
643     MSD.StringIndex = Entry;
644
645     if (Symbol.isUndefined()) {
646       MSD.SectionIndex = ELF::SHN_UNDEF;
647       // XXX: for some reason we dont Emit* this
648       it->setFlags(it->getFlags() | ELF_STB_Global);
649       UndefinedSymbolData.push_back(MSD);
650     } else if (Symbol.isAbsolute()) {
651       MSD.SectionIndex = ELF::SHN_ABS;
652       ExternalSymbolData.push_back(MSD);
653     } else if (it->isCommon()) {
654       MSD.SectionIndex = ELF::SHN_COMMON;
655       ExternalSymbolData.push_back(MSD);
656     } else {
657       MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
658       assert(MSD.SectionIndex && "Invalid section index!");
659       ExternalSymbolData.push_back(MSD);
660     }
661   }
662
663   // Symbols are required to be in lexicographic order.
664   array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
665   array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
666   array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
667
668   // Set the symbol indices. Local symbols must come before all other
669   // symbols with non-local bindings.
670   Index = 0;
671   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
672     LocalSymbolData[i].SymbolData->setIndex(Index++);
673   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
674     ExternalSymbolData[i].SymbolData->setIndex(Index++);
675   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
676     UndefinedSymbolData[i].SymbolData->setIndex(Index++);
677 }
678
679 void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
680                                           const MCSectionData &SD) {
681   if (!Relocations[&SD].empty()) {
682     MCContext &Ctx = Asm.getContext();
683     const MCSection *RelaSection;
684     const MCSectionELF &Section =
685       static_cast<const MCSectionELF&>(SD.getSection());
686
687     const StringRef SectionName = Section.getSectionName();
688     std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
689     RelaSectionName += SectionName;
690
691     unsigned EntrySize;
692     if (HasRelocationAddend)
693       EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
694     else
695       EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
696
697     RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
698                                     ELF::SHT_RELA : ELF::SHT_REL, 0,
699                                     SectionKind::getReadOnly(),
700                                     false, EntrySize);
701
702     MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
703     RelaSD.setAlignment(1);
704
705     MCDataFragment *F = new MCDataFragment(&RelaSD);
706
707     WriteRelocationsFragment(Asm, F, &SD);
708
709     Asm.AddSectionToTheEnd(RelaSD, Layout);
710   }
711 }
712
713 void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
714                                            uint64_t Flags, uint64_t Address,
715                                            uint64_t Offset, uint64_t Size,
716                                            uint32_t Link, uint32_t Info,
717                                            uint64_t Alignment,
718                                            uint64_t EntrySize) {
719   Write32(Name);        // sh_name: index into string table
720   Write32(Type);        // sh_type
721   WriteWord(Flags);     // sh_flags
722   WriteWord(Address);   // sh_addr
723   WriteWord(Offset);    // sh_offset
724   WriteWord(Size);      // sh_size
725   Write32(Link);        // sh_link
726   Write32(Info);        // sh_info
727   WriteWord(Alignment); // sh_addralign
728   WriteWord(EntrySize); // sh_entsize
729 }
730
731 void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
732                                                    MCDataFragment *F,
733                                                    const MCSectionData *SD) {
734   std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
735   // sort by the r_offset just like gnu as does
736   array_pod_sort(Relocs.begin(), Relocs.end());
737
738   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
739     ELFRelocationEntry entry = Relocs[e - i - 1];
740
741     unsigned WordSize = Is64Bit ? 8 : 4;
742     F->getContents() += StringRef((const char *)&entry.r_offset, WordSize);
743     F->getContents() += StringRef((const char *)&entry.r_info, WordSize);
744
745     if (HasRelocationAddend)
746       F->getContents() += StringRef((const char *)&entry.r_addend, WordSize);
747   }
748 }
749
750 void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
751                                                  MCAsmLayout &Layout) {
752   MCContext &Ctx = Asm.getContext();
753   MCDataFragment *F;
754
755   WriteRelocations(Asm, Layout);
756
757   const MCSection *SymtabSection;
758   unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
759
760   SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
761                                     SectionKind::getReadOnly(),
762                                     false, EntrySize);
763
764   MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
765
766   SymtabSD.setAlignment(Is64Bit ? 8 : 4);
767
768   F = new MCDataFragment(&SymtabSD);
769
770   // Symbol table
771   WriteSymbolTable(F, Asm, Layout);
772   Asm.AddSectionToTheEnd(SymtabSD, Layout);
773
774   const MCSection *StrtabSection;
775   StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
776                                     SectionKind::getReadOnly(), false);
777
778   MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
779   StrtabSD.setAlignment(1);
780
781   // FIXME: This isn't right. If the sections get rearranged this will
782   // be wrong. We need a proper lookup.
783   StringTableIndex = Asm.size();
784
785   F = new MCDataFragment(&StrtabSD);
786   F->getContents().append(StringTable.begin(), StringTable.end());
787   Asm.AddSectionToTheEnd(StrtabSD, Layout);
788
789   const MCSection *ShstrtabSection;
790   ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
791                                       SectionKind::getReadOnly(), false);
792
793   MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
794   ShstrtabSD.setAlignment(1);
795
796   F = new MCDataFragment(&ShstrtabSD);
797
798   // FIXME: This isn't right. If the sections get rearranged this will
799   // be wrong. We need a proper lookup.
800   ShstrtabIndex = Asm.size();
801
802   // Section header string table.
803   //
804   // The first entry of a string table holds a null character so skip
805   // section 0.
806   uint64_t Index = 1;
807   F->getContents() += '\x00';
808
809   for (MCAssembler::const_iterator it = Asm.begin(),
810          ie = Asm.end(); it != ie; ++it) {
811     const MCSectionELF &Section =
812       static_cast<const MCSectionELF&>(it->getSection());
813
814     // Remember the index into the string table so we can write it
815     // into the sh_name field of the section header table.
816     SectionStringTableIndex[&it->getSection()] = Index;
817
818     Index += Section.getSectionName().size() + 1;
819     F->getContents() += Section.getSectionName();
820     F->getContents() += '\x00';
821   }
822
823   Asm.AddSectionToTheEnd(ShstrtabSD, Layout);
824 }
825
826 void ELFObjectWriterImpl::WriteObject(const MCAssembler &Asm,
827                                       const MCAsmLayout &Layout) {
828   CreateMetadataSections(const_cast<MCAssembler&>(Asm),
829                          const_cast<MCAsmLayout&>(Layout));
830
831   // Add 1 for the null section.
832   unsigned NumSections = Asm.size() + 1;
833
834   uint64_t SectionDataSize = 0;
835
836   for (MCAssembler::const_iterator it = Asm.begin(),
837          ie = Asm.end(); it != ie; ++it) {
838     const MCSectionData &SD = *it;
839
840     // Get the size of the section in the output file (including padding).
841     uint64_t Size = Layout.getSectionFileSize(&SD);
842     SectionDataSize += Size;
843   }
844
845   // Write out the ELF header ...
846   WriteHeader(SectionDataSize, NumSections);
847   FileOff = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
848
849   // ... then all of the sections ...
850   DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
851
852   DenseMap<const MCSection*, uint8_t> SectionIndexMap;
853
854   unsigned Index = 1;
855   for (MCAssembler::const_iterator it = Asm.begin(),
856          ie = Asm.end(); it != ie; ++it) {
857     // Remember the offset into the file for this section.
858     SectionOffsetMap[&it->getSection()] = FileOff;
859
860     SectionIndexMap[&it->getSection()] = Index++;
861
862     const MCSectionData &SD = *it;
863     FileOff += Layout.getSectionFileSize(&SD);
864
865     Asm.WriteSectionData(it, Layout, Writer);
866   }
867
868   // ... and then the section header table.
869   // Should we align the section header table?
870   //
871   // Null section first.
872   WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
873
874   for (MCAssembler::const_iterator it = Asm.begin(),
875          ie = Asm.end(); it != ie; ++it) {
876     const MCSectionData &SD = *it;
877     const MCSectionELF &Section =
878       static_cast<const MCSectionELF&>(SD.getSection());
879
880     uint64_t sh_link = 0;
881     uint64_t sh_info = 0;
882
883     switch(Section.getType()) {
884     case ELF::SHT_DYNAMIC:
885       sh_link = SectionStringTableIndex[&it->getSection()];
886       sh_info = 0;
887       break;
888
889     case ELF::SHT_REL:
890     case ELF::SHT_RELA: {
891       const MCSection *SymtabSection;
892       const MCSection *InfoSection;
893
894       SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
895                                                      SectionKind::getReadOnly(),
896                                                      false);
897       sh_link = SectionIndexMap[SymtabSection];
898
899       // Remove ".rel" and ".rela" prefixes.
900       unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
901       StringRef SectionName = Section.getSectionName().substr(SecNameLen);
902
903       InfoSection = Asm.getContext().getELFSection(SectionName,
904                                                    ELF::SHT_PROGBITS, 0,
905                                                    SectionKind::getReadOnly(),
906                                                    false);
907       sh_info = SectionIndexMap[InfoSection];
908       break;
909     }
910
911     case ELF::SHT_SYMTAB:
912     case ELF::SHT_DYNSYM:
913       sh_link = StringTableIndex;
914       sh_info = LastLocalSymbolIndex;
915       break;
916
917     case ELF::SHT_PROGBITS:
918     case ELF::SHT_STRTAB:
919     case ELF::SHT_NOBITS:
920       // Nothing to do.
921       break;
922
923     case ELF::SHT_HASH:
924     case ELF::SHT_GROUP:
925     case ELF::SHT_SYMTAB_SHNDX:
926     default:
927       assert(0 && "FIXME: sh_type value not supported!");
928       break;
929     }
930
931     WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
932                      Section.getType(), Section.getFlags(),
933                      Layout.getSectionAddress(&SD),
934                      SectionOffsetMap.lookup(&SD.getSection()),
935                      Layout.getSectionSize(&SD), sh_link,
936                      sh_info, SD.getAlignment(),
937                      Section.getEntrySize());
938   }
939 }
940
941 ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
942                                  bool Is64Bit,
943                                  bool IsLittleEndian,
944                                  bool HasRelocationAddend)
945   : MCObjectWriter(OS, IsLittleEndian)
946 {
947   Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend);
948 }
949
950 ELFObjectWriter::~ELFObjectWriter() {
951   delete (ELFObjectWriterImpl*) Impl;
952 }
953
954 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
955   ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
956 }
957
958 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
959                                        const MCAsmLayout &Layout,
960                                        const MCFragment *Fragment,
961                                        const MCFixup &Fixup, MCValue Target,
962                                        uint64_t &FixedValue) {
963   ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
964                                                   Target, FixedValue);
965 }
966
967 void ELFObjectWriter::WriteObject(const MCAssembler &Asm,
968                                   const MCAsmLayout &Layout) {
969   ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);
970 }