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