blob: 96668e29ecb3bb162eb51cf50a3aad3c34e9ebf7 [file] [log] [blame]
Chris Lattner386b1512005-06-27 06:29:00 +00001//===-- 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
Chris Lattner1932f5c2005-07-07 07:02:20 +000014// #2. '.text' section
15// #3. '.data' section
16// #4. '.bss' section (conceptual position in file)
Chris Lattner386b1512005-06-27 06:29:00 +000017// ...
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]
Chris Lattner1932f5c2005-07-07 07:02:20 +000023// #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 ]
Chris Lattner386b1512005-06-27 06:29:00 +000026// ...
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"
Chris Lattner2244f732005-07-11 05:17:18 +000037#include "llvm/CodeGen/MachineCodeEmitter.h"
38#include "llvm/CodeGen/MachineConstantPool.h"
Chris Lattner386b1512005-06-27 06:29:00 +000039#include "llvm/Target/TargetMachine.h"
Chris Lattnerdfe33bc2005-07-11 03:11:47 +000040#include "llvm/Support/Mangler.h"
Chris Lattner386b1512005-06-27 06:29:00 +000041using namespace llvm;
42
Chris Lattner2244f732005-07-11 05:17:18 +000043namespace llvm {
44 class ELFCodeEmitter : public MachineCodeEmitter {
45 ELFWriter &EW;
46 std::vector<unsigned char> &OutputBuffer;
47 size_t FnStart;
48 public:
49 ELFCodeEmitter(ELFWriter &ew) : EW(ew), OutputBuffer(EW.OutputBuffer) {}
50
51 void startFunction(MachineFunction &F) {
52 // Align the output buffer to the appropriate alignment.
53 unsigned Align = 16; // FIXME: GENERICIZE!!
54 ELFWriter::ELFSection &TextSection = EW.SectionList.back();
55
56 // Upgrade the section alignment if required.
57 if (TextSection.Align < Align) TextSection.Align = Align;
58
59 // Add padding zeros to the end of the buffer to make sure that the
60 // function will start on the correct byte alignment within the section.
61 size_t SectionOff = OutputBuffer.size()-TextSection.Offset;
62 if (SectionOff & (Align-1)) {
63 // Add padding to get alignment to the correct place.
64 size_t Pad = Align-(SectionOff & (Align-1));
65 OutputBuffer.resize(OutputBuffer.size()+Pad);
66 }
67
68 FnStart = OutputBuffer.size();
69 }
70 void finishFunction(MachineFunction &F) {}
71 void emitConstantPool(MachineConstantPool *MCP) {
72 if (MCP->isEmpty()) return;
73 assert(0 && "unimp");
74 }
75 virtual void emitByte(unsigned char B) {
76 OutputBuffer.push_back(B);
77 }
78 virtual void emitWordAt(unsigned W, unsigned *Ptr) {
79 assert(0 && "ni");
80 }
81 virtual void emitWord(unsigned W) {
82 assert(0 && "ni");
83 }
84 virtual uint64_t getCurrentPCValue() {
85 return OutputBuffer.size();
86 }
87 virtual uint64_t getCurrentPCOffset() {
88 return OutputBuffer.size()-FnStart;
89 }
90 void addRelocation(const MachineRelocation &MR) {
91 assert(0 && "relo not handled yet!");
92 }
93 virtual uint64_t getConstantPoolEntryAddress(unsigned Index) {
94 assert(0 && "CP not implementated yet!");
95 }
96 /// JIT SPECIFIC FUNCTIONS
97 void startFunctionStub(unsigned StubSize) {
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
Chris Lattner386b1512005-06-27 06:29:00 +0000110ELFWriter::ELFWriter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) {
111 e_machine = 0; // e_machine defaults to 'No Machine'
112 e_flags = 0; // e_flags defaults to 0, no flags.
113
114 is64Bit = TM.getTargetData().getPointerSizeInBits() == 64;
115 isLittleEndian = TM.getTargetData().isLittleEndian();
Chris Lattner2244f732005-07-11 05:17:18 +0000116
117 // Create the machine code emitter object for this target.
118 MCE = new ELFCodeEmitter(*this);
119}
120
121ELFWriter::~ELFWriter() {
122 delete MCE;
Chris Lattner386b1512005-06-27 06:29:00 +0000123}
124
125// doInitialization - Emit the file header and all of the global variables for
126// the module to the ELF file.
127bool ELFWriter::doInitialization(Module &M) {
Chris Lattnerdfe33bc2005-07-11 03:11:47 +0000128 Mang = new Mangler(M);
129
Chris Lattner386b1512005-06-27 06:29:00 +0000130 outbyte(0x7F); // EI_MAG0
131 outbyte('E'); // EI_MAG1
132 outbyte('L'); // EI_MAG2
133 outbyte('F'); // EI_MAG3
134 outbyte(is64Bit ? 2 : 1); // EI_CLASS
135 outbyte(isLittleEndian ? 1 : 2); // EI_DATA
136 outbyte(1); // EI_VERSION
137 for (unsigned i = OutputBuffer.size(); i != 16; ++i)
138 outbyte(0); // EI_PAD up to 16 bytes.
139
140 // This should change for shared objects.
141 outhalf(1); // e_type = ET_REL
142 outhalf(e_machine); // e_machine = whatever the target wants
143 outword(1); // e_version = 1
144 outaddr(0); // e_entry = 0 -> no entry point in .o file
145 outaddr(0); // e_phoff = 0 -> no program header for .o
146
147 ELFHeader_e_shoff_Offset = OutputBuffer.size();
148 outaddr(0); // e_shoff
149 outword(e_flags); // e_flags = whatever the target wants
150
151 assert(!is64Bit && "These sizes need to be adjusted for 64-bit!");
152 outhalf(52); // e_ehsize = ELF header size
153 outhalf(0); // e_phentsize = prog header entry size
154 outhalf(0); // e_phnum = # prog header entries = 0
155 outhalf(40); // e_shentsize = sect header entry size
156
157
158 ELFHeader_e_shnum_Offset = OutputBuffer.size();
159 outhalf(0); // e_shnum = # of section header ents
160 ELFHeader_e_shstrndx_Offset = OutputBuffer.size();
161 outhalf(0); // e_shstrndx = Section # of '.shstrtab'
162
163 // Add the null section.
164 SectionList.push_back(ELFSection());
165
Chris Lattner1932f5c2005-07-07 07:02:20 +0000166 // Start up the symbol table. The first entry in the symtab is the null
167 // entry.
168 SymbolTable.push_back(ELFSym(0));
Chris Lattner386b1512005-06-27 06:29:00 +0000169
Chris Lattner2244f732005-07-11 05:17:18 +0000170 SectionList.push_back(ELFSection(".text", OutputBuffer.size()));
Chris Lattner386b1512005-06-27 06:29:00 +0000171
Chris Lattner386b1512005-06-27 06:29:00 +0000172 return false;
173}
174
Chris Lattner1932f5c2005-07-07 07:02:20 +0000175void ELFWriter::EmitGlobal(GlobalVariable *GV, ELFSection &DataSection,
176 ELFSection &BSSSection) {
Chris Lattner748de6e2005-07-08 05:47:00 +0000177 // If this is an external global, emit it now. TODO: Note that it would be
178 // better to ignore the symbol here and only add it to the symbol table if
179 // referenced.
180 if (!GV->hasInitializer()) {
181 ELFSym ExternalSym(GV);
182 ExternalSym.SetBind(ELFSym::STB_GLOBAL);
183 ExternalSym.SetType(ELFSym::STT_NOTYPE);
184 ExternalSym.SectionIdx = ELFSection::SHN_UNDEF;
185 SymbolTable.push_back(ExternalSym);
186 return;
187 }
Chris Lattner1932f5c2005-07-07 07:02:20 +0000188
Chris Lattner748de6e2005-07-08 05:47:00 +0000189 const Type *GVType = (const Type*)GV->getType();
190 unsigned Align = TM.getTargetData().getTypeAlignment(GVType);
191 unsigned Size = TM.getTargetData().getTypeSize(GVType);
192
Chris Lattner1932f5c2005-07-07 07:02:20 +0000193 // If this global has a zero initializer, it is part of the .bss or common
194 // section.
195 if (GV->getInitializer()->isNullValue()) {
196 // If this global is part of the common block, add it now. Variables are
197 // part of the common block if they are zero initialized and allowed to be
198 // merged with other symbols.
199 if (GV->hasLinkOnceLinkage() || GV->hasWeakLinkage()) {
200 ELFSym CommonSym(GV);
201 // Value for common symbols is the alignment required.
Chris Lattner748de6e2005-07-08 05:47:00 +0000202 CommonSym.Value = Align;
203 CommonSym.Size = Size;
Chris Lattner1932f5c2005-07-07 07:02:20 +0000204 CommonSym.SetBind(ELFSym::STB_GLOBAL);
205 CommonSym.SetType(ELFSym::STT_OBJECT);
206 // TODO SOMEDAY: add ELF visibility.
207 CommonSym.SectionIdx = ELFSection::SHN_COMMON;
208 SymbolTable.push_back(CommonSym);
209 return;
210 }
Chris Lattner386b1512005-06-27 06:29:00 +0000211
Chris Lattner748de6e2005-07-08 05:47:00 +0000212 // Otherwise, this symbol is part of the .bss section. Emit it now.
213
214 // Handle alignment. Ensure section is aligned at least as much as required
215 // by this symbol.
216 BSSSection.Align = std::max(BSSSection.Align, Align);
217
218 // Within the section, emit enough virtual padding to get us to an alignment
219 // boundary.
220 if (Align)
221 BSSSection.Size = (BSSSection.Size + Align - 1) & ~(Align-1);
222
223 ELFSym BSSSym(GV);
224 BSSSym.Value = BSSSection.Size;
225 BSSSym.Size = Size;
226 BSSSym.SetType(ELFSym::STT_OBJECT);
227
228 switch (GV->getLinkage()) {
229 default: // weak/linkonce handled above
230 assert(0 && "Unexpected linkage type!");
231 case GlobalValue::AppendingLinkage: // FIXME: This should be improved!
232 case GlobalValue::ExternalLinkage:
233 BSSSym.SetBind(ELFSym::STB_GLOBAL);
234 break;
235 case GlobalValue::InternalLinkage:
236 BSSSym.SetBind(ELFSym::STB_LOCAL);
237 break;
238 }
239
240 // Set the idx of the .bss section
241 BSSSym.SectionIdx = &BSSSection-&SectionList[0];
242 SymbolTable.push_back(BSSSym);
243
244 // Reserve space in the .bss section for this symbol.
245 BSSSection.Size += Size;
Chris Lattner1932f5c2005-07-07 07:02:20 +0000246 return;
247 }
Chris Lattner386b1512005-06-27 06:29:00 +0000248
Chris Lattner1932f5c2005-07-07 07:02:20 +0000249 // FIXME: handle .rodata
250 //assert(!GV->isConstant() && "unimp");
Chris Lattner386b1512005-06-27 06:29:00 +0000251
Chris Lattner1932f5c2005-07-07 07:02:20 +0000252 // FIXME: handle .data
253 //assert(0 && "unimp");
Chris Lattner386b1512005-06-27 06:29:00 +0000254}
255
256
257bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
Chris Lattner2244f732005-07-11 05:17:18 +0000258 // Nothing to do here, this is all done through the MCE object above.
Chris Lattner386b1512005-06-27 06:29:00 +0000259 return false;
260}
261
262/// doFinalization - Now that the module has been completely processed, emit
263/// the ELF file to 'O'.
264bool ELFWriter::doFinalization(Module &M) {
Chris Lattner2244f732005-07-11 05:17:18 +0000265 // Okay, the .text section has now been finalized. If it contains nothing, do
266 // not emit it.
267 uint64_t TextSize = OutputBuffer.size() - SectionList.back().Offset;
268 if (TextSize == 0) {
269 SectionList.pop_back();
270 } else {
271 ELFSection &Text = SectionList.back();
272 Text.Size = TextSize;
273 Text.Type = ELFSection::SHT_PROGBITS;
274 Text.Flags = ELFSection::SHF_EXECINSTR | ELFSection::SHF_ALLOC;
275 }
Chris Lattner1932f5c2005-07-07 07:02:20 +0000276
277 // Okay, the ELF header and .text sections have been completed, build the
278 // .data, .bss, and "common" sections next.
Chris Lattner748de6e2005-07-08 05:47:00 +0000279 SectionList.push_back(ELFSection(".data", OutputBuffer.size()));
280 SectionList.push_back(ELFSection(".bss"));
281 ELFSection &DataSection = *(SectionList.end()-2);
282 ELFSection &BSSSection = SectionList.back();
Chris Lattner1932f5c2005-07-07 07:02:20 +0000283 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
284 I != E; ++I)
285 EmitGlobal(I, DataSection, BSSSection);
286
Chris Lattner748de6e2005-07-08 05:47:00 +0000287 // Finish up the data section.
288 DataSection.Type = ELFSection::SHT_PROGBITS;
289 DataSection.Flags = ELFSection::SHF_WRITE | ELFSection::SHF_ALLOC;
Chris Lattner1932f5c2005-07-07 07:02:20 +0000290
Chris Lattner748de6e2005-07-08 05:47:00 +0000291 // The BSS Section logically starts at the end of the Data Section (adjusted
292 // to the required alignment of the BSSSection).
293 BSSSection.Offset = DataSection.Offset+DataSection.Size;
294 BSSSection.Type = ELFSection::SHT_NOBITS;
295 BSSSection.Flags = ELFSection::SHF_WRITE | ELFSection::SHF_ALLOC;
296 if (BSSSection.Align)
297 BSSSection.Offset = (BSSSection.Offset+BSSSection.Align-1) &
298 ~(BSSSection.Align-1);
Chris Lattner1932f5c2005-07-07 07:02:20 +0000299
300 // Emit the symbol table now, if non-empty.
301 EmitSymbolTable();
302
303 // FIXME: Emit the relocations now.
304
Chris Lattner386b1512005-06-27 06:29:00 +0000305 // Emit the string table for the sections in the ELF file we have.
306 EmitSectionTableStringTable();
307
308 // Emit the .o file section table.
309 EmitSectionTable();
310
311 // Emit the .o file to the specified stream.
312 O.write((char*)&OutputBuffer[0], OutputBuffer.size());
313
314 // Free the output buffer.
315 std::vector<unsigned char>().swap(OutputBuffer);
Chris Lattnerdfe33bc2005-07-11 03:11:47 +0000316
317 // Release the name mangler object.
318 delete Mang; Mang = 0;
Chris Lattner386b1512005-06-27 06:29:00 +0000319 return false;
320}
321
Chris Lattner1932f5c2005-07-07 07:02:20 +0000322/// EmitSymbolTable - If the current symbol table is non-empty, emit the string
323/// table for it and then the symbol table itself.
324void ELFWriter::EmitSymbolTable() {
325 if (SymbolTable.size() == 1) return; // Only the null entry.
326
327 // FIXME: compact all local symbols to the start of the symtab.
328 unsigned FirstNonLocalSymbol = 1;
329
330 SectionList.push_back(ELFSection(".strtab", OutputBuffer.size()));
331 ELFSection &StrTab = SectionList.back();
332 StrTab.Type = ELFSection::SHT_STRTAB;
333 StrTab.Align = 1;
334
335 // Set the zero'th symbol to a null byte, as required.
336 outbyte(0);
337 SymbolTable[0].NameIdx = 0;
338 unsigned Index = 1;
339 for (unsigned i = 1, e = SymbolTable.size(); i != e; ++i) {
Chris Lattnerdfe33bc2005-07-11 03:11:47 +0000340 // Use the name mangler to uniquify the LLVM symbol.
341 std::string Name = Mang->getValueName(SymbolTable[i].GV);
Chris Lattner1932f5c2005-07-07 07:02:20 +0000342
343 if (Name.empty()) {
344 SymbolTable[i].NameIdx = 0;
345 } else {
346 SymbolTable[i].NameIdx = Index;
347
348 // Add the name to the output buffer, including the null terminator.
349 OutputBuffer.insert(OutputBuffer.end(), Name.begin(), Name.end());
350
351 // Add a null terminator.
352 OutputBuffer.push_back(0);
353
354 // Keep track of the number of bytes emitted to this section.
355 Index += Name.size()+1;
356 }
357 }
358
359 StrTab.Size = OutputBuffer.size()-StrTab.Offset;
360
361 // Now that we have emitted the string table and know the offset into the
362 // string table of each symbol, emit the symbol table itself.
363 assert(!is64Bit && "Should this be 8 byte aligned for 64-bit?"
364 " (check .Align below also)");
365 align(4);
366
367 SectionList.push_back(ELFSection(".symtab", OutputBuffer.size()));
368 ELFSection &SymTab = SectionList.back();
369 SymTab.Type = ELFSection::SHT_SYMTAB;
370 SymTab.Align = 4; // FIXME: check for ELF64
371 SymTab.Link = SectionList.size()-2; // Section Index of .strtab.
372 SymTab.Info = FirstNonLocalSymbol; // First non-STB_LOCAL symbol.
373 SymTab.EntSize = 16; // Size of each symtab entry. FIXME: wrong for ELF64
374
375 assert(!is64Bit && "check this!");
376 for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i) {
377 ELFSym &Sym = SymbolTable[i];
378 outword(Sym.NameIdx);
379 outaddr(Sym.Value);
380 outword(Sym.Size);
381 outbyte(Sym.Info);
382 outbyte(Sym.Other);
383 outhalf(Sym.SectionIdx);
384 }
385
386 SymTab.Size = OutputBuffer.size()-SymTab.Offset;
387}
388
Chris Lattner386b1512005-06-27 06:29:00 +0000389/// EmitSectionTableStringTable - This method adds and emits a section for the
390/// ELF Section Table string table: the string table that holds all of the
391/// section names.
392void ELFWriter::EmitSectionTableStringTable() {
393 // First step: add the section for the string table to the list of sections:
394 SectionList.push_back(ELFSection(".shstrtab", OutputBuffer.size()));
Chris Lattner1932f5c2005-07-07 07:02:20 +0000395 SectionList.back().Type = ELFSection::SHT_STRTAB;
Chris Lattner386b1512005-06-27 06:29:00 +0000396
397 // Now that we know which section number is the .shstrtab section, update the
398 // e_shstrndx entry in the ELF header.
399 fixhalf(SectionList.size()-1, ELFHeader_e_shstrndx_Offset);
400
401 // Set the NameIdx of each section in the string table and emit the bytes for
402 // the string table.
403 unsigned Index = 0;
404
405 for (unsigned i = 0, e = SectionList.size(); i != e; ++i) {
406 // Set the index into the table. Note if we have lots of entries with
407 // common suffixes, we could memoize them here if we cared.
408 SectionList[i].NameIdx = Index;
409
410 // Add the name to the output buffer, including the null terminator.
411 OutputBuffer.insert(OutputBuffer.end(), SectionList[i].Name.begin(),
412 SectionList[i].Name.end());
413 // Add a null terminator.
414 OutputBuffer.push_back(0);
415
416 // Keep track of the number of bytes emitted to this section.
417 Index += SectionList[i].Name.size()+1;
418 }
419
420 // Set the size of .shstrtab now that we know what it is.
421 SectionList.back().Size = Index;
422}
423
424/// EmitSectionTable - Now that we have emitted the entire contents of the file
425/// (all of the sections), emit the section table which informs the reader where
426/// the boundaries are.
427void ELFWriter::EmitSectionTable() {
428 // Now that all of the sections have been emitted, set the e_shnum entry in
429 // the ELF header.
430 fixhalf(SectionList.size(), ELFHeader_e_shnum_Offset);
431
432 // Now that we know the offset in the file of the section table (which we emit
433 // next), update the e_shoff address in the ELF header.
434 fixaddr(OutputBuffer.size(), ELFHeader_e_shoff_Offset);
435
436 // Emit all of the section table entries.
437 for (unsigned i = 0, e = SectionList.size(); i != e; ++i) {
438 const ELFSection &S = SectionList[i];
439 outword(S.NameIdx); // sh_name - Symbol table name idx
440 outword(S.Type); // sh_type - Section contents & semantics
441 outword(S.Flags); // sh_flags - Section flags.
442 outaddr(S.Addr); // sh_addr - The mem address this section appears in.
443 outaddr(S.Offset); // sh_offset - The offset from the start of the file.
444 outword(S.Size); // sh_size - The section size.
445 outword(S.Link); // sh_link - Section header table index link.
446 outword(S.Info); // sh_info - Auxillary information.
447 outword(S.Align); // sh_addralign - Alignment of section.
448 outword(S.EntSize); // sh_entsize - Size of each entry in the section.
449 }
450
451 // Release the memory allocated for the section list.
452 std::vector<ELFSection>().swap(SectionList);
453}