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