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