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