f8caee9882f6b479b70f8d290b61bb2d82407125
[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     size_t Pos = Name.find("@@@");
1020     std::string FinalName;
1021     if (Pos != StringRef::npos) {
1022       StringRef Prefix = Name.substr(0, Pos);
1023       unsigned n = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1024       StringRef Suffix = Name.substr(Pos + n);
1025       FinalName = Prefix.str() + Suffix.str();
1026     } else {
1027       FinalName = Name.str();
1028     }
1029
1030     uint64_t &Entry = StringIndexMap[FinalName];
1031     if (!Entry) {
1032       Entry = StringTable.size();
1033       StringTable += FinalName;
1034       StringTable += '\x00';
1035     }
1036     MSD.StringIndex = Entry;
1037     if (MSD.SectionIndex == ELF::SHN_UNDEF)
1038       UndefinedSymbolData.push_back(MSD);
1039     else if (Local)
1040       LocalSymbolData.push_back(MSD);
1041     else
1042       ExternalSymbolData.push_back(MSD);
1043   }
1044
1045   // Symbols are required to be in lexicographic order.
1046   array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1047   array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1048   array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1049
1050   // Set the symbol indices. Local symbols must come before all other
1051   // symbols with non-local bindings.
1052   unsigned Index = 0;
1053   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1054     LocalSymbolData[i].SymbolData->setIndex(Index++);
1055   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1056     ExternalSymbolData[i].SymbolData->setIndex(Index++);
1057   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1058     UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1059 }
1060
1061 void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
1062                                           const MCSectionData &SD) {
1063   if (!Relocations[&SD].empty()) {
1064     MCContext &Ctx = Asm.getContext();
1065     const MCSectionELF *RelaSection;
1066     const MCSectionELF &Section =
1067       static_cast<const MCSectionELF&>(SD.getSection());
1068
1069     const StringRef SectionName = Section.getSectionName();
1070     std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
1071     RelaSectionName += SectionName;
1072
1073     unsigned EntrySize;
1074     if (HasRelocationAddend)
1075       EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1076     else
1077       EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1078
1079     RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
1080                                     ELF::SHT_RELA : ELF::SHT_REL, 0,
1081                                     SectionKind::getReadOnly(),
1082                                     EntrySize, "");
1083
1084     MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1085     RelaSD.setAlignment(Is64Bit ? 8 : 4);
1086
1087     MCDataFragment *F = new MCDataFragment(&RelaSD);
1088
1089     WriteRelocationsFragment(Asm, F, &SD);
1090
1091     Asm.AddSectionToTheEnd(*Writer, RelaSD, Layout);
1092   }
1093 }
1094
1095 void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1096                                            uint64_t Flags, uint64_t Address,
1097                                            uint64_t Offset, uint64_t Size,
1098                                            uint32_t Link, uint32_t Info,
1099                                            uint64_t Alignment,
1100                                            uint64_t EntrySize) {
1101   Write32(Name);        // sh_name: index into string table
1102   Write32(Type);        // sh_type
1103   WriteWord(Flags);     // sh_flags
1104   WriteWord(Address);   // sh_addr
1105   WriteWord(Offset);    // sh_offset
1106   WriteWord(Size);      // sh_size
1107   Write32(Link);        // sh_link
1108   Write32(Info);        // sh_info
1109   WriteWord(Alignment); // sh_addralign
1110   WriteWord(EntrySize); // sh_entsize
1111 }
1112
1113 void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
1114                                                    MCDataFragment *F,
1115                                                    const MCSectionData *SD) {
1116   std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1117   // sort by the r_offset just like gnu as does
1118   array_pod_sort(Relocs.begin(), Relocs.end());
1119
1120   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1121     ELFRelocationEntry entry = Relocs[e - i - 1];
1122
1123     if (entry.Index < 0)
1124       entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1125     else
1126       entry.Index += LocalSymbolData.size() + 1;
1127     if (Is64Bit) {
1128       String64(*F, entry.r_offset);
1129
1130       struct ELF::Elf64_Rela ERE64;
1131       ERE64.setSymbolAndType(entry.Index, entry.Type);
1132       String64(*F, ERE64.r_info);
1133
1134       if (HasRelocationAddend)
1135         String64(*F, entry.r_addend);
1136     } else {
1137       String32(*F, entry.r_offset);
1138
1139       struct ELF::Elf32_Rela ERE32;
1140       ERE32.setSymbolAndType(entry.Index, entry.Type);
1141       String32(*F, ERE32.r_info);
1142
1143       if (HasRelocationAddend)
1144         String32(*F, entry.r_addend);
1145     }
1146   }
1147 }
1148
1149 void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
1150                                                  MCAsmLayout &Layout,
1151                                     const SectionIndexMapTy &SectionIndexMap) {
1152   MCContext &Ctx = Asm.getContext();
1153   MCDataFragment *F;
1154
1155   unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1156
1157   // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1158   const MCSectionELF *ShstrtabSection =
1159     Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1160                       SectionKind::getReadOnly());
1161   MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1162   ShstrtabSD.setAlignment(1);
1163   ShstrtabIndex = Asm.size();
1164
1165   const MCSectionELF *SymtabSection =
1166     Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1167                       SectionKind::getReadOnly(),
1168                       EntrySize, "");
1169   MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1170   SymtabSD.setAlignment(Is64Bit ? 8 : 4);
1171   SymbolTableIndex = Asm.size();
1172
1173   MCSectionData *SymtabShndxSD = NULL;
1174
1175   if (NeedsSymtabShndx) {
1176     const MCSectionELF *SymtabShndxSection =
1177       Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1178                         SectionKind::getReadOnly(), 4, "");
1179     SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1180     SymtabShndxSD->setAlignment(4);
1181   }
1182
1183   const MCSection *StrtabSection;
1184   StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1185                                     SectionKind::getReadOnly());
1186   MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1187   StrtabSD.setAlignment(1);
1188   StringTableIndex = Asm.size();
1189
1190   WriteRelocations(Asm, Layout);
1191
1192   // Symbol table
1193   F = new MCDataFragment(&SymtabSD);
1194   MCDataFragment *ShndxF = NULL;
1195   if (NeedsSymtabShndx) {
1196     ShndxF = new MCDataFragment(SymtabShndxSD);
1197     Asm.AddSectionToTheEnd(*Writer, *SymtabShndxSD, Layout);
1198   }
1199   WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1200   Asm.AddSectionToTheEnd(*Writer, SymtabSD, Layout);
1201
1202   F = new MCDataFragment(&StrtabSD);
1203   F->getContents().append(StringTable.begin(), StringTable.end());
1204   Asm.AddSectionToTheEnd(*Writer, StrtabSD, Layout);
1205
1206   F = new MCDataFragment(&ShstrtabSD);
1207
1208   // Section header string table.
1209   //
1210   // The first entry of a string table holds a null character so skip
1211   // section 0.
1212   uint64_t Index = 1;
1213   F->getContents() += '\x00';
1214
1215   StringMap<uint64_t> SecStringMap;
1216   for (MCAssembler::const_iterator it = Asm.begin(),
1217          ie = Asm.end(); it != ie; ++it) {
1218     const MCSectionELF &Section =
1219       static_cast<const MCSectionELF&>(it->getSection());
1220     // FIXME: We could merge suffixes like in .text and .rela.text.
1221
1222     StringRef Name = Section.getSectionName();
1223     if (SecStringMap.count(Name)) {
1224       SectionStringTableIndex[&Section] =  SecStringMap[Name];
1225       continue;
1226     }
1227     // Remember the index into the string table so we can write it
1228     // into the sh_name field of the section header table.
1229     SectionStringTableIndex[&Section] = Index;
1230     SecStringMap[Name] = Index;
1231
1232     Index += Name.size() + 1;
1233     F->getContents() += Name;
1234     F->getContents() += '\x00';
1235   }
1236
1237   Asm.AddSectionToTheEnd(*Writer, ShstrtabSD, Layout);
1238 }
1239
1240 bool ELFObjectWriterImpl::IsFixupFullyResolved(const MCAssembler &Asm,
1241                                                const MCValue Target,
1242                                                bool IsPCRel,
1243                                                const MCFragment *DF) const {
1244   // If this is a PCrel relocation, find the section this fixup value is
1245   // relative to.
1246   const MCSection *BaseSection = 0;
1247   if (IsPCRel) {
1248     BaseSection = &DF->getParent()->getSection();
1249     assert(BaseSection);
1250   }
1251
1252   const MCSection *SectionA = 0;
1253   const MCSymbol *SymbolA = 0;
1254   if (const MCSymbolRefExpr *A = Target.getSymA()) {
1255     SymbolA = &A->getSymbol();
1256     SectionA = &SymbolA->getSection();
1257   }
1258
1259   const MCSection *SectionB = 0;
1260   if (const MCSymbolRefExpr *B = Target.getSymB()) {
1261     SectionB = &B->getSymbol().getSection();
1262   }
1263
1264   if (!BaseSection)
1265     return SectionA == SectionB;
1266
1267   const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1268   if (DataA.isExternal())
1269     return false;
1270
1271   return !SectionB && BaseSection == SectionA;
1272 }
1273
1274 void ELFObjectWriterImpl::CreateGroupSections(MCAssembler &Asm,
1275                                               MCAsmLayout &Layout,
1276                                               GroupMapTy &GroupMap) {
1277   typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
1278   // Build the groups
1279   RevGroupMapTy Groups;
1280   for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1281        it != ie; ++it) {
1282     const MCSectionELF &Section =
1283       static_cast<const MCSectionELF&>(it->getSection());
1284     if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1285       continue;
1286
1287     const MCSymbol *SignatureSymbol = Section.getGroup();
1288     Asm.getOrCreateSymbolData(*SignatureSymbol);
1289     const MCSectionELF *&Group = Groups[SignatureSymbol];
1290     if (!Group) {
1291       Group = Asm.getContext().CreateELFGroupSection();
1292       MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1293       Data.setAlignment(4);
1294       MCDataFragment *F = new MCDataFragment(&Data);
1295       String32(*F, ELF::GRP_COMDAT);
1296     }
1297     GroupMap[Group] = SignatureSymbol;
1298   }
1299
1300   // Add sections to the groups
1301   unsigned Index = 1;
1302   unsigned NumGroups = Groups.size();
1303   for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1304        it != ie; ++it, ++Index) {
1305     const MCSectionELF &Section =
1306       static_cast<const MCSectionELF&>(it->getSection());
1307     if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1308       continue;
1309     const MCSectionELF *Group = Groups[Section.getGroup()];
1310     MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1311     // FIXME: we could use the previous fragment
1312     MCDataFragment *F = new MCDataFragment(&Data);
1313     String32(*F, NumGroups + Index);
1314   }
1315
1316   for (RevGroupMapTy::const_iterator i = Groups.begin(), e = Groups.end();
1317        i != e; ++i) {
1318     const MCSectionELF *Group = i->second;
1319     MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1320     Asm.AddSectionToTheEnd(*Writer, Data, Layout);
1321   }
1322 }
1323
1324 void ELFObjectWriterImpl::WriteSection(MCAssembler &Asm,
1325                                        const SectionIndexMapTy &SectionIndexMap,
1326                                        uint32_t GroupSymbolIndex,
1327                                        uint64_t Offset, uint64_t Size,
1328                                        uint64_t Alignment,
1329                                        const MCSectionELF &Section) {
1330   uint64_t sh_link = 0;
1331   uint64_t sh_info = 0;
1332
1333   switch(Section.getType()) {
1334   case ELF::SHT_DYNAMIC:
1335     sh_link = SectionStringTableIndex[&Section];
1336     sh_info = 0;
1337     break;
1338
1339   case ELF::SHT_REL:
1340   case ELF::SHT_RELA: {
1341     const MCSectionELF *SymtabSection;
1342     const MCSectionELF *InfoSection;
1343     SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1344                                                    0,
1345                                                    SectionKind::getReadOnly());
1346     sh_link = SectionIndexMap.lookup(SymtabSection);
1347     assert(sh_link && ".symtab not found");
1348
1349     // Remove ".rel" and ".rela" prefixes.
1350     unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1351     StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1352
1353     InfoSection = Asm.getContext().getELFSection(SectionName,
1354                                                  ELF::SHT_PROGBITS, 0,
1355                                                  SectionKind::getReadOnly());
1356     sh_info = SectionIndexMap.lookup(InfoSection);
1357     break;
1358   }
1359
1360   case ELF::SHT_SYMTAB:
1361   case ELF::SHT_DYNSYM:
1362     sh_link = StringTableIndex;
1363     sh_info = LastLocalSymbolIndex;
1364     break;
1365
1366   case ELF::SHT_SYMTAB_SHNDX:
1367     sh_link = SymbolTableIndex;
1368     break;
1369
1370   case ELF::SHT_PROGBITS:
1371   case ELF::SHT_STRTAB:
1372   case ELF::SHT_NOBITS:
1373   case ELF::SHT_NULL:
1374   case ELF::SHT_ARM_ATTRIBUTES:
1375     // Nothing to do.
1376     break;
1377
1378   case ELF::SHT_GROUP: {
1379     sh_link = SymbolTableIndex;
1380     sh_info = GroupSymbolIndex;
1381     break;
1382   }
1383
1384   default:
1385     assert(0 && "FIXME: sh_type value not supported!");
1386     break;
1387   }
1388
1389   WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1390                    Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1391                    Alignment, Section.getEntrySize());
1392 }
1393
1394 void ELFObjectWriterImpl::WriteObject(MCAssembler &Asm,
1395                                       const MCAsmLayout &Layout) {
1396
1397   GroupMapTy GroupMap;
1398   CreateGroupSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap);
1399
1400   SectionIndexMapTy SectionIndexMap;
1401
1402   ComputeIndexMap(Asm, SectionIndexMap);
1403
1404   // Compute symbol table information.
1405   ComputeSymbolTable(Asm, SectionIndexMap);
1406
1407   CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1408                          const_cast<MCAsmLayout&>(Layout),
1409                          SectionIndexMap);
1410
1411   // Update to include the metadata sections.
1412   ComputeIndexMap(Asm, SectionIndexMap);
1413
1414   // Add 1 for the null section.
1415   unsigned NumSections = Asm.size() + 1;
1416   uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1417   uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1418   uint64_t FileOff = HeaderSize;
1419
1420   std::vector<const MCSectionELF*> Sections;
1421   Sections.resize(NumSections);
1422
1423   for (SectionIndexMapTy::const_iterator i=
1424          SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1425     const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1426     Sections[p.second] = p.first;
1427   }
1428
1429   for (unsigned i = 1; i < NumSections; ++i) {
1430     const MCSectionELF &Section = *Sections[i];
1431     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1432
1433     FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1434
1435     // Get the size of the section in the output file (including padding).
1436     uint64_t Size = Layout.getSectionFileSize(&SD);
1437
1438     FileOff += Size;
1439   }
1440
1441   FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1442
1443   // Write out the ELF header ...
1444   WriteHeader(FileOff - HeaderSize, NumSections);
1445
1446   FileOff = HeaderSize;
1447
1448   // ... then all of the sections ...
1449   DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1450
1451   for (unsigned i = 1; i < NumSections; ++i) {
1452     const MCSectionELF &Section = *Sections[i];
1453     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1454
1455     uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1456     WriteZeros(Padding);
1457     FileOff += Padding;
1458
1459     // Remember the offset into the file for this section.
1460     SectionOffsetMap[&Section] = FileOff;
1461
1462     FileOff += Layout.getSectionFileSize(&SD);
1463
1464     Asm.WriteSectionData(&SD, Layout, Writer);
1465   }
1466
1467   uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1468   WriteZeros(Padding);
1469   FileOff += Padding;
1470
1471   // ... and then the section header table.
1472   // Should we align the section header table?
1473   //
1474   // Null section first.
1475   uint64_t FirstSectionSize =
1476     NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1477   uint32_t FirstSectionLink =
1478     ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1479   WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1480
1481   for (unsigned i = 1; i < NumSections; ++i) {
1482     const MCSectionELF &Section = *Sections[i];
1483     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1484     uint32_t GroupSymbolIndex;
1485     if (Section.getType() != ELF::SHT_GROUP)
1486       GroupSymbolIndex = 0;
1487     else
1488       GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, GroupMap[&Section]);
1489
1490     WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1491                  SectionOffsetMap[&Section], Layout.getSectionSize(&SD),
1492                  SD.getAlignment(), Section);
1493   }
1494 }
1495
1496 ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1497                                  bool Is64Bit,
1498                                  Triple::OSType OSType,
1499                                  uint16_t EMachine,
1500                                  bool IsLittleEndian,
1501                                  bool HasRelocationAddend)
1502   : MCObjectWriter(OS, IsLittleEndian)
1503 {
1504   Impl = new ELFObjectWriterImpl(this, Is64Bit, EMachine,
1505                                  HasRelocationAddend, OSType);
1506 }
1507
1508 ELFObjectWriter::~ELFObjectWriter() {
1509   delete (ELFObjectWriterImpl*) Impl;
1510 }
1511
1512 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1513   ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1514 }
1515
1516 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1517                                        const MCAsmLayout &Layout,
1518                                        const MCFragment *Fragment,
1519                                        const MCFixup &Fixup, MCValue Target,
1520                                        uint64_t &FixedValue) {
1521   ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1522                                                   Target, FixedValue);
1523 }
1524
1525 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1526                                            const MCValue Target,
1527                                            bool IsPCRel,
1528                                            const MCFragment *DF) const {
1529   return ((ELFObjectWriterImpl*) Impl)->IsFixupFullyResolved(Asm, Target,
1530                                                              IsPCRel, DF);
1531 }
1532
1533 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1534                                   const MCAsmLayout &Layout) {
1535   ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);
1536 }