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