MC/Mach-O: Shuffle enums a bit to make it harder to inadvertently use the wrong
[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
522   if (Symbol.isAbsolute() && Symbol.isVariable()) {
523     if (const MCExpr *Value = Symbol.getVariableValue()) {
524       int64_t IntValue;
525       if (Value->EvaluateAsAbsolute(IntValue, Layout))
526         return (uint64_t)IntValue;
527     }
528   }
529
530   if (!Symbol.isInSection())
531     return 0;
532
533   if (Data.getFragment())
534     return Layout.getSymbolOffset(&Data);
535
536   return 0;
537 }
538
539 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
540                                                const MCAsmLayout &Layout) {
541   // The presence of symbol versions causes undefined symbols and
542   // versions declared with @@@ to be renamed.
543
544   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
545          ie = Asm.symbol_end(); it != ie; ++it) {
546     const MCSymbol &Alias = it->getSymbol();
547     const MCSymbol &Symbol = Alias.AliasedSymbol();
548     MCSymbolData &SD = Asm.getSymbolData(Symbol);
549
550     // Not an alias.
551     if (&Symbol == &Alias)
552       continue;
553
554     StringRef AliasName = Alias.getName();
555     size_t Pos = AliasName.find('@');
556     if (Pos == StringRef::npos)
557       continue;
558
559     // Aliases defined with .symvar copy the binding from the symbol they alias.
560     // This is the first place we are able to copy this information.
561     it->setExternal(SD.isExternal());
562     SetBinding(*it, GetBinding(SD));
563
564     StringRef Rest = AliasName.substr(Pos);
565     if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
566       continue;
567
568     // FIXME: produce a better error message.
569     if (Symbol.isUndefined() && Rest.startswith("@@") &&
570         !Rest.startswith("@@@"))
571       report_fatal_error("A @@ version cannot be undefined");
572
573     Renames.insert(std::make_pair(&Symbol, &Alias));
574   }
575 }
576
577 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
578                                   MCDataFragment *ShndxF,
579                                   ELFSymbolData &MSD,
580                                   const MCAsmLayout &Layout) {
581   MCSymbolData &OrigData = *MSD.SymbolData;
582   MCSymbolData &Data =
583     Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
584
585   bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
586     Data.getSymbol().isVariable();
587
588   uint8_t Binding = GetBinding(OrigData);
589   uint8_t Visibility = GetVisibility(OrigData);
590   uint8_t Type = GetType(Data);
591
592   uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
593   uint8_t Other = Visibility;
594
595   uint64_t Value = SymbolValue(Data, Layout);
596   uint64_t Size = 0;
597   const MCExpr *ESize;
598
599   assert(!(Data.isCommon() && !Data.isExternal()));
600
601   ESize = Data.getSize();
602   if (Data.getSize()) {
603     MCValue Res;
604     if (ESize->getKind() == MCExpr::Binary) {
605       const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
606
607       if (BE->EvaluateAsRelocatable(Res, &Layout)) {
608         assert(!Res.getSymA() || !Res.getSymA()->getSymbol().isDefined());
609         assert(!Res.getSymB() || !Res.getSymB()->getSymbol().isDefined());
610         Size = Res.getConstant();
611       }
612     } else if (ESize->getKind() == MCExpr::Constant) {
613       Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
614     } else {
615       assert(0 && "Unsupported size expression");
616     }
617   }
618
619   // Write out the symbol table entry
620   WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
621                    Size, Other, MSD.SectionIndex, IsReserved);
622 }
623
624 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
625                                        MCDataFragment *ShndxF,
626                                        const MCAssembler &Asm,
627                                        const MCAsmLayout &Layout,
628                                      const SectionIndexMapTy &SectionIndexMap) {
629   // The string table must be emitted first because we need the index
630   // into the string table for all the symbol names.
631   assert(StringTable.size() && "Missing string table");
632
633   // FIXME: Make sure the start of the symbol table is aligned.
634
635   // The first entry is the undefined symbol entry.
636   WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
637
638   // Write the symbol table entries.
639   LastLocalSymbolIndex = LocalSymbolData.size() + 1;
640   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
641     ELFSymbolData &MSD = LocalSymbolData[i];
642     WriteSymbol(SymtabF, ShndxF, MSD, Layout);
643   }
644
645   // Write out a symbol table entry for each regular section.
646   for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
647        ++i) {
648     const MCSectionELF &Section =
649       static_cast<const MCSectionELF&>(i->getSection());
650     if (Section.getType() == ELF::SHT_RELA ||
651         Section.getType() == ELF::SHT_REL ||
652         Section.getType() == ELF::SHT_STRTAB ||
653         Section.getType() == ELF::SHT_SYMTAB)
654       continue;
655     WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
656                      ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section), false);
657     LastLocalSymbolIndex++;
658   }
659
660   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
661     ELFSymbolData &MSD = ExternalSymbolData[i];
662     MCSymbolData &Data = *MSD.SymbolData;
663     assert(((Data.getFlags() & ELF_STB_Global) ||
664             (Data.getFlags() & ELF_STB_Weak)) &&
665            "External symbol requires STB_GLOBAL or STB_WEAK flag");
666     WriteSymbol(SymtabF, ShndxF, MSD, Layout);
667     if (GetBinding(Data) == ELF::STB_LOCAL)
668       LastLocalSymbolIndex++;
669   }
670
671   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
672     ELFSymbolData &MSD = UndefinedSymbolData[i];
673     MCSymbolData &Data = *MSD.SymbolData;
674     WriteSymbol(SymtabF, ShndxF, MSD, Layout);
675     if (GetBinding(Data) == ELF::STB_LOCAL)
676       LastLocalSymbolIndex++;
677   }
678 }
679
680 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
681                                                const MCValue &Target,
682                                                const MCFragment &F) const {
683   const MCSymbol &Symbol = Target.getSymA()->getSymbol();
684   const MCSymbol &ASymbol = Symbol.AliasedSymbol();
685   const MCSymbol *Renamed = Renames.lookup(&Symbol);
686   const MCSymbolData &SD = Asm.getSymbolData(Symbol);
687
688   if (ASymbol.isUndefined()) {
689     if (Renamed)
690       return Renamed;
691     return &ASymbol;
692   }
693
694   if (SD.isExternal()) {
695     if (Renamed)
696       return Renamed;
697     return &Symbol;
698   }
699
700   const MCSectionELF &Section =
701     static_cast<const MCSectionELF&>(ASymbol.getSection());
702   const SectionKind secKind = Section.getKind();
703
704   if (secKind.isBSS())
705     return NULL;
706
707   if (secKind.isThreadLocal()) {
708     if (Renamed)
709       return Renamed;
710     return &Symbol;
711   }
712
713   MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
714   const MCSectionELF &Sec2 =
715     static_cast<const MCSectionELF&>(F.getParent()->getSection());
716
717   if (&Sec2 != &Section &&
718       (Kind == MCSymbolRefExpr::VK_PLT ||
719        Kind == MCSymbolRefExpr::VK_GOTPCREL ||
720        Kind == MCSymbolRefExpr::VK_GOTOFF)) {
721     if (Renamed)
722       return Renamed;
723     return &Symbol;
724   }
725
726   if (Section.getFlags() & MCSectionELF::SHF_MERGE) {
727     if (Target.getConstant() == 0)
728       return NULL;
729     if (Renamed)
730       return Renamed;
731     return &Symbol;
732   }
733
734   return NULL;
735 }
736
737
738 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
739                                        const MCAsmLayout &Layout,
740                                        const MCFragment *Fragment,
741                                        const MCFixup &Fixup,
742                                        MCValue Target,
743                                        uint64_t &FixedValue) {
744   int64_t Addend = 0;
745   int Index = 0;
746   int64_t Value = Target.getConstant();
747   const MCSymbol *RelocSymbol = NULL;
748
749   bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
750   if (!Target.isAbsolute()) {
751     const MCSymbol &Symbol = Target.getSymA()->getSymbol();
752     const MCSymbol &ASymbol = Symbol.AliasedSymbol();
753     RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
754
755     if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
756       const MCSymbol &SymbolB = RefB->getSymbol();
757       MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
758       IsPCRel = true;
759
760       // Offset of the symbol in the section
761       int64_t a = Layout.getSymbolOffset(&SDB);
762
763       // Ofeset of the relocation in the section
764       int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
765       Value += b - a;
766     }
767
768     if (!RelocSymbol) {
769       MCSymbolData &SD = Asm.getSymbolData(ASymbol);
770       MCFragment *F = SD.getFragment();
771
772       Index = F->getParent()->getOrdinal() + 1;
773
774       // Offset of the symbol in the section
775       Value += Layout.getSymbolOffset(&SD);
776     } else {
777       if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
778         WeakrefUsedInReloc.insert(RelocSymbol);
779       else
780         UsedInReloc.insert(RelocSymbol);
781       Index = -1;
782     }
783     Addend = Value;
784     // Compensate for the addend on i386.
785     if (is64Bit())
786       Value = 0;
787   }
788
789   FixedValue = Value;
790   unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
791                                (RelocSymbol != 0), Addend);
792   
793   uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
794     Fixup.getOffset();
795
796   if (!hasRelocationAddend())
797     Addend = 0;
798   ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
799   Relocations[Fragment->getParent()].push_back(ERE);
800 }
801
802
803 uint64_t
804 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
805                                              const MCSymbol *S) {
806   MCSymbolData &SD = Asm.getSymbolData(*S);
807   return SD.getIndex();
808 }
809
810 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
811                        bool Used, bool Renamed) {
812   if (Data.getFlags() & ELF_Other_Weakref)
813     return false;
814
815   if (Used)
816     return true;
817
818   if (Renamed)
819     return false;
820
821   const MCSymbol &Symbol = Data.getSymbol();
822
823   if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
824     return true;
825
826   const MCSymbol &A = Symbol.AliasedSymbol();
827   if (!A.isVariable() && A.isUndefined() && !Data.isCommon())
828     return false;
829
830   if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
831     return false;
832
833   if (Symbol.isTemporary())
834     return false;
835
836   return true;
837 }
838
839 static bool isLocal(const MCSymbolData &Data, bool isSignature,
840                     bool isUsedInReloc) {
841   if (Data.isExternal())
842     return false;
843
844   const MCSymbol &Symbol = Data.getSymbol();
845   const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
846
847   if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
848     if (isSignature && !isUsedInReloc)
849       return true;
850
851     return false;
852   }
853
854   return true;
855 }
856
857 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
858                                       SectionIndexMapTy &SectionIndexMap) {
859   unsigned Index = 1;
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   for (MCAssembler::iterator it = Asm.begin(),
870          ie = Asm.end(); it != ie; ++it) {
871     const MCSectionELF &Section =
872       static_cast<const MCSectionELF &>(it->getSection());
873     if (Section.getType() == ELF::SHT_GROUP)
874       continue;
875     SectionIndexMap[&Section] = Index++;
876   }
877 }
878
879 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
880                                       const SectionIndexMapTy &SectionIndexMap,
881                                       RevGroupMapTy RevGroupMap) {
882   // FIXME: Is this the correct place to do this?
883   if (NeedsGOT) {
884     llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
885     MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
886     MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
887     Data.setExternal(true);
888     SetBinding(Data, ELF::STB_GLOBAL);
889   }
890
891   // Build section lookup table.
892   int NumRegularSections = Asm.size();
893
894   // Index 0 is always the empty string.
895   StringMap<uint64_t> StringIndexMap;
896   StringTable += '\x00';
897
898   // Add the data for the symbols.
899   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
900          ie = Asm.symbol_end(); it != ie; ++it) {
901     const MCSymbol &Symbol = it->getSymbol();
902
903     bool Used = UsedInReloc.count(&Symbol);
904     bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
905     bool isSignature = RevGroupMap.count(&Symbol);
906
907     if (!isInSymtab(Asm, *it,
908                     Used || WeakrefUsed || isSignature,
909                     Renames.count(&Symbol)))
910       continue;
911
912     ELFSymbolData MSD;
913     MSD.SymbolData = it;
914     const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
915
916     // Undefined symbols are global, but this is the first place we
917     // are able to set it.
918     bool Local = isLocal(*it, isSignature, Used);
919     if (!Local && GetBinding(*it) == ELF::STB_LOCAL) {
920       MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
921       SetBinding(*it, ELF::STB_GLOBAL);
922       SetBinding(SD, ELF::STB_GLOBAL);
923     }
924
925     if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
926       SetBinding(*it, ELF::STB_WEAK);
927
928     if (it->isCommon()) {
929       assert(!Local);
930       MSD.SectionIndex = ELF::SHN_COMMON;
931     } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
932       MSD.SectionIndex = ELF::SHN_ABS;
933     } else if (RefSymbol.isUndefined()) {
934       if (isSignature && !Used)
935         MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
936       else
937         MSD.SectionIndex = ELF::SHN_UNDEF;
938     } else {
939       const MCSectionELF &Section =
940         static_cast<const MCSectionELF&>(RefSymbol.getSection());
941       MSD.SectionIndex = SectionIndexMap.lookup(&Section);
942       if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
943         NeedsSymtabShndx = true;
944       assert(MSD.SectionIndex && "Invalid section index!");
945     }
946
947     // The @@@ in symbol version is replaced with @ in undefined symbols and
948     // @@ in defined ones.
949     StringRef Name = Symbol.getName();
950     SmallString<32> Buf;
951
952     size_t Pos = Name.find("@@@");
953     if (Pos != StringRef::npos) {
954       Buf += Name.substr(0, Pos);
955       unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
956       Buf += Name.substr(Pos + Skip);
957       Name = Buf;
958     }
959
960     uint64_t &Entry = StringIndexMap[Name];
961     if (!Entry) {
962       Entry = StringTable.size();
963       StringTable += Name;
964       StringTable += '\x00';
965     }
966     MSD.StringIndex = Entry;
967     if (MSD.SectionIndex == ELF::SHN_UNDEF)
968       UndefinedSymbolData.push_back(MSD);
969     else if (Local)
970       LocalSymbolData.push_back(MSD);
971     else
972       ExternalSymbolData.push_back(MSD);
973   }
974
975   // Symbols are required to be in lexicographic order.
976   array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
977   array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
978   array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
979
980   // Set the symbol indices. Local symbols must come before all other
981   // symbols with non-local bindings.
982   unsigned Index = 1;
983   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
984     LocalSymbolData[i].SymbolData->setIndex(Index++);
985
986   Index += NumRegularSections;
987
988   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
989     ExternalSymbolData[i].SymbolData->setIndex(Index++);
990   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
991     UndefinedSymbolData[i].SymbolData->setIndex(Index++);
992 }
993
994 void ELFObjectWriter::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
995                                       const MCSectionData &SD) {
996   if (!Relocations[&SD].empty()) {
997     MCContext &Ctx = Asm.getContext();
998     const MCSectionELF *RelaSection;
999     const MCSectionELF &Section =
1000       static_cast<const MCSectionELF&>(SD.getSection());
1001
1002     const StringRef SectionName = Section.getSectionName();
1003     std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1004     RelaSectionName += SectionName;
1005
1006     unsigned EntrySize;
1007     if (hasRelocationAddend())
1008       EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1009     else
1010       EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1011
1012     RelaSection = Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1013                                     ELF::SHT_RELA : ELF::SHT_REL, 0,
1014                                     SectionKind::getReadOnly(),
1015                                     EntrySize, "");
1016
1017     MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1018     RelaSD.setAlignment(is64Bit() ? 8 : 4);
1019
1020     MCDataFragment *F = new MCDataFragment(&RelaSD);
1021
1022     WriteRelocationsFragment(Asm, F, &SD);
1023   }
1024 }
1025
1026 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1027                                        uint64_t Flags, uint64_t Address,
1028                                        uint64_t Offset, uint64_t Size,
1029                                        uint32_t Link, uint32_t Info,
1030                                        uint64_t Alignment,
1031                                        uint64_t EntrySize) {
1032   Write32(Name);        // sh_name: index into string table
1033   Write32(Type);        // sh_type
1034   WriteWord(Flags);     // sh_flags
1035   WriteWord(Address);   // sh_addr
1036   WriteWord(Offset);    // sh_offset
1037   WriteWord(Size);      // sh_size
1038   Write32(Link);        // sh_link
1039   Write32(Info);        // sh_info
1040   WriteWord(Alignment); // sh_addralign
1041   WriteWord(EntrySize); // sh_entsize
1042 }
1043
1044 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1045                                                MCDataFragment *F,
1046                                                const MCSectionData *SD) {
1047   std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1048   // sort by the r_offset just like gnu as does
1049   array_pod_sort(Relocs.begin(), Relocs.end());
1050
1051   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1052     ELFRelocationEntry entry = Relocs[e - i - 1];
1053
1054     if (!entry.Index)
1055       ;
1056     else if (entry.Index < 0)
1057       entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1058     else
1059       entry.Index += LocalSymbolData.size();
1060     if (is64Bit()) {
1061       String64(*F, entry.r_offset);
1062
1063       struct ELF::Elf64_Rela ERE64;
1064       ERE64.setSymbolAndType(entry.Index, entry.Type);
1065       String64(*F, ERE64.r_info);
1066
1067       if (hasRelocationAddend())
1068         String64(*F, entry.r_addend);
1069     } else {
1070       String32(*F, entry.r_offset);
1071
1072       struct ELF::Elf32_Rela ERE32;
1073       ERE32.setSymbolAndType(entry.Index, entry.Type);
1074       String32(*F, ERE32.r_info);
1075
1076       if (hasRelocationAddend())
1077         String32(*F, entry.r_addend);
1078     }
1079   }
1080 }
1081
1082 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1083                                              MCAsmLayout &Layout,
1084                                     const SectionIndexMapTy &SectionIndexMap) {
1085   MCContext &Ctx = Asm.getContext();
1086   MCDataFragment *F;
1087
1088   unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1089
1090   // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1091   const MCSectionELF *ShstrtabSection =
1092     Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1093                       SectionKind::getReadOnly());
1094   MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1095   ShstrtabSD.setAlignment(1);
1096   ShstrtabIndex = Asm.size();
1097
1098   const MCSectionELF *SymtabSection =
1099     Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1100                       SectionKind::getReadOnly(),
1101                       EntrySize, "");
1102   MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1103   SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1104   SymbolTableIndex = Asm.size();
1105
1106   MCSectionData *SymtabShndxSD = NULL;
1107
1108   if (NeedsSymtabShndx) {
1109     const MCSectionELF *SymtabShndxSection =
1110       Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1111                         SectionKind::getReadOnly(), 4, "");
1112     SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1113     SymtabShndxSD->setAlignment(4);
1114   }
1115
1116   const MCSection *StrtabSection;
1117   StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1118                                     SectionKind::getReadOnly());
1119   MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1120   StrtabSD.setAlignment(1);
1121   StringTableIndex = Asm.size();
1122
1123   WriteRelocations(Asm, Layout);
1124
1125   // Symbol table
1126   F = new MCDataFragment(&SymtabSD);
1127   MCDataFragment *ShndxF = NULL;
1128   if (NeedsSymtabShndx) {
1129     ShndxF = new MCDataFragment(SymtabShndxSD);
1130   }
1131   WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1132
1133   F = new MCDataFragment(&StrtabSD);
1134   F->getContents().append(StringTable.begin(), StringTable.end());
1135
1136   F = new MCDataFragment(&ShstrtabSD);
1137
1138   // Section header string table.
1139   //
1140   // The first entry of a string table holds a null character so skip
1141   // section 0.
1142   uint64_t Index = 1;
1143   F->getContents() += '\x00';
1144
1145   StringMap<uint64_t> SecStringMap;
1146   for (MCAssembler::const_iterator it = Asm.begin(),
1147          ie = Asm.end(); it != ie; ++it) {
1148     const MCSectionELF &Section =
1149       static_cast<const MCSectionELF&>(it->getSection());
1150     // FIXME: We could merge suffixes like in .text and .rela.text.
1151
1152     StringRef Name = Section.getSectionName();
1153     if (SecStringMap.count(Name)) {
1154       SectionStringTableIndex[&Section] =  SecStringMap[Name];
1155       continue;
1156     }
1157     // Remember the index into the string table so we can write it
1158     // into the sh_name field of the section header table.
1159     SectionStringTableIndex[&Section] = Index;
1160     SecStringMap[Name] = Index;
1161
1162     Index += Name.size() + 1;
1163     F->getContents() += Name;
1164     F->getContents() += '\x00';
1165   }
1166 }
1167
1168 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1169                                            const MCValue Target,
1170                                            bool IsPCRel,
1171                                            const MCFragment *DF) const {
1172   // If this is a PCrel relocation, find the section this fixup value is
1173   // relative to.
1174   const MCSection *BaseSection = 0;
1175   if (IsPCRel) {
1176     BaseSection = &DF->getParent()->getSection();
1177     assert(BaseSection);
1178   }
1179
1180   const MCSection *SectionA = 0;
1181   const MCSymbol *SymbolA = 0;
1182   if (const MCSymbolRefExpr *A = Target.getSymA()) {
1183     SymbolA = &A->getSymbol();
1184     SectionA = &SymbolA->AliasedSymbol().getSection();
1185   }
1186
1187   const MCSection *SectionB = 0;
1188   const MCSymbol *SymbolB = 0;
1189   if (const MCSymbolRefExpr *B = Target.getSymB()) {
1190     SymbolB = &B->getSymbol();
1191     SectionB = &SymbolB->AliasedSymbol().getSection();
1192   }
1193
1194   if (!BaseSection)
1195     return SectionA == SectionB;
1196
1197   if (SymbolB)
1198     return false;
1199
1200   // Absolute address but PCrel instruction, so we need a relocation.
1201   if (!SymbolA)
1202     return false;
1203
1204   // FIXME: This is in here just to match gnu as output. If the two ends
1205   // are in the same section, there is nothing that the linker can do to
1206   // break it.
1207   const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1208   if (DataA.isExternal())
1209     return false;
1210
1211   return BaseSection == SectionA;
1212 }
1213
1214 void ELFObjectWriter::CreateGroupSections(MCAssembler &Asm,
1215                                           MCAsmLayout &Layout,
1216                                           GroupMapTy &GroupMap,
1217                                           RevGroupMapTy &RevGroupMap) {
1218   // Build the groups
1219   for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1220        it != ie; ++it) {
1221     const MCSectionELF &Section =
1222       static_cast<const MCSectionELF&>(it->getSection());
1223     if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1224       continue;
1225
1226     const MCSymbol *SignatureSymbol = Section.getGroup();
1227     Asm.getOrCreateSymbolData(*SignatureSymbol);
1228     const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1229     if (!Group) {
1230       Group = Asm.getContext().CreateELFGroupSection();
1231       MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1232       Data.setAlignment(4);
1233       MCDataFragment *F = new MCDataFragment(&Data);
1234       String32(*F, ELF::GRP_COMDAT);
1235     }
1236     GroupMap[Group] = SignatureSymbol;
1237   }
1238
1239   // Add sections to the groups
1240   unsigned Index = 1;
1241   unsigned NumGroups = RevGroupMap.size();
1242   for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1243        it != ie; ++it, ++Index) {
1244     const MCSectionELF &Section =
1245       static_cast<const MCSectionELF&>(it->getSection());
1246     if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1247       continue;
1248     const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1249     MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1250     // FIXME: we could use the previous fragment
1251     MCDataFragment *F = new MCDataFragment(&Data);
1252     String32(*F, NumGroups + Index);
1253   }
1254 }
1255
1256 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1257                                    const SectionIndexMapTy &SectionIndexMap,
1258                                    uint32_t GroupSymbolIndex,
1259                                    uint64_t Offset, uint64_t Size,
1260                                    uint64_t Alignment,
1261                                    const MCSectionELF &Section) {
1262   uint64_t sh_link = 0;
1263   uint64_t sh_info = 0;
1264
1265   switch(Section.getType()) {
1266   case ELF::SHT_DYNAMIC:
1267     sh_link = SectionStringTableIndex[&Section];
1268     sh_info = 0;
1269     break;
1270
1271   case ELF::SHT_REL:
1272   case ELF::SHT_RELA: {
1273     const MCSectionELF *SymtabSection;
1274     const MCSectionELF *InfoSection;
1275     SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1276                                                    0,
1277                                                    SectionKind::getReadOnly());
1278     sh_link = SectionIndexMap.lookup(SymtabSection);
1279     assert(sh_link && ".symtab not found");
1280
1281     // Remove ".rel" and ".rela" prefixes.
1282     unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1283     StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1284
1285     InfoSection = Asm.getContext().getELFSection(SectionName,
1286                                                  ELF::SHT_PROGBITS, 0,
1287                                                  SectionKind::getReadOnly());
1288     sh_info = SectionIndexMap.lookup(InfoSection);
1289     break;
1290   }
1291
1292   case ELF::SHT_SYMTAB:
1293   case ELF::SHT_DYNSYM:
1294     sh_link = StringTableIndex;
1295     sh_info = LastLocalSymbolIndex;
1296     break;
1297
1298   case ELF::SHT_SYMTAB_SHNDX:
1299     sh_link = SymbolTableIndex;
1300     break;
1301
1302   case ELF::SHT_PROGBITS:
1303   case ELF::SHT_STRTAB:
1304   case ELF::SHT_NOBITS:
1305   case ELF::SHT_NULL:
1306   case ELF::SHT_ARM_ATTRIBUTES:
1307     // Nothing to do.
1308     break;
1309
1310   case ELF::SHT_GROUP: {
1311     sh_link = SymbolTableIndex;
1312     sh_info = GroupSymbolIndex;
1313     break;
1314   }
1315
1316   default:
1317     assert(0 && "FIXME: sh_type value not supported!");
1318     break;
1319   }
1320
1321   WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1322                    Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1323                    Alignment, Section.getEntrySize());
1324 }
1325
1326 static bool IsELFMetaDataSection(const MCSectionData &SD) {
1327   return SD.getOrdinal() == ~UINT32_C(0) &&
1328     !SD.getSection().isVirtualSection();
1329 }
1330
1331 static uint64_t DataSectionSize(const MCSectionData &SD) {
1332   uint64_t Ret = 0;
1333   for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1334        ++i) {
1335     const MCFragment &F = *i;
1336     assert(F.getKind() == MCFragment::FT_Data);
1337     Ret += cast<MCDataFragment>(F).getContents().size();
1338   }
1339   return Ret;
1340 }
1341
1342 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
1343                                    const MCSectionData &SD) {
1344   if (IsELFMetaDataSection(SD))
1345     return DataSectionSize(SD);
1346   return Layout.getSectionFileSize(&SD);
1347 }
1348
1349 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
1350                                       const MCSectionData &SD) {
1351   if (IsELFMetaDataSection(SD))
1352     return DataSectionSize(SD);
1353   return Layout.getSectionAddressSize(&SD);
1354 }
1355
1356 static void WriteDataSectionData(ELFObjectWriter *W, const MCSectionData &SD) {
1357   for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1358        ++i) {
1359     const MCFragment &F = *i;
1360     assert(F.getKind() == MCFragment::FT_Data);
1361     W->WriteBytes(cast<MCDataFragment>(F).getContents().str());
1362   }
1363 }
1364
1365 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1366                                   const MCAsmLayout &Layout) {
1367   GroupMapTy GroupMap;
1368   RevGroupMapTy RevGroupMap;
1369   CreateGroupSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1370                       RevGroupMap);
1371
1372   SectionIndexMapTy SectionIndexMap;
1373
1374   ComputeIndexMap(Asm, SectionIndexMap);
1375
1376   // Compute symbol table information.
1377   ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap);
1378
1379   CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1380                          const_cast<MCAsmLayout&>(Layout),
1381                          SectionIndexMap);
1382
1383   // Update to include the metadata sections.
1384   ComputeIndexMap(Asm, SectionIndexMap);
1385
1386   // Add 1 for the null section.
1387   unsigned NumSections = Asm.size() + 1;
1388   uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1389   uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1390                                     sizeof(ELF::Elf32_Ehdr);
1391   uint64_t FileOff = HeaderSize;
1392
1393   std::vector<const MCSectionELF*> Sections;
1394   Sections.resize(NumSections);
1395
1396   for (SectionIndexMapTy::const_iterator i=
1397          SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1398     const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1399     Sections[p.second] = p.first;
1400   }
1401
1402   for (unsigned i = 1; i < NumSections; ++i) {
1403     const MCSectionELF &Section = *Sections[i];
1404     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1405
1406     FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1407
1408     // Get the size of the section in the output file (including padding).
1409     FileOff += GetSectionFileSize(Layout, SD);
1410   }
1411
1412   FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1413
1414   // Write out the ELF header ...
1415   WriteHeader(FileOff - HeaderSize, NumSections);
1416
1417   FileOff = HeaderSize;
1418
1419   // ... then all of the sections ...
1420   DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1421
1422   for (unsigned i = 1; i < NumSections; ++i) {
1423     const MCSectionELF &Section = *Sections[i];
1424     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1425
1426     uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1427     WriteZeros(Padding);
1428     FileOff += Padding;
1429
1430     // Remember the offset into the file for this section.
1431     SectionOffsetMap[&Section] = FileOff;
1432
1433     FileOff += GetSectionFileSize(Layout, SD);
1434
1435     if (IsELFMetaDataSection(SD))
1436       WriteDataSectionData(this, SD);
1437     else
1438       Asm.WriteSectionData(&SD, Layout);
1439   }
1440
1441   uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1442   WriteZeros(Padding);
1443   FileOff += Padding;
1444
1445   // ... and then the section header table.
1446   // Should we align the section header table?
1447   //
1448   // Null section first.
1449   uint64_t FirstSectionSize =
1450     NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1451   uint32_t FirstSectionLink =
1452     ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1453   WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1454
1455   for (unsigned i = 1; i < NumSections; ++i) {
1456     const MCSectionELF &Section = *Sections[i];
1457     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1458     uint32_t GroupSymbolIndex;
1459     if (Section.getType() != ELF::SHT_GROUP)
1460       GroupSymbolIndex = 0;
1461     else
1462       GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, GroupMap[&Section]);
1463
1464     uint64_t Size = GetSectionAddressSize(Layout, SD);
1465
1466     WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1467                  SectionOffsetMap[&Section], Size,
1468                  SD.getAlignment(), Section);
1469   }
1470 }
1471
1472 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1473                                             raw_ostream &OS,
1474                                             bool IsLittleEndian) {
1475   switch (MOTW->getEMachine()) {
1476     case ELF::EM_386:
1477     case ELF::EM_X86_64:
1478       return new X86ELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1479     case ELF::EM_ARM:
1480       return new ARMELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1481     case ELF::EM_MBLAZE:
1482       return new MBlazeELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1483     default: llvm_unreachable("Unsupported architecture"); break;
1484   }
1485 }
1486
1487
1488 /// START OF SUBCLASSES for ELFObjectWriter
1489 //===- ARMELFObjectWriter -------------------------------------------===//
1490
1491 ARMELFObjectWriter::ARMELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1492                                        raw_ostream &_OS,
1493                                        bool IsLittleEndian)
1494   : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1495 {}
1496
1497 ARMELFObjectWriter::~ARMELFObjectWriter()
1498 {}
1499
1500 unsigned ARMELFObjectWriter::GetRelocType(const MCValue &Target,
1501                                           const MCFixup &Fixup,
1502                                           bool IsPCRel,
1503                                           bool IsRelocWithSymbol,
1504                                           int64_t Addend) {
1505   MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1506     MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1507
1508   unsigned Type = 0;
1509   if (IsPCRel) {
1510     switch ((unsigned)Fixup.getKind()) {
1511     default: assert(0 && "Unimplemented");
1512     case FK_Data_4:
1513       switch (Modifier) {
1514       default: llvm_unreachable("Unsupported Modifier");
1515       case MCSymbolRefExpr::VK_None:
1516         Type = ELF::R_ARM_BASE_PREL; break;
1517       case MCSymbolRefExpr::VK_ARM_TLSGD:
1518         assert(0 && "unimplemented"); break;
1519       case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1520         Type = ELF::R_ARM_TLS_IE32;
1521       } break;
1522     case ARM::fixup_arm_branch:
1523       switch (Modifier) {
1524       case MCSymbolRefExpr::VK_ARM_PLT:
1525         Type = ELF::R_ARM_PLT32; break;
1526       default:
1527         Type = ELF::R_ARM_CALL; break;
1528       } break;
1529     }
1530   } else {
1531     switch ((unsigned)Fixup.getKind()) {
1532     default: llvm_unreachable("invalid fixup kind!");
1533     case FK_Data_4:
1534       switch (Modifier) {
1535       default: llvm_unreachable("Unsupported Modifier"); break;
1536       case MCSymbolRefExpr::VK_ARM_GOT:
1537         Type = ELF::R_ARM_GOT_BREL; break;
1538       case MCSymbolRefExpr::VK_ARM_TLSGD:
1539         Type = ELF::R_ARM_TLS_GD32; break;
1540       case MCSymbolRefExpr::VK_ARM_TPOFF:
1541         Type = ELF::R_ARM_TLS_LE32; break;
1542       case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1543         Type = ELF::R_ARM_TLS_IE32; break;
1544       case MCSymbolRefExpr::VK_None:
1545         Type = ELF::R_ARM_ABS32; break;
1546       case MCSymbolRefExpr::VK_ARM_GOTOFF:
1547         Type = ELF::R_ARM_GOTOFF32; break;
1548       } break;
1549     case ARM::fixup_arm_ldst_pcrel_12:
1550     case ARM::fixup_arm_pcrel_10:
1551     case ARM::fixup_arm_adr_pcrel_12:
1552     case ARM::fixup_arm_thumb_bl:
1553     case ARM::fixup_arm_thumb_cb:
1554     case ARM::fixup_arm_thumb_cp:
1555     case ARM::fixup_arm_thumb_br:
1556       assert(0 && "Unimplemented"); break;
1557     case ARM::fixup_arm_branch:
1558       // FIXME: Differentiate between R_ARM_CALL and
1559       // R_ARM_JUMP24 (latter used for conditional jumps)
1560       Type = ELF::R_ARM_CALL; break;
1561     case ARM::fixup_arm_movt_hi16: 
1562       Type = ELF::R_ARM_MOVT_ABS; break;
1563     case ARM::fixup_arm_movw_lo16:
1564       Type = ELF::R_ARM_MOVW_ABS_NC; break;
1565     }
1566   }
1567
1568   if (RelocNeedsGOT(Modifier))
1569     NeedsGOT = true;
1570   
1571   return Type;
1572 }
1573
1574 //===- MBlazeELFObjectWriter -------------------------------------------===//
1575
1576 MBlazeELFObjectWriter::MBlazeELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1577                                              raw_ostream &_OS,
1578                                              bool IsLittleEndian)
1579   : ELFObjectWriter(MOTW, _OS, IsLittleEndian) {
1580 }
1581
1582 MBlazeELFObjectWriter::~MBlazeELFObjectWriter() {
1583 }
1584
1585 unsigned MBlazeELFObjectWriter::GetRelocType(const MCValue &Target,
1586                                              const MCFixup &Fixup,
1587                                              bool IsPCRel,
1588                                              bool IsRelocWithSymbol,
1589                                              int64_t Addend) {
1590   // determine the type of the relocation
1591   unsigned Type;
1592   if (IsPCRel) {
1593     switch ((unsigned)Fixup.getKind()) {
1594     default:
1595       llvm_unreachable("Unimplemented");
1596     case FK_PCRel_4:
1597       Type = ELF::R_MICROBLAZE_64_PCREL;
1598       break;
1599     case FK_PCRel_2:
1600       Type = ELF::R_MICROBLAZE_32_PCREL;
1601       break;
1602     }
1603   } else {
1604     switch ((unsigned)Fixup.getKind()) {
1605     default: llvm_unreachable("invalid fixup kind!");
1606     case FK_Data_4:
1607       Type = ((IsRelocWithSymbol || Addend !=0)
1608               ? ELF::R_MICROBLAZE_32
1609               : ELF::R_MICROBLAZE_64);
1610       break;
1611     case FK_Data_2:
1612       Type = ELF::R_MICROBLAZE_32;
1613       break;
1614     }
1615   }
1616   return Type;
1617 }
1618
1619 //===- X86ELFObjectWriter -------------------------------------------===//
1620
1621
1622 X86ELFObjectWriter::X86ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1623                                        raw_ostream &_OS,
1624                                        bool IsLittleEndian)
1625   : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1626 {}
1627
1628 X86ELFObjectWriter::~X86ELFObjectWriter()
1629 {}
1630
1631 unsigned X86ELFObjectWriter::GetRelocType(const MCValue &Target,
1632                                           const MCFixup &Fixup,
1633                                           bool IsPCRel,
1634                                           bool IsRelocWithSymbol,
1635                                           int64_t Addend) {
1636   // determine the type of the relocation
1637
1638   MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1639     MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1640   unsigned Type;
1641   if (is64Bit()) {
1642     if (IsPCRel) {
1643       switch (Modifier) {
1644       default:
1645         llvm_unreachable("Unimplemented");
1646       case MCSymbolRefExpr::VK_None:
1647         Type = ELF::R_X86_64_PC32;
1648         break;
1649       case MCSymbolRefExpr::VK_PLT:
1650         Type = ELF::R_X86_64_PLT32;
1651         break;
1652       case MCSymbolRefExpr::VK_GOTPCREL:
1653         Type = ELF::R_X86_64_GOTPCREL;
1654         break;
1655       case MCSymbolRefExpr::VK_GOTTPOFF:
1656         Type = ELF::R_X86_64_GOTTPOFF;
1657         break;
1658       case MCSymbolRefExpr::VK_TLSGD:
1659         Type = ELF::R_X86_64_TLSGD;
1660         break;
1661       case MCSymbolRefExpr::VK_TLSLD:
1662         Type = ELF::R_X86_64_TLSLD;
1663         break;
1664       }
1665     } else {
1666       switch ((unsigned)Fixup.getKind()) {
1667       default: llvm_unreachable("invalid fixup kind!");
1668       case FK_Data_8: Type = ELF::R_X86_64_64; break;
1669       case X86::reloc_signed_4byte:
1670       case FK_PCRel_4:
1671         assert(isInt<32>(Target.getConstant()));
1672         switch (Modifier) {
1673         default:
1674           llvm_unreachable("Unimplemented");
1675         case MCSymbolRefExpr::VK_None:
1676           Type = ELF::R_X86_64_32S;
1677           break;
1678         case MCSymbolRefExpr::VK_GOT:
1679           Type = ELF::R_X86_64_GOT32;
1680           break;
1681         case MCSymbolRefExpr::VK_GOTPCREL:
1682           Type = ELF::R_X86_64_GOTPCREL;
1683           break;
1684         case MCSymbolRefExpr::VK_TPOFF:
1685           Type = ELF::R_X86_64_TPOFF32;
1686           break;
1687         case MCSymbolRefExpr::VK_DTPOFF:
1688           Type = ELF::R_X86_64_DTPOFF32;
1689           break;
1690         }
1691         break;
1692       case FK_Data_4:
1693         Type = ELF::R_X86_64_32;
1694         break;
1695       case FK_Data_2: Type = ELF::R_X86_64_16; break;
1696       case FK_PCRel_1:
1697       case FK_Data_1: Type = ELF::R_X86_64_8; break;
1698       }
1699     }
1700   } else {
1701     if (IsPCRel) {
1702       switch (Modifier) {
1703       default:
1704         llvm_unreachable("Unimplemented");
1705       case MCSymbolRefExpr::VK_None:
1706         Type = ELF::R_386_PC32;
1707         break;
1708       case MCSymbolRefExpr::VK_PLT:
1709         Type = ELF::R_386_PLT32;
1710         break;
1711       }
1712     } else {
1713       switch ((unsigned)Fixup.getKind()) {
1714       default: llvm_unreachable("invalid fixup kind!");
1715
1716       case X86::reloc_global_offset_table:
1717         Type = ELF::R_386_GOTPC;
1718         break;
1719
1720       // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
1721       // instead?
1722       case X86::reloc_signed_4byte:
1723       case FK_PCRel_4:
1724       case FK_Data_4:
1725         switch (Modifier) {
1726         default:
1727           llvm_unreachable("Unimplemented");
1728         case MCSymbolRefExpr::VK_None:
1729           Type = ELF::R_386_32;
1730           break;
1731         case MCSymbolRefExpr::VK_GOT:
1732           Type = ELF::R_386_GOT32;
1733           break;
1734         case MCSymbolRefExpr::VK_GOTOFF:
1735           Type = ELF::R_386_GOTOFF;
1736           break;
1737         case MCSymbolRefExpr::VK_TLSGD:
1738           Type = ELF::R_386_TLS_GD;
1739           break;
1740         case MCSymbolRefExpr::VK_TPOFF:
1741           Type = ELF::R_386_TLS_LE_32;
1742           break;
1743         case MCSymbolRefExpr::VK_INDNTPOFF:
1744           Type = ELF::R_386_TLS_IE;
1745           break;
1746         case MCSymbolRefExpr::VK_NTPOFF:
1747           Type = ELF::R_386_TLS_LE;
1748           break;
1749         case MCSymbolRefExpr::VK_GOTNTPOFF:
1750           Type = ELF::R_386_TLS_GOTIE;
1751           break;
1752         case MCSymbolRefExpr::VK_TLSLDM:
1753           Type = ELF::R_386_TLS_LDM;
1754           break;
1755         case MCSymbolRefExpr::VK_DTPOFF:
1756           Type = ELF::R_386_TLS_LDO_32;
1757           break;
1758         }
1759         break;
1760       case FK_Data_2: Type = ELF::R_386_16; break;
1761       case FK_PCRel_1:
1762       case FK_Data_1: Type = ELF::R_386_8; break;
1763       }
1764     }
1765   }
1766
1767   if (RelocNeedsGOT(Modifier))
1768     NeedsGOT = true;
1769
1770   return Type;
1771 }