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