5cffef03d3ae29c92826f95d24a8374a34f37c0f
[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/SmallPtrSet.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAssembler.h"
20 #include "llvm/MC/MCAsmLayout.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCELFSymbolFlags.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCObjectWriter.h"
25 #include "llvm/MC/MCSectionELF.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/MC/MCValue.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/ELF.h"
31 #include "llvm/Target/TargetAsmBackend.h"
32
33 #include "../Target/X86/X86FixupKinds.h"
34
35 #include <vector>
36 using namespace llvm;
37
38 static unsigned GetType(const MCSymbolData &SD) {
39   uint32_t Type = (SD.getFlags() & (0xf << ELF_STT_Shift)) >> ELF_STT_Shift;
40   assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
41          Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
42          Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
43          Type == ELF::STT_TLS);
44   return Type;
45 }
46
47 static unsigned GetBinding(const MCSymbolData &SD) {
48   uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
49   assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
50          Binding == ELF::STB_WEAK);
51   return Binding;
52 }
53
54 static void SetBinding(MCSymbolData &SD, unsigned Binding) {
55   assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
56          Binding == ELF::STB_WEAK);
57   uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
58   SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
59 }
60
61 static unsigned GetVisibility(MCSymbolData &SD) {
62   unsigned Visibility =
63     (SD.getFlags() & (0xf << ELF_STV_Shift)) >> ELF_STV_Shift;
64   assert(Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_INTERNAL ||
65          Visibility == ELF::STV_HIDDEN || Visibility == ELF::STV_PROTECTED);
66   return Visibility;
67 }
68
69 static bool isFixupKindX86PCRel(unsigned Kind) {
70   switch (Kind) {
71   default:
72     return false;
73   case X86::reloc_pcrel_1byte:
74   case X86::reloc_pcrel_4byte:
75   case X86::reloc_riprel_4byte:
76   case X86::reloc_riprel_4byte_movq_load:
77     return true;
78   }
79 }
80
81 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
82   switch (Variant) {
83   default:
84     return false;
85   case MCSymbolRefExpr::VK_GOT:
86   case MCSymbolRefExpr::VK_PLT:
87   case MCSymbolRefExpr::VK_GOTPCREL:
88   case MCSymbolRefExpr::VK_TPOFF:
89   case MCSymbolRefExpr::VK_TLSGD:
90   case MCSymbolRefExpr::VK_GOTTPOFF:
91   case MCSymbolRefExpr::VK_INDNTPOFF:
92   case MCSymbolRefExpr::VK_NTPOFF:
93   case MCSymbolRefExpr::VK_GOTNTPOFF:
94   case MCSymbolRefExpr::VK_TLSLDM:
95   case MCSymbolRefExpr::VK_DTPOFF:
96     return true;
97   }
98 }
99
100 namespace {
101
102   class ELFObjectWriterImpl {
103     /*static bool isFixupKindX86RIPRel(unsigned Kind) {
104       return Kind == X86::reloc_riprel_4byte ||
105         Kind == X86::reloc_riprel_4byte_movq_load;
106     }*/
107
108
109     /// ELFSymbolData - Helper struct for containing some precomputed information
110     /// on symbols.
111     struct ELFSymbolData {
112       MCSymbolData *SymbolData;
113       uint64_t StringIndex;
114       uint32_t SectionIndex;
115
116       // Support lexicographic sorting.
117       bool operator<(const ELFSymbolData &RHS) const {
118         if (GetType(*SymbolData) == ELF::STT_FILE)
119           return true;
120         if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
121           return false;
122         return SymbolData->getSymbol().getName() <
123                RHS.SymbolData->getSymbol().getName();
124       }
125     };
126
127     /// @name Relocation Data
128     /// @{
129
130     struct ELFRelocationEntry {
131       // Make these big enough for both 32-bit and 64-bit
132       uint64_t r_offset;
133       int Index;
134       unsigned Type;
135       const MCSymbol *Symbol;
136       uint64_t r_addend;
137
138       // Support lexicographic sorting.
139       bool operator<(const ELFRelocationEntry &RE) const {
140         return RE.r_offset < r_offset;
141       }
142     };
143
144     SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
145     DenseMap<const MCSymbol *, const MCSymbol *> Renames;
146
147     llvm::DenseMap<const MCSectionData*,
148                    std::vector<ELFRelocationEntry> > Relocations;
149     DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
150
151     /// @}
152     /// @name Symbol Table Data
153     /// @{
154
155     SmallString<256> StringTable;
156     std::vector<ELFSymbolData> LocalSymbolData;
157     std::vector<ELFSymbolData> ExternalSymbolData;
158     std::vector<ELFSymbolData> UndefinedSymbolData;
159
160     /// @}
161
162     int NumRegularSections;
163
164     bool NeedsGOT;
165
166     ELFObjectWriter *Writer;
167
168     raw_ostream &OS;
169
170     unsigned Is64Bit : 1;
171
172     bool HasRelocationAddend;
173
174     Triple::OSType OSType;
175
176     uint16_t EMachine;
177
178     // This holds the symbol table index of the last local symbol.
179     unsigned LastLocalSymbolIndex;
180     // This holds the .strtab section index.
181     unsigned StringTableIndex;
182
183     unsigned ShstrtabIndex;
184
185   public:
186     ELFObjectWriterImpl(ELFObjectWriter *_Writer, bool _Is64Bit,
187                         uint16_t _EMachine, bool _HasRelAddend,
188                         Triple::OSType _OSType)
189       : NeedsGOT(false), Writer(_Writer), OS(Writer->getStream()),
190         Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
191         OSType(_OSType), EMachine(_EMachine) {
192     }
193
194     void Write8(uint8_t Value) { Writer->Write8(Value); }
195     void Write16(uint16_t Value) { Writer->Write16(Value); }
196     void Write32(uint32_t Value) { Writer->Write32(Value); }
197     //void Write64(uint64_t Value) { Writer->Write64(Value); }
198     void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
199     //void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
200     //  Writer->WriteBytes(Str, ZeroFillSize);
201     //}
202
203     void WriteWord(uint64_t W) {
204       if (Is64Bit)
205         Writer->Write64(W);
206       else
207         Writer->Write32(W);
208     }
209
210     void String8(char *buf, uint8_t Value) {
211       buf[0] = Value;
212     }
213
214     void StringLE16(char *buf, uint16_t Value) {
215       buf[0] = char(Value >> 0);
216       buf[1] = char(Value >> 8);
217     }
218
219     void StringLE32(char *buf, uint32_t Value) {
220       StringLE16(buf, uint16_t(Value >> 0));
221       StringLE16(buf + 2, uint16_t(Value >> 16));
222     }
223
224     void StringLE64(char *buf, uint64_t Value) {
225       StringLE32(buf, uint32_t(Value >> 0));
226       StringLE32(buf + 4, uint32_t(Value >> 32));
227     }
228
229     void StringBE16(char *buf ,uint16_t Value) {
230       buf[0] = char(Value >> 8);
231       buf[1] = char(Value >> 0);
232     }
233
234     void StringBE32(char *buf, uint32_t Value) {
235       StringBE16(buf, uint16_t(Value >> 16));
236       StringBE16(buf + 2, uint16_t(Value >> 0));
237     }
238
239     void StringBE64(char *buf, uint64_t Value) {
240       StringBE32(buf, uint32_t(Value >> 32));
241       StringBE32(buf + 4, uint32_t(Value >> 0));
242     }
243
244     void String16(char *buf, uint16_t Value) {
245       if (Writer->isLittleEndian())
246         StringLE16(buf, Value);
247       else
248         StringBE16(buf, Value);
249     }
250
251     void String32(char *buf, uint32_t Value) {
252       if (Writer->isLittleEndian())
253         StringLE32(buf, Value);
254       else
255         StringBE32(buf, Value);
256     }
257
258     void String64(char *buf, uint64_t Value) {
259       if (Writer->isLittleEndian())
260         StringLE64(buf, Value);
261       else
262         StringBE64(buf, Value);
263     }
264
265     void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
266
267     void WriteSymbolEntry(MCDataFragment *F, uint64_t name, uint8_t info,
268                           uint64_t value, uint64_t size,
269                           uint8_t other, uint16_t shndx);
270
271     void WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
272                      const MCAsmLayout &Layout);
273
274     void WriteSymbolTable(MCDataFragment *F, const MCAssembler &Asm,
275                           const MCAsmLayout &Layout,
276                           unsigned NumRegularSections);
277
278     void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
279                           const MCFragment *Fragment, const MCFixup &Fixup,
280                           MCValue Target, uint64_t &FixedValue);
281
282     uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
283                                          const MCSymbol *S);
284
285     /// ComputeSymbolTable - Compute the symbol table data
286     ///
287     /// \param StringTable [out] - The string table data.
288     /// \param StringIndexMap [out] - Map from symbol names to offsets in the
289     /// string table.
290     void ComputeSymbolTable(MCAssembler &Asm);
291
292     void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
293                          const MCSectionData &SD);
294
295     void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
296       for (MCAssembler::const_iterator it = Asm.begin(),
297              ie = Asm.end(); it != ie; ++it) {
298         WriteRelocation(Asm, Layout, *it);
299       }
300     }
301
302     void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
303
304     void ExecutePostLayoutBinding(MCAssembler &Asm);
305
306     void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
307                           uint64_t Address, uint64_t Offset,
308                           uint64_t Size, uint32_t Link, uint32_t Info,
309                           uint64_t Alignment, uint64_t EntrySize);
310
311     void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
312                                   const MCSectionData *SD);
313
314     bool IsFixupFullyResolved(const MCAssembler &Asm,
315                               const MCValue Target,
316                               bool IsPCRel,
317                               const MCFragment *DF) const;
318
319     void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
320   };
321
322 }
323
324 // Emit the ELF header.
325 void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
326                                       unsigned NumberOfSections) {
327   // ELF Header
328   // ----------
329   //
330   // Note
331   // ----
332   // emitWord method behaves differently for ELF32 and ELF64, writing
333   // 4 bytes in the former and 8 in the latter.
334
335   Write8(0x7f); // e_ident[EI_MAG0]
336   Write8('E');  // e_ident[EI_MAG1]
337   Write8('L');  // e_ident[EI_MAG2]
338   Write8('F');  // e_ident[EI_MAG3]
339
340   Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
341
342   // e_ident[EI_DATA]
343   Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
344
345   Write8(ELF::EV_CURRENT);        // e_ident[EI_VERSION]
346   // e_ident[EI_OSABI]
347   switch (OSType) {
348     case Triple::FreeBSD:  Write8(ELF::ELFOSABI_FREEBSD); break;
349     case Triple::Linux:    Write8(ELF::ELFOSABI_LINUX); break;
350     default:               Write8(ELF::ELFOSABI_NONE); break;
351   }
352   Write8(0);                  // e_ident[EI_ABIVERSION]
353
354   WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
355
356   Write16(ELF::ET_REL);             // e_type
357
358   Write16(EMachine); // e_machine = target
359
360   Write32(ELF::EV_CURRENT);         // e_version
361   WriteWord(0);                    // e_entry, no entry point in .o file
362   WriteWord(0);                    // e_phoff, no program header for .o
363   WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
364             sizeof(ELF::Elf32_Ehdr)));  // e_shoff = sec hdr table off in bytes
365
366   // FIXME: Make this configurable.
367   Write32(0);   // e_flags = whatever the target wants
368
369   // e_ehsize = ELF header size
370   Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
371
372   Write16(0);                  // e_phentsize = prog header entry size
373   Write16(0);                  // e_phnum = # prog header entries = 0
374
375   // e_shentsize = Section header entry size
376   Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
377
378   // e_shnum     = # of section header ents
379   Write16(NumberOfSections);
380
381   // e_shstrndx  = Section # of '.shstrtab'
382   Write16(ShstrtabIndex);
383 }
384
385 void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
386                                            uint8_t info, uint64_t value,
387                                            uint64_t size, uint8_t other,
388                                            uint16_t shndx) {
389   if (Is64Bit) {
390     char buf[8];
391
392     String32(buf, name);
393     F->getContents() += StringRef(buf, 4); // st_name
394
395     String8(buf, info);
396     F->getContents() += StringRef(buf, 1);  // st_info
397
398     String8(buf, other);
399     F->getContents() += StringRef(buf, 1); // st_other
400
401     String16(buf, shndx);
402     F->getContents() += StringRef(buf, 2); // st_shndx
403
404     String64(buf, value);
405     F->getContents() += StringRef(buf, 8); // st_value
406
407     String64(buf, size);
408     F->getContents() += StringRef(buf, 8);  // st_size
409   } else {
410     char buf[4];
411
412     String32(buf, name);
413     F->getContents() += StringRef(buf, 4);  // st_name
414
415     String32(buf, value);
416     F->getContents() += StringRef(buf, 4); // st_value
417
418     String32(buf, size);
419     F->getContents() += StringRef(buf, 4);  // st_size
420
421     String8(buf, info);
422     F->getContents() += StringRef(buf, 1);  // st_info
423
424     String8(buf, other);
425     F->getContents() += StringRef(buf, 1); // st_other
426
427     String16(buf, shndx);
428     F->getContents() += StringRef(buf, 2); // st_shndx
429   }
430 }
431
432 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
433   if (Data.isCommon() && Data.isExternal())
434     return Data.getCommonAlignment();
435
436   const MCSymbol &Symbol = Data.getSymbol();
437   if (!Symbol.isInSection())
438     return 0;
439
440   if (!Data.isCommon() && !(Data.getFlags() & ELF_STB_Weak))
441     if (MCFragment *FF = Data.getFragment())
442       return Layout.getSymbolAddress(&Data) -
443              Layout.getSectionAddress(FF->getParent());
444
445   return 0;
446 }
447
448 static const MCSymbol &AliasedSymbol(const MCSymbol &Symbol) {
449   const MCSymbol *S = &Symbol;
450   while (S->isVariable()) {
451     const MCExpr *Value = S->getVariableValue();
452     if (Value->getKind() != MCExpr::SymbolRef)
453       return *S;
454     const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Value);
455     S = &Ref->getSymbol();
456   }
457   return *S;
458 }
459
460 void ELFObjectWriterImpl::ExecutePostLayoutBinding(MCAssembler &Asm) {
461   // The presence of symbol versions causes undefined symbols and
462   // versions declared with @@@ to be renamed.
463
464   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
465          ie = Asm.symbol_end(); it != ie; ++it) {
466     const MCSymbol &Alias = it->getSymbol();
467     if (!Alias.isVariable())
468       continue;
469     const MCSymbol &Symbol = AliasedSymbol(Alias);
470     StringRef AliasName = Alias.getName();
471     size_t Pos = AliasName.find('@');
472     if (Pos == StringRef::npos)
473       continue;
474
475     StringRef Rest = AliasName.substr(Pos);
476     if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
477       continue;
478
479     // FIXME: produce a better error message.
480     if (Symbol.isUndefined() && Rest.startswith("@@") &&
481         !Rest.startswith("@@@"))
482       report_fatal_error("A @@ version cannot be undefined");
483
484     Renames.insert(std::make_pair(&Symbol, &Alias));
485   }
486 }
487
488 void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
489                                       const MCAsmLayout &Layout) {
490   MCSymbolData &OrigData = *MSD.SymbolData;
491   MCSymbolData &Data =
492     Layout.getAssembler().getSymbolData(AliasedSymbol(OrigData.getSymbol()));
493
494   uint8_t Binding = GetBinding(OrigData);
495   uint8_t Visibility = GetVisibility(OrigData);
496   uint8_t Type = GetType(Data);
497
498   uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
499   uint8_t Other = Visibility;
500
501   uint64_t Value = SymbolValue(Data, Layout);
502   uint64_t Size = 0;
503   const MCExpr *ESize;
504
505   assert(!(Data.isCommon() && !Data.isExternal()));
506
507   ESize = Data.getSize();
508   if (Data.getSize()) {
509     MCValue Res;
510     if (ESize->getKind() == MCExpr::Binary) {
511       const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
512
513       if (BE->EvaluateAsRelocatable(Res, &Layout)) {
514         assert(!Res.getSymA() || !Res.getSymA()->getSymbol().isDefined());
515         assert(!Res.getSymB() || !Res.getSymB()->getSymbol().isDefined());
516         Size = Res.getConstant();
517       }
518     } else if (ESize->getKind() == MCExpr::Constant) {
519       Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
520     } else {
521       assert(0 && "Unsupported size expression");
522     }
523   }
524
525   // Write out the symbol table entry
526   WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
527                    Size, Other, MSD.SectionIndex);
528 }
529
530 void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
531                                            const MCAssembler &Asm,
532                                            const MCAsmLayout &Layout,
533                                            unsigned NumRegularSections) {
534   // The string table must be emitted first because we need the index
535   // into the string table for all the symbol names.
536   assert(StringTable.size() && "Missing string table");
537
538   // FIXME: Make sure the start of the symbol table is aligned.
539
540   // The first entry is the undefined symbol entry.
541   unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
542   F->getContents().append(EntrySize, '\x00');
543
544   // Write the symbol table entries.
545   LastLocalSymbolIndex = LocalSymbolData.size() + 1;
546   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
547     ELFSymbolData &MSD = LocalSymbolData[i];
548     WriteSymbol(F, MSD, Layout);
549   }
550
551   // Write out a symbol table entry for each regular section.
552   unsigned Index = 1;
553   for (MCAssembler::const_iterator it = Asm.begin();
554        Index <= NumRegularSections; ++it, ++Index) {
555     const MCSectionELF &Section =
556       static_cast<const MCSectionELF&>(it->getSection());
557     // Leave out relocations so we don't have indexes within
558     // the relocations messed up
559     if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
560       continue;
561     WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
562     LastLocalSymbolIndex++;
563   }
564
565   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
566     ELFSymbolData &MSD = ExternalSymbolData[i];
567     MCSymbolData &Data = *MSD.SymbolData;
568     assert(((Data.getFlags() & ELF_STB_Global) ||
569             (Data.getFlags() & ELF_STB_Weak)) &&
570            "External symbol requires STB_GLOBAL or STB_WEAK flag");
571     WriteSymbol(F, MSD, Layout);
572     if (GetBinding(Data) == ELF::STB_LOCAL)
573       LastLocalSymbolIndex++;
574   }
575
576   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
577     ELFSymbolData &MSD = UndefinedSymbolData[i];
578     MCSymbolData &Data = *MSD.SymbolData;
579     WriteSymbol(F, MSD, Layout);
580     if (GetBinding(Data) == ELF::STB_LOCAL)
581       LastLocalSymbolIndex++;
582   }
583 }
584
585 static bool ShouldRelocOnSymbol(const MCSymbolData &SD,
586                                 const MCValue &Target,
587                                 const MCFragment &F) {
588   const MCSymbol &Symbol = SD.getSymbol();
589   if (Symbol.isUndefined())
590     return true;
591
592   const MCSectionELF &Section =
593     static_cast<const MCSectionELF&>(Symbol.getSection());
594
595   if (SD.isExternal())
596     return true;
597
598   MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
599   const MCSectionELF &Sec2 =
600     static_cast<const MCSectionELF&>(F.getParent()->getSection());
601
602   if (Section.getKind().isBSS())
603     return false;
604
605   if (&Sec2 != &Section &&
606       (Kind == MCSymbolRefExpr::VK_PLT ||
607        Kind == MCSymbolRefExpr::VK_GOTPCREL ||
608        Kind == MCSymbolRefExpr::VK_GOTOFF))
609     return true;
610
611   if (Section.getFlags() & MCSectionELF::SHF_MERGE)
612     return Target.getConstant() != 0;
613
614   return false;
615 }
616
617 // FIXME: this is currently X86/X86_64 only
618 void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
619                                            const MCAsmLayout &Layout,
620                                            const MCFragment *Fragment,
621                                            const MCFixup &Fixup,
622                                            MCValue Target,
623                                            uint64_t &FixedValue) {
624   int64_t Addend = 0;
625   int Index = 0;
626   int64_t Value = Target.getConstant();
627   const MCSymbol *Symbol = 0;
628
629   bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
630   if (!Target.isAbsolute()) {
631     Symbol = &AliasedSymbol(Target.getSymA()->getSymbol());
632     const MCSymbol *Renamed = Renames.lookup(Symbol);
633     if (Renamed)
634       Symbol = Renamed;
635     MCSymbolData &SD = Asm.getSymbolData(*Symbol);
636     MCFragment *F = SD.getFragment();
637
638     if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
639       const MCSymbol &SymbolB = RefB->getSymbol();
640       MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
641       IsPCRel = true;
642       MCSectionData *Sec = Fragment->getParent();
643
644       // Offset of the symbol in the section
645       int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
646
647       // Ofeset of the relocation in the section
648       int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
649       Value += b - a;
650     }
651
652     // Check that this case has already been fully resolved before we get
653     // here.
654     if (Symbol->isDefined() && !SD.isExternal() &&
655         IsPCRel &&
656         &Fragment->getParent()->getSection() == &Symbol->getSection()) {
657       llvm_unreachable("We don't need a relocation in this case.");
658       return;
659     }
660
661     bool RelocOnSymbol = ShouldRelocOnSymbol(SD, Target, *Fragment);
662     if (!RelocOnSymbol) {
663       Index = F->getParent()->getOrdinal();
664
665       MCSectionData *FSD = F->getParent();
666       // Offset of the symbol in the section
667       Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
668     } else {
669       UsedInReloc.insert(Symbol);
670       Index = -1;
671     }
672     Addend = Value;
673     // Compensate for the addend on i386.
674     if (Is64Bit)
675       Value = 0;
676   }
677
678   FixedValue = Value;
679
680   // determine the type of the relocation
681
682   MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
683   unsigned Type;
684   if (Is64Bit) {
685     if (IsPCRel) {
686       switch (Modifier) {
687       default:
688         llvm_unreachable("Unimplemented");
689       case MCSymbolRefExpr::VK_None:
690         Type = ELF::R_X86_64_PC32;
691         break;
692       case MCSymbolRefExpr::VK_PLT:
693         Type = ELF::R_X86_64_PLT32;
694         break;
695       case MCSymbolRefExpr::VK_GOTPCREL:
696         Type = ELF::R_X86_64_GOTPCREL;
697         break;
698       case MCSymbolRefExpr::VK_GOTTPOFF:
699         Type = ELF::R_X86_64_GOTTPOFF;
700         break;
701       case MCSymbolRefExpr::VK_TLSGD:
702         Type = ELF::R_X86_64_TLSGD;
703         break;
704       }
705     } else {
706       switch ((unsigned)Fixup.getKind()) {
707       default: llvm_unreachable("invalid fixup kind!");
708       case FK_Data_8: Type = ELF::R_X86_64_64; break;
709       case X86::reloc_signed_4byte:
710       case X86::reloc_pcrel_4byte:
711         assert(isInt<32>(Target.getConstant()));
712         switch (Modifier) {
713         default:
714           llvm_unreachable("Unimplemented");
715         case MCSymbolRefExpr::VK_None:
716           Type = ELF::R_X86_64_32S;
717           break;
718         case MCSymbolRefExpr::VK_GOT:
719           Type = ELF::R_X86_64_GOT32;
720           break;
721         case MCSymbolRefExpr::VK_GOTPCREL:
722           Type = ELF::R_X86_64_GOTPCREL;
723           break;
724         case MCSymbolRefExpr::VK_TPOFF:
725           Type = ELF::R_X86_64_TPOFF32;
726           break;
727         }
728         break;
729       case FK_Data_4:
730         Type = ELF::R_X86_64_32;
731         break;
732       case FK_Data_2: Type = ELF::R_X86_64_16; break;
733       case X86::reloc_pcrel_1byte:
734       case FK_Data_1: Type = ELF::R_X86_64_8; break;
735       }
736     }
737   } else {
738     if (IsPCRel) {
739       switch (Modifier) {
740       default:
741         llvm_unreachable("Unimplemented");
742       case MCSymbolRefExpr::VK_None:
743         Type = ELF::R_386_PC32;
744         break;
745       case MCSymbolRefExpr::VK_PLT:
746         Type = ELF::R_386_PLT32;
747         break;
748       }
749     } else {
750       switch ((unsigned)Fixup.getKind()) {
751       default: llvm_unreachable("invalid fixup kind!");
752
753       case X86::reloc_global_offset_table:
754         Type = ELF::R_386_GOTPC;
755         break;
756
757       // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
758       // instead?
759       case X86::reloc_signed_4byte:
760       case X86::reloc_pcrel_4byte:
761       case FK_Data_4:
762         switch (Modifier) {
763         default:
764           llvm_unreachable("Unimplemented");
765         case MCSymbolRefExpr::VK_None:
766           Type = ELF::R_386_32;
767           break;
768         case MCSymbolRefExpr::VK_GOT:
769           Type = ELF::R_386_GOT32;
770           break;
771         case MCSymbolRefExpr::VK_GOTOFF:
772           Type = ELF::R_386_GOTOFF;
773           break;
774         case MCSymbolRefExpr::VK_TLSGD:
775           Type = ELF::R_386_TLS_GD;
776           break;
777         case MCSymbolRefExpr::VK_TPOFF:
778           Type = ELF::R_386_TLS_LE_32;
779           break;
780         case MCSymbolRefExpr::VK_INDNTPOFF:
781           Type = ELF::R_386_TLS_IE;
782           break;
783         case MCSymbolRefExpr::VK_NTPOFF:
784           Type = ELF::R_386_TLS_LE;
785           break;
786         case MCSymbolRefExpr::VK_GOTNTPOFF:
787           Type = ELF::R_386_TLS_GOTIE;
788           break;
789         case MCSymbolRefExpr::VK_TLSLDM:
790           Type = ELF::R_386_TLS_LDM;
791           break;
792         case MCSymbolRefExpr::VK_DTPOFF:
793           Type = ELF::R_386_TLS_LDO_32;
794           break;
795         }
796         break;
797       case FK_Data_2: Type = ELF::R_386_16; break;
798       case X86::reloc_pcrel_1byte:
799       case FK_Data_1: Type = ELF::R_386_8; break;
800       }
801     }
802   }
803
804   if (RelocNeedsGOT(Modifier))
805     NeedsGOT = true;
806
807   ELFRelocationEntry ERE;
808
809   ERE.Index = Index;
810   ERE.Type = Type;
811   ERE.Symbol = Symbol;
812
813   ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
814
815   if (HasRelocationAddend)
816     ERE.r_addend = Addend;
817   else
818     ERE.r_addend = 0; // Silence compiler warning.
819
820   Relocations[Fragment->getParent()].push_back(ERE);
821 }
822
823 uint64_t
824 ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
825                                                  const MCSymbol *S) {
826   MCSymbolData &SD = Asm.getSymbolData(*S);
827
828   // Local symbol.
829   if (!SD.isExternal() && !S->isUndefined())
830     return SD.getIndex() + /* empty symbol */ 1;
831
832   // External or undefined symbol.
833   return SD.getIndex() + NumRegularSections + /* empty symbol */ 1;
834 }
835
836 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
837                        bool Used, bool Renamed) {
838   if (Used)
839     return true;
840
841   if (Renamed)
842     return false;
843
844   const MCSymbol &Symbol = Data.getSymbol();
845
846   const MCSymbol &A = AliasedSymbol(Symbol);
847   if (&A != &Symbol && A.isUndefined())
848     return false;
849
850   if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
851     return false;
852
853   if (Symbol.isTemporary())
854     return false;
855
856   return true;
857 }
858
859 static bool isLocal(const MCSymbolData &Data) {
860   if (Data.isExternal())
861     return false;
862
863   const MCSymbol &Symbol = Data.getSymbol();
864   if (Symbol.isUndefined() && !Symbol.isVariable())
865     return false;
866
867   return true;
868 }
869
870 void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
871   // FIXME: Is this the correct place to do this?
872   if (NeedsGOT) {
873     llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
874     MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
875     MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
876     Data.setExternal(true);
877   }
878
879   // Build section lookup table.
880   NumRegularSections = Asm.size();
881   DenseMap<const MCSection*, uint32_t> SectionIndexMap;
882   unsigned Index = 1;
883   for (MCAssembler::iterator it = Asm.begin(),
884          ie = Asm.end(); it != ie; ++it, ++Index)
885     SectionIndexMap[&it->getSection()] = Index;
886
887   // Index 0 is always the empty string.
888   StringMap<uint64_t> StringIndexMap;
889   StringTable += '\x00';
890
891   // Add the data for the symbols.
892   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
893          ie = Asm.symbol_end(); it != ie; ++it) {
894     const MCSymbol &Symbol = it->getSymbol();
895
896     if (!isInSymtab(Asm, *it, UsedInReloc.count(&Symbol),
897                     Renames.count(&Symbol)))
898       continue;
899
900     ELFSymbolData MSD;
901     MSD.SymbolData = it;
902     bool Local = isLocal(*it);
903     const MCSymbol &RefSymbol = AliasedSymbol(Symbol);
904
905     if (it->isCommon()) {
906       assert(!Local);
907       MSD.SectionIndex = ELF::SHN_COMMON;
908     } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
909       MSD.SectionIndex = ELF::SHN_ABS;
910     } else if (RefSymbol.isUndefined()) {
911       MSD.SectionIndex = ELF::SHN_UNDEF;
912       // FIXME: Undefined symbols are global, but this is the first place we
913       // are able to set it.
914       if (GetBinding(*it) == ELF::STB_LOCAL)
915         SetBinding(*it, ELF::STB_GLOBAL);
916     } else {
917       MSD.SectionIndex = SectionIndexMap.lookup(&RefSymbol.getSection());
918       assert(MSD.SectionIndex && "Invalid section index!");
919     }
920
921     // The @@@ in symbol version is replaced with @ in undefined symbols and
922     // @@ in defined ones.
923     StringRef Name = Symbol.getName();
924     size_t Pos = Name.find("@@@");
925     std::string FinalName;
926     if (Pos != StringRef::npos) {
927       StringRef Prefix = Name.substr(0, Pos);
928       unsigned n = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
929       StringRef Suffix = Name.substr(Pos + n);
930       FinalName = Prefix.str() + Suffix.str();
931     } else {
932       FinalName = Name.str();
933     }
934
935     uint64_t &Entry = StringIndexMap[FinalName];
936     if (!Entry) {
937       Entry = StringTable.size();
938       StringTable += FinalName;
939       StringTable += '\x00';
940     }
941     MSD.StringIndex = Entry;
942     if (MSD.SectionIndex == ELF::SHN_UNDEF)
943       UndefinedSymbolData.push_back(MSD);
944     else if (Local)
945       LocalSymbolData.push_back(MSD);
946     else
947       ExternalSymbolData.push_back(MSD);
948   }
949
950   // Symbols are required to be in lexicographic order.
951   array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
952   array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
953   array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
954
955   // Set the symbol indices. Local symbols must come before all other
956   // symbols with non-local bindings.
957   Index = 0;
958   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
959     LocalSymbolData[i].SymbolData->setIndex(Index++);
960   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
961     ExternalSymbolData[i].SymbolData->setIndex(Index++);
962   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
963     UndefinedSymbolData[i].SymbolData->setIndex(Index++);
964 }
965
966 void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
967                                           const MCSectionData &SD) {
968   if (!Relocations[&SD].empty()) {
969     MCContext &Ctx = Asm.getContext();
970     const MCSection *RelaSection;
971     const MCSectionELF &Section =
972       static_cast<const MCSectionELF&>(SD.getSection());
973
974     const StringRef SectionName = Section.getSectionName();
975     std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
976     RelaSectionName += SectionName;
977
978     unsigned EntrySize;
979     if (HasRelocationAddend)
980       EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
981     else
982       EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
983
984     RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
985                                     ELF::SHT_RELA : ELF::SHT_REL, 0,
986                                     SectionKind::getReadOnly(),
987                                     false, EntrySize);
988
989     MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
990     RelaSD.setAlignment(Is64Bit ? 8 : 4);
991
992     MCDataFragment *F = new MCDataFragment(&RelaSD);
993
994     WriteRelocationsFragment(Asm, F, &SD);
995
996     Asm.AddSectionToTheEnd(*Writer, RelaSD, Layout);
997   }
998 }
999
1000 void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1001                                            uint64_t Flags, uint64_t Address,
1002                                            uint64_t Offset, uint64_t Size,
1003                                            uint32_t Link, uint32_t Info,
1004                                            uint64_t Alignment,
1005                                            uint64_t EntrySize) {
1006   Write32(Name);        // sh_name: index into string table
1007   Write32(Type);        // sh_type
1008   WriteWord(Flags);     // sh_flags
1009   WriteWord(Address);   // sh_addr
1010   WriteWord(Offset);    // sh_offset
1011   WriteWord(Size);      // sh_size
1012   Write32(Link);        // sh_link
1013   Write32(Info);        // sh_info
1014   WriteWord(Alignment); // sh_addralign
1015   WriteWord(EntrySize); // sh_entsize
1016 }
1017
1018 void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
1019                                                    MCDataFragment *F,
1020                                                    const MCSectionData *SD) {
1021   std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1022   // sort by the r_offset just like gnu as does
1023   array_pod_sort(Relocs.begin(), Relocs.end());
1024
1025   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1026     ELFRelocationEntry entry = Relocs[e - i - 1];
1027
1028     if (entry.Index < 0)
1029       entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1030     else
1031       entry.Index += LocalSymbolData.size() + 1;
1032     if (Is64Bit) {
1033       char buf[8];
1034
1035       String64(buf, entry.r_offset);
1036       F->getContents() += StringRef(buf, 8);
1037
1038       struct ELF::Elf64_Rela ERE64;
1039       ERE64.setSymbolAndType(entry.Index, entry.Type);
1040       String64(buf, ERE64.r_info);
1041       F->getContents() += StringRef(buf, 8);
1042
1043       if (HasRelocationAddend) {
1044         String64(buf, entry.r_addend);
1045         F->getContents() += StringRef(buf, 8);
1046       }
1047     } else {
1048       char buf[4];
1049
1050       String32(buf, entry.r_offset);
1051       F->getContents() += StringRef(buf, 4);
1052
1053       struct ELF::Elf32_Rela ERE32;
1054       ERE32.setSymbolAndType(entry.Index, entry.Type);
1055       String32(buf, ERE32.r_info);
1056       F->getContents() += StringRef(buf, 4);
1057
1058       if (HasRelocationAddend) {
1059         String32(buf, entry.r_addend);
1060         F->getContents() += StringRef(buf, 4);
1061       }
1062     }
1063   }
1064 }
1065
1066 void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
1067                                                  MCAsmLayout &Layout) {
1068   MCContext &Ctx = Asm.getContext();
1069   MCDataFragment *F;
1070
1071   const MCSection *SymtabSection;
1072   unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1073
1074   unsigned NumRegularSections = Asm.size();
1075
1076   // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1077   const MCSection *ShstrtabSection;
1078   ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1079                                       SectionKind::getReadOnly(), false);
1080   MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1081   ShstrtabSD.setAlignment(1);
1082   ShstrtabIndex = Asm.size();
1083
1084   SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1085                                     SectionKind::getReadOnly(),
1086                                     false, EntrySize);
1087   MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1088   SymtabSD.setAlignment(Is64Bit ? 8 : 4);
1089
1090   const MCSection *StrtabSection;
1091   StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1092                                     SectionKind::getReadOnly(), false);
1093   MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1094   StrtabSD.setAlignment(1);
1095   StringTableIndex = Asm.size();
1096
1097   WriteRelocations(Asm, Layout);
1098
1099   // Symbol table
1100   F = new MCDataFragment(&SymtabSD);
1101   WriteSymbolTable(F, Asm, Layout, NumRegularSections);
1102   Asm.AddSectionToTheEnd(*Writer, SymtabSD, Layout);
1103
1104   F = new MCDataFragment(&StrtabSD);
1105   F->getContents().append(StringTable.begin(), StringTable.end());
1106   Asm.AddSectionToTheEnd(*Writer, StrtabSD, Layout);
1107
1108   F = new MCDataFragment(&ShstrtabSD);
1109
1110   // Section header string table.
1111   //
1112   // The first entry of a string table holds a null character so skip
1113   // section 0.
1114   uint64_t Index = 1;
1115   F->getContents() += '\x00';
1116
1117   for (MCAssembler::const_iterator it = Asm.begin(),
1118          ie = Asm.end(); it != ie; ++it) {
1119     const MCSectionELF &Section =
1120       static_cast<const MCSectionELF&>(it->getSection());
1121     // FIXME: We could merge suffixes like in .text and .rela.text.
1122
1123     // Remember the index into the string table so we can write it
1124     // into the sh_name field of the section header table.
1125     SectionStringTableIndex[&it->getSection()] = Index;
1126
1127     Index += Section.getSectionName().size() + 1;
1128     F->getContents() += Section.getSectionName();
1129     F->getContents() += '\x00';
1130   }
1131
1132   Asm.AddSectionToTheEnd(*Writer, ShstrtabSD, Layout);
1133 }
1134
1135 bool ELFObjectWriterImpl::IsFixupFullyResolved(const MCAssembler &Asm,
1136                                                const MCValue Target,
1137                                                bool IsPCRel,
1138                                                const MCFragment *DF) const {
1139   // If this is a PCrel relocation, find the section this fixup value is
1140   // relative to.
1141   const MCSection *BaseSection = 0;
1142   if (IsPCRel) {
1143     BaseSection = &DF->getParent()->getSection();
1144     assert(BaseSection);
1145   }
1146
1147   const MCSection *SectionA = 0;
1148   const MCSymbol *SymbolA = 0;
1149   if (const MCSymbolRefExpr *A = Target.getSymA()) {
1150     SymbolA = &A->getSymbol();
1151     SectionA = &SymbolA->getSection();
1152   }
1153
1154   const MCSection *SectionB = 0;
1155   if (const MCSymbolRefExpr *B = Target.getSymB()) {
1156     SectionB = &B->getSymbol().getSection();
1157   }
1158
1159   if (!BaseSection)
1160     return SectionA == SectionB;
1161
1162   const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1163   if (DataA.isExternal())
1164     return false;
1165
1166   return !SectionB && BaseSection == SectionA;
1167 }
1168
1169 void ELFObjectWriterImpl::WriteObject(MCAssembler &Asm,
1170                                       const MCAsmLayout &Layout) {
1171   // Compute symbol table information.
1172   ComputeSymbolTable(Asm);
1173
1174   CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1175                          const_cast<MCAsmLayout&>(Layout));
1176
1177   // Add 1 for the null section.
1178   unsigned NumSections = Asm.size() + 1;
1179   uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1180   uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1181   uint64_t FileOff = HeaderSize;
1182
1183   for (MCAssembler::const_iterator it = Asm.begin(),
1184          ie = Asm.end(); it != ie; ++it) {
1185     const MCSectionData &SD = *it;
1186
1187     FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1188
1189     // Get the size of the section in the output file (including padding).
1190     uint64_t Size = Layout.getSectionFileSize(&SD);
1191
1192     FileOff += Size;
1193   }
1194
1195   FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1196
1197   // Write out the ELF header ...
1198   WriteHeader(FileOff - HeaderSize, NumSections);
1199
1200   FileOff = HeaderSize;
1201
1202   // ... then all of the sections ...
1203   DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1204
1205   DenseMap<const MCSection*, uint32_t> SectionIndexMap;
1206
1207   unsigned Index = 1;
1208   for (MCAssembler::const_iterator it = Asm.begin(),
1209          ie = Asm.end(); it != ie; ++it) {
1210     const MCSectionData &SD = *it;
1211
1212     uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1213     WriteZeros(Padding);
1214     FileOff += Padding;
1215
1216     // Remember the offset into the file for this section.
1217     SectionOffsetMap[&it->getSection()] = FileOff;
1218     SectionIndexMap[&it->getSection()] = Index++;
1219
1220     FileOff += Layout.getSectionFileSize(&SD);
1221
1222     Asm.WriteSectionData(it, Layout, Writer);
1223   }
1224
1225   uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1226   WriteZeros(Padding);
1227   FileOff += Padding;
1228
1229   // ... and then the section header table.
1230   // Should we align the section header table?
1231   //
1232   // Null section first.
1233   WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1234
1235   for (MCAssembler::const_iterator it = Asm.begin(),
1236          ie = Asm.end(); it != ie; ++it) {
1237     const MCSectionData &SD = *it;
1238     const MCSectionELF &Section =
1239       static_cast<const MCSectionELF&>(SD.getSection());
1240
1241     uint64_t sh_link = 0;
1242     uint64_t sh_info = 0;
1243
1244     switch(Section.getType()) {
1245     case ELF::SHT_DYNAMIC:
1246       sh_link = SectionStringTableIndex[&it->getSection()];
1247       sh_info = 0;
1248       break;
1249
1250     case ELF::SHT_REL:
1251     case ELF::SHT_RELA: {
1252       const MCSection *SymtabSection;
1253       const MCSection *InfoSection;
1254
1255       SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1256                                                      SectionKind::getReadOnly(),
1257                                                      false);
1258       sh_link = SectionIndexMap[SymtabSection];
1259
1260       // Remove ".rel" and ".rela" prefixes.
1261       unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1262       StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1263
1264       InfoSection = Asm.getContext().getELFSection(SectionName,
1265                                                    ELF::SHT_PROGBITS, 0,
1266                                                    SectionKind::getReadOnly(),
1267                                                    false);
1268       sh_info = SectionIndexMap[InfoSection];
1269       break;
1270     }
1271
1272     case ELF::SHT_SYMTAB:
1273     case ELF::SHT_DYNSYM:
1274       sh_link = StringTableIndex;
1275       sh_info = LastLocalSymbolIndex;
1276       break;
1277
1278     case ELF::SHT_PROGBITS:
1279     case ELF::SHT_STRTAB:
1280     case ELF::SHT_NOBITS:
1281     case ELF::SHT_NULL:
1282     case ELF::SHT_ARM_ATTRIBUTES:
1283       // Nothing to do.
1284       break;
1285
1286     default:
1287       assert(0 && "FIXME: sh_type value not supported!");
1288       break;
1289     }
1290
1291     WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
1292                      Section.getType(), Section.getFlags(),
1293                      0,
1294                      SectionOffsetMap.lookup(&SD.getSection()),
1295                      Layout.getSectionSize(&SD), sh_link,
1296                      sh_info, SD.getAlignment(),
1297                      Section.getEntrySize());
1298   }
1299 }
1300
1301 ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1302                                  bool Is64Bit,
1303                                  Triple::OSType OSType,
1304                                  uint16_t EMachine,
1305                                  bool IsLittleEndian,
1306                                  bool HasRelocationAddend)
1307   : MCObjectWriter(OS, IsLittleEndian)
1308 {
1309   Impl = new ELFObjectWriterImpl(this, Is64Bit, EMachine,
1310                                  HasRelocationAddend, OSType);
1311 }
1312
1313 ELFObjectWriter::~ELFObjectWriter() {
1314   delete (ELFObjectWriterImpl*) Impl;
1315 }
1316
1317 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1318   ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1319 }
1320
1321 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1322                                        const MCAsmLayout &Layout,
1323                                        const MCFragment *Fragment,
1324                                        const MCFixup &Fixup, MCValue Target,
1325                                        uint64_t &FixedValue) {
1326   ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1327                                                   Target, FixedValue);
1328 }
1329
1330 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1331                                            const MCValue Target,
1332                                            bool IsPCRel,
1333                                            const MCFragment *DF) const {
1334   return ((ELFObjectWriterImpl*) Impl)->IsFixupFullyResolved(Asm, Target,
1335                                                              IsPCRel, DF);
1336 }
1337
1338 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1339                                   const MCAsmLayout &Layout) {
1340   ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);
1341 }