Factor symbol value computation into a function.
[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 namespace {
61
62   class ELFObjectWriterImpl {
63     static bool isFixupKindX86PCRel(unsigned Kind) {
64       switch (Kind) {
65       default:
66         return false;
67       case X86::reloc_pcrel_1byte:
68       case X86::reloc_pcrel_4byte:
69       case X86::reloc_riprel_4byte:
70       case X86::reloc_riprel_4byte_movq_load:
71         return true;
72       }
73     }
74
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     void WriteObject(const MCAssembler &Asm, const MCAsmLayout &Layout);
278   };
279
280 }
281
282 // Emit the ELF header.
283 void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
284                                       unsigned NumberOfSections) {
285   // ELF Header
286   // ----------
287   //
288   // Note
289   // ----
290   // emitWord method behaves differently for ELF32 and ELF64, writing
291   // 4 bytes in the former and 8 in the latter.
292
293   Write8(0x7f); // e_ident[EI_MAG0]
294   Write8('E');  // e_ident[EI_MAG1]
295   Write8('L');  // e_ident[EI_MAG2]
296   Write8('F');  // e_ident[EI_MAG3]
297
298   Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
299
300   // e_ident[EI_DATA]
301   Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
302
303   Write8(ELF::EV_CURRENT);        // e_ident[EI_VERSION]
304   // e_ident[EI_OSABI]
305   switch (OSType) {
306     case Triple::FreeBSD:  Write8(ELF::ELFOSABI_FREEBSD); break;
307     case Triple::Linux:    Write8(ELF::ELFOSABI_LINUX); break;
308     default:               Write8(ELF::ELFOSABI_NONE); break;
309   }
310   Write8(0);                  // e_ident[EI_ABIVERSION]
311
312   WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
313
314   Write16(ELF::ET_REL);             // e_type
315
316   // FIXME: Make this configurable
317   Write16(Is64Bit ? ELF::EM_X86_64 : ELF::EM_386); // e_machine = target
318
319   Write32(ELF::EV_CURRENT);         // e_version
320   WriteWord(0);                    // e_entry, no entry point in .o file
321   WriteWord(0);                    // e_phoff, no program header for .o
322   WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
323             sizeof(ELF::Elf32_Ehdr)));  // e_shoff = sec hdr table off in bytes
324
325   // FIXME: Make this configurable.
326   Write32(0);   // e_flags = whatever the target wants
327
328   // e_ehsize = ELF header size
329   Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
330
331   Write16(0);                  // e_phentsize = prog header entry size
332   Write16(0);                  // e_phnum = # prog header entries = 0
333
334   // e_shentsize = Section header entry size
335   Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
336
337   // e_shnum     = # of section header ents
338   Write16(NumberOfSections);
339
340   // e_shstrndx  = Section # of '.shstrtab'
341   Write16(ShstrtabIndex);
342 }
343
344 void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
345                                            uint8_t info, uint64_t value,
346                                            uint64_t size, uint8_t other,
347                                            uint16_t shndx) {
348   if (Is64Bit) {
349     char buf[8];
350
351     String32(buf, name);
352     F->getContents() += StringRef(buf, 4); // st_name
353
354     String8(buf, info);
355     F->getContents() += StringRef(buf, 1);  // st_info
356
357     String8(buf, other);
358     F->getContents() += StringRef(buf, 1); // st_other
359
360     String16(buf, shndx);
361     F->getContents() += StringRef(buf, 2); // st_shndx
362
363     String64(buf, value);
364     F->getContents() += StringRef(buf, 8); // st_value
365
366     String64(buf, size);
367     F->getContents() += StringRef(buf, 8);  // st_size
368   } else {
369     char buf[4];
370
371     String32(buf, name);
372     F->getContents() += StringRef(buf, 4);  // st_name
373
374     String32(buf, value);
375     F->getContents() += StringRef(buf, 4); // st_value
376
377     String32(buf, size);
378     F->getContents() += StringRef(buf, 4);  // st_size
379
380     String8(buf, info);
381     F->getContents() += StringRef(buf, 1);  // st_info
382
383     String8(buf, other);
384     F->getContents() += StringRef(buf, 1); // st_other
385
386     String16(buf, shndx);
387     F->getContents() += StringRef(buf, 2); // st_shndx
388   }
389 }
390
391 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
392   if (Data.isCommon() && Data.isExternal())
393     return Data.getCommonAlignment();
394
395   const MCSymbol &Symbol = Data.getSymbol();
396   if (!Symbol.isInSection())
397     return 0;
398
399   if (!Data.isCommon() && !(Data.getFlags() & ELF_STB_Weak))
400     if (MCFragment *FF = Data.getFragment())
401       return Layout.getSymbolAddress(&Data) -
402              Layout.getSectionAddress(FF->getParent());
403
404   return 0;
405 }
406
407 void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
408                                       const MCAsmLayout &Layout) {
409   MCSymbolData &Data = *MSD.SymbolData;
410   uint8_t Info = (Data.getFlags() & 0xff);
411   uint8_t Other = ((Data.getFlags() & 0xf00) >> ELF_STV_Shift);
412   uint64_t Value = SymbolValue(Data, Layout);
413   uint64_t Size = 0;
414   const MCExpr *ESize;
415
416   assert(!(Data.isCommon() && !Data.isExternal()));
417
418   ESize = Data.getSize();
419   if (Data.getSize()) {
420     MCValue Res;
421     if (ESize->getKind() == MCExpr::Binary) {
422       const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
423
424       if (BE->EvaluateAsRelocatable(Res, &Layout)) {
425         MCSymbolData &A =
426           Layout.getAssembler().getSymbolData(Res.getSymA()->getSymbol());
427         MCSymbolData &B =
428           Layout.getAssembler().getSymbolData(Res.getSymB()->getSymbol());
429
430         Size = Layout.getSymbolAddress(&A) - Layout.getSymbolAddress(&B);
431       }
432     } else if (ESize->getKind() == MCExpr::Constant) {
433       Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
434     } else {
435       assert(0 && "Unsupported size expression");
436     }
437   }
438
439   // Write out the symbol table entry
440   WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
441                    Size, Other, MSD.SectionIndex);
442 }
443
444 void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
445                                            const MCAssembler &Asm,
446                                            const MCAsmLayout &Layout,
447                                            unsigned NumRegularSections) {
448   // The string table must be emitted first because we need the index
449   // into the string table for all the symbol names.
450   assert(StringTable.size() && "Missing string table");
451
452   // FIXME: Make sure the start of the symbol table is aligned.
453
454   // The first entry is the undefined symbol entry.
455   unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
456   F->getContents().append(EntrySize, '\x00');
457
458   // Write the symbol table entries.
459   LastLocalSymbolIndex = LocalSymbolData.size() + 1;
460   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
461     ELFSymbolData &MSD = LocalSymbolData[i];
462     WriteSymbol(F, MSD, Layout);
463   }
464
465   // Write out a symbol table entry for each regular section.
466   unsigned Index = 1;
467   for (MCAssembler::const_iterator it = Asm.begin();
468        Index <= NumRegularSections; ++it, ++Index) {
469     const MCSectionELF &Section =
470       static_cast<const MCSectionELF&>(it->getSection());
471     // Leave out relocations so we don't have indexes within
472     // the relocations messed up
473     if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
474       continue;
475     WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
476     LastLocalSymbolIndex++;
477   }
478
479   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
480     ELFSymbolData &MSD = ExternalSymbolData[i];
481     MCSymbolData &Data = *MSD.SymbolData;
482     assert((Data.getFlags() & ELF_STB_Global) &&
483            "External symbol requires STB_GLOBAL flag");
484     WriteSymbol(F, MSD, Layout);
485     if (GetBinding(Data) == ELF::STB_LOCAL)
486       LastLocalSymbolIndex++;
487   }
488
489   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
490     ELFSymbolData &MSD = UndefinedSymbolData[i];
491     MCSymbolData &Data = *MSD.SymbolData;
492     WriteSymbol(F, MSD, Layout);
493     if (GetBinding(Data) == ELF::STB_LOCAL)
494       LastLocalSymbolIndex++;
495   }
496 }
497
498 static const MCSymbolData *getAtom(const MCSymbolData &SD) {
499   if (!SD.getFragment())
500     return 0;
501
502   return SD.getFragment()->getAtom();
503 }
504
505 // FIXME: this is currently X86/X86_64 only
506 void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
507                                            const MCAsmLayout &Layout,
508                                            const MCFragment *Fragment,
509                                            const MCFixup &Fixup,
510                                            MCValue Target,
511                                            uint64_t &FixedValue) {
512   int64_t Addend = 0;
513   unsigned Index = 0;
514   int64_t Value = Target.getConstant();
515
516   bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
517   if (!Target.isAbsolute()) {
518     const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
519     MCSymbolData &SD = Asm.getSymbolData(*Symbol);
520     const MCSymbolData *Base = getAtom(SD);
521     MCFragment *F = SD.getFragment();
522
523     // Avoid relocations for cases like jumps and calls in the same file.
524     if (Symbol->isDefined() && !SD.isExternal() &&
525         IsPCRel &&
526         &Fragment->getParent()->getSection() == &Symbol->getSection()) {
527       uint64_t FixupAddr = Layout.getFragmentAddress(Fragment) + Fixup.getOffset();
528       FixedValue = Layout.getSymbolAddress(&SD) + Target.getConstant() - FixupAddr;
529       return;
530     }
531
532     if (Base) {
533       if (Base != &SD) {
534         Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
535
536         MCSectionData *FSD = F->getParent();
537         // Offset of the symbol in the section
538         Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
539       } else
540         Index = getSymbolIndexInSymbolTable(Asm, Symbol);
541       Addend = Value;
542       // Compensate for the addend on i386.
543       if (Is64Bit)
544         Value = 0;
545     } else {
546       if (F) {
547         // Index of the section in .symtab against this symbol
548         // is being relocated + 2 (empty section + abs. symbols).
549         Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
550
551         MCSectionData *FSD = F->getParent();
552         // Offset of the symbol in the section
553         Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
554       } else {
555         Index = getSymbolIndexInSymbolTable(Asm, Symbol);
556       }
557       Addend = Value;
558       // Compensate for the addend on i386.
559       if (Is64Bit)
560         Value = 0;
561     }
562   }
563
564   FixedValue = Value;
565
566   // determine the type of the relocation
567   unsigned Type;
568   if (Is64Bit) {
569     if (IsPCRel) {
570       Type = ELF::R_X86_64_PC32;
571     } else {
572       switch ((unsigned)Fixup.getKind()) {
573       default: llvm_unreachable("invalid fixup kind!");
574       case FK_Data_8: Type = ELF::R_X86_64_64; break;
575       case X86::reloc_pcrel_4byte:
576       case FK_Data_4:
577         // check that the offset fits within a signed long
578         if (Target.getConstant() < 0) {
579           assert(isInt<32>(Target.getConstant()));
580           Type = ELF::R_X86_64_32S;
581         } else {
582           assert(isUInt<32>(Target.getConstant()));
583           Type = ELF::R_X86_64_32;
584         }
585         break;
586       case FK_Data_2: Type = ELF::R_X86_64_16; break;
587       case X86::reloc_pcrel_1byte:
588       case FK_Data_1: Type = ELF::R_X86_64_8; break;
589       }
590     }
591   } else {
592     if (IsPCRel) {
593       Type = ELF::R_386_PC32;
594     } else {
595       switch ((unsigned)Fixup.getKind()) {
596       default: llvm_unreachable("invalid fixup kind!");
597       case X86::reloc_pcrel_4byte:
598       case FK_Data_4: Type = ELF::R_386_32; break;
599       case FK_Data_2: Type = ELF::R_386_16; break;
600       case X86::reloc_pcrel_1byte:
601       case FK_Data_1: Type = ELF::R_386_8; break;
602       }
603     }
604   }
605
606   ELFRelocationEntry ERE;
607
608   if (Is64Bit) {
609     struct ELF::Elf64_Rela ERE64;
610     ERE64.setSymbolAndType(Index, Type);
611     ERE.r_info = ERE64.r_info;
612   } else {
613     struct ELF::Elf32_Rela ERE32;
614     ERE32.setSymbolAndType(Index, Type);
615     ERE.r_info = ERE32.r_info;
616   }
617
618   ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
619
620   if (HasRelocationAddend)
621     ERE.r_addend = Addend;
622   else
623     ERE.r_addend = 0; // Silence compiler warning.
624
625   Relocations[Fragment->getParent()].push_back(ERE);
626 }
627
628 uint64_t
629 ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
630                                                  const MCSymbol *S) {
631   MCSymbolData &SD = Asm.getSymbolData(*S);
632
633   // Local symbol.
634   if (!SD.isExternal() && !S->isUndefined())
635     return SD.getIndex() + /* empty symbol */ 1;
636
637   // External or undefined symbol.
638   return SD.getIndex() + Asm.size() + /* empty symbol */ 1;
639 }
640
641 void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
642   // Build section lookup table.
643   DenseMap<const MCSection*, uint8_t> SectionIndexMap;
644   unsigned Index = 1;
645   for (MCAssembler::iterator it = Asm.begin(),
646          ie = Asm.end(); it != ie; ++it, ++Index)
647     SectionIndexMap[&it->getSection()] = Index;
648
649   // Index 0 is always the empty string.
650   StringMap<uint64_t> StringIndexMap;
651   StringTable += '\x00';
652
653   // Add the data for local symbols.
654   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
655          ie = Asm.symbol_end(); it != ie; ++it) {
656     const MCSymbol &Symbol = it->getSymbol();
657
658     // Ignore non-linker visible symbols.
659     if (!Asm.isSymbolLinkerVisible(Symbol))
660       continue;
661
662     if (it->isExternal() || Symbol.isUndefined())
663       continue;
664
665     uint64_t &Entry = StringIndexMap[Symbol.getName()];
666     if (!Entry) {
667       Entry = StringTable.size();
668       StringTable += Symbol.getName();
669       StringTable += '\x00';
670     }
671
672     ELFSymbolData MSD;
673     MSD.SymbolData = it;
674     MSD.StringIndex = Entry;
675
676     if (Symbol.isAbsolute()) {
677       MSD.SectionIndex = ELF::SHN_ABS;
678       LocalSymbolData.push_back(MSD);
679     } else {
680       MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
681       assert(MSD.SectionIndex && "Invalid section index!");
682       LocalSymbolData.push_back(MSD);
683     }
684   }
685
686   // Now add non-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 (it->isCommon()) {
710       MSD.SectionIndex = ELF::SHN_COMMON;
711       ExternalSymbolData.push_back(MSD);
712     } else if (Symbol.isUndefined()) {
713       MSD.SectionIndex = ELF::SHN_UNDEF;
714       // FIXME: Undefined symbols are global, but this is the first place we
715       // are able to set it.
716       if (GetBinding(*it) == ELF::STB_LOCAL)
717         SetBinding(*it, ELF::STB_GLOBAL);
718       UndefinedSymbolData.push_back(MSD);
719     } else if (Symbol.isAbsolute()) {
720       MSD.SectionIndex = ELF::SHN_ABS;
721       ExternalSymbolData.push_back(MSD);
722     } else {
723       MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
724       assert(MSD.SectionIndex && "Invalid section index!");
725       ExternalSymbolData.push_back(MSD);
726     }
727   }
728
729   // Symbols are required to be in lexicographic order.
730   array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
731   array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
732   array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
733
734   // Set the symbol indices. Local symbols must come before all other
735   // symbols with non-local bindings.
736   Index = 0;
737   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
738     LocalSymbolData[i].SymbolData->setIndex(Index++);
739   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
740     ExternalSymbolData[i].SymbolData->setIndex(Index++);
741   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
742     UndefinedSymbolData[i].SymbolData->setIndex(Index++);
743 }
744
745 void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
746                                           const MCSectionData &SD) {
747   if (!Relocations[&SD].empty()) {
748     MCContext &Ctx = Asm.getContext();
749     const MCSection *RelaSection;
750     const MCSectionELF &Section =
751       static_cast<const MCSectionELF&>(SD.getSection());
752
753     const StringRef SectionName = Section.getSectionName();
754     std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
755     RelaSectionName += SectionName;
756
757     unsigned EntrySize;
758     if (HasRelocationAddend)
759       EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
760     else
761       EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
762
763     RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
764                                     ELF::SHT_RELA : ELF::SHT_REL, 0,
765                                     SectionKind::getReadOnly(),
766                                     false, EntrySize);
767
768     MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
769     RelaSD.setAlignment(Is64Bit ? 8 : 4);
770
771     MCDataFragment *F = new MCDataFragment(&RelaSD);
772
773     WriteRelocationsFragment(Asm, F, &SD);
774
775     Asm.AddSectionToTheEnd(RelaSD, Layout);
776   }
777 }
778
779 void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
780                                            uint64_t Flags, uint64_t Address,
781                                            uint64_t Offset, uint64_t Size,
782                                            uint32_t Link, uint32_t Info,
783                                            uint64_t Alignment,
784                                            uint64_t EntrySize) {
785   Write32(Name);        // sh_name: index into string table
786   Write32(Type);        // sh_type
787   WriteWord(Flags);     // sh_flags
788   WriteWord(Address);   // sh_addr
789   WriteWord(Offset);    // sh_offset
790   WriteWord(Size);      // sh_size
791   Write32(Link);        // sh_link
792   Write32(Info);        // sh_info
793   WriteWord(Alignment); // sh_addralign
794   WriteWord(EntrySize); // sh_entsize
795 }
796
797 void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
798                                                    MCDataFragment *F,
799                                                    const MCSectionData *SD) {
800   std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
801   // sort by the r_offset just like gnu as does
802   array_pod_sort(Relocs.begin(), Relocs.end());
803
804   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
805     ELFRelocationEntry entry = Relocs[e - i - 1];
806
807     if (Is64Bit) {
808       char buf[8];
809
810       String64(buf, entry.r_offset);
811       F->getContents() += StringRef(buf, 8);
812
813       String64(buf, entry.r_info);
814       F->getContents() += StringRef(buf, 8);
815
816       if (HasRelocationAddend) {
817         String64(buf, entry.r_addend);
818         F->getContents() += StringRef(buf, 8);
819       }
820     } else {
821       char buf[4];
822
823       String32(buf, entry.r_offset);
824       F->getContents() += StringRef(buf, 4);
825
826       String32(buf, entry.r_info);
827       F->getContents() += StringRef(buf, 4);
828
829       if (HasRelocationAddend) {
830         String32(buf, entry.r_addend);
831         F->getContents() += StringRef(buf, 4);
832       }
833     }
834   }
835 }
836
837 void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
838                                                  MCAsmLayout &Layout) {
839   MCContext &Ctx = Asm.getContext();
840   MCDataFragment *F;
841
842   WriteRelocations(Asm, Layout);
843
844   const MCSection *SymtabSection;
845   unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
846
847   unsigned NumRegularSections = Asm.size();
848
849   // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
850   const MCSection *ShstrtabSection;
851   ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
852                                       SectionKind::getReadOnly(), false);
853   MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
854   ShstrtabSD.setAlignment(1);
855   ShstrtabIndex = Asm.size();
856
857   SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
858                                     SectionKind::getReadOnly(),
859                                     false, EntrySize);
860   MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
861   SymtabSD.setAlignment(Is64Bit ? 8 : 4);
862
863   const MCSection *StrtabSection;
864   StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
865                                     SectionKind::getReadOnly(), false);
866   MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
867   StrtabSD.setAlignment(1);
868   StringTableIndex = Asm.size();
869
870
871   // Symbol table
872   F = new MCDataFragment(&SymtabSD);
873   WriteSymbolTable(F, Asm, Layout, NumRegularSections);
874   Asm.AddSectionToTheEnd(SymtabSD, Layout);
875
876   F = new MCDataFragment(&StrtabSD);
877   F->getContents().append(StringTable.begin(), StringTable.end());
878   Asm.AddSectionToTheEnd(StrtabSD, Layout);
879
880   F = new MCDataFragment(&ShstrtabSD);
881
882   // Section header string table.
883   //
884   // The first entry of a string table holds a null character so skip
885   // section 0.
886   uint64_t Index = 1;
887   F->getContents() += '\x00';
888
889   for (MCAssembler::const_iterator it = Asm.begin(),
890          ie = Asm.end(); it != ie; ++it) {
891     const MCSectionELF &Section =
892       static_cast<const MCSectionELF&>(it->getSection());
893     // FIXME: We could merge suffixes like in .text and .rela.text.
894
895     // Remember the index into the string table so we can write it
896     // into the sh_name field of the section header table.
897     SectionStringTableIndex[&it->getSection()] = Index;
898
899     Index += Section.getSectionName().size() + 1;
900     F->getContents() += Section.getSectionName();
901     F->getContents() += '\x00';
902   }
903
904   Asm.AddSectionToTheEnd(ShstrtabSD, Layout);
905 }
906
907 void ELFObjectWriterImpl::WriteObject(const MCAssembler &Asm,
908                                       const MCAsmLayout &Layout) {
909   CreateMetadataSections(const_cast<MCAssembler&>(Asm),
910                          const_cast<MCAsmLayout&>(Layout));
911
912   // Add 1 for the null section.
913   unsigned NumSections = Asm.size() + 1;
914   uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
915   uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
916   uint64_t FileOff = HeaderSize;
917
918   for (MCAssembler::const_iterator it = Asm.begin(),
919          ie = Asm.end(); it != ie; ++it) {
920     const MCSectionData &SD = *it;
921
922     FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
923
924     // Get the size of the section in the output file (including padding).
925     uint64_t Size = Layout.getSectionFileSize(&SD);
926
927     FileOff += Size;
928   }
929
930   FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
931
932   // Write out the ELF header ...
933   WriteHeader(FileOff - HeaderSize, NumSections);
934
935   FileOff = HeaderSize;
936
937   // ... then all of the sections ...
938   DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
939
940   DenseMap<const MCSection*, uint8_t> SectionIndexMap;
941
942   unsigned Index = 1;
943   for (MCAssembler::const_iterator it = Asm.begin(),
944          ie = Asm.end(); it != ie; ++it) {
945     const MCSectionData &SD = *it;
946
947     uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
948     WriteZeros(Padding);
949     FileOff += Padding;
950
951     // Remember the offset into the file for this section.
952     SectionOffsetMap[&it->getSection()] = FileOff;
953     SectionIndexMap[&it->getSection()] = Index++;
954
955     FileOff += Layout.getSectionFileSize(&SD);
956
957     Asm.WriteSectionData(it, Layout, Writer);
958   }
959
960   uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
961   WriteZeros(Padding);
962   FileOff += Padding;
963
964   // ... and then the section header table.
965   // Should we align the section header table?
966   //
967   // Null section first.
968   WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
969
970   for (MCAssembler::const_iterator it = Asm.begin(),
971          ie = Asm.end(); it != ie; ++it) {
972     const MCSectionData &SD = *it;
973     const MCSectionELF &Section =
974       static_cast<const MCSectionELF&>(SD.getSection());
975
976     uint64_t sh_link = 0;
977     uint64_t sh_info = 0;
978
979     switch(Section.getType()) {
980     case ELF::SHT_DYNAMIC:
981       sh_link = SectionStringTableIndex[&it->getSection()];
982       sh_info = 0;
983       break;
984
985     case ELF::SHT_REL:
986     case ELF::SHT_RELA: {
987       const MCSection *SymtabSection;
988       const MCSection *InfoSection;
989
990       SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
991                                                      SectionKind::getReadOnly(),
992                                                      false);
993       sh_link = SectionIndexMap[SymtabSection];
994
995       // Remove ".rel" and ".rela" prefixes.
996       unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
997       StringRef SectionName = Section.getSectionName().substr(SecNameLen);
998
999       InfoSection = Asm.getContext().getELFSection(SectionName,
1000                                                    ELF::SHT_PROGBITS, 0,
1001                                                    SectionKind::getReadOnly(),
1002                                                    false);
1003       sh_info = SectionIndexMap[InfoSection];
1004       break;
1005     }
1006
1007     case ELF::SHT_SYMTAB:
1008     case ELF::SHT_DYNSYM:
1009       sh_link = StringTableIndex;
1010       sh_info = LastLocalSymbolIndex;
1011       break;
1012
1013     case ELF::SHT_PROGBITS:
1014     case ELF::SHT_STRTAB:
1015     case ELF::SHT_NOBITS:
1016     case ELF::SHT_NULL:
1017       // Nothing to do.
1018       break;
1019
1020     case ELF::SHT_HASH:
1021     case ELF::SHT_GROUP:
1022     case ELF::SHT_SYMTAB_SHNDX:
1023     default:
1024       assert(0 && "FIXME: sh_type value not supported!");
1025       break;
1026     }
1027
1028     WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
1029                      Section.getType(), Section.getFlags(),
1030                      0,
1031                      SectionOffsetMap.lookup(&SD.getSection()),
1032                      Layout.getSectionSize(&SD), sh_link,
1033                      sh_info, SD.getAlignment(),
1034                      Section.getEntrySize());
1035   }
1036 }
1037
1038 ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1039                                  bool Is64Bit,
1040                                  Triple::OSType OSType,
1041                                  bool IsLittleEndian,
1042                                  bool HasRelocationAddend)
1043   : MCObjectWriter(OS, IsLittleEndian)
1044 {
1045   Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend, OSType);
1046 }
1047
1048 ELFObjectWriter::~ELFObjectWriter() {
1049   delete (ELFObjectWriterImpl*) Impl;
1050 }
1051
1052 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1053   ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1054 }
1055
1056 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1057                                        const MCAsmLayout &Layout,
1058                                        const MCFragment *Fragment,
1059                                        const MCFixup &Fixup, MCValue Target,
1060                                        uint64_t &FixedValue) {
1061   ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1062                                                   Target, FixedValue);
1063 }
1064
1065 void ELFObjectWriter::WriteObject(const MCAssembler &Asm,
1066                                   const MCAsmLayout &Layout) {
1067   ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);
1068 }