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