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