72a6cbd5ef44171b4ac04031cacef4740dc6cb90
[oota-llvm.git] / lib / MC / ELFObjectWriter.cpp
1 //===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements ELF object file writer information.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/MC/ELFObjectWriter.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAssembler.h"
20 #include "llvm/MC/MCAsmLayout.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCELFSymbolFlags.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCObjectWriter.h"
25 #include "llvm/MC/MCSectionELF.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/MC/MCValue.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/ELF.h"
31 #include "llvm/Target/TargetAsmBackend.h"
32
33 #include "../Target/X86/X86FixupKinds.h"
34
35 #include <vector>
36 using namespace llvm;
37
38 static unsigned GetType(const MCSymbolData &SD) {
39   uint32_t Type = (SD.getFlags() & (0xf << ELF_STT_Shift)) >> ELF_STT_Shift;
40   assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
41          Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
42          Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
43          Type == ELF::STT_TLS);
44   return Type;
45 }
46
47 static unsigned GetBinding(const MCSymbolData &SD) {
48   uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
49   assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
50          Binding == ELF::STB_WEAK);
51   return Binding;
52 }
53
54 static void SetBinding(MCSymbolData &SD, unsigned Binding) {
55   assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
56          Binding == ELF::STB_WEAK);
57   uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
58   SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
59 }
60
61 static bool isFixupKindX86PCRel(unsigned Kind) {
62   switch (Kind) {
63   default:
64     return false;
65   case X86::reloc_pcrel_1byte:
66   case X86::reloc_pcrel_4byte:
67   case X86::reloc_riprel_4byte:
68   case X86::reloc_riprel_4byte_movq_load:
69     return true;
70   }
71 }
72
73 static bool RelocNeedsGOT(unsigned Type) {
74   switch (Type) {
75   default:
76     return false;
77   case ELF::R_X86_64_GOT32:
78   case ELF::R_X86_64_PLT32:
79   case ELF::R_X86_64_GOTPCREL:
80     return true;
81   }
82 }
83
84 namespace {
85
86   class ELFObjectWriterImpl {
87     /*static bool isFixupKindX86RIPRel(unsigned Kind) {
88       return Kind == X86::reloc_riprel_4byte ||
89         Kind == X86::reloc_riprel_4byte_movq_load;
90     }*/
91
92
93     /// ELFSymbolData - Helper struct for containing some precomputed information
94     /// on symbols.
95     struct ELFSymbolData {
96       MCSymbolData *SymbolData;
97       uint64_t StringIndex;
98       uint32_t SectionIndex;
99
100       // Support lexicographic sorting.
101       bool operator<(const ELFSymbolData &RHS) const {
102         if (GetType(*SymbolData) == ELF::STT_FILE)
103           return true;
104         if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
105           return false;
106         return SymbolData->getSymbol().getName() <
107                RHS.SymbolData->getSymbol().getName();
108       }
109     };
110
111     /// @name Relocation Data
112     /// @{
113
114     struct ELFRelocationEntry {
115       // Make these big enough for both 32-bit and 64-bit
116       uint64_t r_offset;
117       int Index;
118       unsigned Type;
119       const MCSymbol *Symbol;
120       uint64_t r_addend;
121
122       // Support lexicographic sorting.
123       bool operator<(const ELFRelocationEntry &RE) const {
124         return RE.r_offset < r_offset;
125       }
126     };
127
128     SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
129
130     llvm::DenseMap<const MCSectionData*,
131                    std::vector<ELFRelocationEntry> > Relocations;
132     DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
133
134     /// @}
135     /// @name Symbol Table Data
136     /// @{
137
138     SmallString<256> StringTable;
139     std::vector<ELFSymbolData> LocalSymbolData;
140     std::vector<ELFSymbolData> ExternalSymbolData;
141     std::vector<ELFSymbolData> UndefinedSymbolData;
142
143     /// @}
144
145     int NumRegularSections;
146
147     bool NeedsGOT;
148
149     ELFObjectWriter *Writer;
150
151     raw_ostream &OS;
152
153     unsigned Is64Bit : 1;
154
155     bool HasRelocationAddend;
156
157     Triple::OSType OSType;
158
159     // This holds the symbol table index of the last local symbol.
160     unsigned LastLocalSymbolIndex;
161     // This holds the .strtab section index.
162     unsigned StringTableIndex;
163
164     unsigned ShstrtabIndex;
165
166   public:
167     ELFObjectWriterImpl(ELFObjectWriter *_Writer, bool _Is64Bit,
168                         bool _HasRelAddend, Triple::OSType _OSType)
169       : NeedsGOT(false), Writer(_Writer), OS(Writer->getStream()),
170         Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
171         OSType(_OSType) {
172     }
173
174     void Write8(uint8_t Value) { Writer->Write8(Value); }
175     void Write16(uint16_t Value) { Writer->Write16(Value); }
176     void Write32(uint32_t Value) { Writer->Write32(Value); }
177     //void Write64(uint64_t Value) { Writer->Write64(Value); }
178     void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
179     //void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
180     //  Writer->WriteBytes(Str, ZeroFillSize);
181     //}
182
183     void WriteWord(uint64_t W) {
184       if (Is64Bit)
185         Writer->Write64(W);
186       else
187         Writer->Write32(W);
188     }
189
190     void String8(char *buf, uint8_t Value) {
191       buf[0] = Value;
192     }
193
194     void StringLE16(char *buf, uint16_t Value) {
195       buf[0] = char(Value >> 0);
196       buf[1] = char(Value >> 8);
197     }
198
199     void StringLE32(char *buf, uint32_t Value) {
200       StringLE16(buf, uint16_t(Value >> 0));
201       StringLE16(buf + 2, uint16_t(Value >> 16));
202     }
203
204     void StringLE64(char *buf, uint64_t Value) {
205       StringLE32(buf, uint32_t(Value >> 0));
206       StringLE32(buf + 4, uint32_t(Value >> 32));
207     }
208
209     void StringBE16(char *buf ,uint16_t Value) {
210       buf[0] = char(Value >> 8);
211       buf[1] = char(Value >> 0);
212     }
213
214     void StringBE32(char *buf, uint32_t Value) {
215       StringBE16(buf, uint16_t(Value >> 16));
216       StringBE16(buf + 2, uint16_t(Value >> 0));
217     }
218
219     void StringBE64(char *buf, uint64_t Value) {
220       StringBE32(buf, uint32_t(Value >> 32));
221       StringBE32(buf + 4, uint32_t(Value >> 0));
222     }
223
224     void String16(char *buf, uint16_t Value) {
225       if (Writer->isLittleEndian())
226         StringLE16(buf, Value);
227       else
228         StringBE16(buf, Value);
229     }
230
231     void String32(char *buf, uint32_t Value) {
232       if (Writer->isLittleEndian())
233         StringLE32(buf, Value);
234       else
235         StringBE32(buf, Value);
236     }
237
238     void String64(char *buf, uint64_t Value) {
239       if (Writer->isLittleEndian())
240         StringLE64(buf, Value);
241       else
242         StringBE64(buf, Value);
243     }
244
245     void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
246
247     void WriteSymbolEntry(MCDataFragment *F, uint64_t name, uint8_t info,
248                           uint64_t value, uint64_t size,
249                           uint8_t other, uint16_t shndx);
250
251     void WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
252                      const MCAsmLayout &Layout);
253
254     void WriteSymbolTable(MCDataFragment *F, const MCAssembler &Asm,
255                           const MCAsmLayout &Layout,
256                           unsigned NumRegularSections);
257
258     void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
259                           const MCFragment *Fragment, const MCFixup &Fixup,
260                           MCValue Target, uint64_t &FixedValue);
261
262     uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
263                                          const MCSymbol *S);
264
265     /// ComputeSymbolTable - Compute the symbol table data
266     ///
267     /// \param StringTable [out] - The string table data.
268     /// \param StringIndexMap [out] - Map from symbol names to offsets in the
269     /// string table.
270     void ComputeSymbolTable(MCAssembler &Asm);
271
272     void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
273                          const MCSectionData &SD);
274
275     void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
276       for (MCAssembler::const_iterator it = Asm.begin(),
277              ie = Asm.end(); it != ie; ++it) {
278         WriteRelocation(Asm, Layout, *it);
279       }
280     }
281
282     void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
283
284     void ExecutePostLayoutBinding(MCAssembler &Asm) {
285     }
286
287     void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
288                           uint64_t Address, uint64_t Offset,
289                           uint64_t Size, uint32_t Link, uint32_t Info,
290                           uint64_t Alignment, uint64_t EntrySize);
291
292     void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
293                                   const MCSectionData *SD);
294
295     bool IsFixupFullyResolved(const MCAssembler &Asm,
296                               const MCValue Target,
297                               bool IsPCRel,
298                               const MCFragment *DF) const;
299
300     void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
301   };
302
303 }
304
305 // Emit the ELF header.
306 void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
307                                       unsigned NumberOfSections) {
308   // ELF Header
309   // ----------
310   //
311   // Note
312   // ----
313   // emitWord method behaves differently for ELF32 and ELF64, writing
314   // 4 bytes in the former and 8 in the latter.
315
316   Write8(0x7f); // e_ident[EI_MAG0]
317   Write8('E');  // e_ident[EI_MAG1]
318   Write8('L');  // e_ident[EI_MAG2]
319   Write8('F');  // e_ident[EI_MAG3]
320
321   Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
322
323   // e_ident[EI_DATA]
324   Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
325
326   Write8(ELF::EV_CURRENT);        // e_ident[EI_VERSION]
327   // e_ident[EI_OSABI]
328   switch (OSType) {
329     case Triple::FreeBSD:  Write8(ELF::ELFOSABI_FREEBSD); break;
330     case Triple::Linux:    Write8(ELF::ELFOSABI_LINUX); break;
331     default:               Write8(ELF::ELFOSABI_NONE); break;
332   }
333   Write8(0);                  // e_ident[EI_ABIVERSION]
334
335   WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
336
337   Write16(ELF::ET_REL);             // e_type
338
339   // FIXME: Make this configurable
340   Write16(Is64Bit ? ELF::EM_X86_64 : ELF::EM_386); // e_machine = target
341
342   Write32(ELF::EV_CURRENT);         // e_version
343   WriteWord(0);                    // e_entry, no entry point in .o file
344   WriteWord(0);                    // e_phoff, no program header for .o
345   WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
346             sizeof(ELF::Elf32_Ehdr)));  // e_shoff = sec hdr table off in bytes
347
348   // FIXME: Make this configurable.
349   Write32(0);   // e_flags = whatever the target wants
350
351   // e_ehsize = ELF header size
352   Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
353
354   Write16(0);                  // e_phentsize = prog header entry size
355   Write16(0);                  // e_phnum = # prog header entries = 0
356
357   // e_shentsize = Section header entry size
358   Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
359
360   // e_shnum     = # of section header ents
361   Write16(NumberOfSections);
362
363   // e_shstrndx  = Section # of '.shstrtab'
364   Write16(ShstrtabIndex);
365 }
366
367 void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
368                                            uint8_t info, uint64_t value,
369                                            uint64_t size, uint8_t other,
370                                            uint16_t shndx) {
371   if (Is64Bit) {
372     char buf[8];
373
374     String32(buf, name);
375     F->getContents() += StringRef(buf, 4); // st_name
376
377     String8(buf, info);
378     F->getContents() += StringRef(buf, 1);  // st_info
379
380     String8(buf, other);
381     F->getContents() += StringRef(buf, 1); // st_other
382
383     String16(buf, shndx);
384     F->getContents() += StringRef(buf, 2); // st_shndx
385
386     String64(buf, value);
387     F->getContents() += StringRef(buf, 8); // st_value
388
389     String64(buf, size);
390     F->getContents() += StringRef(buf, 8);  // st_size
391   } else {
392     char buf[4];
393
394     String32(buf, name);
395     F->getContents() += StringRef(buf, 4);  // st_name
396
397     String32(buf, value);
398     F->getContents() += StringRef(buf, 4); // st_value
399
400     String32(buf, size);
401     F->getContents() += StringRef(buf, 4);  // st_size
402
403     String8(buf, info);
404     F->getContents() += StringRef(buf, 1);  // st_info
405
406     String8(buf, other);
407     F->getContents() += StringRef(buf, 1); // st_other
408
409     String16(buf, shndx);
410     F->getContents() += StringRef(buf, 2); // st_shndx
411   }
412 }
413
414 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
415   if (Data.isCommon() && Data.isExternal())
416     return Data.getCommonAlignment();
417
418   const MCSymbol &Symbol = Data.getSymbol();
419   if (!Symbol.isInSection())
420     return 0;
421
422   if (!Data.isCommon() && !(Data.getFlags() & ELF_STB_Weak))
423     if (MCFragment *FF = Data.getFragment())
424       return Layout.getSymbolAddress(&Data) -
425              Layout.getSectionAddress(FF->getParent());
426
427   return 0;
428 }
429
430 void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
431                                       const MCAsmLayout &Layout) {
432   MCSymbolData &Data = *MSD.SymbolData;
433   uint8_t Info = (Data.getFlags() & 0xff);
434   uint8_t Other = ((Data.getFlags() & 0xf00) >> ELF_STV_Shift);
435   uint64_t Value = SymbolValue(Data, Layout);
436   uint64_t Size = 0;
437   const MCExpr *ESize;
438
439   assert(!(Data.isCommon() && !Data.isExternal()));
440
441   ESize = Data.getSize();
442   if (Data.getSize()) {
443     MCValue Res;
444     if (ESize->getKind() == MCExpr::Binary) {
445       const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
446
447       if (BE->EvaluateAsRelocatable(Res, &Layout)) {
448         MCSymbolData &A =
449           Layout.getAssembler().getSymbolData(Res.getSymA()->getSymbol());
450         MCSymbolData &B =
451           Layout.getAssembler().getSymbolData(Res.getSymB()->getSymbol());
452
453         Size = Layout.getSymbolAddress(&A) - Layout.getSymbolAddress(&B);
454       }
455     } else if (ESize->getKind() == MCExpr::Constant) {
456       Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
457     } else {
458       assert(0 && "Unsupported size expression");
459     }
460   }
461
462   // Write out the symbol table entry
463   WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
464                    Size, Other, MSD.SectionIndex);
465 }
466
467 void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
468                                            const MCAssembler &Asm,
469                                            const MCAsmLayout &Layout,
470                                            unsigned NumRegularSections) {
471   // The string table must be emitted first because we need the index
472   // into the string table for all the symbol names.
473   assert(StringTable.size() && "Missing string table");
474
475   // FIXME: Make sure the start of the symbol table is aligned.
476
477   // The first entry is the undefined symbol entry.
478   unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
479   F->getContents().append(EntrySize, '\x00');
480
481   // Write the symbol table entries.
482   LastLocalSymbolIndex = LocalSymbolData.size() + 1;
483   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
484     ELFSymbolData &MSD = LocalSymbolData[i];
485     WriteSymbol(F, MSD, Layout);
486   }
487
488   // Write out a symbol table entry for each regular section.
489   unsigned Index = 1;
490   for (MCAssembler::const_iterator it = Asm.begin();
491        Index <= NumRegularSections; ++it, ++Index) {
492     const MCSectionELF &Section =
493       static_cast<const MCSectionELF&>(it->getSection());
494     // Leave out relocations so we don't have indexes within
495     // the relocations messed up
496     if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
497       continue;
498     WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
499     LastLocalSymbolIndex++;
500   }
501
502   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
503     ELFSymbolData &MSD = ExternalSymbolData[i];
504     MCSymbolData &Data = *MSD.SymbolData;
505     assert((Data.getFlags() & ELF_STB_Global) &&
506            "External symbol requires STB_GLOBAL flag");
507     WriteSymbol(F, MSD, Layout);
508     if (GetBinding(Data) == ELF::STB_LOCAL)
509       LastLocalSymbolIndex++;
510   }
511
512   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
513     ELFSymbolData &MSD = UndefinedSymbolData[i];
514     MCSymbolData &Data = *MSD.SymbolData;
515     WriteSymbol(F, MSD, Layout);
516     if (GetBinding(Data) == ELF::STB_LOCAL)
517       LastLocalSymbolIndex++;
518   }
519 }
520
521 static bool ShouldRelocOnSymbol(const MCSymbolData &SD,
522                                 const MCValue &Target) {
523   const MCSymbol &Symbol = SD.getSymbol();
524   if (Symbol.isUndefined())
525     return true;
526
527   const MCSectionELF &Section =
528     static_cast<const MCSectionELF&>(Symbol.getSection());
529
530   if (Section.getFlags() & MCSectionELF::SHF_MERGE)
531     return Target.getConstant() != 0;
532
533   if (SD.isExternal())
534     return true;
535
536   return false;
537 }
538
539 // FIXME: this is currently X86/X86_64 only
540 void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
541                                            const MCAsmLayout &Layout,
542                                            const MCFragment *Fragment,
543                                            const MCFixup &Fixup,
544                                            MCValue Target,
545                                            uint64_t &FixedValue) {
546   int64_t Addend = 0;
547   int Index = 0;
548   int64_t Value = Target.getConstant();
549   const MCSymbol *Symbol = 0;
550
551   bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
552   if (!Target.isAbsolute()) {
553     Symbol = &Target.getSymA()->getSymbol();
554     MCSymbolData &SD = Asm.getSymbolData(*Symbol);
555     MCFragment *F = SD.getFragment();
556
557     if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
558       const MCSymbol &SymbolB = RefB->getSymbol();
559       MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
560       IsPCRel = true;
561       MCSectionData *Sec = Fragment->getParent();
562
563       // Offset of the symbol in the section
564       int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
565
566       // Ofeset of the relocation in the section
567       int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
568       Value += b - a;
569     }
570
571     // Check that this case has already been fully resolved before we get
572     // here.
573     if (Symbol->isDefined() && !SD.isExternal() &&
574         IsPCRel &&
575         &Fragment->getParent()->getSection() == &Symbol->getSection()) {
576       llvm_unreachable("We don't need a relocation in this case.");
577       return;
578     }
579
580     bool RelocOnSymbol = ShouldRelocOnSymbol(SD, Target);
581     if (!RelocOnSymbol) {
582       Index = F->getParent()->getOrdinal();
583
584       MCSectionData *FSD = F->getParent();
585       // Offset of the symbol in the section
586       Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
587     } else {
588       UsedInReloc.insert(Symbol);
589       Index = -1;
590     }
591     Addend = Value;
592     // Compensate for the addend on i386.
593     if (Is64Bit)
594       Value = 0;
595   }
596
597   FixedValue = Value;
598
599   // determine the type of the relocation
600
601   MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
602   unsigned Type;
603   if (Is64Bit) {
604     if (IsPCRel) {
605       switch (Modifier) {
606       case MCSymbolRefExpr::VK_None:
607         Type = ELF::R_X86_64_PC32;
608         break;
609       case MCSymbolRefExpr::VK_PLT:
610         Type = ELF::R_X86_64_PLT32;
611         break;
612       case llvm::MCSymbolRefExpr::VK_GOTPCREL:
613         Type = ELF::R_X86_64_GOTPCREL;
614         break;
615       default:
616         llvm_unreachable("Unimplemented");
617       }
618     } else {
619       switch ((unsigned)Fixup.getKind()) {
620       default: llvm_unreachable("invalid fixup kind!");
621       case FK_Data_8: Type = ELF::R_X86_64_64; break;
622       case X86::reloc_signed_4byte:
623       case X86::reloc_pcrel_4byte:
624         assert(isInt<32>(Target.getConstant()));
625         switch (Modifier) {
626         case MCSymbolRefExpr::VK_None:
627           Type = ELF::R_X86_64_32S;
628           break;
629         case MCSymbolRefExpr::VK_GOT:
630           Type = ELF::R_X86_64_GOT32;
631           break;
632         default:
633           llvm_unreachable("Unimplemented");
634         }
635         break;
636       case FK_Data_4:
637         Type = ELF::R_X86_64_32;
638         break;
639       case FK_Data_2: Type = ELF::R_X86_64_16; break;
640       case X86::reloc_pcrel_1byte:
641       case FK_Data_1: Type = ELF::R_X86_64_8; break;
642       }
643     }
644   } else {
645     if (IsPCRel) {
646       Type = ELF::R_386_PC32;
647     } else {
648       switch ((unsigned)Fixup.getKind()) {
649       default: llvm_unreachable("invalid fixup kind!");
650
651       // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
652       // instead?
653       case X86::reloc_signed_4byte:
654       case X86::reloc_pcrel_4byte:
655       case FK_Data_4: Type = ELF::R_386_32; break;
656       case FK_Data_2: Type = ELF::R_386_16; break;
657       case X86::reloc_pcrel_1byte:
658       case FK_Data_1: Type = ELF::R_386_8; break;
659       }
660     }
661   }
662
663   if (RelocNeedsGOT(Type))
664     NeedsGOT = true;
665
666   ELFRelocationEntry ERE;
667
668   ERE.Index = Index;
669   ERE.Type = Type;
670   ERE.Symbol = Symbol;
671
672   ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
673
674   if (HasRelocationAddend)
675     ERE.r_addend = Addend;
676   else
677     ERE.r_addend = 0; // Silence compiler warning.
678
679   Relocations[Fragment->getParent()].push_back(ERE);
680 }
681
682 uint64_t
683 ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
684                                                  const MCSymbol *S) {
685   MCSymbolData &SD = Asm.getSymbolData(*S);
686
687   // Local symbol.
688   if (!SD.isExternal() && !S->isUndefined())
689     return SD.getIndex() + /* empty symbol */ 1;
690
691   // External or undefined symbol.
692   return SD.getIndex() + NumRegularSections + /* empty symbol */ 1;
693 }
694
695 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
696                        bool Used) {
697   const MCSymbol &Symbol = Data.getSymbol();
698   if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
699     return false;
700
701   if (!Used && Symbol.isTemporary())
702     return false;
703
704   return true;
705 }
706
707 static bool isLocal(const MCSymbolData &Data) {
708   if (Data.isExternal())
709     return false;
710
711   const MCSymbol &Symbol = Data.getSymbol();
712   if (Symbol.isUndefined() && !Symbol.isVariable())
713     return false;
714
715   return true;
716 }
717
718 void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
719   // FIXME: Is this the correct place to do this?
720   if (NeedsGOT) {
721     llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
722     MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
723     MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
724     Data.setExternal(true);
725   }
726
727   // Build section lookup table.
728   NumRegularSections = Asm.size();
729   DenseMap<const MCSection*, uint8_t> SectionIndexMap;
730   unsigned Index = 1;
731   for (MCAssembler::iterator it = Asm.begin(),
732          ie = Asm.end(); it != ie; ++it, ++Index)
733     SectionIndexMap[&it->getSection()] = Index;
734
735   // Index 0 is always the empty string.
736   StringMap<uint64_t> StringIndexMap;
737   StringTable += '\x00';
738
739   // Add the data for local symbols.
740   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
741          ie = Asm.symbol_end(); it != ie; ++it) {
742     const MCSymbol &Symbol = it->getSymbol();
743
744     if (!isInSymtab(Asm, *it, UsedInReloc.count(&Symbol)))
745       continue;
746
747     if (!isLocal(*it))
748       continue;
749
750     uint64_t &Entry = StringIndexMap[Symbol.getName()];
751     if (!Entry) {
752       Entry = StringTable.size();
753       StringTable += Symbol.getName();
754       StringTable += '\x00';
755     }
756
757     ELFSymbolData MSD;
758     MSD.SymbolData = it;
759     MSD.StringIndex = Entry;
760
761     if (Symbol.isAbsolute()) {
762       MSD.SectionIndex = ELF::SHN_ABS;
763       LocalSymbolData.push_back(MSD);
764     } else {
765       const MCSymbol *SymbolP = &Symbol;
766       if (Symbol.isVariable()) {
767         const MCExpr *Value = Symbol.getVariableValue();
768         assert (Value->getKind() == MCExpr::SymbolRef && "Unimplemented");
769         const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Value);
770         SymbolP = &Ref->getSymbol();
771       }
772       MSD.SectionIndex = SectionIndexMap.lookup(&SymbolP->getSection());
773       assert(MSD.SectionIndex && "Invalid section index!");
774       LocalSymbolData.push_back(MSD);
775     }
776   }
777
778   // Now add non-local symbols.
779   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
780          ie = Asm.symbol_end(); it != ie; ++it) {
781     const MCSymbol &Symbol = it->getSymbol();
782
783     if (!isInSymtab(Asm, *it, UsedInReloc.count(&Symbol)))
784       continue;
785
786     if (isLocal(*it))
787       continue;
788
789     uint64_t &Entry = StringIndexMap[Symbol.getName()];
790     if (!Entry) {
791       Entry = StringTable.size();
792       StringTable += Symbol.getName();
793       StringTable += '\x00';
794     }
795
796     ELFSymbolData MSD;
797     MSD.SymbolData = it;
798     MSD.StringIndex = Entry;
799
800     if (it->isCommon()) {
801       MSD.SectionIndex = ELF::SHN_COMMON;
802       ExternalSymbolData.push_back(MSD);
803     } else if (Symbol.isUndefined()) {
804       MSD.SectionIndex = ELF::SHN_UNDEF;
805       // FIXME: Undefined symbols are global, but this is the first place we
806       // are able to set it.
807       if (GetBinding(*it) == ELF::STB_LOCAL)
808         SetBinding(*it, ELF::STB_GLOBAL);
809       UndefinedSymbolData.push_back(MSD);
810     } else if (Symbol.isAbsolute()) {
811       MSD.SectionIndex = ELF::SHN_ABS;
812       ExternalSymbolData.push_back(MSD);
813     } else {
814       MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
815       assert(MSD.SectionIndex && "Invalid section index!");
816       ExternalSymbolData.push_back(MSD);
817     }
818   }
819
820   // Symbols are required to be in lexicographic order.
821   array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
822   array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
823   array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
824
825   // Set the symbol indices. Local symbols must come before all other
826   // symbols with non-local bindings.
827   Index = 0;
828   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
829     LocalSymbolData[i].SymbolData->setIndex(Index++);
830   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
831     ExternalSymbolData[i].SymbolData->setIndex(Index++);
832   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
833     UndefinedSymbolData[i].SymbolData->setIndex(Index++);
834 }
835
836 void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
837                                           const MCSectionData &SD) {
838   if (!Relocations[&SD].empty()) {
839     MCContext &Ctx = Asm.getContext();
840     const MCSection *RelaSection;
841     const MCSectionELF &Section =
842       static_cast<const MCSectionELF&>(SD.getSection());
843
844     const StringRef SectionName = Section.getSectionName();
845     std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
846     RelaSectionName += SectionName;
847
848     unsigned EntrySize;
849     if (HasRelocationAddend)
850       EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
851     else
852       EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
853
854     RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
855                                     ELF::SHT_RELA : ELF::SHT_REL, 0,
856                                     SectionKind::getReadOnly(),
857                                     false, EntrySize);
858
859     MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
860     RelaSD.setAlignment(Is64Bit ? 8 : 4);
861
862     MCDataFragment *F = new MCDataFragment(&RelaSD);
863
864     WriteRelocationsFragment(Asm, F, &SD);
865
866     Asm.AddSectionToTheEnd(*Writer, RelaSD, Layout);
867   }
868 }
869
870 void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
871                                            uint64_t Flags, uint64_t Address,
872                                            uint64_t Offset, uint64_t Size,
873                                            uint32_t Link, uint32_t Info,
874                                            uint64_t Alignment,
875                                            uint64_t EntrySize) {
876   Write32(Name);        // sh_name: index into string table
877   Write32(Type);        // sh_type
878   WriteWord(Flags);     // sh_flags
879   WriteWord(Address);   // sh_addr
880   WriteWord(Offset);    // sh_offset
881   WriteWord(Size);      // sh_size
882   Write32(Link);        // sh_link
883   Write32(Info);        // sh_info
884   WriteWord(Alignment); // sh_addralign
885   WriteWord(EntrySize); // sh_entsize
886 }
887
888 void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
889                                                    MCDataFragment *F,
890                                                    const MCSectionData *SD) {
891   std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
892   // sort by the r_offset just like gnu as does
893   array_pod_sort(Relocs.begin(), Relocs.end());
894
895   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
896     ELFRelocationEntry entry = Relocs[e - i - 1];
897
898     if (entry.Index < 0)
899       entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
900     else
901       entry.Index += LocalSymbolData.size() + 1;
902     if (Is64Bit) {
903       char buf[8];
904
905       String64(buf, entry.r_offset);
906       F->getContents() += StringRef(buf, 8);
907
908       struct ELF::Elf64_Rela ERE64;
909       ERE64.setSymbolAndType(entry.Index, entry.Type);
910       String64(buf, ERE64.r_info);
911       F->getContents() += StringRef(buf, 8);
912
913       if (HasRelocationAddend) {
914         String64(buf, entry.r_addend);
915         F->getContents() += StringRef(buf, 8);
916       }
917     } else {
918       char buf[4];
919
920       String32(buf, entry.r_offset);
921       F->getContents() += StringRef(buf, 4);
922
923       struct ELF::Elf32_Rela ERE32;
924       ERE32.setSymbolAndType(entry.Index, entry.Type);
925       String32(buf, ERE32.r_info);
926       F->getContents() += StringRef(buf, 4);
927
928       if (HasRelocationAddend) {
929         String32(buf, entry.r_addend);
930         F->getContents() += StringRef(buf, 4);
931       }
932     }
933   }
934 }
935
936 void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
937                                                  MCAsmLayout &Layout) {
938   MCContext &Ctx = Asm.getContext();
939   MCDataFragment *F;
940
941   const MCSection *SymtabSection;
942   unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
943
944   unsigned NumRegularSections = Asm.size();
945
946   // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
947   const MCSection *ShstrtabSection;
948   ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
949                                       SectionKind::getReadOnly(), false);
950   MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
951   ShstrtabSD.setAlignment(1);
952   ShstrtabIndex = Asm.size();
953
954   SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
955                                     SectionKind::getReadOnly(),
956                                     false, EntrySize);
957   MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
958   SymtabSD.setAlignment(Is64Bit ? 8 : 4);
959
960   const MCSection *StrtabSection;
961   StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
962                                     SectionKind::getReadOnly(), false);
963   MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
964   StrtabSD.setAlignment(1);
965   StringTableIndex = Asm.size();
966
967   WriteRelocations(Asm, Layout);
968
969   // Symbol table
970   F = new MCDataFragment(&SymtabSD);
971   WriteSymbolTable(F, Asm, Layout, NumRegularSections);
972   Asm.AddSectionToTheEnd(*Writer, SymtabSD, Layout);
973
974   F = new MCDataFragment(&StrtabSD);
975   F->getContents().append(StringTable.begin(), StringTable.end());
976   Asm.AddSectionToTheEnd(*Writer, StrtabSD, Layout);
977
978   F = new MCDataFragment(&ShstrtabSD);
979
980   // Section header string table.
981   //
982   // The first entry of a string table holds a null character so skip
983   // section 0.
984   uint64_t Index = 1;
985   F->getContents() += '\x00';
986
987   for (MCAssembler::const_iterator it = Asm.begin(),
988          ie = Asm.end(); it != ie; ++it) {
989     const MCSectionELF &Section =
990       static_cast<const MCSectionELF&>(it->getSection());
991     // FIXME: We could merge suffixes like in .text and .rela.text.
992
993     // Remember the index into the string table so we can write it
994     // into the sh_name field of the section header table.
995     SectionStringTableIndex[&it->getSection()] = Index;
996
997     Index += Section.getSectionName().size() + 1;
998     F->getContents() += Section.getSectionName();
999     F->getContents() += '\x00';
1000   }
1001
1002   Asm.AddSectionToTheEnd(*Writer, ShstrtabSD, Layout);
1003 }
1004
1005 bool ELFObjectWriterImpl::IsFixupFullyResolved(const MCAssembler &Asm,
1006                                                const MCValue Target,
1007                                                bool IsPCRel,
1008                                                const MCFragment *DF) const {
1009   // If this is a PCrel relocation, find the section this fixup value is
1010   // relative to.
1011   const MCSection *BaseSection = 0;
1012   if (IsPCRel) {
1013     BaseSection = &DF->getParent()->getSection();
1014     assert(BaseSection);
1015   }
1016
1017   const MCSection *SectionA = 0;
1018   const MCSymbol *SymbolA = 0;
1019   if (const MCSymbolRefExpr *A = Target.getSymA()) {
1020     SymbolA = &A->getSymbol();
1021     SectionA = &SymbolA->getSection();
1022   }
1023
1024   const MCSection *SectionB = 0;
1025   if (const MCSymbolRefExpr *B = Target.getSymB()) {
1026     SectionB = &B->getSymbol().getSection();
1027   }
1028
1029   if (!BaseSection)
1030     return SectionA == SectionB;
1031
1032   const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1033   if (DataA.isExternal())
1034     return false;
1035
1036   return !SectionB && BaseSection == SectionA;
1037 }
1038
1039 void ELFObjectWriterImpl::WriteObject(MCAssembler &Asm,
1040                                       const MCAsmLayout &Layout) {
1041   // Compute symbol table information.
1042   ComputeSymbolTable(Asm);
1043
1044   CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1045                          const_cast<MCAsmLayout&>(Layout));
1046
1047   // Add 1 for the null section.
1048   unsigned NumSections = Asm.size() + 1;
1049   uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1050   uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1051   uint64_t FileOff = HeaderSize;
1052
1053   for (MCAssembler::const_iterator it = Asm.begin(),
1054          ie = Asm.end(); it != ie; ++it) {
1055     const MCSectionData &SD = *it;
1056
1057     FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1058
1059     // Get the size of the section in the output file (including padding).
1060     uint64_t Size = Layout.getSectionFileSize(&SD);
1061
1062     FileOff += Size;
1063   }
1064
1065   FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1066
1067   // Write out the ELF header ...
1068   WriteHeader(FileOff - HeaderSize, NumSections);
1069
1070   FileOff = HeaderSize;
1071
1072   // ... then all of the sections ...
1073   DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1074
1075   DenseMap<const MCSection*, uint8_t> SectionIndexMap;
1076
1077   unsigned Index = 1;
1078   for (MCAssembler::const_iterator it = Asm.begin(),
1079          ie = Asm.end(); it != ie; ++it) {
1080     const MCSectionData &SD = *it;
1081
1082     uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1083     WriteZeros(Padding);
1084     FileOff += Padding;
1085
1086     // Remember the offset into the file for this section.
1087     SectionOffsetMap[&it->getSection()] = FileOff;
1088     SectionIndexMap[&it->getSection()] = Index++;
1089
1090     FileOff += Layout.getSectionFileSize(&SD);
1091
1092     Asm.WriteSectionData(it, Layout, Writer);
1093   }
1094
1095   uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1096   WriteZeros(Padding);
1097   FileOff += Padding;
1098
1099   // ... and then the section header table.
1100   // Should we align the section header table?
1101   //
1102   // Null section first.
1103   WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1104
1105   for (MCAssembler::const_iterator it = Asm.begin(),
1106          ie = Asm.end(); it != ie; ++it) {
1107     const MCSectionData &SD = *it;
1108     const MCSectionELF &Section =
1109       static_cast<const MCSectionELF&>(SD.getSection());
1110
1111     uint64_t sh_link = 0;
1112     uint64_t sh_info = 0;
1113
1114     switch(Section.getType()) {
1115     case ELF::SHT_DYNAMIC:
1116       sh_link = SectionStringTableIndex[&it->getSection()];
1117       sh_info = 0;
1118       break;
1119
1120     case ELF::SHT_REL:
1121     case ELF::SHT_RELA: {
1122       const MCSection *SymtabSection;
1123       const MCSection *InfoSection;
1124
1125       SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1126                                                      SectionKind::getReadOnly(),
1127                                                      false);
1128       sh_link = SectionIndexMap[SymtabSection];
1129
1130       // Remove ".rel" and ".rela" prefixes.
1131       unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1132       StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1133
1134       InfoSection = Asm.getContext().getELFSection(SectionName,
1135                                                    ELF::SHT_PROGBITS, 0,
1136                                                    SectionKind::getReadOnly(),
1137                                                    false);
1138       sh_info = SectionIndexMap[InfoSection];
1139       break;
1140     }
1141
1142     case ELF::SHT_SYMTAB:
1143     case ELF::SHT_DYNSYM:
1144       sh_link = StringTableIndex;
1145       sh_info = LastLocalSymbolIndex;
1146       break;
1147
1148     case ELF::SHT_PROGBITS:
1149     case ELF::SHT_STRTAB:
1150     case ELF::SHT_NOBITS:
1151     case ELF::SHT_NULL:
1152       // Nothing to do.
1153       break;
1154
1155     case ELF::SHT_HASH:
1156     case ELF::SHT_GROUP:
1157     case ELF::SHT_SYMTAB_SHNDX:
1158     default:
1159       assert(0 && "FIXME: sh_type value not supported!");
1160       break;
1161     }
1162
1163     WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
1164                      Section.getType(), Section.getFlags(),
1165                      0,
1166                      SectionOffsetMap.lookup(&SD.getSection()),
1167                      Layout.getSectionSize(&SD), sh_link,
1168                      sh_info, SD.getAlignment(),
1169                      Section.getEntrySize());
1170   }
1171 }
1172
1173 ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1174                                  bool Is64Bit,
1175                                  Triple::OSType OSType,
1176                                  bool IsLittleEndian,
1177                                  bool HasRelocationAddend)
1178   : MCObjectWriter(OS, IsLittleEndian)
1179 {
1180   Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend, OSType);
1181 }
1182
1183 ELFObjectWriter::~ELFObjectWriter() {
1184   delete (ELFObjectWriterImpl*) Impl;
1185 }
1186
1187 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1188   ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1189 }
1190
1191 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1192                                        const MCAsmLayout &Layout,
1193                                        const MCFragment *Fragment,
1194                                        const MCFixup &Fixup, MCValue Target,
1195                                        uint64_t &FixedValue) {
1196   ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1197                                                   Target, FixedValue);
1198 }
1199
1200 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1201                                            const MCValue Target,
1202                                            bool IsPCRel,
1203                                            const MCFragment *DF) const {
1204   return ((ELFObjectWriterImpl*) Impl)->IsFixupFullyResolved(Asm, Target,
1205                                                              IsPCRel, DF);
1206 }
1207
1208 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1209                                   const MCAsmLayout &Layout) {
1210   ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);
1211 }