02cd805cb55549480757034d43648ba8401f0c9d
[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/Target/TargetMachine.h"
38 using namespace llvm;
39
40 ELFWriter::ELFWriter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) {
41   e_machine = 0;  // e_machine defaults to 'No Machine'
42   e_flags = 0;    // e_flags defaults to 0, no flags.
43
44   is64Bit = TM.getTargetData().getPointerSizeInBits() == 64;  
45   isLittleEndian = TM.getTargetData().isLittleEndian();
46 }
47
48 // doInitialization - Emit the file header and all of the global variables for
49 // the module to the ELF file.
50 bool ELFWriter::doInitialization(Module &M) {
51   outbyte(0x7F);                     // EI_MAG0
52   outbyte('E');                      // EI_MAG1
53   outbyte('L');                      // EI_MAG2
54   outbyte('F');                      // EI_MAG3
55   outbyte(is64Bit ? 2 : 1);          // EI_CLASS
56   outbyte(isLittleEndian ? 1 : 2);   // EI_DATA
57   outbyte(1);                        // EI_VERSION
58   for (unsigned i = OutputBuffer.size(); i != 16; ++i)
59     outbyte(0);                      // EI_PAD up to 16 bytes.
60   
61   // This should change for shared objects.
62   outhalf(1);                        // e_type = ET_REL
63   outhalf(e_machine);                // e_machine = whatever the target wants
64   outword(1);                        // e_version = 1
65   outaddr(0);                        // e_entry = 0 -> no entry point in .o file
66   outaddr(0);                        // e_phoff = 0 -> no program header for .o
67
68   ELFHeader_e_shoff_Offset = OutputBuffer.size();
69   outaddr(0);                        // e_shoff
70   outword(e_flags);                  // e_flags = whatever the target wants
71
72   assert(!is64Bit && "These sizes need to be adjusted for 64-bit!");
73   outhalf(52);                       // e_ehsize = ELF header size
74   outhalf(0);                        // e_phentsize = prog header entry size
75   outhalf(0);                        // e_phnum     = # prog header entries = 0
76   outhalf(40);                       // e_shentsize = sect header entry size
77
78   
79   ELFHeader_e_shnum_Offset = OutputBuffer.size();
80   outhalf(0);                        // e_shnum     = # of section header ents
81   ELFHeader_e_shstrndx_Offset = OutputBuffer.size();
82   outhalf(0);                        // e_shstrndx  = Section # of '.shstrtab'
83
84   // Add the null section.
85   SectionList.push_back(ELFSection());
86
87   // Start up the symbol table.  The first entry in the symtab is the null
88   // entry.
89   SymbolTable.push_back(ELFSym(0));
90
91
92
93   // FIXME: Should start the .text section.
94   return false;
95 }
96
97 void ELFWriter::EmitGlobal(GlobalVariable *GV, ELFSection &DataSection,
98                            ELFSection &BSSSection) {
99   // If this is an external global, emit it...
100   assert(GV->hasInitializer() && "FIXME: unimp");
101   
102   // If this global has a zero initializer, it is part of the .bss or common
103   // section.
104   if (GV->getInitializer()->isNullValue()) {
105     // If this global is part of the common block, add it now.  Variables are
106     // part of the common block if they are zero initialized and allowed to be
107     // merged with other symbols.
108     if (GV->hasLinkOnceLinkage() || GV->hasWeakLinkage()) {
109       ELFSym CommonSym(GV);
110       // Value for common symbols is the alignment required.
111       const Type *GVType = (const Type*)GV->getType();
112       CommonSym.Value = TM.getTargetData().getTypeAlignment(GVType);
113       CommonSym.Size  = TM.getTargetData().getTypeSize(GVType);
114       CommonSym.SetBind(ELFSym::STB_GLOBAL);
115       CommonSym.SetType(ELFSym::STT_OBJECT);
116       // TODO SOMEDAY: add ELF visibility.
117       CommonSym.SectionIdx = ELFSection::SHN_COMMON;
118       SymbolTable.push_back(CommonSym);
119       return;
120     }
121
122     // FIXME: Implement the .bss section.
123     return;
124   }
125
126   // FIXME: handle .rodata
127   //assert(!GV->isConstant() && "unimp");
128
129   // FIXME: handle .data
130   //assert(0 && "unimp");
131 }
132
133
134 bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
135   return false;
136 }
137
138 /// doFinalization - Now that the module has been completely processed, emit
139 /// the ELF file to 'O'.
140 bool ELFWriter::doFinalization(Module &M) {
141   // Okay, the .text section has now been finalized.
142   // FIXME: finalize the .text section.
143
144   // Okay, the ELF header and .text sections have been completed, build the
145   // .data, .bss, and "common" sections next.
146   ELFSection DataSection(".data", OutputBuffer.size());
147   ELFSection BSSSection (".bss");
148   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
149        I != E; ++I)
150     EmitGlobal(I, DataSection, BSSSection);
151
152   // If the .data section is nonempty, add it to our list.
153   if (DataSection.Size) {
154     DataSection.Align = 4;   // FIXME: Compute!
155     // FIXME: Set the right flags and stuff.
156     SectionList.push_back(DataSection);
157   }
158
159   // If the .bss section is nonempty, add it to our list.
160   if (BSSSection.Size) {
161     BSSSection.Offset = OutputBuffer.size();
162     BSSSection.Align = 4;  // FIXME: Compute!
163     // FIXME: Set the right flags and stuff.
164     SectionList.push_back(BSSSection);
165   }
166
167   // Emit the symbol table now, if non-empty.
168   EmitSymbolTable();
169
170   // FIXME: Emit the relocations now.
171
172   // Emit the string table for the sections in the ELF file we have.
173   EmitSectionTableStringTable();
174
175   // Emit the .o file section table.
176   EmitSectionTable();
177
178   // Emit the .o file to the specified stream.
179   O.write((char*)&OutputBuffer[0], OutputBuffer.size());
180
181   // Free the output buffer.
182   std::vector<unsigned char>().swap(OutputBuffer);
183   return false;
184 }
185
186 /// EmitSymbolTable - If the current symbol table is non-empty, emit the string
187 /// table for it and then the symbol table itself.
188 void ELFWriter::EmitSymbolTable() {
189   if (SymbolTable.size() == 1) return;  // Only the null entry.
190
191   // FIXME: compact all local symbols to the start of the symtab.
192   unsigned FirstNonLocalSymbol = 1;
193
194   SectionList.push_back(ELFSection(".strtab", OutputBuffer.size()));
195   ELFSection &StrTab = SectionList.back();
196   StrTab.Type = ELFSection::SHT_STRTAB;
197   StrTab.Align = 1;
198
199   // Set the zero'th symbol to a null byte, as required.
200   outbyte(0);
201   SymbolTable[0].NameIdx = 0;
202   unsigned Index = 1;
203   for (unsigned i = 1, e = SymbolTable.size(); i != e; ++i) {
204     // FIXME: USE A MANGLER!!
205     const std::string &Name = SymbolTable[i].GV->getName();
206
207     if (Name.empty()) {
208       SymbolTable[i].NameIdx = 0;
209     } else {
210       SymbolTable[i].NameIdx = Index;
211
212       // Add the name to the output buffer, including the null terminator.
213       OutputBuffer.insert(OutputBuffer.end(), Name.begin(), Name.end());
214
215       // Add a null terminator.
216       OutputBuffer.push_back(0);
217
218       // Keep track of the number of bytes emitted to this section.
219       Index += Name.size()+1;
220     }
221   }
222
223   StrTab.Size = OutputBuffer.size()-StrTab.Offset;
224
225   // Now that we have emitted the string table and know the offset into the
226   // string table of each symbol, emit the symbol table itself.
227   assert(!is64Bit && "Should this be 8 byte aligned for 64-bit?"
228          " (check .Align below also)");
229   align(4);
230
231   SectionList.push_back(ELFSection(".symtab", OutputBuffer.size()));
232   ELFSection &SymTab = SectionList.back();
233   SymTab.Type = ELFSection::SHT_SYMTAB;
234   SymTab.Align = 4;   // FIXME: check for ELF64
235   SymTab.Link = SectionList.size()-2;  // Section Index of .strtab.
236   SymTab.Info = FirstNonLocalSymbol;   // First non-STB_LOCAL symbol.
237   SymTab.EntSize = 16; // Size of each symtab entry. FIXME: wrong for ELF64
238
239   assert(!is64Bit && "check this!");
240   for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i) {
241     ELFSym &Sym = SymbolTable[i];
242     outword(Sym.NameIdx);
243     outaddr(Sym.Value);
244     outword(Sym.Size);
245     outbyte(Sym.Info);
246     outbyte(Sym.Other);
247     outhalf(Sym.SectionIdx);
248   }
249
250   SymTab.Size = OutputBuffer.size()-SymTab.Offset;
251 }
252
253 /// EmitSectionTableStringTable - This method adds and emits a section for the
254 /// ELF Section Table string table: the string table that holds all of the
255 /// section names.
256 void ELFWriter::EmitSectionTableStringTable() {
257   // First step: add the section for the string table to the list of sections:
258   SectionList.push_back(ELFSection(".shstrtab", OutputBuffer.size()));
259   SectionList.back().Type = ELFSection::SHT_STRTAB;
260
261   // Now that we know which section number is the .shstrtab section, update the
262   // e_shstrndx entry in the ELF header.
263   fixhalf(SectionList.size()-1, ELFHeader_e_shstrndx_Offset);
264
265   // Set the NameIdx of each section in the string table and emit the bytes for
266   // the string table.
267   unsigned Index = 0;
268
269   for (unsigned i = 0, e = SectionList.size(); i != e; ++i) {
270     // Set the index into the table.  Note if we have lots of entries with
271     // common suffixes, we could memoize them here if we cared.
272     SectionList[i].NameIdx = Index;
273
274     // Add the name to the output buffer, including the null terminator.
275     OutputBuffer.insert(OutputBuffer.end(), SectionList[i].Name.begin(),
276                         SectionList[i].Name.end());
277     // Add a null terminator.
278     OutputBuffer.push_back(0);
279
280     // Keep track of the number of bytes emitted to this section.
281     Index += SectionList[i].Name.size()+1;
282   }
283
284   // Set the size of .shstrtab now that we know what it is.
285   SectionList.back().Size = Index;
286 }
287
288 /// EmitSectionTable - Now that we have emitted the entire contents of the file
289 /// (all of the sections), emit the section table which informs the reader where
290 /// the boundaries are.
291 void ELFWriter::EmitSectionTable() {
292   // Now that all of the sections have been emitted, set the e_shnum entry in
293   // the ELF header.
294   fixhalf(SectionList.size(), ELFHeader_e_shnum_Offset);
295   
296   // Now that we know the offset in the file of the section table (which we emit
297   // next), update the e_shoff address in the ELF header.
298   fixaddr(OutputBuffer.size(), ELFHeader_e_shoff_Offset);
299   
300   // Emit all of the section table entries.
301   for (unsigned i = 0, e = SectionList.size(); i != e; ++i) {
302     const ELFSection &S = SectionList[i];
303     outword(S.NameIdx);  // sh_name - Symbol table name idx
304     outword(S.Type);     // sh_type - Section contents & semantics
305     outword(S.Flags);    // sh_flags - Section flags.
306     outaddr(S.Addr);     // sh_addr - The mem address this section appears in.
307     outaddr(S.Offset);   // sh_offset - The offset from the start of the file.
308     outword(S.Size);     // sh_size - The section size.
309     outword(S.Link);     // sh_link - Section header table index link.
310     outword(S.Info);     // sh_info - Auxillary information.
311     outword(S.Align);    // sh_addralign - Alignment of section.
312     outword(S.EntSize);  // sh_entsize - Size of each entry in the section.
313   }
314
315   // Release the memory allocated for the section list.
316   std::vector<ELFSection>().swap(SectionList);
317 }