cd6c04229630bfc085958a786618818d40359c62
[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   };
346
347 }
348
349 // Emit the ELF header.
350 void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
351                                       unsigned NumberOfSections) {
352   // ELF Header
353   // ----------
354   //
355   // Note
356   // ----
357   // emitWord method behaves differently for ELF32 and ELF64, writing
358   // 4 bytes in the former and 8 in the latter.
359
360   Write8(0x7f); // e_ident[EI_MAG0]
361   Write8('E');  // e_ident[EI_MAG1]
362   Write8('L');  // e_ident[EI_MAG2]
363   Write8('F');  // e_ident[EI_MAG3]
364
365   Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
366
367   // e_ident[EI_DATA]
368   Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
369
370   Write8(ELF::EV_CURRENT);        // e_ident[EI_VERSION]
371   // e_ident[EI_OSABI]
372   switch (OSType) {
373     case Triple::FreeBSD:  Write8(ELF::ELFOSABI_FREEBSD); break;
374     case Triple::Linux:    Write8(ELF::ELFOSABI_LINUX); break;
375     default:               Write8(ELF::ELFOSABI_NONE); break;
376   }
377   Write8(0);                  // e_ident[EI_ABIVERSION]
378
379   WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
380
381   Write16(ELF::ET_REL);             // e_type
382
383   Write16(EMachine); // e_machine = target
384
385   Write32(ELF::EV_CURRENT);         // e_version
386   WriteWord(0);                    // e_entry, no entry point in .o file
387   WriteWord(0);                    // e_phoff, no program header for .o
388   WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
389             sizeof(ELF::Elf32_Ehdr)));  // e_shoff = sec hdr table off in bytes
390
391   // FIXME: Make this configurable.
392   Write32(0);   // e_flags = whatever the target wants
393
394   // e_ehsize = ELF header size
395   Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
396
397   Write16(0);                  // e_phentsize = prog header entry size
398   Write16(0);                  // e_phnum = # prog header entries = 0
399
400   // e_shentsize = Section header entry size
401   Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
402
403   // e_shnum     = # of section header ents
404   if (NumberOfSections >= ELF::SHN_LORESERVE)
405     Write16(0);
406   else
407     Write16(NumberOfSections);
408
409   // e_shstrndx  = Section # of '.shstrtab'
410   if (NumberOfSections >= ELF::SHN_LORESERVE)
411     Write16(ELF::SHN_XINDEX);
412   else
413     Write16(ShstrtabIndex);
414 }
415
416 void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *SymtabF,
417                                            MCDataFragment *ShndxF,
418                                            uint64_t name,
419                                            uint8_t info, uint64_t value,
420                                            uint64_t size, uint8_t other,
421                                            uint32_t shndx,
422                                            bool Reserved) {
423   if (ShndxF) {
424     if (shndx >= ELF::SHN_LORESERVE && !Reserved)
425       String32(*ShndxF, shndx);
426     else
427       String32(*ShndxF, 0);
428   }
429
430   uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
431     uint16_t(ELF::SHN_XINDEX) : shndx;
432
433   if (Is64Bit) {
434     String32(*SymtabF, name);  // st_name
435     String8(*SymtabF, info);   // st_info
436     String8(*SymtabF, other);  // st_other
437     String16(*SymtabF, Index); // st_shndx
438     String64(*SymtabF, value); // st_value
439     String64(*SymtabF, size);  // st_size
440   } else {
441     String32(*SymtabF, name);  // st_name
442     String32(*SymtabF, value); // st_value
443     String32(*SymtabF, size);  // st_size
444     String8(*SymtabF, info);   // st_info
445     String8(*SymtabF, other);  // st_other
446     String16(*SymtabF, Index); // st_shndx
447   }
448 }
449
450 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
451   if (Data.isCommon() && Data.isExternal())
452     return Data.getCommonAlignment();
453
454   const MCSymbol &Symbol = Data.getSymbol();
455   if (!Symbol.isInSection())
456     return 0;
457
458   if (MCFragment *FF = Data.getFragment())
459     return Layout.getSymbolAddress(&Data) -
460       Layout.getSectionAddress(FF->getParent());
461
462   return 0;
463 }
464
465 static const MCSymbol &AliasedSymbol(const MCSymbol &Symbol) {
466   const MCSymbol *S = &Symbol;
467   while (S->isVariable()) {
468     const MCExpr *Value = S->getVariableValue();
469     if (Value->getKind() != MCExpr::SymbolRef)
470       return *S;
471     const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Value);
472     S = &Ref->getSymbol();
473   }
474   return *S;
475 }
476
477 void ELFObjectWriterImpl::ExecutePostLayoutBinding(MCAssembler &Asm) {
478   // The presence of symbol versions causes undefined symbols and
479   // versions declared with @@@ to be renamed.
480
481   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
482          ie = Asm.symbol_end(); it != ie; ++it) {
483     const MCSymbol &Alias = it->getSymbol();
484     const MCSymbol &Symbol = AliasedSymbol(Alias);
485     MCSymbolData &SD = Asm.getSymbolData(Symbol);
486
487     // Undefined symbols are global, but this is the first place we
488     // are able to set it.
489     if (Symbol.isUndefined() && !Symbol.isVariable()) {
490       if (GetBinding(SD) == ELF::STB_LOCAL) {
491         SetBinding(SD, ELF::STB_GLOBAL);
492         SetBinding(*it, ELF::STB_GLOBAL);
493       }
494     }
495
496     // Not an alias.
497     if (&Symbol == &Alias)
498       continue;
499
500     StringRef AliasName = Alias.getName();
501     size_t Pos = AliasName.find('@');
502     if (Pos == StringRef::npos)
503       continue;
504
505     // Aliases defined with .symvar copy the binding from the symbol they alias.
506     // This is the first place we are able to copy this information.
507     it->setExternal(SD.isExternal());
508     SetBinding(*it, GetBinding(SD));
509
510     StringRef Rest = AliasName.substr(Pos);
511     if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
512       continue;
513
514     // FIXME: produce a better error message.
515     if (Symbol.isUndefined() && Rest.startswith("@@") &&
516         !Rest.startswith("@@@"))
517       report_fatal_error("A @@ version cannot be undefined");
518
519     Renames.insert(std::make_pair(&Symbol, &Alias));
520   }
521 }
522
523 void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *SymtabF,
524                                       MCDataFragment *ShndxF,
525                                       ELFSymbolData &MSD,
526                                       const MCAsmLayout &Layout) {
527   MCSymbolData &OrigData = *MSD.SymbolData;
528   MCSymbolData &Data =
529     Layout.getAssembler().getSymbolData(AliasedSymbol(OrigData.getSymbol()));
530
531   bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
532     Data.getSymbol().isVariable();
533
534   uint8_t Binding = GetBinding(OrigData);
535   uint8_t Visibility = GetVisibility(OrigData);
536   uint8_t Type = GetType(Data);
537
538   uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
539   uint8_t Other = Visibility;
540
541   uint64_t Value = SymbolValue(Data, Layout);
542   uint64_t Size = 0;
543   const MCExpr *ESize;
544
545   assert(!(Data.isCommon() && !Data.isExternal()));
546
547   ESize = Data.getSize();
548   if (Data.getSize()) {
549     MCValue Res;
550     if (ESize->getKind() == MCExpr::Binary) {
551       const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
552
553       if (BE->EvaluateAsRelocatable(Res, &Layout)) {
554         assert(!Res.getSymA() || !Res.getSymA()->getSymbol().isDefined());
555         assert(!Res.getSymB() || !Res.getSymB()->getSymbol().isDefined());
556         Size = Res.getConstant();
557       }
558     } else if (ESize->getKind() == MCExpr::Constant) {
559       Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
560     } else {
561       assert(0 && "Unsupported size expression");
562     }
563   }
564
565   // Write out the symbol table entry
566   WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
567                    Size, Other, MSD.SectionIndex, IsReserved);
568 }
569
570 void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *SymtabF,
571                                            MCDataFragment *ShndxF,
572                                            const MCAssembler &Asm,
573                                            const MCAsmLayout &Layout,
574                                      const SectionIndexMapTy &SectionIndexMap) {
575   // The string table must be emitted first because we need the index
576   // into the string table for all the symbol names.
577   assert(StringTable.size() && "Missing string table");
578
579   // FIXME: Make sure the start of the symbol table is aligned.
580
581   // The first entry is the undefined symbol entry.
582   WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
583
584   // Write the symbol table entries.
585   LastLocalSymbolIndex = LocalSymbolData.size() + 1;
586   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
587     ELFSymbolData &MSD = LocalSymbolData[i];
588     WriteSymbol(SymtabF, ShndxF, MSD, Layout);
589   }
590
591   // Write out a symbol table entry for each regular section.
592   for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
593        ++i) {
594     const MCSectionELF &Section =
595       static_cast<const MCSectionELF&>(i->getSection());
596     if (Section.getType() == ELF::SHT_RELA ||
597         Section.getType() == ELF::SHT_REL ||
598         Section.getType() == ELF::SHT_STRTAB ||
599         Section.getType() == ELF::SHT_SYMTAB)
600       continue;
601     WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
602                      ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section), false);
603     LastLocalSymbolIndex++;
604   }
605
606   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
607     ELFSymbolData &MSD = ExternalSymbolData[i];
608     MCSymbolData &Data = *MSD.SymbolData;
609     assert(((Data.getFlags() & ELF_STB_Global) ||
610             (Data.getFlags() & ELF_STB_Weak)) &&
611            "External symbol requires STB_GLOBAL or STB_WEAK flag");
612     WriteSymbol(SymtabF, ShndxF, MSD, Layout);
613     if (GetBinding(Data) == ELF::STB_LOCAL)
614       LastLocalSymbolIndex++;
615   }
616
617   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
618     ELFSymbolData &MSD = UndefinedSymbolData[i];
619     MCSymbolData &Data = *MSD.SymbolData;
620     WriteSymbol(SymtabF, ShndxF, MSD, Layout);
621     if (GetBinding(Data) == ELF::STB_LOCAL)
622       LastLocalSymbolIndex++;
623   }
624 }
625
626 static bool ShouldRelocOnSymbol(const MCSymbolData &SD,
627                                 const MCValue &Target,
628                                 const MCFragment &F) {
629   const MCSymbol &Symbol = SD.getSymbol();
630   if (Symbol.isUndefined())
631     return true;
632
633   const MCSectionELF &Section =
634     static_cast<const MCSectionELF&>(Symbol.getSection());
635
636   if (SD.isExternal())
637     return true;
638
639   MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
640   const MCSectionELF &Sec2 =
641     static_cast<const MCSectionELF&>(F.getParent()->getSection());
642
643   if (Section.getKind().isBSS())
644     return false;
645
646   if (&Sec2 != &Section &&
647       (Kind == MCSymbolRefExpr::VK_PLT ||
648        Kind == MCSymbolRefExpr::VK_GOTPCREL ||
649        Kind == MCSymbolRefExpr::VK_GOTOFF))
650     return true;
651
652   if (Section.getFlags() & MCSectionELF::SHF_MERGE)
653     return Target.getConstant() != 0;
654
655   return false;
656 }
657
658 // FIXME: this is currently X86/X86_64 only
659 void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
660                                            const MCAsmLayout &Layout,
661                                            const MCFragment *Fragment,
662                                            const MCFixup &Fixup,
663                                            MCValue Target,
664                                            uint64_t &FixedValue) {
665   int64_t Addend = 0;
666   int Index = 0;
667   int64_t Value = Target.getConstant();
668   const MCSymbol *Symbol = 0;
669   const MCSymbol *Renamed = 0;
670
671   bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
672   if (!Target.isAbsolute()) {
673     Symbol = &AliasedSymbol(Target.getSymA()->getSymbol());
674     Renamed = Renames.lookup(Symbol);
675     if (!Renamed)
676       Renamed = &Target.getSymA()->getSymbol();
677     MCSymbolData &SD = Asm.getSymbolData(*Symbol);
678     MCFragment *F = SD.getFragment();
679
680     if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
681       const MCSymbol &SymbolB = RefB->getSymbol();
682       MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
683       IsPCRel = true;
684       MCSectionData *Sec = Fragment->getParent();
685
686       // Offset of the symbol in the section
687       int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
688
689       // Ofeset of the relocation in the section
690       int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
691       Value += b - a;
692     }
693
694     // Check that this case has already been fully resolved before we get
695     // here.
696     if (Symbol->isDefined() && !SD.isExternal() &&
697         IsPCRel &&
698         &Fragment->getParent()->getSection() == &Symbol->getSection()) {
699       llvm_unreachable("We don't need a relocation in this case.");
700       return;
701     }
702
703     bool RelocOnSymbol = ShouldRelocOnSymbol(SD, Target, *Fragment);
704     if (!RelocOnSymbol) {
705       Index = F->getParent()->getOrdinal();
706
707       MCSectionData *FSD = F->getParent();
708       // Offset of the symbol in the section
709       Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
710     } else {
711       UsedInReloc.insert(Renamed);
712       MCSymbolData &RenamedSD = Asm.getSymbolData(*Renamed);
713       if (RenamedSD.getFlags() & ELF_Other_Weakref) {
714         WeakrefUsedInReloc.insert(Symbol);
715       }
716       Index = -1;
717     }
718     Addend = Value;
719     // Compensate for the addend on i386.
720     if (Is64Bit)
721       Value = 0;
722   }
723
724   FixedValue = Value;
725
726   // determine the type of the relocation
727
728   MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
729   unsigned Type;
730   if (Is64Bit) {
731     if (IsPCRel) {
732       switch (Modifier) {
733       default:
734         llvm_unreachable("Unimplemented");
735       case MCSymbolRefExpr::VK_None:
736         Type = ELF::R_X86_64_PC32;
737         break;
738       case MCSymbolRefExpr::VK_PLT:
739         Type = ELF::R_X86_64_PLT32;
740         break;
741       case MCSymbolRefExpr::VK_GOTPCREL:
742         Type = ELF::R_X86_64_GOTPCREL;
743         break;
744       case MCSymbolRefExpr::VK_GOTTPOFF:
745         Type = ELF::R_X86_64_GOTTPOFF;
746         break;
747       case MCSymbolRefExpr::VK_TLSGD:
748         Type = ELF::R_X86_64_TLSGD;
749         break;
750       case MCSymbolRefExpr::VK_TLSLD:
751         Type = ELF::R_X86_64_TLSLD;
752         break;
753       }
754     } else {
755       switch ((unsigned)Fixup.getKind()) {
756       default: llvm_unreachable("invalid fixup kind!");
757       case FK_Data_8: Type = ELF::R_X86_64_64; break;
758       case X86::reloc_signed_4byte:
759       case X86::reloc_pcrel_4byte:
760         assert(isInt<32>(Target.getConstant()));
761         switch (Modifier) {
762         default:
763           llvm_unreachable("Unimplemented");
764         case MCSymbolRefExpr::VK_None:
765           Type = ELF::R_X86_64_32S;
766           break;
767         case MCSymbolRefExpr::VK_GOT:
768           Type = ELF::R_X86_64_GOT32;
769           break;
770         case MCSymbolRefExpr::VK_GOTPCREL:
771           Type = ELF::R_X86_64_GOTPCREL;
772           break;
773         case MCSymbolRefExpr::VK_TPOFF:
774           Type = ELF::R_X86_64_TPOFF32;
775           break;
776         case MCSymbolRefExpr::VK_DTPOFF:
777           Type = ELF::R_X86_64_DTPOFF32;
778           break;
779         }
780         break;
781       case FK_Data_4:
782         Type = ELF::R_X86_64_32;
783         break;
784       case FK_Data_2: Type = ELF::R_X86_64_16; break;
785       case X86::reloc_pcrel_1byte:
786       case FK_Data_1: Type = ELF::R_X86_64_8; break;
787       }
788     }
789   } else {
790     if (IsPCRel) {
791       switch (Modifier) {
792       default:
793         llvm_unreachable("Unimplemented");
794       case MCSymbolRefExpr::VK_None:
795         Type = ELF::R_386_PC32;
796         break;
797       case MCSymbolRefExpr::VK_PLT:
798         Type = ELF::R_386_PLT32;
799         break;
800       }
801     } else {
802       switch ((unsigned)Fixup.getKind()) {
803       default: llvm_unreachable("invalid fixup kind!");
804
805       case X86::reloc_global_offset_table:
806         Type = ELF::R_386_GOTPC;
807         break;
808
809       // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
810       // instead?
811       case X86::reloc_signed_4byte:
812       case X86::reloc_pcrel_4byte:
813       case FK_Data_4:
814         switch (Modifier) {
815         default:
816           llvm_unreachable("Unimplemented");
817         case MCSymbolRefExpr::VK_None:
818           Type = ELF::R_386_32;
819           break;
820         case MCSymbolRefExpr::VK_GOT:
821           Type = ELF::R_386_GOT32;
822           break;
823         case MCSymbolRefExpr::VK_GOTOFF:
824           Type = ELF::R_386_GOTOFF;
825           break;
826         case MCSymbolRefExpr::VK_TLSGD:
827           Type = ELF::R_386_TLS_GD;
828           break;
829         case MCSymbolRefExpr::VK_TPOFF:
830           Type = ELF::R_386_TLS_LE_32;
831           break;
832         case MCSymbolRefExpr::VK_INDNTPOFF:
833           Type = ELF::R_386_TLS_IE;
834           break;
835         case MCSymbolRefExpr::VK_NTPOFF:
836           Type = ELF::R_386_TLS_LE;
837           break;
838         case MCSymbolRefExpr::VK_GOTNTPOFF:
839           Type = ELF::R_386_TLS_GOTIE;
840           break;
841         case MCSymbolRefExpr::VK_TLSLDM:
842           Type = ELF::R_386_TLS_LDM;
843           break;
844         case MCSymbolRefExpr::VK_DTPOFF:
845           Type = ELF::R_386_TLS_LDO_32;
846           break;
847         }
848         break;
849       case FK_Data_2: Type = ELF::R_386_16; break;
850       case X86::reloc_pcrel_1byte:
851       case FK_Data_1: Type = ELF::R_386_8; break;
852       }
853     }
854   }
855
856   if (RelocNeedsGOT(Modifier))
857     NeedsGOT = true;
858
859   ELFRelocationEntry ERE;
860
861   ERE.Index = Index;
862   ERE.Type = Type;
863   ERE.Symbol = Renamed;
864
865   ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
866
867   if (HasRelocationAddend)
868     ERE.r_addend = Addend;
869   else
870     ERE.r_addend = 0; // Silence compiler warning.
871
872   Relocations[Fragment->getParent()].push_back(ERE);
873 }
874
875 uint64_t
876 ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
877                                                  const MCSymbol *S) {
878   MCSymbolData &SD = Asm.getSymbolData(*S);
879
880   // Local symbol.
881   if (!SD.isExternal() && !S->isUndefined())
882     return SD.getIndex() + /* empty symbol */ 1;
883
884   // External or undefined symbol.
885   return SD.getIndex() + NumRegularSections + /* empty symbol */ 1;
886 }
887
888 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
889                        bool Used, bool Renamed) {
890   if (Data.getFlags() & ELF_Other_Weakref)
891     return false;
892
893   if (Used)
894     return true;
895
896   if (Renamed)
897     return false;
898
899   const MCSymbol &Symbol = Data.getSymbol();
900
901   if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
902     return true;
903
904   const MCSymbol &A = AliasedSymbol(Symbol);
905   if (!A.isVariable() && A.isUndefined() && !Data.isCommon())
906     return false;
907
908   if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
909     return false;
910
911   if (Symbol.isTemporary())
912     return false;
913
914   return true;
915 }
916
917 static bool isLocal(const MCSymbolData &Data) {
918   if (Data.isExternal())
919     return false;
920
921   const MCSymbol &Symbol = Data.getSymbol();
922   if (Symbol.isUndefined() && !Symbol.isVariable())
923     return false;
924
925   return true;
926 }
927
928 void ELFObjectWriterImpl::ComputeIndexMap(MCAssembler &Asm,
929                                           SectionIndexMapTy &SectionIndexMap) {
930   unsigned Index = 1;
931   for (MCAssembler::iterator it = Asm.begin(),
932          ie = Asm.end(); it != ie; ++it) {
933     const MCSectionELF &Section =
934       static_cast<const MCSectionELF &>(it->getSection());
935     SectionIndexMap[&Section] = Index++;
936   }
937 }
938
939 void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm,
940                                      const SectionIndexMapTy &SectionIndexMap) {
941   // FIXME: Is this the correct place to do this?
942   if (NeedsGOT) {
943     llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
944     MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
945     MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
946     Data.setExternal(true);
947     SetBinding(Data, ELF::STB_GLOBAL);
948   }
949
950   // Build section lookup table.
951   NumRegularSections = Asm.size();
952
953   // Index 0 is always the empty string.
954   StringMap<uint64_t> StringIndexMap;
955   StringTable += '\x00';
956
957   // Add the data for the symbols.
958   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
959          ie = Asm.symbol_end(); it != ie; ++it) {
960     const MCSymbol &Symbol = it->getSymbol();
961
962     bool Used = UsedInReloc.count(&Symbol);
963     bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
964     if (!isInSymtab(Asm, *it, Used || WeakrefUsed,
965                     Renames.count(&Symbol)))
966       continue;
967
968     ELFSymbolData MSD;
969     MSD.SymbolData = it;
970     bool Local = isLocal(*it);
971     const MCSymbol &RefSymbol = AliasedSymbol(Symbol);
972
973     if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
974       SetBinding(*it, ELF::STB_WEAK);
975
976     if (it->isCommon()) {
977       assert(!Local);
978       MSD.SectionIndex = ELF::SHN_COMMON;
979     } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
980       MSD.SectionIndex = ELF::SHN_ABS;
981     } else if (RefSymbol.isUndefined()) {
982       MSD.SectionIndex = ELF::SHN_UNDEF;
983     } else {
984       const MCSectionELF &Section =
985         static_cast<const MCSectionELF&>(RefSymbol.getSection());
986       MSD.SectionIndex = SectionIndexMap.lookup(&Section);
987       if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
988         NeedsSymtabShndx = true;
989       assert(MSD.SectionIndex && "Invalid section index!");
990     }
991
992     // The @@@ in symbol version is replaced with @ in undefined symbols and
993     // @@ in defined ones.
994     StringRef Name = Symbol.getName();
995     size_t Pos = Name.find("@@@");
996     std::string FinalName;
997     if (Pos != StringRef::npos) {
998       StringRef Prefix = Name.substr(0, Pos);
999       unsigned n = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1000       StringRef Suffix = Name.substr(Pos + n);
1001       FinalName = Prefix.str() + Suffix.str();
1002     } else {
1003       FinalName = Name.str();
1004     }
1005
1006     uint64_t &Entry = StringIndexMap[FinalName];
1007     if (!Entry) {
1008       Entry = StringTable.size();
1009       StringTable += FinalName;
1010       StringTable += '\x00';
1011     }
1012     MSD.StringIndex = Entry;
1013     if (MSD.SectionIndex == ELF::SHN_UNDEF)
1014       UndefinedSymbolData.push_back(MSD);
1015     else if (Local)
1016       LocalSymbolData.push_back(MSD);
1017     else
1018       ExternalSymbolData.push_back(MSD);
1019   }
1020
1021   // Symbols are required to be in lexicographic order.
1022   array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1023   array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1024   array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1025
1026   // Set the symbol indices. Local symbols must come before all other
1027   // symbols with non-local bindings.
1028   unsigned Index = 0;
1029   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1030     LocalSymbolData[i].SymbolData->setIndex(Index++);
1031   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1032     ExternalSymbolData[i].SymbolData->setIndex(Index++);
1033   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1034     UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1035 }
1036
1037 void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
1038                                           const MCSectionData &SD) {
1039   if (!Relocations[&SD].empty()) {
1040     MCContext &Ctx = Asm.getContext();
1041     const MCSectionELF *RelaSection;
1042     const MCSectionELF &Section =
1043       static_cast<const MCSectionELF&>(SD.getSection());
1044
1045     const StringRef SectionName = Section.getSectionName();
1046     std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
1047     RelaSectionName += SectionName;
1048
1049     unsigned EntrySize;
1050     if (HasRelocationAddend)
1051       EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1052     else
1053       EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1054
1055     RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
1056                                     ELF::SHT_RELA : ELF::SHT_REL, 0,
1057                                     SectionKind::getReadOnly(),
1058                                     EntrySize);
1059
1060     MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1061     RelaSD.setAlignment(Is64Bit ? 8 : 4);
1062
1063     MCDataFragment *F = new MCDataFragment(&RelaSD);
1064
1065     WriteRelocationsFragment(Asm, F, &SD);
1066
1067     Asm.AddSectionToTheEnd(*Writer, RelaSD, Layout);
1068   }
1069 }
1070
1071 void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1072                                            uint64_t Flags, uint64_t Address,
1073                                            uint64_t Offset, uint64_t Size,
1074                                            uint32_t Link, uint32_t Info,
1075                                            uint64_t Alignment,
1076                                            uint64_t EntrySize) {
1077   Write32(Name);        // sh_name: index into string table
1078   Write32(Type);        // sh_type
1079   WriteWord(Flags);     // sh_flags
1080   WriteWord(Address);   // sh_addr
1081   WriteWord(Offset);    // sh_offset
1082   WriteWord(Size);      // sh_size
1083   Write32(Link);        // sh_link
1084   Write32(Info);        // sh_info
1085   WriteWord(Alignment); // sh_addralign
1086   WriteWord(EntrySize); // sh_entsize
1087 }
1088
1089 void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
1090                                                    MCDataFragment *F,
1091                                                    const MCSectionData *SD) {
1092   std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1093   // sort by the r_offset just like gnu as does
1094   array_pod_sort(Relocs.begin(), Relocs.end());
1095
1096   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1097     ELFRelocationEntry entry = Relocs[e - i - 1];
1098
1099     if (entry.Index < 0)
1100       entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1101     else
1102       entry.Index += LocalSymbolData.size() + 1;
1103     if (Is64Bit) {
1104       String64(*F, entry.r_offset);
1105
1106       struct ELF::Elf64_Rela ERE64;
1107       ERE64.setSymbolAndType(entry.Index, entry.Type);
1108       String64(*F, ERE64.r_info);
1109
1110       if (HasRelocationAddend)
1111         String64(*F, entry.r_addend);
1112     } else {
1113       String32(*F, entry.r_offset);
1114
1115       struct ELF::Elf32_Rela ERE32;
1116       ERE32.setSymbolAndType(entry.Index, entry.Type);
1117       String32(*F, ERE32.r_info);
1118
1119       if (HasRelocationAddend)
1120         String32(*F, entry.r_addend);
1121     }
1122   }
1123 }
1124
1125 void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
1126                                                  MCAsmLayout &Layout,
1127                                     const SectionIndexMapTy &SectionIndexMap) {
1128   MCContext &Ctx = Asm.getContext();
1129   MCDataFragment *F;
1130
1131   unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1132
1133   // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1134   const MCSectionELF *ShstrtabSection =
1135     Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1136                       SectionKind::getReadOnly(), false);
1137   MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1138   ShstrtabSD.setAlignment(1);
1139   ShstrtabIndex = Asm.size();
1140
1141   const MCSectionELF *SymtabSection =
1142     Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1143                       SectionKind::getReadOnly(),
1144                       EntrySize);
1145   MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1146   SymtabSD.setAlignment(Is64Bit ? 8 : 4);
1147   SymbolTableIndex = Asm.size();
1148
1149   MCSectionData *SymtabShndxSD = NULL;
1150
1151   if (NeedsSymtabShndx) {
1152     const MCSectionELF *SymtabShndxSection =
1153       Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1154                         SectionKind::getReadOnly(), 4);
1155     SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1156     SymtabShndxSD->setAlignment(4);
1157   }
1158
1159   const MCSection *StrtabSection;
1160   StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1161                                     SectionKind::getReadOnly(), false);
1162   MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1163   StrtabSD.setAlignment(1);
1164   StringTableIndex = Asm.size();
1165
1166   WriteRelocations(Asm, Layout);
1167
1168   // Symbol table
1169   F = new MCDataFragment(&SymtabSD);
1170   MCDataFragment *ShndxF = NULL;
1171   if (NeedsSymtabShndx) {
1172     ShndxF = new MCDataFragment(SymtabShndxSD);
1173     Asm.AddSectionToTheEnd(*Writer, *SymtabShndxSD, Layout);
1174   }
1175   WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1176   Asm.AddSectionToTheEnd(*Writer, SymtabSD, Layout);
1177
1178   F = new MCDataFragment(&StrtabSD);
1179   F->getContents().append(StringTable.begin(), StringTable.end());
1180   Asm.AddSectionToTheEnd(*Writer, StrtabSD, Layout);
1181
1182   F = new MCDataFragment(&ShstrtabSD);
1183
1184   // Section header string table.
1185   //
1186   // The first entry of a string table holds a null character so skip
1187   // section 0.
1188   uint64_t Index = 1;
1189   F->getContents() += '\x00';
1190
1191   for (MCAssembler::const_iterator it = Asm.begin(),
1192          ie = Asm.end(); it != ie; ++it) {
1193     const MCSectionELF &Section =
1194       static_cast<const MCSectionELF&>(it->getSection());
1195     // FIXME: We could merge suffixes like in .text and .rela.text.
1196
1197     // Remember the index into the string table so we can write it
1198     // into the sh_name field of the section header table.
1199     SectionStringTableIndex[&it->getSection()] = Index;
1200
1201     Index += Section.getSectionName().size() + 1;
1202     F->getContents() += Section.getSectionName();
1203     F->getContents() += '\x00';
1204   }
1205
1206   Asm.AddSectionToTheEnd(*Writer, ShstrtabSD, Layout);
1207 }
1208
1209 bool ELFObjectWriterImpl::IsFixupFullyResolved(const MCAssembler &Asm,
1210                                                const MCValue Target,
1211                                                bool IsPCRel,
1212                                                const MCFragment *DF) const {
1213   // If this is a PCrel relocation, find the section this fixup value is
1214   // relative to.
1215   const MCSection *BaseSection = 0;
1216   if (IsPCRel) {
1217     BaseSection = &DF->getParent()->getSection();
1218     assert(BaseSection);
1219   }
1220
1221   const MCSection *SectionA = 0;
1222   const MCSymbol *SymbolA = 0;
1223   if (const MCSymbolRefExpr *A = Target.getSymA()) {
1224     SymbolA = &A->getSymbol();
1225     SectionA = &SymbolA->getSection();
1226   }
1227
1228   const MCSection *SectionB = 0;
1229   if (const MCSymbolRefExpr *B = Target.getSymB()) {
1230     SectionB = &B->getSymbol().getSection();
1231   }
1232
1233   if (!BaseSection)
1234     return SectionA == SectionB;
1235
1236   const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1237   if (DataA.isExternal())
1238     return false;
1239
1240   return !SectionB && BaseSection == SectionA;
1241 }
1242
1243 void ELFObjectWriterImpl::WriteObject(MCAssembler &Asm,
1244                                       const MCAsmLayout &Layout) {
1245   SectionIndexMapTy SectionIndexMap;
1246
1247   ComputeIndexMap(Asm, SectionIndexMap);
1248
1249   // Compute symbol table information.
1250   ComputeSymbolTable(Asm, SectionIndexMap);
1251
1252   CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1253                          const_cast<MCAsmLayout&>(Layout),
1254                          SectionIndexMap);
1255
1256   // Add 1 for the null section.
1257   unsigned NumSections = Asm.size() + 1;
1258   uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1259   uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1260   uint64_t FileOff = HeaderSize;
1261
1262   for (MCAssembler::const_iterator it = Asm.begin(),
1263          ie = Asm.end(); it != ie; ++it) {
1264     const MCSectionData &SD = *it;
1265
1266     FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1267
1268     // Get the size of the section in the output file (including padding).
1269     uint64_t Size = Layout.getSectionFileSize(&SD);
1270
1271     FileOff += Size;
1272   }
1273
1274   FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1275
1276   // Write out the ELF header ...
1277   WriteHeader(FileOff - HeaderSize, NumSections);
1278
1279   FileOff = HeaderSize;
1280
1281   // ... then all of the sections ...
1282   DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1283
1284   for (MCAssembler::const_iterator it = Asm.begin(),
1285          ie = Asm.end(); it != ie; ++it) {
1286     const MCSectionData &SD = *it;
1287
1288     uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1289     WriteZeros(Padding);
1290     FileOff += Padding;
1291
1292     // Remember the offset into the file for this section.
1293     SectionOffsetMap[&it->getSection()] = FileOff;
1294
1295     FileOff += Layout.getSectionFileSize(&SD);
1296
1297     Asm.WriteSectionData(it, Layout, Writer);
1298   }
1299
1300   uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1301   WriteZeros(Padding);
1302   FileOff += Padding;
1303
1304   // ... and then the section header table.
1305   // Should we align the section header table?
1306   //
1307   // Null section first.
1308   uint64_t FirstSectionSize =
1309     NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1310   uint32_t FirstSectionLink =
1311     ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1312   WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1313
1314   for (MCAssembler::const_iterator it = Asm.begin(),
1315          ie = Asm.end(); it != ie; ++it) {
1316     const MCSectionData &SD = *it;
1317     const MCSectionELF &Section =
1318       static_cast<const MCSectionELF&>(SD.getSection());
1319
1320     uint64_t sh_link = 0;
1321     uint64_t sh_info = 0;
1322
1323     switch(Section.getType()) {
1324     case ELF::SHT_DYNAMIC:
1325       sh_link = SectionStringTableIndex[&it->getSection()];
1326       sh_info = 0;
1327       break;
1328
1329     case ELF::SHT_REL:
1330     case ELF::SHT_RELA: {
1331       const MCSectionELF *SymtabSection;
1332       const MCSectionELF *InfoSection;
1333
1334       SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1335                                                      SectionKind::getReadOnly(),
1336                                                      false);
1337       sh_link = SectionIndexMap[SymtabSection];
1338
1339       // Remove ".rel" and ".rela" prefixes.
1340       unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1341       StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1342
1343       InfoSection = Asm.getContext().getELFSection(SectionName,
1344                                                    ELF::SHT_PROGBITS, 0,
1345                                                    SectionKind::getReadOnly(),
1346                                                    false);
1347       sh_info = SectionIndexMap[InfoSection];
1348       break;
1349     }
1350
1351     case ELF::SHT_SYMTAB:
1352     case ELF::SHT_DYNSYM:
1353       sh_link = StringTableIndex;
1354       sh_info = LastLocalSymbolIndex;
1355       break;
1356
1357     case ELF::SHT_SYMTAB_SHNDX:
1358       sh_link = SymbolTableIndex;
1359       break;
1360
1361     case ELF::SHT_PROGBITS:
1362     case ELF::SHT_STRTAB:
1363     case ELF::SHT_NOBITS:
1364     case ELF::SHT_NULL:
1365     case ELF::SHT_ARM_ATTRIBUTES:
1366       // Nothing to do.
1367       break;
1368
1369     default:
1370       assert(0 && "FIXME: sh_type value not supported!");
1371       break;
1372     }
1373
1374     WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
1375                      Section.getType(), Section.getFlags(),
1376                      0,
1377                      SectionOffsetMap.lookup(&SD.getSection()),
1378                      Layout.getSectionSize(&SD), sh_link,
1379                      sh_info, SD.getAlignment(),
1380                      Section.getEntrySize());
1381   }
1382 }
1383
1384 ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1385                                  bool Is64Bit,
1386                                  Triple::OSType OSType,
1387                                  uint16_t EMachine,
1388                                  bool IsLittleEndian,
1389                                  bool HasRelocationAddend)
1390   : MCObjectWriter(OS, IsLittleEndian)
1391 {
1392   Impl = new ELFObjectWriterImpl(this, Is64Bit, EMachine,
1393                                  HasRelocationAddend, OSType);
1394 }
1395
1396 ELFObjectWriter::~ELFObjectWriter() {
1397   delete (ELFObjectWriterImpl*) Impl;
1398 }
1399
1400 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1401   ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1402 }
1403
1404 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1405                                        const MCAsmLayout &Layout,
1406                                        const MCFragment *Fragment,
1407                                        const MCFixup &Fixup, MCValue Target,
1408                                        uint64_t &FixedValue) {
1409   ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1410                                                   Target, FixedValue);
1411 }
1412
1413 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1414                                            const MCValue Target,
1415                                            bool IsPCRel,
1416                                            const MCFragment *DF) const {
1417   return ((ELFObjectWriterImpl*) Impl)->IsFixupFullyResolved(Asm, Target,
1418                                                              IsPCRel, DF);
1419 }
1420
1421 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1422                                   const MCAsmLayout &Layout) {
1423   ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);
1424 }