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