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 "llvm/CodeGen/ELFWriter.h"
35 #include "llvm/Module.h"
36 #include "llvm/CodeGen/MachineCodeEmitter.h"
37 #include "llvm/CodeGen/MachineConstantPool.h"
38 #include "llvm/Target/TargetData.h"
39 #include "llvm/Target/TargetELFWriterInfo.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Support/Mangler.h"
42 #include "llvm/Support/OutputBuffer.h"
43 #include "llvm/Support/Streams.h"
46 //===----------------------------------------------------------------------===//
47 // ELFCodeEmitter Implementation
48 //===----------------------------------------------------------------------===//
51 /// ELFCodeEmitter - This class is used by the ELFWriter to emit the code for
52 /// functions to the ELF file.
53 class ELFCodeEmitter : public MachineCodeEmitter {
56 ELFWriter::ELFSection *ES; // Section to write to.
57 std::vector<unsigned char> *OutBuffer;
60 ELFCodeEmitter(ELFWriter &ew) : EW(ew), TM(EW.TM), OutBuffer(0) {}
62 void startFunction(MachineFunction &F);
63 bool finishFunction(MachineFunction &F);
65 void addRelocation(const MachineRelocation &MR) {
66 assert(0 && "relo not handled yet!");
69 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
72 virtual intptr_t getConstantPoolEntryAddress(unsigned Index) const {
73 assert(0 && "CP not implementated yet!");
76 virtual intptr_t getJumpTableEntryAddress(unsigned Index) const {
77 assert(0 && "JT not implementated yet!");
81 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
82 assert(0 && "JT not implementated yet!");
86 /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
87 void startFunctionStub(unsigned StubSize, unsigned Alignment = 1) {
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 // Get the ELF Section that this function belongs in.
105 ES = &EW.getSection(".text", ELFWriter::ELFSection::SHT_PROGBITS,
106 ELFWriter::ELFSection::SHF_EXECINSTR |
107 ELFWriter::ELFSection::SHF_ALLOC);
108 OutBuffer = &ES->SectionData;
109 cerr << "FIXME: This code needs to be updated for changes in the "
110 << "CodeEmitter interfaces. In particular, this should set "
111 << "BufferBegin/BufferEnd/CurBufferPtr, not deal with OutBuffer!";
114 // Upgrade the section alignment if required.
115 if (ES->Align < Align) ES->Align = Align;
117 // Add padding zeros to the end of the buffer to make sure that the
118 // function will start on the correct byte alignment within the section.
119 OutputBuffer OB(*OutBuffer,
120 TM.getTargetData()->getPointerSizeInBits() == 64,
121 TM.getTargetData()->isLittleEndian());
123 FnStart = OutBuffer->size();
126 /// finishFunction - This callback is invoked after the function is completely
128 bool ELFCodeEmitter::finishFunction(MachineFunction &F) {
129 // We now know the size of the function, add a symbol to represent it.
130 ELFWriter::ELFSym FnSym(F.getFunction());
132 // Figure out the binding (linkage) of the symbol.
133 switch (F.getFunction()->getLinkage()) {
135 // appending linkage is illegal for functions.
136 assert(0 && "Unknown linkage type!");
137 case GlobalValue::ExternalLinkage:
138 FnSym.SetBind(ELFWriter::ELFSym::STB_GLOBAL);
140 case GlobalValue::LinkOnceLinkage:
141 case GlobalValue::WeakLinkage:
142 FnSym.SetBind(ELFWriter::ELFSym::STB_WEAK);
144 case GlobalValue::InternalLinkage:
145 FnSym.SetBind(ELFWriter::ELFSym::STB_LOCAL);
149 ES->Size = OutBuffer->size();
151 FnSym.SetType(ELFWriter::ELFSym::STT_FUNC);
152 FnSym.SectionIdx = ES->SectionIdx;
153 FnSym.Value = FnStart; // Value = Offset from start of Section.
154 FnSym.Size = OutBuffer->size()-FnStart;
156 // Finally, add it to the symtab.
157 EW.SymbolTable.push_back(FnSym);
161 //===----------------------------------------------------------------------===//
162 // ELFWriter Implementation
163 //===----------------------------------------------------------------------===//
165 ELFWriter::ELFWriter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) {
166 e_flags = 0; // e_flags defaults to 0, no flags.
168 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
169 isLittleEndian = TM.getTargetData()->isLittleEndian();
171 // Create the machine code emitter object for this target.
172 MCE = new ELFCodeEmitter(*this);
176 ELFWriter::~ELFWriter() {
180 // doInitialization - Emit the file header and all of the global variables for
181 // the module to the ELF file.
182 bool ELFWriter::doInitialization(Module &M) {
183 Mang = new Mangler(M);
185 // Local alias to shortenify coming code.
186 std::vector<unsigned char> &FH = FileHeader;
187 OutputBuffer FHOut(FH, is64Bit, isLittleEndian);
189 FHOut.outbyte(0x7F); // EI_MAG0
190 FHOut.outbyte('E'); // EI_MAG1
191 FHOut.outbyte('L'); // EI_MAG2
192 FHOut.outbyte('F'); // EI_MAG3
193 FHOut.outbyte(is64Bit ? 2 : 1); // EI_CLASS
194 FHOut.outbyte(isLittleEndian ? 1 : 2); // EI_DATA
195 FHOut.outbyte(1); // EI_VERSION
196 FH.resize(16); // EI_PAD up to 16 bytes.
198 // This should change for shared objects.
199 FHOut.outhalf(1); // e_type = ET_REL
200 FHOut.outword(TM.getELFWriterInfo()->getEMachine()); // target-defined
201 FHOut.outword(1); // e_version = 1
202 FHOut.outaddr(0); // e_entry = 0 -> no entry point in .o file
203 FHOut.outaddr(0); // e_phoff = 0 -> no program header for .o
205 ELFHeader_e_shoff_Offset = FH.size();
206 FHOut.outaddr(0); // e_shoff
207 FHOut.outword(e_flags); // e_flags = whatever the target wants
209 FHOut.outhalf(is64Bit ? 64 : 52); // e_ehsize = ELF header size
210 FHOut.outhalf(0); // e_phentsize = prog header entry size
211 FHOut.outhalf(0); // e_phnum = # prog header entries = 0
212 FHOut.outhalf(is64Bit ? 64 : 40); // e_shentsize = sect hdr entry size
215 ELFHeader_e_shnum_Offset = FH.size();
216 FHOut.outhalf(0); // e_shnum = # of section header ents
217 ELFHeader_e_shstrndx_Offset = FH.size();
218 FHOut.outhalf(0); // e_shstrndx = Section # of '.shstrtab'
220 // Add the null section, which is required to be first in the file.
221 getSection("", 0, 0);
223 // Start up the symbol table. The first entry in the symtab is the null
225 SymbolTable.push_back(ELFSym(0));
230 void ELFWriter::EmitGlobal(GlobalVariable *GV) {
231 // If this is an external global, emit it now. TODO: Note that it would be
232 // better to ignore the symbol here and only add it to the symbol table if
234 if (!GV->hasInitializer()) {
235 ELFSym ExternalSym(GV);
236 ExternalSym.SetBind(ELFSym::STB_GLOBAL);
237 ExternalSym.SetType(ELFSym::STT_NOTYPE);
238 ExternalSym.SectionIdx = ELFSection::SHN_UNDEF;
239 SymbolTable.push_back(ExternalSym);
243 const Type *GVType = (const Type*)GV->getType();
244 unsigned Align = TM.getTargetData()->getTypeAlignmentPref(GVType);
245 unsigned Size = TM.getTargetData()->getTypeSize(GVType);
247 // If this global has a zero initializer, it is part of the .bss or common
249 if (GV->getInitializer()->isNullValue()) {
250 // If this global is part of the common block, add it now. Variables are
251 // part of the common block if they are zero initialized and allowed to be
252 // merged with other symbols.
253 if (GV->hasLinkOnceLinkage() || GV->hasWeakLinkage()) {
254 ELFSym CommonSym(GV);
255 // Value for common symbols is the alignment required.
256 CommonSym.Value = Align;
257 CommonSym.Size = Size;
258 CommonSym.SetBind(ELFSym::STB_GLOBAL);
259 CommonSym.SetType(ELFSym::STT_OBJECT);
260 // TODO SOMEDAY: add ELF visibility.
261 CommonSym.SectionIdx = ELFSection::SHN_COMMON;
262 SymbolTable.push_back(CommonSym);
266 // Otherwise, this symbol is part of the .bss section. Emit it now.
268 // Handle alignment. Ensure section is aligned at least as much as required
270 ELFSection &BSSSection = getBSSSection();
271 BSSSection.Align = std::max(BSSSection.Align, Align);
273 // Within the section, emit enough virtual padding to get us to an alignment
276 BSSSection.Size = (BSSSection.Size + Align - 1) & ~(Align-1);
279 BSSSym.Value = BSSSection.Size;
281 BSSSym.SetType(ELFSym::STT_OBJECT);
283 switch (GV->getLinkage()) {
284 default: // weak/linkonce handled above
285 assert(0 && "Unexpected linkage type!");
286 case GlobalValue::AppendingLinkage: // FIXME: This should be improved!
287 case GlobalValue::ExternalLinkage:
288 BSSSym.SetBind(ELFSym::STB_GLOBAL);
290 case GlobalValue::InternalLinkage:
291 BSSSym.SetBind(ELFSym::STB_LOCAL);
295 // Set the idx of the .bss section
296 BSSSym.SectionIdx = BSSSection.SectionIdx;
297 SymbolTable.push_back(BSSSym);
299 // Reserve space in the .bss section for this symbol.
300 BSSSection.Size += Size;
304 // FIXME: handle .rodata
305 //assert(!GV->isConstant() && "unimp");
307 // FIXME: handle .data
308 //assert(0 && "unimp");
312 bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
313 // Nothing to do here, this is all done through the MCE object above.
317 /// doFinalization - Now that the module has been completely processed, emit
318 /// the ELF file to 'O'.
319 bool ELFWriter::doFinalization(Module &M) {
320 // Okay, the ELF header and .text sections have been completed, build the
321 // .data, .bss, and "common" sections next.
322 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
326 // Emit the symbol table now, if non-empty.
329 // FIXME: Emit the relocations now.
331 // Emit the string table for the sections in the ELF file we have.
332 EmitSectionTableStringTable();
334 // Emit the sections to the .o file, and emit the section table for the file.
335 OutputSectionsAndSectionTable();
337 // We are done with the abstract symbols.
341 // Release the name mangler object.
342 delete Mang; Mang = 0;
346 /// EmitSymbolTable - If the current symbol table is non-empty, emit the string
347 /// table for it and then the symbol table itself.
348 void ELFWriter::EmitSymbolTable() {
349 if (SymbolTable.size() == 1) return; // Only the null entry.
351 // FIXME: compact all local symbols to the start of the symtab.
352 unsigned FirstNonLocalSymbol = 1;
354 ELFSection &StrTab = getSection(".strtab", ELFSection::SHT_STRTAB, 0);
357 DataBuffer &StrTabBuf = StrTab.SectionData;
358 OutputBuffer StrTabOut(StrTabBuf, is64Bit, isLittleEndian);
360 // Set the zero'th symbol to a null byte, as required.
361 StrTabOut.outbyte(0);
362 SymbolTable[0].NameIdx = 0;
364 for (unsigned i = 1, e = SymbolTable.size(); i != e; ++i) {
365 // Use the name mangler to uniquify the LLVM symbol.
366 std::string Name = Mang->getValueName(SymbolTable[i].GV);
369 SymbolTable[i].NameIdx = 0;
371 SymbolTable[i].NameIdx = Index;
373 // Add the name to the output buffer, including the null terminator.
374 StrTabBuf.insert(StrTabBuf.end(), Name.begin(), Name.end());
376 // Add a null terminator.
377 StrTabBuf.push_back(0);
379 // Keep track of the number of bytes emitted to this section.
380 Index += Name.size()+1;
383 assert(Index == StrTabBuf.size());
386 // Now that we have emitted the string table and know the offset into the
387 // string table of each symbol, emit the symbol table itself.
388 ELFSection &SymTab = getSection(".symtab", ELFSection::SHT_SYMTAB, 0);
389 SymTab.Align = is64Bit ? 8 : 4;
390 SymTab.Link = SymTab.SectionIdx; // Section Index of .strtab.
391 SymTab.Info = FirstNonLocalSymbol; // First non-STB_LOCAL symbol.
392 SymTab.EntSize = 16; // Size of each symtab entry. FIXME: wrong for ELF64
393 DataBuffer &SymTabBuf = SymTab.SectionData;
394 OutputBuffer SymTabOut(SymTabBuf, is64Bit, isLittleEndian);
396 if (!is64Bit) { // 32-bit and 64-bit formats are shuffled a bit.
397 for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i) {
398 ELFSym &Sym = SymbolTable[i];
399 SymTabOut.outword(Sym.NameIdx);
400 SymTabOut.outaddr32(Sym.Value);
401 SymTabOut.outword(Sym.Size);
402 SymTabOut.outbyte(Sym.Info);
403 SymTabOut.outbyte(Sym.Other);
404 SymTabOut.outhalf(Sym.SectionIdx);
407 for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i) {
408 ELFSym &Sym = SymbolTable[i];
409 SymTabOut.outword(Sym.NameIdx);
410 SymTabOut.outbyte(Sym.Info);
411 SymTabOut.outbyte(Sym.Other);
412 SymTabOut.outhalf(Sym.SectionIdx);
413 SymTabOut.outaddr64(Sym.Value);
414 SymTabOut.outxword(Sym.Size);
418 SymTab.Size = SymTabBuf.size();
421 /// EmitSectionTableStringTable - This method adds and emits a section for the
422 /// ELF Section Table string table: the string table that holds all of the
424 void ELFWriter::EmitSectionTableStringTable() {
425 // First step: add the section for the string table to the list of sections:
426 ELFSection &SHStrTab = getSection(".shstrtab", ELFSection::SHT_STRTAB, 0);
428 // Now that we know which section number is the .shstrtab section, update the
429 // e_shstrndx entry in the ELF header.
430 OutputBuffer FHOut(FileHeader, is64Bit, isLittleEndian);
431 FHOut.fixhalf(SHStrTab.SectionIdx, ELFHeader_e_shstrndx_Offset);
433 // Set the NameIdx of each section in the string table and emit the bytes for
436 DataBuffer &Buf = SHStrTab.SectionData;
438 for (std::list<ELFSection>::iterator I = SectionList.begin(),
439 E = SectionList.end(); I != E; ++I) {
440 // Set the index into the table. Note if we have lots of entries with
441 // common suffixes, we could memoize them here if we cared.
444 // Add the name to the output buffer, including the null terminator.
445 Buf.insert(Buf.end(), I->Name.begin(), I->Name.end());
447 // Add a null terminator.
450 // Keep track of the number of bytes emitted to this section.
451 Index += I->Name.size()+1;
454 // Set the size of .shstrtab now that we know what it is.
455 assert(Index == Buf.size());
456 SHStrTab.Size = Index;
459 /// OutputSectionsAndSectionTable - Now that we have constructed the file header
460 /// and all of the sections, emit these to the ostream destination and emit the
462 void ELFWriter::OutputSectionsAndSectionTable() {
463 // Pass #1: Compute the file offset for each section.
464 size_t FileOff = FileHeader.size(); // File header first.
466 // Emit all of the section data in order.
467 for (std::list<ELFSection>::iterator I = SectionList.begin(),
468 E = SectionList.end(); I != E; ++I) {
469 // Align FileOff to whatever the alignment restrictions of the section are.
471 FileOff = (FileOff+I->Align-1) & ~(I->Align-1);
473 FileOff += I->SectionData.size();
476 // Align Section Header.
477 unsigned TableAlign = is64Bit ? 8 : 4;
478 FileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
480 // Now that we know where all of the sections will be emitted, set the e_shnum
481 // entry in the ELF header.
482 OutputBuffer FHOut(FileHeader, is64Bit, isLittleEndian);
483 FHOut.fixhalf(NumSections, ELFHeader_e_shnum_Offset);
485 // Now that we know the offset in the file of the section table, update the
486 // e_shoff address in the ELF header.
487 FHOut.fixaddr(FileOff, ELFHeader_e_shoff_Offset);
489 // Now that we know all of the data in the file header, emit it and all of the
491 O.write((char*)&FileHeader[0], FileHeader.size());
492 FileOff = FileHeader.size();
493 DataBuffer().swap(FileHeader);
496 OutputBuffer TableOut(Table, is64Bit, isLittleEndian);
498 // Emit all of the section data and build the section table itself.
499 while (!SectionList.empty()) {
500 const ELFSection &S = *SectionList.begin();
502 // Align FileOff to whatever the alignment restrictions of the section are.
504 for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
505 FileOff != NewFileOff; ++FileOff)
507 O.write((char*)&S.SectionData[0], S.SectionData.size());
508 FileOff += S.SectionData.size();
510 TableOut.outword(S.NameIdx); // sh_name - Symbol table name idx
511 TableOut.outword(S.Type); // sh_type - Section contents & semantics
512 TableOut.outword(S.Flags); // sh_flags - Section flags.
513 TableOut.outaddr(S.Addr); // sh_addr - The mem addr this section is in.
514 TableOut.outaddr(S.Offset); // sh_offset - Offset from the file start.
515 TableOut.outword(S.Size); // sh_size - The section size.
516 TableOut.outword(S.Link); // sh_link - Section header table index link.
517 TableOut.outword(S.Info); // sh_info - Auxillary information.
518 TableOut.outword(S.Align); // sh_addralign - Alignment of section.
519 TableOut.outword(S.EntSize); // sh_entsize - Size of entries in the section
521 SectionList.pop_front();
524 // Align output for the section table.
525 for (size_t NewFileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
526 FileOff != NewFileOff; ++FileOff)
529 // Emit the section table itself.
530 O.write((char*)&Table[0], Table.size());