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