1 //===-- ELFWriter.cpp - Target-independent ELF Writer code ----------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements the target-independent ELF writer. This file writes out
11 // the ELF file in the following order:
14 // #2. '.text' section
15 // #3. '.data' section
16 // #4. '.bss' section (conceptual position in file)
18 // #X. '.shstrtab' section
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 ]
27 // #N. ".shstrtab" entry - String table for the section names.
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!
33 //===----------------------------------------------------------------------===//
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"
43 //===----------------------------------------------------------------------===//
44 // ELFCodeEmitter Implementation
45 //===----------------------------------------------------------------------===//
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 {
52 std::vector<unsigned char> &OutputBuffer;
55 ELFCodeEmitter(ELFWriter &ew) : EW(ew), OutputBuffer(EW.OutputBuffer) {}
57 void startFunction(MachineFunction &F);
58 void finishFunction(MachineFunction &F);
60 void emitConstantPool(MachineConstantPool *MCP) {
61 if (MCP->isEmpty()) return;
64 virtual void emitByte(unsigned char B) {
65 OutputBuffer.push_back(B);
67 virtual void emitWordAt(unsigned W, unsigned *Ptr) {
70 virtual void emitWord(unsigned W) {
73 virtual uint64_t getCurrentPCValue() {
74 return OutputBuffer.size();
76 virtual uint64_t getCurrentPCOffset() {
77 return OutputBuffer.size()-FnStart;
79 void addRelocation(const MachineRelocation &MR) {
80 assert(0 && "relo not handled yet!");
82 virtual uint64_t getConstantPoolEntryAddress(unsigned Index) {
83 assert(0 && "CP not implementated yet!");
86 /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
87 void startFunctionStub(unsigned StubSize) {
88 assert(0 && "JIT specific function called!");
91 void *finishFunctionStub(const Function *F) {
92 assert(0 && "JIT specific function called!");
99 /// startFunction - This callback is invoked when a new machine function is
100 /// about to be emitted.
101 void ELFCodeEmitter::startFunction(MachineFunction &F) {
102 // Align the output buffer to the appropriate alignment.
103 unsigned Align = 16; // FIXME: GENERICIZE!!
104 ELFWriter::ELFSection &TextSection = EW.SectionList.back();
106 // Upgrade the section alignment if required.
107 if (TextSection.Align < Align) TextSection.Align = Align;
109 // Add padding zeros to the end of the buffer to make sure that the
110 // function will start on the correct byte alignment within the section.
111 size_t SectionOff = OutputBuffer.size()-TextSection.Offset;
112 if (SectionOff & (Align-1)) {
113 // Add padding to get alignment to the correct place.
114 size_t Pad = Align-(SectionOff & (Align-1));
115 OutputBuffer.resize(OutputBuffer.size()+Pad);
118 FnStart = OutputBuffer.size();
121 /// finishFunction - This callback is invoked after the function is completely
123 void ELFCodeEmitter::finishFunction(MachineFunction &F) {
124 // We now know the size of the function, add a symbol to represent it.
125 ELFWriter::ELFSym FnSym(F.getFunction());
127 // Figure out the binding (linkage) of the symbol.
128 switch (F.getFunction()->getLinkage()) {
130 // appending linkage is illegal for functions.
131 assert(0 && "Unknown linkage type!");
132 case GlobalValue::ExternalLinkage:
133 FnSym.SetBind(ELFWriter::ELFSym::STB_GLOBAL);
135 case GlobalValue::LinkOnceLinkage:
136 case GlobalValue::WeakLinkage:
137 FnSym.SetBind(ELFWriter::ELFSym::STB_WEAK);
139 case GlobalValue::InternalLinkage:
140 FnSym.SetBind(ELFWriter::ELFSym::STB_LOCAL);
144 FnSym.SetType(ELFWriter::ELFSym::STT_FUNC);
145 FnSym.SectionIdx = EW.SectionList.size()-1; // .text section.
146 // Value = Offset from start of .text
147 FnSym.Value = FnStart - EW.SectionList.back().Offset;
148 FnSym.Size = OutputBuffer.size()-FnStart;
150 // Finally, add it to the symtab.
151 EW.SymbolTable.push_back(FnSym);
154 //===----------------------------------------------------------------------===//
155 // ELFWriter Implementation
156 //===----------------------------------------------------------------------===//
158 ELFWriter::ELFWriter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) {
159 e_machine = 0; // e_machine defaults to 'No Machine'
160 e_flags = 0; // e_flags defaults to 0, no flags.
162 is64Bit = TM.getTargetData().getPointerSizeInBits() == 64;
163 isLittleEndian = TM.getTargetData().isLittleEndian();
165 // Create the machine code emitter object for this target.
166 MCE = new ELFCodeEmitter(*this);
169 ELFWriter::~ELFWriter() {
173 // doInitialization - Emit the file header and all of the global variables for
174 // the module to the ELF file.
175 bool ELFWriter::doInitialization(Module &M) {
176 Mang = new Mangler(M);
178 outbyte(0x7F); // EI_MAG0
179 outbyte('E'); // EI_MAG1
180 outbyte('L'); // EI_MAG2
181 outbyte('F'); // EI_MAG3
182 outbyte(is64Bit ? 2 : 1); // EI_CLASS
183 outbyte(isLittleEndian ? 1 : 2); // EI_DATA
184 outbyte(1); // EI_VERSION
185 for (unsigned i = OutputBuffer.size(); i != 16; ++i)
186 outbyte(0); // EI_PAD up to 16 bytes.
188 // This should change for shared objects.
189 outhalf(1); // e_type = ET_REL
190 outhalf(e_machine); // e_machine = whatever the target wants
191 outword(1); // e_version = 1
192 outaddr(0); // e_entry = 0 -> no entry point in .o file
193 outaddr(0); // e_phoff = 0 -> no program header for .o
195 ELFHeader_e_shoff_Offset = OutputBuffer.size();
196 outaddr(0); // e_shoff
197 outword(e_flags); // e_flags = whatever the target wants
199 assert(!is64Bit && "These sizes need to be adjusted for 64-bit!");
200 outhalf(52); // e_ehsize = ELF header size
201 outhalf(0); // e_phentsize = prog header entry size
202 outhalf(0); // e_phnum = # prog header entries = 0
203 outhalf(40); // e_shentsize = sect header entry size
206 ELFHeader_e_shnum_Offset = OutputBuffer.size();
207 outhalf(0); // e_shnum = # of section header ents
208 ELFHeader_e_shstrndx_Offset = OutputBuffer.size();
209 outhalf(0); // e_shstrndx = Section # of '.shstrtab'
211 // Add the null section.
212 SectionList.push_back(ELFSection());
214 // Start up the symbol table. The first entry in the symtab is the null
216 SymbolTable.push_back(ELFSym(0));
218 SectionList.push_back(ELFSection(".text", OutputBuffer.size()));
223 void ELFWriter::EmitGlobal(GlobalVariable *GV, ELFSection &DataSection,
224 ELFSection &BSSSection) {
225 // If this is an external global, emit it now. TODO: Note that it would be
226 // better to ignore the symbol here and only add it to the symbol table if
228 if (!GV->hasInitializer()) {
229 ELFSym ExternalSym(GV);
230 ExternalSym.SetBind(ELFSym::STB_GLOBAL);
231 ExternalSym.SetType(ELFSym::STT_NOTYPE);
232 ExternalSym.SectionIdx = ELFSection::SHN_UNDEF;
233 SymbolTable.push_back(ExternalSym);
237 const Type *GVType = (const Type*)GV->getType();
238 unsigned Align = TM.getTargetData().getTypeAlignment(GVType);
239 unsigned Size = TM.getTargetData().getTypeSize(GVType);
241 // If this global has a zero initializer, it is part of the .bss or common
243 if (GV->getInitializer()->isNullValue()) {
244 // If this global is part of the common block, add it now. Variables are
245 // part of the common block if they are zero initialized and allowed to be
246 // merged with other symbols.
247 if (GV->hasLinkOnceLinkage() || GV->hasWeakLinkage()) {
248 ELFSym CommonSym(GV);
249 // Value for common symbols is the alignment required.
250 CommonSym.Value = Align;
251 CommonSym.Size = Size;
252 CommonSym.SetBind(ELFSym::STB_GLOBAL);
253 CommonSym.SetType(ELFSym::STT_OBJECT);
254 // TODO SOMEDAY: add ELF visibility.
255 CommonSym.SectionIdx = ELFSection::SHN_COMMON;
256 SymbolTable.push_back(CommonSym);
260 // Otherwise, this symbol is part of the .bss section. Emit it now.
262 // Handle alignment. Ensure section is aligned at least as much as required
264 BSSSection.Align = std::max(BSSSection.Align, Align);
266 // Within the section, emit enough virtual padding to get us to an alignment
269 BSSSection.Size = (BSSSection.Size + Align - 1) & ~(Align-1);
272 BSSSym.Value = BSSSection.Size;
274 BSSSym.SetType(ELFSym::STT_OBJECT);
276 switch (GV->getLinkage()) {
277 default: // weak/linkonce handled above
278 assert(0 && "Unexpected linkage type!");
279 case GlobalValue::AppendingLinkage: // FIXME: This should be improved!
280 case GlobalValue::ExternalLinkage:
281 BSSSym.SetBind(ELFSym::STB_GLOBAL);
283 case GlobalValue::InternalLinkage:
284 BSSSym.SetBind(ELFSym::STB_LOCAL);
288 // Set the idx of the .bss section
289 BSSSym.SectionIdx = &BSSSection-&SectionList[0];
290 SymbolTable.push_back(BSSSym);
292 // Reserve space in the .bss section for this symbol.
293 BSSSection.Size += Size;
297 // FIXME: handle .rodata
298 //assert(!GV->isConstant() && "unimp");
300 // FIXME: handle .data
301 //assert(0 && "unimp");
305 bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
306 // Nothing to do here, this is all done through the MCE object above.
310 /// doFinalization - Now that the module has been completely processed, emit
311 /// the ELF file to 'O'.
312 bool ELFWriter::doFinalization(Module &M) {
313 // Okay, the .text section has now been finalized. If it contains nothing, do
315 uint64_t TextSize = OutputBuffer.size() - SectionList.back().Offset;
317 SectionList.pop_back();
319 ELFSection &Text = SectionList.back();
320 Text.Size = TextSize;
321 Text.Type = ELFSection::SHT_PROGBITS;
322 Text.Flags = ELFSection::SHF_EXECINSTR | ELFSection::SHF_ALLOC;
325 // Okay, the ELF header and .text sections have been completed, build the
326 // .data, .bss, and "common" sections next.
327 SectionList.push_back(ELFSection(".data", OutputBuffer.size()));
328 SectionList.push_back(ELFSection(".bss"));
329 ELFSection &DataSection = *(SectionList.end()-2);
330 ELFSection &BSSSection = SectionList.back();
331 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
333 EmitGlobal(I, DataSection, BSSSection);
335 // Finish up the data section.
336 DataSection.Type = ELFSection::SHT_PROGBITS;
337 DataSection.Flags = ELFSection::SHF_WRITE | ELFSection::SHF_ALLOC;
339 // The BSS Section logically starts at the end of the Data Section (adjusted
340 // to the required alignment of the BSSSection).
341 BSSSection.Offset = DataSection.Offset+DataSection.Size;
342 BSSSection.Type = ELFSection::SHT_NOBITS;
343 BSSSection.Flags = ELFSection::SHF_WRITE | ELFSection::SHF_ALLOC;
344 if (BSSSection.Align)
345 BSSSection.Offset = (BSSSection.Offset+BSSSection.Align-1) &
346 ~(BSSSection.Align-1);
348 // Emit the symbol table now, if non-empty.
351 // FIXME: Emit the relocations now.
353 // Emit the string table for the sections in the ELF file we have.
354 EmitSectionTableStringTable();
356 // Emit the .o file section table.
359 // Emit the .o file to the specified stream.
360 O.write((char*)&OutputBuffer[0], OutputBuffer.size());
362 // Free the output buffer.
363 std::vector<unsigned char>().swap(OutputBuffer);
365 // Release the name mangler object.
366 delete Mang; Mang = 0;
370 /// EmitSymbolTable - If the current symbol table is non-empty, emit the string
371 /// table for it and then the symbol table itself.
372 void ELFWriter::EmitSymbolTable() {
373 if (SymbolTable.size() == 1) return; // Only the null entry.
375 // FIXME: compact all local symbols to the start of the symtab.
376 unsigned FirstNonLocalSymbol = 1;
378 SectionList.push_back(ELFSection(".strtab", OutputBuffer.size()));
379 ELFSection &StrTab = SectionList.back();
380 StrTab.Type = ELFSection::SHT_STRTAB;
383 // Set the zero'th symbol to a null byte, as required.
385 SymbolTable[0].NameIdx = 0;
387 for (unsigned i = 1, e = SymbolTable.size(); i != e; ++i) {
388 // Use the name mangler to uniquify the LLVM symbol.
389 std::string Name = Mang->getValueName(SymbolTable[i].GV);
392 SymbolTable[i].NameIdx = 0;
394 SymbolTable[i].NameIdx = Index;
396 // Add the name to the output buffer, including the null terminator.
397 OutputBuffer.insert(OutputBuffer.end(), Name.begin(), Name.end());
399 // Add a null terminator.
400 OutputBuffer.push_back(0);
402 // Keep track of the number of bytes emitted to this section.
403 Index += Name.size()+1;
407 StrTab.Size = OutputBuffer.size()-StrTab.Offset;
409 // Now that we have emitted the string table and know the offset into the
410 // string table of each symbol, emit the symbol table itself.
411 assert(!is64Bit && "Should this be 8 byte aligned for 64-bit?"
412 " (check .Align below also)");
415 SectionList.push_back(ELFSection(".symtab", OutputBuffer.size()));
416 ELFSection &SymTab = SectionList.back();
417 SymTab.Type = ELFSection::SHT_SYMTAB;
418 SymTab.Align = 4; // FIXME: check for ELF64
419 SymTab.Link = SectionList.size()-2; // Section Index of .strtab.
420 SymTab.Info = FirstNonLocalSymbol; // First non-STB_LOCAL symbol.
421 SymTab.EntSize = 16; // Size of each symtab entry. FIXME: wrong for ELF64
423 assert(!is64Bit && "check this!");
424 for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i) {
425 ELFSym &Sym = SymbolTable[i];
426 outword(Sym.NameIdx);
431 outhalf(Sym.SectionIdx);
434 SymTab.Size = OutputBuffer.size()-SymTab.Offset;
437 /// EmitSectionTableStringTable - This method adds and emits a section for the
438 /// ELF Section Table string table: the string table that holds all of the
440 void ELFWriter::EmitSectionTableStringTable() {
441 // First step: add the section for the string table to the list of sections:
442 SectionList.push_back(ELFSection(".shstrtab", OutputBuffer.size()));
443 SectionList.back().Type = ELFSection::SHT_STRTAB;
445 // Now that we know which section number is the .shstrtab section, update the
446 // e_shstrndx entry in the ELF header.
447 fixhalf(SectionList.size()-1, ELFHeader_e_shstrndx_Offset);
449 // Set the NameIdx of each section in the string table and emit the bytes for
453 for (unsigned i = 0, e = SectionList.size(); i != e; ++i) {
454 // Set the index into the table. Note if we have lots of entries with
455 // common suffixes, we could memoize them here if we cared.
456 SectionList[i].NameIdx = Index;
458 // Add the name to the output buffer, including the null terminator.
459 OutputBuffer.insert(OutputBuffer.end(), SectionList[i].Name.begin(),
460 SectionList[i].Name.end());
461 // Add a null terminator.
462 OutputBuffer.push_back(0);
464 // Keep track of the number of bytes emitted to this section.
465 Index += SectionList[i].Name.size()+1;
468 // Set the size of .shstrtab now that we know what it is.
469 SectionList.back().Size = Index;
472 /// EmitSectionTable - Now that we have emitted the entire contents of the file
473 /// (all of the sections), emit the section table which informs the reader where
474 /// the boundaries are.
475 void ELFWriter::EmitSectionTable() {
476 // Now that all of the sections have been emitted, set the e_shnum entry in
478 fixhalf(SectionList.size(), ELFHeader_e_shnum_Offset);
480 // Now that we know the offset in the file of the section table (which we emit
481 // next), update the e_shoff address in the ELF header.
482 fixaddr(OutputBuffer.size(), ELFHeader_e_shoff_Offset);
484 // Emit all of the section table entries.
485 for (unsigned i = 0, e = SectionList.size(); i != e; ++i) {
486 const ELFSection &S = SectionList[i];
487 outword(S.NameIdx); // sh_name - Symbol table name idx
488 outword(S.Type); // sh_type - Section contents & semantics
489 outword(S.Flags); // sh_flags - Section flags.
490 outaddr(S.Addr); // sh_addr - The mem address this section appears in.
491 outaddr(S.Offset); // sh_offset - The offset from the start of the file.
492 outword(S.Size); // sh_size - The section size.
493 outword(S.Link); // sh_link - Section header table index link.
494 outword(S.Info); // sh_info - Auxillary information.
495 outword(S.Align); // sh_addralign - Alignment of section.
496 outword(S.EntSize); // sh_entsize - Size of each entry in the section.
499 // Release the memory allocated for the section list.
500 std::vector<ELFSection>().swap(SectionList);