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