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