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