For PR786:
[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 was developed by Chris Lattner and is distributed under the
6 // University of Illinois Open Source 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 #include "llvm/CodeGen/ELFWriter.h"
35 #include "llvm/Module.h"
36 #include "llvm/CodeGen/MachineCodeEmitter.h"
37 #include "llvm/CodeGen/MachineConstantPool.h"
38 #include "llvm/Target/TargetData.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Support/Mangler.h"
41 #include <iostream>
42 using namespace llvm;
43
44 //===----------------------------------------------------------------------===//
45 //                       ELFCodeEmitter Implementation
46 //===----------------------------------------------------------------------===//
47
48 namespace llvm {
49   /// ELFCodeEmitter - This class is used by the ELFWriter to emit the code for
50   /// functions to the ELF file.
51   class ELFCodeEmitter : public MachineCodeEmitter {
52     ELFWriter &EW;
53     ELFWriter::ELFSection *ES;  // Section to write to.
54     std::vector<unsigned char> *OutBuffer;
55     size_t FnStart;
56   public:
57     ELFCodeEmitter(ELFWriter &ew) : EW(ew), OutBuffer(0) {}
58
59     void startFunction(MachineFunction &F);
60     bool finishFunction(MachineFunction &F);
61
62     void addRelocation(const MachineRelocation &MR) {
63       assert(0 && "relo not handled yet!");
64     }
65     
66     virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
67     }
68
69     virtual intptr_t getConstantPoolEntryAddress(unsigned Index) const {
70       assert(0 && "CP not implementated yet!");
71       return 0;
72     }
73     virtual intptr_t getJumpTableEntryAddress(unsigned Index) const {
74       assert(0 && "JT not implementated yet!");
75       return 0;
76     }
77
78     virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
79       assert(0 && "JT not implementated yet!");
80       return 0;
81     }
82
83     /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
84     void startFunctionStub(unsigned StubSize) {
85       assert(0 && "JIT specific function called!");
86       abort();
87     }
88     void *finishFunctionStub(const Function *F) {
89       assert(0 && "JIT specific function called!");
90       abort();
91       return 0;
92     }
93   };
94 }
95
96 /// startFunction - This callback is invoked when a new machine function is
97 /// about to be emitted.
98 void ELFCodeEmitter::startFunction(MachineFunction &F) {
99   // Align the output buffer to the appropriate alignment.
100   unsigned Align = 16;   // FIXME: GENERICIZE!!
101   // Get the ELF Section that this function belongs in.
102   ES = &EW.getSection(".text", ELFWriter::ELFSection::SHT_PROGBITS,
103                       ELFWriter::ELFSection::SHF_EXECINSTR |
104                       ELFWriter::ELFSection::SHF_ALLOC);
105   OutBuffer = &ES->SectionData;
106   std::cerr << "FIXME: This code needs to be updated for changes in the"
107             << " CodeEmitter interfaces.  In particular, this should set "
108             << "BufferBegin/BufferEnd/CurBufferPtr, not deal with OutBuffer!";
109   abort();
110
111   // Upgrade the section alignment if required.
112   if (ES->Align < Align) ES->Align = Align;
113
114   // Add padding zeros to the end of the buffer to make sure that the
115   // function will start on the correct byte alignment within the section.
116   ELFWriter::align(*OutBuffer, Align);
117
118   FnStart = OutBuffer->size();
119 }
120
121 /// finishFunction - This callback is invoked after the function is completely
122 /// finished.
123 bool ELFCodeEmitter::finishFunction(MachineFunction &F) {
124   // We now know the size of the function, add a symbol to represent it.
125   ELFWriter::ELFSym FnSym(F.getFunction());
126
127   // Figure out the binding (linkage) of the symbol.
128   switch (F.getFunction()->getLinkage()) {
129   default:
130     // appending linkage is illegal for functions.
131     assert(0 && "Unknown linkage type!");
132   case GlobalValue::ExternalLinkage:
133     FnSym.SetBind(ELFWriter::ELFSym::STB_GLOBAL);
134     break;
135   case GlobalValue::LinkOnceLinkage:
136   case GlobalValue::WeakLinkage:
137     FnSym.SetBind(ELFWriter::ELFSym::STB_WEAK);
138     break;
139   case GlobalValue::InternalLinkage:
140     FnSym.SetBind(ELFWriter::ELFSym::STB_LOCAL);
141     break;
142   }
143
144   ES->Size = OutBuffer->size();
145
146   FnSym.SetType(ELFWriter::ELFSym::STT_FUNC);
147   FnSym.SectionIdx = ES->SectionIdx;
148     FnSym.Value = FnStart;   // Value = Offset from start of Section.
149   FnSym.Size = OutBuffer->size()-FnStart;
150
151   // Finally, add it to the symtab.
152   EW.SymbolTable.push_back(FnSym);
153   return false;
154 }
155
156 //===----------------------------------------------------------------------===//
157 //                          ELFWriter Implementation
158 //===----------------------------------------------------------------------===//
159
160 ELFWriter::ELFWriter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) {
161   e_machine = 0;  // e_machine defaults to 'No Machine'
162   e_flags = 0;    // e_flags defaults to 0, no flags.
163
164   is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
165   isLittleEndian = TM.getTargetData()->isLittleEndian();
166
167   // Create the machine code emitter object for this target.
168   MCE = new ELFCodeEmitter(*this);
169   NumSections = 0;
170 }
171
172 ELFWriter::~ELFWriter() {
173   delete MCE;
174 }
175
176 // doInitialization - Emit the file header and all of the global variables for
177 // the module to the ELF file.
178 bool ELFWriter::doInitialization(Module &M) {
179   Mang = new Mangler(M);
180
181   // Local alias to shortenify coming code.
182   std::vector<unsigned char> &FH = FileHeader;
183
184   outbyte(FH, 0x7F);                     // EI_MAG0
185   outbyte(FH, 'E');                      // EI_MAG1
186   outbyte(FH, 'L');                      // EI_MAG2
187   outbyte(FH, 'F');                      // EI_MAG3
188   outbyte(FH, is64Bit ? 2 : 1);          // EI_CLASS
189   outbyte(FH, isLittleEndian ? 1 : 2);   // EI_DATA
190   outbyte(FH, 1);                        // EI_VERSION
191   FH.resize(16);                         // EI_PAD up to 16 bytes.
192
193   // This should change for shared objects.
194   outhalf(FH, 1);                 // e_type = ET_REL
195   outhalf(FH, e_machine);         // e_machine = whatever the target wants
196   outword(FH, 1);                 // e_version = 1
197   outaddr(FH, 0);                 // e_entry = 0 -> no entry point in .o file
198   outaddr(FH, 0);                 // e_phoff = 0 -> no program header for .o
199
200   ELFHeader_e_shoff_Offset = FH.size();
201   outaddr(FH, 0);                 // e_shoff
202   outword(FH, e_flags);           // e_flags = whatever the target wants
203
204   outhalf(FH, is64Bit ? 64 : 52); // e_ehsize = ELF header size
205   outhalf(FH, 0);                 // e_phentsize = prog header entry size
206   outhalf(FH, 0);                 // e_phnum     = # prog header entries = 0
207   outhalf(FH, is64Bit ? 64 : 40); // e_shentsize = sect hdr entry size
208
209
210   ELFHeader_e_shnum_Offset = FH.size();
211   outhalf(FH, 0);                 // e_shnum     = # of section header ents
212   ELFHeader_e_shstrndx_Offset = FH.size();
213   outhalf(FH, 0);                 // e_shstrndx  = Section # of '.shstrtab'
214
215   // Add the null section, which is required to be first in the file.
216   getSection("", 0, 0);
217
218   // Start up the symbol table.  The first entry in the symtab is the null
219   // entry.
220   SymbolTable.push_back(ELFSym(0));
221
222   return false;
223 }
224
225 void ELFWriter::EmitGlobal(GlobalVariable *GV) {
226   // If this is an external global, emit it now.  TODO: Note that it would be
227   // better to ignore the symbol here and only add it to the symbol table if
228   // referenced.
229   if (!GV->hasInitializer()) {
230     ELFSym ExternalSym(GV);
231     ExternalSym.SetBind(ELFSym::STB_GLOBAL);
232     ExternalSym.SetType(ELFSym::STT_NOTYPE);
233     ExternalSym.SectionIdx = ELFSection::SHN_UNDEF;
234     SymbolTable.push_back(ExternalSym);
235     return;
236   }
237
238   const Type *GVType = (const Type*)GV->getType();
239   unsigned Align = TM.getTargetData()->getTypeAlignment(GVType);
240   unsigned Size  = TM.getTargetData()->getTypeSize(GVType);
241
242   // If this global has a zero initializer, it is part of the .bss or common
243   // section.
244   if (GV->getInitializer()->isNullValue()) {
245     // If this global is part of the common block, add it now.  Variables are
246     // part of the common block if they are zero initialized and allowed to be
247     // merged with other symbols.
248     if (GV->hasLinkOnceLinkage() || GV->hasWeakLinkage()) {
249       ELFSym CommonSym(GV);
250       // Value for common symbols is the alignment required.
251       CommonSym.Value = Align;
252       CommonSym.Size  = Size;
253       CommonSym.SetBind(ELFSym::STB_GLOBAL);
254       CommonSym.SetType(ELFSym::STT_OBJECT);
255       // TODO SOMEDAY: add ELF visibility.
256       CommonSym.SectionIdx = ELFSection::SHN_COMMON;
257       SymbolTable.push_back(CommonSym);
258       return;
259     }
260
261     // Otherwise, this symbol is part of the .bss section.  Emit it now.
262
263     // Handle alignment.  Ensure section is aligned at least as much as required
264     // by this symbol.
265     ELFSection &BSSSection = getBSSSection();
266     BSSSection.Align = std::max(BSSSection.Align, Align);
267
268     // Within the section, emit enough virtual padding to get us to an alignment
269     // boundary.
270     if (Align)
271       BSSSection.Size = (BSSSection.Size + Align - 1) & ~(Align-1);
272
273     ELFSym BSSSym(GV);
274     BSSSym.Value = BSSSection.Size;
275     BSSSym.Size = Size;
276     BSSSym.SetType(ELFSym::STT_OBJECT);
277
278     switch (GV->getLinkage()) {
279     default:  // weak/linkonce handled above
280       assert(0 && "Unexpected linkage type!");
281     case GlobalValue::AppendingLinkage:  // FIXME: This should be improved!
282     case GlobalValue::ExternalLinkage:
283       BSSSym.SetBind(ELFSym::STB_GLOBAL);
284       break;
285     case GlobalValue::InternalLinkage:
286       BSSSym.SetBind(ELFSym::STB_LOCAL);
287       break;
288     }
289
290     // Set the idx of the .bss section
291     BSSSym.SectionIdx = BSSSection.SectionIdx;
292     SymbolTable.push_back(BSSSym);
293
294     // Reserve space in the .bss section for this symbol.
295     BSSSection.Size += Size;
296     return;
297   }
298
299   // FIXME: handle .rodata
300   //assert(!GV->isConstant() && "unimp");
301
302   // FIXME: handle .data
303   //assert(0 && "unimp");
304 }
305
306
307 bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
308   // Nothing to do here, this is all done through the MCE object above.
309   return false;
310 }
311
312 /// doFinalization - Now that the module has been completely processed, emit
313 /// the ELF file to 'O'.
314 bool ELFWriter::doFinalization(Module &M) {
315   // Okay, the ELF header and .text sections have been completed, build the
316   // .data, .bss, and "common" sections next.
317   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
318        I != E; ++I)
319     EmitGlobal(I);
320
321   // Emit the symbol table now, if non-empty.
322   EmitSymbolTable();
323
324   // FIXME: Emit the relocations now.
325
326   // Emit the string table for the sections in the ELF file we have.
327   EmitSectionTableStringTable();
328
329   // Emit the sections to the .o file, and emit the section table for the file.
330   OutputSectionsAndSectionTable();
331
332   // We are done with the abstract symbols.
333   SectionList.clear();
334   NumSections = 0;
335
336   // Release the name mangler object.
337   delete Mang; Mang = 0;
338   return false;
339 }
340
341 /// EmitSymbolTable - If the current symbol table is non-empty, emit the string
342 /// table for it and then the symbol table itself.
343 void ELFWriter::EmitSymbolTable() {
344   if (SymbolTable.size() == 1) return;  // Only the null entry.
345
346   // FIXME: compact all local symbols to the start of the symtab.
347   unsigned FirstNonLocalSymbol = 1;
348
349   ELFSection &StrTab = getSection(".strtab", ELFSection::SHT_STRTAB, 0);
350   StrTab.Align = 1;
351
352   DataBuffer &StrTabBuf = StrTab.SectionData;
353
354   // Set the zero'th symbol to a null byte, as required.
355   outbyte(StrTabBuf, 0);
356   SymbolTable[0].NameIdx = 0;
357   unsigned Index = 1;
358   for (unsigned i = 1, e = SymbolTable.size(); i != e; ++i) {
359     // Use the name mangler to uniquify the LLVM symbol.
360     std::string Name = Mang->getValueName(SymbolTable[i].GV);
361
362     if (Name.empty()) {
363       SymbolTable[i].NameIdx = 0;
364     } else {
365       SymbolTable[i].NameIdx = Index;
366
367       // Add the name to the output buffer, including the null terminator.
368       StrTabBuf.insert(StrTabBuf.end(), Name.begin(), Name.end());
369
370       // Add a null terminator.
371       StrTabBuf.push_back(0);
372
373       // Keep track of the number of bytes emitted to this section.
374       Index += Name.size()+1;
375     }
376   }
377   assert(Index == StrTabBuf.size());
378   StrTab.Size = Index;
379
380   // Now that we have emitted the string table and know the offset into the
381   // string table of each symbol, emit the symbol table itself.
382   ELFSection &SymTab = getSection(".symtab", ELFSection::SHT_SYMTAB, 0);
383   SymTab.Align = is64Bit ? 8 : 4;
384   SymTab.Link = SymTab.SectionIdx;     // Section Index of .strtab.
385   SymTab.Info = FirstNonLocalSymbol;   // First non-STB_LOCAL symbol.
386   SymTab.EntSize = 16; // Size of each symtab entry. FIXME: wrong for ELF64
387   DataBuffer &SymTabBuf = SymTab.SectionData;
388
389   if (!is64Bit) {   // 32-bit and 64-bit formats are shuffled a bit.
390     for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i) {
391       ELFSym &Sym = SymbolTable[i];
392       outword(SymTabBuf, Sym.NameIdx);
393       outaddr32(SymTabBuf, Sym.Value);
394       outword(SymTabBuf, Sym.Size);
395       outbyte(SymTabBuf, Sym.Info);
396       outbyte(SymTabBuf, Sym.Other);
397       outhalf(SymTabBuf, Sym.SectionIdx);
398     }
399   } else {
400     for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i) {
401       ELFSym &Sym = SymbolTable[i];
402       outword(SymTabBuf, Sym.NameIdx);
403       outbyte(SymTabBuf, Sym.Info);
404       outbyte(SymTabBuf, Sym.Other);
405       outhalf(SymTabBuf, Sym.SectionIdx);
406       outaddr64(SymTabBuf, Sym.Value);
407       outxword(SymTabBuf, Sym.Size);
408     }
409   }
410
411   SymTab.Size = SymTabBuf.size();
412 }
413
414 /// EmitSectionTableStringTable - This method adds and emits a section for the
415 /// ELF Section Table string table: the string table that holds all of the
416 /// section names.
417 void ELFWriter::EmitSectionTableStringTable() {
418   // First step: add the section for the string table to the list of sections:
419   ELFSection &SHStrTab = getSection(".shstrtab", ELFSection::SHT_STRTAB, 0);
420
421   // Now that we know which section number is the .shstrtab section, update the
422   // e_shstrndx entry in the ELF header.
423   fixhalf(FileHeader, SHStrTab.SectionIdx, ELFHeader_e_shstrndx_Offset);
424
425   // Set the NameIdx of each section in the string table and emit the bytes for
426   // the string table.
427   unsigned Index = 0;
428   DataBuffer &Buf = SHStrTab.SectionData;
429
430   for (std::list<ELFSection>::iterator I = SectionList.begin(),
431          E = SectionList.end(); I != E; ++I) {
432     // Set the index into the table.  Note if we have lots of entries with
433     // common suffixes, we could memoize them here if we cared.
434     I->NameIdx = Index;
435
436     // Add the name to the output buffer, including the null terminator.
437     Buf.insert(Buf.end(), I->Name.begin(), I->Name.end());
438
439     // Add a null terminator.
440     Buf.push_back(0);
441
442     // Keep track of the number of bytes emitted to this section.
443     Index += I->Name.size()+1;
444   }
445
446   // Set the size of .shstrtab now that we know what it is.
447   assert(Index == Buf.size());
448   SHStrTab.Size = Index;
449 }
450
451 /// OutputSectionsAndSectionTable - Now that we have constructed the file header
452 /// and all of the sections, emit these to the ostream destination and emit the
453 /// SectionTable.
454 void ELFWriter::OutputSectionsAndSectionTable() {
455   // Pass #1: Compute the file offset for each section.
456   size_t FileOff = FileHeader.size();   // File header first.
457
458   // Emit all of the section data in order.
459   for (std::list<ELFSection>::iterator I = SectionList.begin(),
460          E = SectionList.end(); I != E; ++I) {
461     // Align FileOff to whatever the alignment restrictions of the section are.
462     if (I->Align)
463       FileOff = (FileOff+I->Align-1) & ~(I->Align-1);
464     I->Offset = FileOff;
465     FileOff += I->SectionData.size();
466   }
467
468   // Align Section Header.
469   unsigned TableAlign = is64Bit ? 8 : 4;
470   FileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
471
472   // Now that we know where all of the sections will be emitted, set the e_shnum
473   // entry in the ELF header.
474   fixhalf(FileHeader, NumSections, ELFHeader_e_shnum_Offset);
475
476   // Now that we know the offset in the file of the section table, update the
477   // e_shoff address in the ELF header.
478   fixaddr(FileHeader, FileOff, ELFHeader_e_shoff_Offset);
479
480   // Now that we know all of the data in the file header, emit it and all of the
481   // sections!
482   O.write((char*)&FileHeader[0], FileHeader.size());
483   FileOff = FileHeader.size();
484   DataBuffer().swap(FileHeader);
485
486   DataBuffer Table;
487
488   // Emit all of the section data and build the section table itself.
489   while (!SectionList.empty()) {
490     const ELFSection &S = *SectionList.begin();
491
492     // Align FileOff to whatever the alignment restrictions of the section are.
493     if (S.Align)
494       for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
495            FileOff != NewFileOff; ++FileOff)
496         O.put((char)0xAB);
497     O.write((char*)&S.SectionData[0], S.SectionData.size());
498     FileOff += S.SectionData.size();
499
500     outword(Table, S.NameIdx);  // sh_name - Symbol table name idx
501     outword(Table, S.Type);     // sh_type - Section contents & semantics
502     outword(Table, S.Flags);    // sh_flags - Section flags.
503     outaddr(Table, S.Addr);     // sh_addr - The mem addr this section is in.
504     outaddr(Table, S.Offset);   // sh_offset - Offset from the file start.
505     outword(Table, S.Size);     // sh_size - The section size.
506     outword(Table, S.Link);     // sh_link - Section header table index link.
507     outword(Table, S.Info);     // sh_info - Auxillary information.
508     outword(Table, S.Align);    // sh_addralign - Alignment of section.
509     outword(Table, S.EntSize);  // sh_entsize - Size of entries in the section.
510
511     SectionList.pop_front();
512   }
513
514   // Align output for the section table.
515   for (size_t NewFileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
516        FileOff != NewFileOff; ++FileOff)
517     O.put((char)0xAB);
518
519   // Emit the section table itself.
520   O.write((char*)&Table[0], Table.size());
521 }