Simple ELF32/64 binary files can now be emitted for x86 and x86_64 without
[oota-llvm.git] / lib / CodeGen / ELFWriter.cpp
1 //===-- ELFWriter.cpp - Target-independent ELF Writer code ----------------===//
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 the target-independent ELF writer.  This file writes out
11 // the ELF file in the following order:
12 //
13 //  #1. ELF Header
14 //  #2. '.text' section
15 //  #3. '.data' section
16 //  #4. '.bss' section  (conceptual position in file)
17 //  ...
18 //  #X. '.shstrtab' section
19 //  #Y. Section Table
20 //
21 // The entries in the section table are laid out as:
22 //  #0. Null entry [required]
23 //  #1. ".text" entry - the program code
24 //  #2. ".data" entry - global variables with initializers.     [ if needed ]
25 //  #3. ".bss" entry  - global variables without initializers.  [ if needed ]
26 //  ...
27 //  #N. ".shstrtab" entry - String table for the section names.
28 //
29 // NOTE: This code should eventually be extended to support 64-bit ELF (this
30 // won't be hard), but we haven't done so yet!
31 //
32 //===----------------------------------------------------------------------===//
33
34 #define DEBUG_TYPE "elfwriter"
35
36 #include "ELFWriter.h"
37 #include "ELFCodeEmitter.h"
38 #include "ELF.h"
39 #include "llvm/Module.h"
40 #include "llvm/PassManager.h"
41 #include "llvm/DerivedTypes.h"
42 #include "llvm/CodeGen/FileWriters.h"
43 #include "llvm/CodeGen/MachineCodeEmitter.h"
44 #include "llvm/CodeGen/MachineConstantPool.h"
45 #include "llvm/CodeGen/MachineFunctionPass.h"
46 #include "llvm/Target/TargetData.h"
47 #include "llvm/Target/TargetELFWriterInfo.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include "llvm/Support/Mangler.h"
50 #include "llvm/Support/OutputBuffer.h"
51 #include "llvm/Support/Streams.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Support/Debug.h"
54 #include <list>
55 using namespace llvm;
56
57 char ELFWriter::ID = 0;
58 /// AddELFWriter - Concrete function to add the ELF writer to the function pass
59 /// manager.
60 MachineCodeEmitter *llvm::AddELFWriter(PassManagerBase &PM,
61                                        raw_ostream &O,
62                                        TargetMachine &TM) {
63   ELFWriter *EW = new ELFWriter(O, TM);
64   PM.add(EW);
65   return &EW->getMachineCodeEmitter();
66 }
67
68 //===----------------------------------------------------------------------===//
69 //                          ELFWriter Implementation
70 //===----------------------------------------------------------------------===//
71
72 ELFWriter::ELFWriter(raw_ostream &o, TargetMachine &tm)
73   : MachineFunctionPass(&ID), O(o), TM(tm), ElfHdr() {
74   is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
75   isLittleEndian = TM.getTargetData()->isLittleEndian();
76
77   ElfHdr = new ELFHeader(TM.getELFWriterInfo()->getEMachine(), 0,
78                          is64Bit, isLittleEndian);
79
80   // Create the machine code emitter object for this target.
81   MCE = new ELFCodeEmitter(*this);
82   NumSections = 0;
83 }
84
85 ELFWriter::~ELFWriter() {
86   delete MCE;
87   delete ElfHdr;
88 }
89
90 // doInitialization - Emit the file header and all of the global variables for
91 // the module to the ELF file.
92 bool ELFWriter::doInitialization(Module &M) {
93   Mang = new Mangler(M);
94
95   // Local alias to shortenify coming code.
96   std::vector<unsigned char> &FH = FileHeader;
97   OutputBuffer FHOut(FH, is64Bit, isLittleEndian);
98
99   // ELF Header
100   // ----------
101   // Fields e_shnum e_shstrndx are only known after all section have
102   // been emitted. They locations in the ouput buffer are recorded so
103   // to be patched up later.
104   //
105   // Note
106   // ----
107   // FHOut.outaddr method behaves differently for ELF32 and ELF64 writing
108   // 4 bytes in the former and 8 in the last for *_off and *_addr elf types
109
110   FHOut.outbyte(0x7f); // e_ident[EI_MAG0]
111   FHOut.outbyte('E');  // e_ident[EI_MAG1]
112   FHOut.outbyte('L');  // e_ident[EI_MAG2]
113   FHOut.outbyte('F');  // e_ident[EI_MAG3]
114
115   FHOut.outbyte(ElfHdr->getElfClass());   // e_ident[EI_CLASS]
116   FHOut.outbyte(ElfHdr->getByteOrder());  // e_ident[EI_DATA]
117   FHOut.outbyte(EV_CURRENT);  // e_ident[EI_VERSION]
118
119   FH.resize(16);  // e_ident[EI_NIDENT-EI_PAD]
120
121   FHOut.outhalf(ET_REL);               // e_type
122   FHOut.outhalf(ElfHdr->getMachine()); // e_machine = target
123   FHOut.outword(EV_CURRENT);           // e_version
124   FHOut.outaddr(0);                    // e_entry = 0, no entry point in .o file
125   FHOut.outaddr(0);                    // e_phoff = 0, no program header for .o
126   ELFHdr_e_shoff_Offset = FH.size();
127   FHOut.outaddr(0);                    // e_shoff = sec hdr table off in bytes
128   FHOut.outword(ElfHdr->getFlags());   // e_flags = whatever the target wants
129   FHOut.outhalf(ElfHdr->getSize());    // e_ehsize = ELF header size
130   FHOut.outhalf(0);                    // e_phentsize = prog header entry size
131   FHOut.outhalf(0);                    // e_phnum = # prog header entries = 0
132
133   // e_shentsize = Section header entry size
134   FHOut.outhalf(ELFSection::getSectionHdrSize(is64Bit));
135
136   // e_shnum     = # of section header ents
137   ELFHdr_e_shnum_Offset = FH.size();
138   FHOut.outhalf(0);
139
140   // e_shstrndx  = Section # of '.shstrtab'
141   ELFHdr_e_shstrndx_Offset = FH.size();
142   FHOut.outhalf(0);
143
144   // Add the null section, which is required to be first in the file.
145   getSection("", ELFSection::SHT_NULL, 0);
146
147   // Start up the symbol table.  The first entry in the symtab is the null
148   // entry.
149   SymbolTable.push_back(ELFSym(0));
150
151   return false;
152 }
153
154 void ELFWriter::EmitGlobal(GlobalVariable *GV) {
155   // If this is an external global, emit it now.  TODO: Note that it would be
156   // better to ignore the symbol here and only add it to the symbol table if
157   // referenced.
158   if (!GV->hasInitializer()) {
159     ELFSym ExternalSym(GV);
160     ExternalSym.SetBind(ELFSym::STB_GLOBAL);
161     ExternalSym.SetType(ELFSym::STT_NOTYPE);
162     ExternalSym.SectionIdx = ELFSection::SHN_UNDEF;
163     SymbolTable.push_back(ExternalSym);
164     return;
165   }
166
167   unsigned Align = TM.getTargetData()->getPreferredAlignment(GV);
168   unsigned Size  =
169     TM.getTargetData()->getTypeAllocSize(GV->getType()->getElementType());
170
171   // If this global has a zero initializer, it is part of the .bss or common
172   // section.
173   if (GV->getInitializer()->isNullValue()) {
174     // If this global is part of the common block, add it now.  Variables are
175     // part of the common block if they are zero initialized and allowed to be
176     // merged with other symbols.
177     if (GV->hasLinkOnceLinkage() || GV->hasWeakLinkage() ||
178         GV->hasCommonLinkage()) {
179       ELFSym CommonSym(GV);
180       // Value for common symbols is the alignment required.
181       CommonSym.Value = Align;
182       CommonSym.Size  = Size;
183       CommonSym.SetBind(ELFSym::STB_GLOBAL);
184       CommonSym.SetType(ELFSym::STT_OBJECT);
185       // TODO SOMEDAY: add ELF visibility.
186       CommonSym.SectionIdx = ELFSection::SHN_COMMON;
187       SymbolTable.push_back(CommonSym);
188       return;
189     }
190
191     // Otherwise, this symbol is part of the .bss section.  Emit it now.
192
193     // Handle alignment.  Ensure section is aligned at least as much as required
194     // by this symbol.
195     ELFSection &BSSSection = getBSSSection();
196     BSSSection.Align = std::max(BSSSection.Align, Align);
197
198     // Within the section, emit enough virtual padding to get us to an alignment
199     // boundary.
200     if (Align)
201       BSSSection.Size = (BSSSection.Size + Align - 1) & ~(Align-1);
202
203     ELFSym BSSSym(GV);
204     BSSSym.Value = BSSSection.Size;
205     BSSSym.Size = Size;
206     BSSSym.SetType(ELFSym::STT_OBJECT);
207
208     switch (GV->getLinkage()) {
209     default:  // weak/linkonce/common handled above
210       assert(0 && "Unexpected linkage type!");
211     case GlobalValue::AppendingLinkage:  // FIXME: This should be improved!
212     case GlobalValue::ExternalLinkage:
213       BSSSym.SetBind(ELFSym::STB_GLOBAL);
214       break;
215     case GlobalValue::InternalLinkage:
216       BSSSym.SetBind(ELFSym::STB_LOCAL);
217       break;
218     }
219
220     // Set the idx of the .bss section
221     BSSSym.SectionIdx = BSSSection.SectionIdx;
222     if (!GV->hasPrivateLinkage())
223       SymbolTable.push_back(BSSSym);
224
225     // Reserve space in the .bss section for this symbol.
226     BSSSection.Size += Size;
227     return;
228   }
229
230   // FIXME: handle .rodata
231   //assert(!GV->isConstant() && "unimp");
232
233   // FIXME: handle .data
234   //assert(0 && "unimp");
235 }
236
237
238 bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
239   // Nothing to do here, this is all done through the MCE object above.
240   return false;
241 }
242
243 /// doFinalization - Now that the module has been completely processed, emit
244 /// the ELF file to 'O'.
245 bool ELFWriter::doFinalization(Module &M) {
246   // Okay, the ELF header and .text sections have been completed, build the
247   // .data, .bss, and "common" sections next.
248   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
249        I != E; ++I)
250     EmitGlobal(I);
251
252   // Emit the symbol table now, if non-empty.
253   EmitSymbolTable();
254
255   // Emit the relocation sections.
256   EmitRelocations();
257
258   // Emit the string table for the sections in the ELF file.
259   EmitSectionTableStringTable();
260
261   // Emit the sections to the .o file, and emit the section table for the file.
262   OutputSectionsAndSectionTable();
263
264   // We are done with the abstract symbols.
265   SectionList.clear();
266   NumSections = 0;
267
268   // Release the name mangler object.
269   delete Mang; Mang = 0;
270   return false;
271 }
272
273 /// EmitRelocations - Emit relocations
274 void ELFWriter::EmitRelocations() {
275 }
276
277 /// EmitSymbolTable - If the current symbol table is non-empty, emit the string
278 /// table for it and then the symbol table itself.
279 void ELFWriter::EmitSymbolTable() {
280   if (SymbolTable.size() == 1) return;  // Only the null entry.
281
282   // FIXME: compact all local symbols to the start of the symtab.
283   unsigned FirstNonLocalSymbol = 1;
284
285   ELFSection &StrTab = getSection(".strtab", ELFSection::SHT_STRTAB, 0);
286   StrTab.Align = 1;
287
288   DataBuffer &StrTabBuf = StrTab.SectionData;
289   OutputBuffer StrTabOut(StrTabBuf, is64Bit, isLittleEndian);
290
291   // Set the zero'th symbol to a null byte, as required.
292   StrTabOut.outbyte(0);
293   //SymbolTable[0].NameIdx = 0;
294   unsigned Index = 1;
295   for (unsigned i = 1, e = SymbolTable.size(); i != e; ++i) {
296     // Use the name mangler to uniquify the LLVM symbol.
297     std::string Name = Mang->getValueName(SymbolTable[i].GV);
298
299     if (Name.empty()) {
300       SymbolTable[i].NameIdx = 0;
301     } else {
302       SymbolTable[i].NameIdx = Index;
303
304       // Add the name to the output buffer, including the null terminator.
305       StrTabBuf.insert(StrTabBuf.end(), Name.begin(), Name.end());
306
307       // Add a null terminator.
308       StrTabBuf.push_back(0);
309
310       // Keep track of the number of bytes emitted to this section.
311       Index += Name.size()+1;
312     }
313   }
314   assert(Index == StrTabBuf.size());
315   StrTab.Size = Index;
316
317   // Now that we have emitted the string table and know the offset into the
318   // string table of each symbol, emit the symbol table itself.
319   ELFSection &SymTab = getSection(".symtab", ELFSection::SHT_SYMTAB, 0);
320   SymTab.Align = is64Bit ? 8 : 4;
321   SymTab.Link = StrTab.SectionIdx;      // Section Index of .strtab.
322   SymTab.Info = FirstNonLocalSymbol;    // First non-STB_LOCAL symbol.
323   SymTab.EntSize = is64Bit ? 24 : 16;   // Size of each symtab entry. 
324   DataBuffer &SymTabBuf = SymTab.SectionData;
325   OutputBuffer SymTabOut(SymTabBuf, is64Bit, isLittleEndian);
326
327   if (!is64Bit) {   // 32-bit and 64-bit formats are shuffled a bit.
328     for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i) {
329       ELFSym &Sym = SymbolTable[i];
330       SymTabOut.outword(Sym.NameIdx);
331       SymTabOut.outaddr32(Sym.Value);
332       SymTabOut.outword(Sym.Size);
333       SymTabOut.outbyte(Sym.Info);
334       SymTabOut.outbyte(Sym.Other);
335       SymTabOut.outhalf(Sym.SectionIdx);
336     }
337   } else {
338     for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i) {
339       ELFSym &Sym = SymbolTable[i];
340       SymTabOut.outword(Sym.NameIdx);
341       SymTabOut.outbyte(Sym.Info);
342       SymTabOut.outbyte(Sym.Other);
343       SymTabOut.outhalf(Sym.SectionIdx);
344       SymTabOut.outaddr64(Sym.Value);
345       SymTabOut.outxword(Sym.Size);
346     }
347   }
348
349   SymTab.Size = SymTabBuf.size();
350 }
351
352 /// EmitSectionTableStringTable - This method adds and emits a section for the
353 /// ELF Section Table string table: the string table that holds all of the
354 /// section names.
355 void ELFWriter::EmitSectionTableStringTable() {
356   // First step: add the section for the string table to the list of sections:
357   ELFSection &SHStrTab = getSection(".shstrtab", ELFSection::SHT_STRTAB, 0);
358
359   // Now that we know which section number is the .shstrtab section, update the
360   // e_shstrndx entry in the ELF header.
361   OutputBuffer FHOut(FileHeader, is64Bit, isLittleEndian);
362   FHOut.fixhalf(SHStrTab.SectionIdx, ELFHdr_e_shstrndx_Offset);
363
364   // Set the NameIdx of each section in the string table and emit the bytes for
365   // the string table.
366   unsigned Index = 0;
367   DataBuffer &Buf = SHStrTab.SectionData;
368
369   for (std::list<ELFSection>::iterator I = SectionList.begin(),
370          E = SectionList.end(); I != E; ++I) {
371     // Set the index into the table.  Note if we have lots of entries with
372     // common suffixes, we could memoize them here if we cared.
373     I->NameIdx = Index;
374
375     // Add the name to the output buffer, including the null terminator.
376     Buf.insert(Buf.end(), I->Name.begin(), I->Name.end());
377
378     // Add a null terminator.
379     Buf.push_back(0);
380
381     // Keep track of the number of bytes emitted to this section.
382     Index += I->Name.size()+1;
383   }
384
385   // Set the size of .shstrtab now that we know what it is.
386   assert(Index == Buf.size());
387   SHStrTab.Size = Index;
388 }
389
390 /// OutputSectionsAndSectionTable - Now that we have constructed the file header
391 /// and all of the sections, emit these to the ostream destination and emit the
392 /// SectionTable.
393 void ELFWriter::OutputSectionsAndSectionTable() {
394   // Pass #1: Compute the file offset for each section.
395   size_t FileOff = FileHeader.size();   // File header first.
396
397   // Emit all of the section data in order.
398   for (std::list<ELFSection>::iterator I = SectionList.begin(),
399          E = SectionList.end(); I != E; ++I) {
400
401     // Section idx 0 has 0 offset
402     if (!I->SectionIdx)
403       continue;
404
405     // Update Section size
406     if (!I->Size)
407       I->Size = I->SectionData.size();
408
409     // Align FileOff to whatever the alignment restrictions of the section are.
410     if (I->Align)
411       FileOff = (FileOff+I->Align-1) & ~(I->Align-1);
412
413     I->Offset = FileOff;
414     FileOff += I->Size;
415   }
416
417   // Align Section Header.
418   unsigned TableAlign = is64Bit ? 8 : 4;
419   FileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
420
421   // Now that we know where all of the sections will be emitted, set the e_shnum
422   // entry in the ELF header.
423   OutputBuffer FHOut(FileHeader, is64Bit, isLittleEndian);
424   FHOut.fixhalf(NumSections, ELFHdr_e_shnum_Offset);
425
426   // Now that we know the offset in the file of the section table, update the
427   // e_shoff address in the ELF header.
428   FHOut.fixaddr(FileOff, ELFHdr_e_shoff_Offset);
429
430   // Now that we know all of the data in the file header, emit it and all of the
431   // sections!
432   O.write((char*)&FileHeader[0], FileHeader.size());
433   FileOff = FileHeader.size();
434   DataBuffer().swap(FileHeader);
435
436   DataBuffer Table;
437   OutputBuffer TableOut(Table, is64Bit, isLittleEndian);
438
439   // Emit all of the section data and build the section table itself.
440   while (!SectionList.empty()) {
441     const ELFSection &S = *SectionList.begin();
442
443     // Align FileOff to whatever the alignment restrictions of the section are.
444     if (S.Align)
445       for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
446            FileOff != NewFileOff; ++FileOff)
447         O << (char)0xAB;
448     O.write((char*)&S.SectionData[0], S.Size);
449
450     DOUT << "SectionIdx: " << S.SectionIdx << ", Name: " << S.Name
451          << ", Size: " << S.Size << ", Offset: " << S.Offset << "\n";
452
453     FileOff += S.Size;
454
455     TableOut.outword(S.NameIdx);  // sh_name - Symbol table name idx
456     TableOut.outword(S.Type);     // sh_type - Section contents & semantics
457     TableOut.outaddr(S.Flags);    // sh_flags - Section flags.
458     TableOut.outaddr(S.Addr);     // sh_addr - The mem addr this section is in.
459     TableOut.outaddr(S.Offset);   // sh_offset - Offset from the file start.
460     TableOut.outaddr(S.Size);     // sh_size - The section size.
461     TableOut.outword(S.Link);     // sh_link - Section header table index link.
462     TableOut.outword(S.Info);     // sh_info - Auxillary information.
463     TableOut.outaddr(S.Align);    // sh_addralign - Alignment of section.
464     TableOut.outaddr(S.EntSize);  // sh_entsize - Size of entries in the section
465
466     SectionList.pop_front();
467   }
468
469   // Align output for the section table.
470   for (size_t NewFileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
471        FileOff != NewFileOff; ++FileOff)
472     O << (char)0xAB;
473
474   // Emit the section table itself.
475   O.write((char*)&Table[0], Table.size());
476 }