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