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