1 //===-- ELFWriter.cpp - Target-independent ELF Writer code ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under the
6 // 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.
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!
32 //===----------------------------------------------------------------------===//
34 #include "ELFWriter.h"
35 #include "llvm/Module.h"
36 #include "llvm/PassManager.h"
37 #include "llvm/CodeGen/FileWriters.h"
38 #include "llvm/CodeGen/MachineCodeEmitter.h"
39 #include "llvm/CodeGen/MachineConstantPool.h"
40 #include "llvm/CodeGen/MachineFunctionPass.h"
41 #include "llvm/Target/TargetData.h"
42 #include "llvm/Target/TargetELFWriterInfo.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Support/Mangler.h"
45 #include "llvm/Support/OutputBuffer.h"
46 #include "llvm/Support/Streams.h"
50 /// AddELFWriter - Concrete function to add the ELF writer to the function pass
52 MachineCodeEmitter *llvm::AddELFWriter(FunctionPassManager &FPM,
55 ELFWriter *EW = new ELFWriter(O, TM);
57 return &EW->getMachineCodeEmitter();
60 //===----------------------------------------------------------------------===//
61 // ELFCodeEmitter Implementation
62 //===----------------------------------------------------------------------===//
65 /// ELFCodeEmitter - This class is used by the ELFWriter to emit the code for
66 /// functions to the ELF file.
67 class ELFCodeEmitter : public MachineCodeEmitter {
70 ELFWriter::ELFSection *ES; // Section to write to.
71 std::vector<unsigned char> *OutBuffer;
74 ELFCodeEmitter(ELFWriter &ew) : EW(ew), TM(EW.TM), OutBuffer(0) {}
76 void startFunction(MachineFunction &F);
77 bool finishFunction(MachineFunction &F);
79 void addRelocation(const MachineRelocation &MR) {
80 assert(0 && "relo not handled yet!");
83 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
86 virtual intptr_t getConstantPoolEntryAddress(unsigned Index) const {
87 assert(0 && "CP not implementated yet!");
90 virtual intptr_t getJumpTableEntryAddress(unsigned Index) const {
91 assert(0 && "JT not implementated yet!");
95 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
96 assert(0 && "JT not implementated yet!");
100 /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
101 void startFunctionStub(unsigned StubSize, unsigned Alignment = 1) {
102 assert(0 && "JIT specific function called!");
105 void *finishFunctionStub(const Function *F) {
106 assert(0 && "JIT specific function called!");
113 /// startFunction - This callback is invoked when a new machine function is
114 /// about to be emitted.
115 void ELFCodeEmitter::startFunction(MachineFunction &F) {
116 // Align the output buffer to the appropriate alignment.
117 unsigned Align = 16; // FIXME: GENERICIZE!!
118 // Get the ELF Section that this function belongs in.
119 ES = &EW.getSection(".text", ELFWriter::ELFSection::SHT_PROGBITS,
120 ELFWriter::ELFSection::SHF_EXECINSTR |
121 ELFWriter::ELFSection::SHF_ALLOC);
122 OutBuffer = &ES->SectionData;
123 cerr << "FIXME: This code needs to be updated for changes in the "
124 << "CodeEmitter interfaces. In particular, this should set "
125 << "BufferBegin/BufferEnd/CurBufferPtr, not deal with OutBuffer!";
128 // Upgrade the section alignment if required.
129 if (ES->Align < Align) ES->Align = Align;
131 // Add padding zeros to the end of the buffer to make sure that the
132 // function will start on the correct byte alignment within the section.
133 OutputBuffer OB(*OutBuffer,
134 TM.getTargetData()->getPointerSizeInBits() == 64,
135 TM.getTargetData()->isLittleEndian());
137 FnStart = OutBuffer->size();
140 /// finishFunction - This callback is invoked after the function is completely
142 bool ELFCodeEmitter::finishFunction(MachineFunction &F) {
143 // We now know the size of the function, add a symbol to represent it.
144 ELFWriter::ELFSym FnSym(F.getFunction());
146 // Figure out the binding (linkage) of the symbol.
147 switch (F.getFunction()->getLinkage()) {
149 // appending linkage is illegal for functions.
150 assert(0 && "Unknown linkage type!");
151 case GlobalValue::ExternalLinkage:
152 FnSym.SetBind(ELFWriter::ELFSym::STB_GLOBAL);
154 case GlobalValue::LinkOnceLinkage:
155 case GlobalValue::WeakLinkage:
156 FnSym.SetBind(ELFWriter::ELFSym::STB_WEAK);
158 case GlobalValue::InternalLinkage:
159 FnSym.SetBind(ELFWriter::ELFSym::STB_LOCAL);
163 ES->Size = OutBuffer->size();
165 FnSym.SetType(ELFWriter::ELFSym::STT_FUNC);
166 FnSym.SectionIdx = ES->SectionIdx;
167 FnSym.Value = FnStart; // Value = Offset from start of Section.
168 FnSym.Size = OutBuffer->size()-FnStart;
170 // Finally, add it to the symtab.
171 EW.SymbolTable.push_back(FnSym);
175 //===----------------------------------------------------------------------===//
176 // ELFWriter Implementation
177 //===----------------------------------------------------------------------===//
179 ELFWriter::ELFWriter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) {
180 e_flags = 0; // e_flags defaults to 0, no flags.
182 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
183 isLittleEndian = TM.getTargetData()->isLittleEndian();
185 // Create the machine code emitter object for this target.
186 MCE = new ELFCodeEmitter(*this);
190 ELFWriter::~ELFWriter() {
194 // doInitialization - Emit the file header and all of the global variables for
195 // the module to the ELF file.
196 bool ELFWriter::doInitialization(Module &M) {
197 Mang = new Mangler(M);
199 // Local alias to shortenify coming code.
200 std::vector<unsigned char> &FH = FileHeader;
201 OutputBuffer FHOut(FH, is64Bit, isLittleEndian);
203 FHOut.outbyte(0x7F); // EI_MAG0
204 FHOut.outbyte('E'); // EI_MAG1
205 FHOut.outbyte('L'); // EI_MAG2
206 FHOut.outbyte('F'); // EI_MAG3
207 FHOut.outbyte(is64Bit ? 2 : 1); // EI_CLASS
208 FHOut.outbyte(isLittleEndian ? 1 : 2); // EI_DATA
209 FHOut.outbyte(1); // EI_VERSION
210 FH.resize(16); // EI_PAD up to 16 bytes.
212 // This should change for shared objects.
213 FHOut.outhalf(1); // e_type = ET_REL
214 FHOut.outword(TM.getELFWriterInfo()->getEMachine()); // target-defined
215 FHOut.outword(1); // e_version = 1
216 FHOut.outaddr(0); // e_entry = 0 -> no entry point in .o file
217 FHOut.outaddr(0); // e_phoff = 0 -> no program header for .o
219 ELFHeader_e_shoff_Offset = FH.size();
220 FHOut.outaddr(0); // e_shoff
221 FHOut.outword(e_flags); // e_flags = whatever the target wants
223 FHOut.outhalf(is64Bit ? 64 : 52); // e_ehsize = ELF header size
224 FHOut.outhalf(0); // e_phentsize = prog header entry size
225 FHOut.outhalf(0); // e_phnum = # prog header entries = 0
226 FHOut.outhalf(is64Bit ? 64 : 40); // e_shentsize = sect hdr entry size
229 ELFHeader_e_shnum_Offset = FH.size();
230 FHOut.outhalf(0); // e_shnum = # of section header ents
231 ELFHeader_e_shstrndx_Offset = FH.size();
232 FHOut.outhalf(0); // e_shstrndx = Section # of '.shstrtab'
234 // Add the null section, which is required to be first in the file.
235 getSection("", 0, 0);
237 // Start up the symbol table. The first entry in the symtab is the null
239 SymbolTable.push_back(ELFSym(0));
244 void ELFWriter::EmitGlobal(GlobalVariable *GV) {
245 // If this is an external global, emit it now. TODO: Note that it would be
246 // better to ignore the symbol here and only add it to the symbol table if
248 if (!GV->hasInitializer()) {
249 ELFSym ExternalSym(GV);
250 ExternalSym.SetBind(ELFSym::STB_GLOBAL);
251 ExternalSym.SetType(ELFSym::STT_NOTYPE);
252 ExternalSym.SectionIdx = ELFSection::SHN_UNDEF;
253 SymbolTable.push_back(ExternalSym);
257 const Type *GVType = (const Type*)GV->getType();
258 unsigned Align = TM.getTargetData()->getPrefTypeAlignment(GVType);
259 unsigned Size = TM.getTargetData()->getTypeSize(GVType);
261 // If this global has a zero initializer, it is part of the .bss or common
263 if (GV->getInitializer()->isNullValue()) {
264 // If this global is part of the common block, add it now. Variables are
265 // part of the common block if they are zero initialized and allowed to be
266 // merged with other symbols.
267 if (GV->hasLinkOnceLinkage() || GV->hasWeakLinkage()) {
268 ELFSym CommonSym(GV);
269 // Value for common symbols is the alignment required.
270 CommonSym.Value = Align;
271 CommonSym.Size = Size;
272 CommonSym.SetBind(ELFSym::STB_GLOBAL);
273 CommonSym.SetType(ELFSym::STT_OBJECT);
274 // TODO SOMEDAY: add ELF visibility.
275 CommonSym.SectionIdx = ELFSection::SHN_COMMON;
276 SymbolTable.push_back(CommonSym);
280 // Otherwise, this symbol is part of the .bss section. Emit it now.
282 // Handle alignment. Ensure section is aligned at least as much as required
284 ELFSection &BSSSection = getBSSSection();
285 BSSSection.Align = std::max(BSSSection.Align, Align);
287 // Within the section, emit enough virtual padding to get us to an alignment
290 BSSSection.Size = (BSSSection.Size + Align - 1) & ~(Align-1);
293 BSSSym.Value = BSSSection.Size;
295 BSSSym.SetType(ELFSym::STT_OBJECT);
297 switch (GV->getLinkage()) {
298 default: // weak/linkonce handled above
299 assert(0 && "Unexpected linkage type!");
300 case GlobalValue::AppendingLinkage: // FIXME: This should be improved!
301 case GlobalValue::ExternalLinkage:
302 BSSSym.SetBind(ELFSym::STB_GLOBAL);
304 case GlobalValue::InternalLinkage:
305 BSSSym.SetBind(ELFSym::STB_LOCAL);
309 // Set the idx of the .bss section
310 BSSSym.SectionIdx = BSSSection.SectionIdx;
311 SymbolTable.push_back(BSSSym);
313 // Reserve space in the .bss section for this symbol.
314 BSSSection.Size += Size;
318 // FIXME: handle .rodata
319 //assert(!GV->isConstant() && "unimp");
321 // FIXME: handle .data
322 //assert(0 && "unimp");
326 bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
327 // Nothing to do here, this is all done through the MCE object above.
331 /// doFinalization - Now that the module has been completely processed, emit
332 /// the ELF file to 'O'.
333 bool ELFWriter::doFinalization(Module &M) {
334 // Okay, the ELF header and .text sections have been completed, build the
335 // .data, .bss, and "common" sections next.
336 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
340 // Emit the symbol table now, if non-empty.
343 // FIXME: Emit the relocations now.
345 // Emit the string table for the sections in the ELF file we have.
346 EmitSectionTableStringTable();
348 // Emit the sections to the .o file, and emit the section table for the file.
349 OutputSectionsAndSectionTable();
351 // We are done with the abstract symbols.
355 // Release the name mangler object.
356 delete Mang; Mang = 0;
360 /// EmitSymbolTable - If the current symbol table is non-empty, emit the string
361 /// table for it and then the symbol table itself.
362 void ELFWriter::EmitSymbolTable() {
363 if (SymbolTable.size() == 1) return; // Only the null entry.
365 // FIXME: compact all local symbols to the start of the symtab.
366 unsigned FirstNonLocalSymbol = 1;
368 ELFSection &StrTab = getSection(".strtab", ELFSection::SHT_STRTAB, 0);
371 DataBuffer &StrTabBuf = StrTab.SectionData;
372 OutputBuffer StrTabOut(StrTabBuf, is64Bit, isLittleEndian);
374 // Set the zero'th symbol to a null byte, as required.
375 StrTabOut.outbyte(0);
376 SymbolTable[0].NameIdx = 0;
378 for (unsigned i = 1, e = SymbolTable.size(); i != e; ++i) {
379 // Use the name mangler to uniquify the LLVM symbol.
380 std::string Name = Mang->getValueName(SymbolTable[i].GV);
383 SymbolTable[i].NameIdx = 0;
385 SymbolTable[i].NameIdx = Index;
387 // Add the name to the output buffer, including the null terminator.
388 StrTabBuf.insert(StrTabBuf.end(), Name.begin(), Name.end());
390 // Add a null terminator.
391 StrTabBuf.push_back(0);
393 // Keep track of the number of bytes emitted to this section.
394 Index += Name.size()+1;
397 assert(Index == StrTabBuf.size());
400 // Now that we have emitted the string table and know the offset into the
401 // string table of each symbol, emit the symbol table itself.
402 ELFSection &SymTab = getSection(".symtab", ELFSection::SHT_SYMTAB, 0);
403 SymTab.Align = is64Bit ? 8 : 4;
404 SymTab.Link = SymTab.SectionIdx; // Section Index of .strtab.
405 SymTab.Info = FirstNonLocalSymbol; // First non-STB_LOCAL symbol.
406 SymTab.EntSize = 16; // Size of each symtab entry. FIXME: wrong for ELF64
407 DataBuffer &SymTabBuf = SymTab.SectionData;
408 OutputBuffer SymTabOut(SymTabBuf, is64Bit, isLittleEndian);
410 if (!is64Bit) { // 32-bit and 64-bit formats are shuffled a bit.
411 for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i) {
412 ELFSym &Sym = SymbolTable[i];
413 SymTabOut.outword(Sym.NameIdx);
414 SymTabOut.outaddr32(Sym.Value);
415 SymTabOut.outword(Sym.Size);
416 SymTabOut.outbyte(Sym.Info);
417 SymTabOut.outbyte(Sym.Other);
418 SymTabOut.outhalf(Sym.SectionIdx);
421 for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i) {
422 ELFSym &Sym = SymbolTable[i];
423 SymTabOut.outword(Sym.NameIdx);
424 SymTabOut.outbyte(Sym.Info);
425 SymTabOut.outbyte(Sym.Other);
426 SymTabOut.outhalf(Sym.SectionIdx);
427 SymTabOut.outaddr64(Sym.Value);
428 SymTabOut.outxword(Sym.Size);
432 SymTab.Size = SymTabBuf.size();
435 /// EmitSectionTableStringTable - This method adds and emits a section for the
436 /// ELF Section Table string table: the string table that holds all of the
438 void ELFWriter::EmitSectionTableStringTable() {
439 // First step: add the section for the string table to the list of sections:
440 ELFSection &SHStrTab = getSection(".shstrtab", ELFSection::SHT_STRTAB, 0);
442 // Now that we know which section number is the .shstrtab section, update the
443 // e_shstrndx entry in the ELF header.
444 OutputBuffer FHOut(FileHeader, is64Bit, isLittleEndian);
445 FHOut.fixhalf(SHStrTab.SectionIdx, ELFHeader_e_shstrndx_Offset);
447 // Set the NameIdx of each section in the string table and emit the bytes for
450 DataBuffer &Buf = SHStrTab.SectionData;
452 for (std::list<ELFSection>::iterator I = SectionList.begin(),
453 E = SectionList.end(); 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.
458 // Add the name to the output buffer, including the null terminator.
459 Buf.insert(Buf.end(), I->Name.begin(), I->Name.end());
461 // Add a null terminator.
464 // Keep track of the number of bytes emitted to this section.
465 Index += I->Name.size()+1;
468 // Set the size of .shstrtab now that we know what it is.
469 assert(Index == Buf.size());
470 SHStrTab.Size = Index;
473 /// OutputSectionsAndSectionTable - Now that we have constructed the file header
474 /// and all of the sections, emit these to the ostream destination and emit the
476 void ELFWriter::OutputSectionsAndSectionTable() {
477 // Pass #1: Compute the file offset for each section.
478 size_t FileOff = FileHeader.size(); // File header first.
480 // Emit all of the section data in order.
481 for (std::list<ELFSection>::iterator I = SectionList.begin(),
482 E = SectionList.end(); I != E; ++I) {
483 // Align FileOff to whatever the alignment restrictions of the section are.
485 FileOff = (FileOff+I->Align-1) & ~(I->Align-1);
487 FileOff += I->SectionData.size();
490 // Align Section Header.
491 unsigned TableAlign = is64Bit ? 8 : 4;
492 FileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
494 // Now that we know where all of the sections will be emitted, set the e_shnum
495 // entry in the ELF header.
496 OutputBuffer FHOut(FileHeader, is64Bit, isLittleEndian);
497 FHOut.fixhalf(NumSections, ELFHeader_e_shnum_Offset);
499 // Now that we know the offset in the file of the section table, update the
500 // e_shoff address in the ELF header.
501 FHOut.fixaddr(FileOff, ELFHeader_e_shoff_Offset);
503 // Now that we know all of the data in the file header, emit it and all of the
505 O.write((char*)&FileHeader[0], FileHeader.size());
506 FileOff = FileHeader.size();
507 DataBuffer().swap(FileHeader);
510 OutputBuffer TableOut(Table, is64Bit, isLittleEndian);
512 // Emit all of the section data and build the section table itself.
513 while (!SectionList.empty()) {
514 const ELFSection &S = *SectionList.begin();
516 // Align FileOff to whatever the alignment restrictions of the section are.
518 for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
519 FileOff != NewFileOff; ++FileOff)
521 O.write((char*)&S.SectionData[0], S.SectionData.size());
522 FileOff += S.SectionData.size();
524 TableOut.outword(S.NameIdx); // sh_name - Symbol table name idx
525 TableOut.outword(S.Type); // sh_type - Section contents & semantics
526 TableOut.outword(S.Flags); // sh_flags - Section flags.
527 TableOut.outaddr(S.Addr); // sh_addr - The mem addr this section is in.
528 TableOut.outaddr(S.Offset); // sh_offset - Offset from the file start.
529 TableOut.outword(S.Size); // sh_size - The section size.
530 TableOut.outword(S.Link); // sh_link - Section header table index link.
531 TableOut.outword(S.Info); // sh_info - Auxillary information.
532 TableOut.outword(S.Align); // sh_addralign - Alignment of section.
533 TableOut.outword(S.EntSize); // sh_entsize - Size of entries in the section
535 SectionList.pop_front();
538 // Align output for the section table.
539 for (size_t NewFileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
540 FileOff != NewFileOff; ++FileOff)
543 // Emit the section table itself.
544 O.write((char*)&Table[0], Table.size());