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