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