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