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