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!");
87 /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
88 void startFunctionStub(unsigned StubSize) {
89 assert(0 && "JIT specific function called!");
92 void *finishFunctionStub(const Function *F) {
93 assert(0 && "JIT specific function called!");
100 /// startFunction - This callback is invoked when a new machine function is
101 /// about to be emitted.
102 void ELFCodeEmitter::startFunction(MachineFunction &F) {
103 // Align the output buffer to the appropriate alignment.
104 unsigned Align = 16; // FIXME: GENERICIZE!!
105 ELFWriter::ELFSection &TextSection = EW.SectionList.back();
107 // Upgrade the section alignment if required.
108 if (TextSection.Align < Align) TextSection.Align = Align;
110 // Add padding zeros to the end of the buffer to make sure that the
111 // function will start on the correct byte alignment within the section.
112 size_t SectionOff = OutputBuffer.size()-TextSection.Offset;
113 if (SectionOff & (Align-1)) {
114 // Add padding to get alignment to the correct place.
115 size_t Pad = Align-(SectionOff & (Align-1));
116 OutputBuffer.resize(OutputBuffer.size()+Pad);
119 FnStart = OutputBuffer.size();
122 /// finishFunction - This callback is invoked after the function is completely
124 void ELFCodeEmitter::finishFunction(MachineFunction &F) {
125 // We now know the size of the function, add a symbol to represent it.
126 ELFWriter::ELFSym FnSym(F.getFunction());
128 // Figure out the binding (linkage) of the symbol.
129 switch (F.getFunction()->getLinkage()) {
131 // appending linkage is illegal for functions.
132 assert(0 && "Unknown linkage type!");
133 case GlobalValue::ExternalLinkage:
134 FnSym.SetBind(ELFWriter::ELFSym::STB_GLOBAL);
136 case GlobalValue::LinkOnceLinkage:
137 case GlobalValue::WeakLinkage:
138 FnSym.SetBind(ELFWriter::ELFSym::STB_WEAK);
140 case GlobalValue::InternalLinkage:
141 FnSym.SetBind(ELFWriter::ELFSym::STB_LOCAL);
145 FnSym.SetType(ELFWriter::ELFSym::STT_FUNC);
146 FnSym.SectionIdx = EW.SectionList.size()-1; // .text section.
147 // Value = Offset from start of .text
148 FnSym.Value = FnStart - EW.SectionList.back().Offset;
149 FnSym.Size = OutputBuffer.size()-FnStart;
151 // Finally, add it to the symtab.
152 EW.SymbolTable.push_back(FnSym);
155 //===----------------------------------------------------------------------===//
156 // ELFWriter Implementation
157 //===----------------------------------------------------------------------===//
159 ELFWriter::ELFWriter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) {
160 e_machine = 0; // e_machine defaults to 'No Machine'
161 e_flags = 0; // e_flags defaults to 0, no flags.
163 is64Bit = TM.getTargetData().getPointerSizeInBits() == 64;
164 isLittleEndian = TM.getTargetData().isLittleEndian();
166 // Create the machine code emitter object for this target.
167 MCE = new ELFCodeEmitter(*this);
170 ELFWriter::~ELFWriter() {
174 // doInitialization - Emit the file header and all of the global variables for
175 // the module to the ELF file.
176 bool ELFWriter::doInitialization(Module &M) {
177 Mang = new Mangler(M);
179 outbyte(0x7F); // EI_MAG0
180 outbyte('E'); // EI_MAG1
181 outbyte('L'); // EI_MAG2
182 outbyte('F'); // EI_MAG3
183 outbyte(is64Bit ? 2 : 1); // EI_CLASS
184 outbyte(isLittleEndian ? 1 : 2); // EI_DATA
185 outbyte(1); // EI_VERSION
186 for (unsigned i = OutputBuffer.size(); i != 16; ++i)
187 outbyte(0); // EI_PAD up to 16 bytes.
189 // This should change for shared objects.
190 outhalf(1); // e_type = ET_REL
191 outhalf(e_machine); // e_machine = whatever the target wants
192 outword(1); // e_version = 1
193 outaddr(0); // e_entry = 0 -> no entry point in .o file
194 outaddr(0); // e_phoff = 0 -> no program header for .o
196 ELFHeader_e_shoff_Offset = OutputBuffer.size();
197 outaddr(0); // e_shoff
198 outword(e_flags); // e_flags = whatever the target wants
200 assert(!is64Bit && "These sizes need to be adjusted for 64-bit!");
201 outhalf(52); // e_ehsize = ELF header size
202 outhalf(0); // e_phentsize = prog header entry size
203 outhalf(0); // e_phnum = # prog header entries = 0
204 outhalf(40); // e_shentsize = sect header entry size
207 ELFHeader_e_shnum_Offset = OutputBuffer.size();
208 outhalf(0); // e_shnum = # of section header ents
209 ELFHeader_e_shstrndx_Offset = OutputBuffer.size();
210 outhalf(0); // e_shstrndx = Section # of '.shstrtab'
212 // Add the null section.
213 SectionList.push_back(ELFSection());
215 // Start up the symbol table. The first entry in the symtab is the null
217 SymbolTable.push_back(ELFSym(0));
219 SectionList.push_back(ELFSection(".text", OutputBuffer.size()));
224 void ELFWriter::EmitGlobal(GlobalVariable *GV, ELFSection &DataSection,
225 ELFSection &BSSSection) {
226 // If this is an external global, emit it now. TODO: Note that it would be
227 // better to ignore the symbol here and only add it to the symbol table if
229 if (!GV->hasInitializer()) {
230 ELFSym ExternalSym(GV);
231 ExternalSym.SetBind(ELFSym::STB_GLOBAL);
232 ExternalSym.SetType(ELFSym::STT_NOTYPE);
233 ExternalSym.SectionIdx = ELFSection::SHN_UNDEF;
234 SymbolTable.push_back(ExternalSym);
238 const Type *GVType = (const Type*)GV->getType();
239 unsigned Align = TM.getTargetData().getTypeAlignment(GVType);
240 unsigned Size = TM.getTargetData().getTypeSize(GVType);
242 // If this global has a zero initializer, it is part of the .bss or common
244 if (GV->getInitializer()->isNullValue()) {
245 // If this global is part of the common block, add it now. Variables are
246 // part of the common block if they are zero initialized and allowed to be
247 // merged with other symbols.
248 if (GV->hasLinkOnceLinkage() || GV->hasWeakLinkage()) {
249 ELFSym CommonSym(GV);
250 // Value for common symbols is the alignment required.
251 CommonSym.Value = Align;
252 CommonSym.Size = Size;
253 CommonSym.SetBind(ELFSym::STB_GLOBAL);
254 CommonSym.SetType(ELFSym::STT_OBJECT);
255 // TODO SOMEDAY: add ELF visibility.
256 CommonSym.SectionIdx = ELFSection::SHN_COMMON;
257 SymbolTable.push_back(CommonSym);
261 // Otherwise, this symbol is part of the .bss section. Emit it now.
263 // Handle alignment. Ensure section is aligned at least as much as required
265 BSSSection.Align = std::max(BSSSection.Align, Align);
267 // Within the section, emit enough virtual padding to get us to an alignment
270 BSSSection.Size = (BSSSection.Size + Align - 1) & ~(Align-1);
273 BSSSym.Value = BSSSection.Size;
275 BSSSym.SetType(ELFSym::STT_OBJECT);
277 switch (GV->getLinkage()) {
278 default: // weak/linkonce handled above
279 assert(0 && "Unexpected linkage type!");
280 case GlobalValue::AppendingLinkage: // FIXME: This should be improved!
281 case GlobalValue::ExternalLinkage:
282 BSSSym.SetBind(ELFSym::STB_GLOBAL);
284 case GlobalValue::InternalLinkage:
285 BSSSym.SetBind(ELFSym::STB_LOCAL);
289 // Set the idx of the .bss section
290 BSSSym.SectionIdx = &BSSSection-&SectionList[0];
291 SymbolTable.push_back(BSSSym);
293 // Reserve space in the .bss section for this symbol.
294 BSSSection.Size += Size;
298 // FIXME: handle .rodata
299 //assert(!GV->isConstant() && "unimp");
301 // FIXME: handle .data
302 //assert(0 && "unimp");
306 bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
307 // Nothing to do here, this is all done through the MCE object above.
311 /// doFinalization - Now that the module has been completely processed, emit
312 /// the ELF file to 'O'.
313 bool ELFWriter::doFinalization(Module &M) {
314 // Okay, the .text section has now been finalized. If it contains nothing, do
316 uint64_t TextSize = OutputBuffer.size() - SectionList.back().Offset;
318 SectionList.pop_back();
320 ELFSection &Text = SectionList.back();
321 Text.Size = TextSize;
322 Text.Type = ELFSection::SHT_PROGBITS;
323 Text.Flags = ELFSection::SHF_EXECINSTR | ELFSection::SHF_ALLOC;
326 // Okay, the ELF header and .text sections have been completed, build the
327 // .data, .bss, and "common" sections next.
328 SectionList.push_back(ELFSection(".data", OutputBuffer.size()));
329 SectionList.push_back(ELFSection(".bss"));
330 ELFSection &DataSection = *(SectionList.end()-2);
331 ELFSection &BSSSection = SectionList.back();
332 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
334 EmitGlobal(I, DataSection, BSSSection);
336 // Finish up the data section.
337 DataSection.Type = ELFSection::SHT_PROGBITS;
338 DataSection.Flags = ELFSection::SHF_WRITE | ELFSection::SHF_ALLOC;
340 // The BSS Section logically starts at the end of the Data Section (adjusted
341 // to the required alignment of the BSSSection).
342 BSSSection.Offset = DataSection.Offset+DataSection.Size;
343 BSSSection.Type = ELFSection::SHT_NOBITS;
344 BSSSection.Flags = ELFSection::SHF_WRITE | ELFSection::SHF_ALLOC;
345 if (BSSSection.Align)
346 BSSSection.Offset = (BSSSection.Offset+BSSSection.Align-1) &
347 ~(BSSSection.Align-1);
349 // Emit the symbol table now, if non-empty.
352 // FIXME: Emit the relocations now.
354 // Emit the string table for the sections in the ELF file we have.
355 EmitSectionTableStringTable();
357 // Emit the .o file section table.
360 // Emit the .o file to the specified stream.
361 O.write((char*)&OutputBuffer[0], OutputBuffer.size());
363 // Free the output buffer.
364 std::vector<unsigned char>().swap(OutputBuffer);
366 // Release the name mangler object.
367 delete Mang; Mang = 0;
371 /// EmitSymbolTable - If the current symbol table is non-empty, emit the string
372 /// table for it and then the symbol table itself.
373 void ELFWriter::EmitSymbolTable() {
374 if (SymbolTable.size() == 1) return; // Only the null entry.
376 // FIXME: compact all local symbols to the start of the symtab.
377 unsigned FirstNonLocalSymbol = 1;
379 SectionList.push_back(ELFSection(".strtab", OutputBuffer.size()));
380 ELFSection &StrTab = SectionList.back();
381 StrTab.Type = ELFSection::SHT_STRTAB;
384 // Set the zero'th symbol to a null byte, as required.
386 SymbolTable[0].NameIdx = 0;
388 for (unsigned i = 1, e = SymbolTable.size(); i != e; ++i) {
389 // Use the name mangler to uniquify the LLVM symbol.
390 std::string Name = Mang->getValueName(SymbolTable[i].GV);
393 SymbolTable[i].NameIdx = 0;
395 SymbolTable[i].NameIdx = Index;
397 // Add the name to the output buffer, including the null terminator.
398 OutputBuffer.insert(OutputBuffer.end(), Name.begin(), Name.end());
400 // Add a null terminator.
401 OutputBuffer.push_back(0);
403 // Keep track of the number of bytes emitted to this section.
404 Index += Name.size()+1;
408 StrTab.Size = OutputBuffer.size()-StrTab.Offset;
410 // Now that we have emitted the string table and know the offset into the
411 // string table of each symbol, emit the symbol table itself.
412 assert(!is64Bit && "Should this be 8 byte aligned for 64-bit?"
413 " (check .Align below also)");
416 SectionList.push_back(ELFSection(".symtab", OutputBuffer.size()));
417 ELFSection &SymTab = SectionList.back();
418 SymTab.Type = ELFSection::SHT_SYMTAB;
419 SymTab.Align = 4; // FIXME: check for ELF64
420 SymTab.Link = SectionList.size()-2; // Section Index of .strtab.
421 SymTab.Info = FirstNonLocalSymbol; // First non-STB_LOCAL symbol.
422 SymTab.EntSize = 16; // Size of each symtab entry. FIXME: wrong for ELF64
424 assert(!is64Bit && "check this!");
425 for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i) {
426 ELFSym &Sym = SymbolTable[i];
427 outword(Sym.NameIdx);
432 outhalf(Sym.SectionIdx);
435 SymTab.Size = OutputBuffer.size()-SymTab.Offset;
438 /// EmitSectionTableStringTable - This method adds and emits a section for the
439 /// ELF Section Table string table: the string table that holds all of the
441 void ELFWriter::EmitSectionTableStringTable() {
442 // First step: add the section for the string table to the list of sections:
443 SectionList.push_back(ELFSection(".shstrtab", OutputBuffer.size()));
444 SectionList.back().Type = ELFSection::SHT_STRTAB;
446 // Now that we know which section number is the .shstrtab section, update the
447 // e_shstrndx entry in the ELF header.
448 fixhalf(SectionList.size()-1, ELFHeader_e_shstrndx_Offset);
450 // Set the NameIdx of each section in the string table and emit the bytes for
454 for (unsigned i = 0, e = SectionList.size(); i != e; ++i) {
455 // Set the index into the table. Note if we have lots of entries with
456 // common suffixes, we could memoize them here if we cared.
457 SectionList[i].NameIdx = Index;
459 // Add the name to the output buffer, including the null terminator.
460 OutputBuffer.insert(OutputBuffer.end(), SectionList[i].Name.begin(),
461 SectionList[i].Name.end());
462 // Add a null terminator.
463 OutputBuffer.push_back(0);
465 // Keep track of the number of bytes emitted to this section.
466 Index += SectionList[i].Name.size()+1;
469 // Set the size of .shstrtab now that we know what it is.
470 SectionList.back().Size = Index;
473 /// EmitSectionTable - Now that we have emitted the entire contents of the file
474 /// (all of the sections), emit the section table which informs the reader where
475 /// the boundaries are.
476 void ELFWriter::EmitSectionTable() {
477 // Now that all of the sections have been emitted, set the e_shnum entry in
479 fixhalf(SectionList.size(), ELFHeader_e_shnum_Offset);
481 // Now that we know the offset in the file of the section table (which we emit
482 // next), update the e_shoff address in the ELF header.
483 fixaddr(OutputBuffer.size(), ELFHeader_e_shoff_Offset);
485 // Emit all of the section table entries.
486 for (unsigned i = 0, e = SectionList.size(); i != e; ++i) {
487 const ELFSection &S = SectionList[i];
488 outword(S.NameIdx); // sh_name - Symbol table name idx
489 outword(S.Type); // sh_type - Section contents & semantics
490 outword(S.Flags); // sh_flags - Section flags.
491 outaddr(S.Addr); // sh_addr - The mem address this section appears in.
492 outaddr(S.Offset); // sh_offset - The offset from the start of the file.
493 outword(S.Size); // sh_size - The section size.
494 outword(S.Link); // sh_link - Section header table index link.
495 outword(S.Info); // sh_info - Auxillary information.
496 outword(S.Align); // sh_addralign - Alignment of section.
497 outword(S.EntSize); // sh_entsize - Size of each entry in the section.
500 // Release the memory allocated for the section list.
501 std::vector<ELFSection>().swap(SectionList);