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