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