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