198e9cca5e7ed9011071c4024ba29b9a6e6ee61f
[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       return 0;
85     }
86
87     /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
88     void startFunctionStub(unsigned StubSize) {
89       assert(0 && "JIT specific function called!");
90       abort();
91     }
92     void *finishFunctionStub(const Function *F) {
93       assert(0 && "JIT specific function called!");
94       abort();
95       return 0;
96     }
97   };
98 }
99
100 /// startFunction - This callback is invoked when a new machine function is
101 /// about to be emitted.
102 void ELFCodeEmitter::startFunction(MachineFunction &F) {
103   // Align the output buffer to the appropriate alignment.
104   unsigned Align = 16;   // FIXME: GENERICIZE!!
105   ELFWriter::ELFSection &TextSection = EW.SectionList.back();
106   
107   // Upgrade the section alignment if required.
108   if (TextSection.Align < Align) TextSection.Align = Align;
109   
110   // Add padding zeros to the end of the buffer to make sure that the
111   // function will start on the correct byte alignment within the section.
112   size_t SectionOff = OutputBuffer.size()-TextSection.Offset;
113   if (SectionOff & (Align-1)) {
114     // Add padding to get alignment to the correct place.
115     size_t Pad = Align-(SectionOff & (Align-1));
116     OutputBuffer.resize(OutputBuffer.size()+Pad);
117   }
118   
119   FnStart = OutputBuffer.size();
120 }
121
122 /// finishFunction - This callback is invoked after the function is completely
123 /// finished.
124 void ELFCodeEmitter::finishFunction(MachineFunction &F) {
125   // We now know the size of the function, add a symbol to represent it.
126   ELFWriter::ELFSym FnSym(F.getFunction());
127   
128   // Figure out the binding (linkage) of the symbol.
129   switch (F.getFunction()->getLinkage()) {
130   default:
131     // appending linkage is illegal for functions.
132     assert(0 && "Unknown linkage type!");
133   case GlobalValue::ExternalLinkage:
134     FnSym.SetBind(ELFWriter::ELFSym::STB_GLOBAL);
135     break;
136   case GlobalValue::LinkOnceLinkage:
137   case GlobalValue::WeakLinkage:
138     FnSym.SetBind(ELFWriter::ELFSym::STB_WEAK);
139     break;
140   case GlobalValue::InternalLinkage:
141     FnSym.SetBind(ELFWriter::ELFSym::STB_LOCAL);
142     break;
143   }
144   
145   FnSym.SetType(ELFWriter::ELFSym::STT_FUNC);
146   FnSym.SectionIdx = EW.SectionList.size()-1;  // .text section.
147   // Value = Offset from start of .text
148   FnSym.Value = FnStart - EW.SectionList.back().Offset;
149   FnSym.Size = OutputBuffer.size()-FnStart;
150   
151   // Finally, add it to the symtab.
152   EW.SymbolTable.push_back(FnSym);
153 }
154
155 //===----------------------------------------------------------------------===//
156 //                          ELFWriter Implementation
157 //===----------------------------------------------------------------------===//
158
159 ELFWriter::ELFWriter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) {
160   e_machine = 0;  // e_machine defaults to 'No Machine'
161   e_flags = 0;    // e_flags defaults to 0, no flags.
162
163   is64Bit = TM.getTargetData().getPointerSizeInBits() == 64;  
164   isLittleEndian = TM.getTargetData().isLittleEndian();
165
166   // Create the machine code emitter object for this target.
167   MCE = new ELFCodeEmitter(*this);
168 }
169
170 ELFWriter::~ELFWriter() {
171   delete MCE;
172 }
173
174 // doInitialization - Emit the file header and all of the global variables for
175 // the module to the ELF file.
176 bool ELFWriter::doInitialization(Module &M) {
177   Mang = new Mangler(M);
178
179   outbyte(0x7F);                     // EI_MAG0
180   outbyte('E');                      // EI_MAG1
181   outbyte('L');                      // EI_MAG2
182   outbyte('F');                      // EI_MAG3
183   outbyte(is64Bit ? 2 : 1);          // EI_CLASS
184   outbyte(isLittleEndian ? 1 : 2);   // EI_DATA
185   outbyte(1);                        // EI_VERSION
186   for (unsigned i = OutputBuffer.size(); i != 16; ++i)
187     outbyte(0);                      // EI_PAD up to 16 bytes.
188   
189   // This should change for shared objects.
190   outhalf(1);                        // e_type = ET_REL
191   outhalf(e_machine);                // e_machine = whatever the target wants
192   outword(1);                        // e_version = 1
193   outaddr(0);                        // e_entry = 0 -> no entry point in .o file
194   outaddr(0);                        // e_phoff = 0 -> no program header for .o
195
196   ELFHeader_e_shoff_Offset = OutputBuffer.size();
197   outaddr(0);                        // e_shoff
198   outword(e_flags);                  // e_flags = whatever the target wants
199
200   assert(!is64Bit && "These sizes need to be adjusted for 64-bit!");
201   outhalf(52);                       // e_ehsize = ELF header size
202   outhalf(0);                        // e_phentsize = prog header entry size
203   outhalf(0);                        // e_phnum     = # prog header entries = 0
204   outhalf(40);                       // e_shentsize = sect header entry size
205
206   
207   ELFHeader_e_shnum_Offset = OutputBuffer.size();
208   outhalf(0);                        // e_shnum     = # of section header ents
209   ELFHeader_e_shstrndx_Offset = OutputBuffer.size();
210   outhalf(0);                        // e_shstrndx  = Section # of '.shstrtab'
211
212   // Add the null section.
213   SectionList.push_back(ELFSection());
214
215   // Start up the symbol table.  The first entry in the symtab is the null
216   // entry.
217   SymbolTable.push_back(ELFSym(0));
218
219   SectionList.push_back(ELFSection(".text", OutputBuffer.size()));
220
221   return false;
222 }
223
224 void ELFWriter::EmitGlobal(GlobalVariable *GV, ELFSection &DataSection,
225                            ELFSection &BSSSection) {
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     BSSSection.Align = std::max(BSSSection.Align, Align);
266
267     // Within the section, emit enough virtual padding to get us to an alignment
268     // boundary.
269     if (Align)
270       BSSSection.Size = (BSSSection.Size + Align - 1) & ~(Align-1);
271
272     ELFSym BSSSym(GV);
273     BSSSym.Value = BSSSection.Size;
274     BSSSym.Size = Size;
275     BSSSym.SetType(ELFSym::STT_OBJECT);
276
277     switch (GV->getLinkage()) {
278     default:  // weak/linkonce handled above
279       assert(0 && "Unexpected linkage type!");
280     case GlobalValue::AppendingLinkage:  // FIXME: This should be improved!
281     case GlobalValue::ExternalLinkage:
282       BSSSym.SetBind(ELFSym::STB_GLOBAL);
283       break;
284     case GlobalValue::InternalLinkage:
285       BSSSym.SetBind(ELFSym::STB_LOCAL);
286       break;
287     }
288
289     // Set the idx of the .bss section
290     BSSSym.SectionIdx = &BSSSection-&SectionList[0];
291     SymbolTable.push_back(BSSSym);
292
293     // Reserve space in the .bss section for this symbol.
294     BSSSection.Size += Size;
295     return;
296   }
297
298   // FIXME: handle .rodata
299   //assert(!GV->isConstant() && "unimp");
300
301   // FIXME: handle .data
302   //assert(0 && "unimp");
303 }
304
305
306 bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
307   // Nothing to do here, this is all done through the MCE object above.
308   return false;
309 }
310
311 /// doFinalization - Now that the module has been completely processed, emit
312 /// the ELF file to 'O'.
313 bool ELFWriter::doFinalization(Module &M) {
314   // Okay, the .text section has now been finalized.  If it contains nothing, do
315   // not emit it.
316   uint64_t TextSize = OutputBuffer.size() - SectionList.back().Offset;
317   if (TextSize == 0) {
318     SectionList.pop_back();
319   } else {
320     ELFSection &Text = SectionList.back();
321     Text.Size = TextSize;
322     Text.Type = ELFSection::SHT_PROGBITS;
323     Text.Flags = ELFSection::SHF_EXECINSTR | ELFSection::SHF_ALLOC;
324   }
325
326   // Okay, the ELF header and .text sections have been completed, build the
327   // .data, .bss, and "common" sections next.
328   SectionList.push_back(ELFSection(".data", OutputBuffer.size()));
329   SectionList.push_back(ELFSection(".bss"));
330   ELFSection &DataSection = *(SectionList.end()-2);
331   ELFSection &BSSSection = SectionList.back();
332   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
333        I != E; ++I)
334     EmitGlobal(I, DataSection, BSSSection);
335
336   // Finish up the data section.
337   DataSection.Type  = ELFSection::SHT_PROGBITS;
338   DataSection.Flags = ELFSection::SHF_WRITE | ELFSection::SHF_ALLOC;
339
340   // The BSS Section logically starts at the end of the Data Section (adjusted
341   // to the required alignment of the BSSSection).
342   BSSSection.Offset = DataSection.Offset+DataSection.Size;
343   BSSSection.Type   = ELFSection::SHT_NOBITS; 
344   BSSSection.Flags  = ELFSection::SHF_WRITE | ELFSection::SHF_ALLOC;
345   if (BSSSection.Align)
346     BSSSection.Offset = (BSSSection.Offset+BSSSection.Align-1) &
347                         ~(BSSSection.Align-1);
348
349   // Emit the symbol table now, if non-empty.
350   EmitSymbolTable();
351
352   // FIXME: Emit the relocations now.
353
354   // Emit the string table for the sections in the ELF file we have.
355   EmitSectionTableStringTable();
356
357   // Emit the .o file section table.
358   EmitSectionTable();
359
360   // Emit the .o file to the specified stream.
361   O.write((char*)&OutputBuffer[0], OutputBuffer.size());
362
363   // Free the output buffer.
364   std::vector<unsigned char>().swap(OutputBuffer);
365
366   // Release the name mangler object.
367   delete Mang; Mang = 0;
368   return false;
369 }
370
371 /// EmitSymbolTable - If the current symbol table is non-empty, emit the string
372 /// table for it and then the symbol table itself.
373 void ELFWriter::EmitSymbolTable() {
374   if (SymbolTable.size() == 1) return;  // Only the null entry.
375
376   // FIXME: compact all local symbols to the start of the symtab.
377   unsigned FirstNonLocalSymbol = 1;
378
379   SectionList.push_back(ELFSection(".strtab", OutputBuffer.size()));
380   ELFSection &StrTab = SectionList.back();
381   StrTab.Type = ELFSection::SHT_STRTAB;
382   StrTab.Align = 1;
383
384   // Set the zero'th symbol to a null byte, as required.
385   outbyte(0);
386   SymbolTable[0].NameIdx = 0;
387   unsigned Index = 1;
388   for (unsigned i = 1, e = SymbolTable.size(); i != e; ++i) {
389     // Use the name mangler to uniquify the LLVM symbol.
390     std::string Name = Mang->getValueName(SymbolTable[i].GV);
391
392     if (Name.empty()) {
393       SymbolTable[i].NameIdx = 0;
394     } else {
395       SymbolTable[i].NameIdx = Index;
396
397       // Add the name to the output buffer, including the null terminator.
398       OutputBuffer.insert(OutputBuffer.end(), Name.begin(), Name.end());
399
400       // Add a null terminator.
401       OutputBuffer.push_back(0);
402
403       // Keep track of the number of bytes emitted to this section.
404       Index += Name.size()+1;
405     }
406   }
407
408   StrTab.Size = OutputBuffer.size()-StrTab.Offset;
409
410   // Now that we have emitted the string table and know the offset into the
411   // string table of each symbol, emit the symbol table itself.
412   assert(!is64Bit && "Should this be 8 byte aligned for 64-bit?"
413          " (check .Align below also)");
414   align(4);
415
416   SectionList.push_back(ELFSection(".symtab", OutputBuffer.size()));
417   ELFSection &SymTab = SectionList.back();
418   SymTab.Type = ELFSection::SHT_SYMTAB;
419   SymTab.Align = 4;   // FIXME: check for ELF64
420   SymTab.Link = SectionList.size()-2;  // Section Index of .strtab.
421   SymTab.Info = FirstNonLocalSymbol;   // First non-STB_LOCAL symbol.
422   SymTab.EntSize = 16; // Size of each symtab entry. FIXME: wrong for ELF64
423
424   assert(!is64Bit && "check this!");
425   for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i) {
426     ELFSym &Sym = SymbolTable[i];
427     outword(Sym.NameIdx);
428     outaddr(Sym.Value);
429     outword(Sym.Size);
430     outbyte(Sym.Info);
431     outbyte(Sym.Other);
432     outhalf(Sym.SectionIdx);
433   }
434
435   SymTab.Size = OutputBuffer.size()-SymTab.Offset;
436 }
437
438 /// EmitSectionTableStringTable - This method adds and emits a section for the
439 /// ELF Section Table string table: the string table that holds all of the
440 /// section names.
441 void ELFWriter::EmitSectionTableStringTable() {
442   // First step: add the section for the string table to the list of sections:
443   SectionList.push_back(ELFSection(".shstrtab", OutputBuffer.size()));
444   SectionList.back().Type = ELFSection::SHT_STRTAB;
445
446   // Now that we know which section number is the .shstrtab section, update the
447   // e_shstrndx entry in the ELF header.
448   fixhalf(SectionList.size()-1, ELFHeader_e_shstrndx_Offset);
449
450   // Set the NameIdx of each section in the string table and emit the bytes for
451   // the string table.
452   unsigned Index = 0;
453
454   for (unsigned i = 0, e = SectionList.size(); i != e; ++i) {
455     // Set the index into the table.  Note if we have lots of entries with
456     // common suffixes, we could memoize them here if we cared.
457     SectionList[i].NameIdx = Index;
458
459     // Add the name to the output buffer, including the null terminator.
460     OutputBuffer.insert(OutputBuffer.end(), SectionList[i].Name.begin(),
461                         SectionList[i].Name.end());
462     // Add a null terminator.
463     OutputBuffer.push_back(0);
464
465     // Keep track of the number of bytes emitted to this section.
466     Index += SectionList[i].Name.size()+1;
467   }
468
469   // Set the size of .shstrtab now that we know what it is.
470   SectionList.back().Size = Index;
471 }
472
473 /// EmitSectionTable - Now that we have emitted the entire contents of the file
474 /// (all of the sections), emit the section table which informs the reader where
475 /// the boundaries are.
476 void ELFWriter::EmitSectionTable() {
477   // Now that all of the sections have been emitted, set the e_shnum entry in
478   // the ELF header.
479   fixhalf(SectionList.size(), ELFHeader_e_shnum_Offset);
480   
481   // Now that we know the offset in the file of the section table (which we emit
482   // next), update the e_shoff address in the ELF header.
483   fixaddr(OutputBuffer.size(), ELFHeader_e_shoff_Offset);
484   
485   // Emit all of the section table entries.
486   for (unsigned i = 0, e = SectionList.size(); i != e; ++i) {
487     const ELFSection &S = SectionList[i];
488     outword(S.NameIdx);  // sh_name - Symbol table name idx
489     outword(S.Type);     // sh_type - Section contents & semantics
490     outword(S.Flags);    // sh_flags - Section flags.
491     outaddr(S.Addr);     // sh_addr - The mem address this section appears in.
492     outaddr(S.Offset);   // sh_offset - The offset from the start of the file.
493     outword(S.Size);     // sh_size - The section size.
494     outword(S.Link);     // sh_link - Section header table index link.
495     outword(S.Info);     // sh_info - Auxillary information.
496     outword(S.Align);    // sh_addralign - Alignment of section.
497     outword(S.EntSize);  // sh_entsize - Size of each entry in the section.
498   }
499
500   // Release the memory allocated for the section list.
501   std::vector<ELFSection>().swap(SectionList);
502 }