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