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/TargetMachine.h"
40 #include "llvm/Support/Mangler.h"
41 #include "llvm/Support/OutputBuffer.h"
42 #include "llvm/Support/Streams.h"
45 //===----------------------------------------------------------------------===//
46 // ELFCodeEmitter Implementation
47 //===----------------------------------------------------------------------===//
50 /// ELFCodeEmitter - This class is used by the ELFWriter to emit the code for
51 /// functions to the ELF file.
52 class ELFCodeEmitter : public MachineCodeEmitter {
55 ELFWriter::ELFSection *ES; // Section to write to.
56 std::vector<unsigned char> *OutBuffer;
59 ELFCodeEmitter(ELFWriter &ew) : EW(ew), TM(EW.TM), OutBuffer(0) {}
61 void startFunction(MachineFunction &F);
62 bool finishFunction(MachineFunction &F);
64 void addRelocation(const MachineRelocation &MR) {
65 assert(0 && "relo not handled yet!");
68 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
71 virtual intptr_t getConstantPoolEntryAddress(unsigned Index) const {
72 assert(0 && "CP not implementated yet!");
75 virtual intptr_t getJumpTableEntryAddress(unsigned Index) const {
76 assert(0 && "JT not implementated yet!");
80 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
81 assert(0 && "JT not implementated yet!");
85 /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
86 void startFunctionStub(unsigned StubSize, unsigned Alignment = 1) {
87 assert(0 && "JIT specific function called!");
90 void *finishFunctionStub(const Function *F) {
91 assert(0 && "JIT specific function called!");
98 /// startFunction - This callback is invoked when a new machine function is
99 /// about to be emitted.
100 void ELFCodeEmitter::startFunction(MachineFunction &F) {
101 // Align the output buffer to the appropriate alignment.
102 unsigned Align = 16; // FIXME: GENERICIZE!!
103 // Get the ELF Section that this function belongs in.
104 ES = &EW.getSection(".text", ELFWriter::ELFSection::SHT_PROGBITS,
105 ELFWriter::ELFSection::SHF_EXECINSTR |
106 ELFWriter::ELFSection::SHF_ALLOC);
107 OutBuffer = &ES->SectionData;
108 cerr << "FIXME: This code needs to be updated for changes in the "
109 << "CodeEmitter interfaces. In particular, this should set "
110 << "BufferBegin/BufferEnd/CurBufferPtr, not deal with OutBuffer!";
113 // Upgrade the section alignment if required.
114 if (ES->Align < Align) ES->Align = Align;
116 // Add padding zeros to the end of the buffer to make sure that the
117 // function will start on the correct byte alignment within the section.
118 OutputBuffer OB(TM, *OutBuffer);
120 FnStart = OutBuffer->size();
123 /// finishFunction - This callback is invoked after the function is completely
125 bool ELFCodeEmitter::finishFunction(MachineFunction &F) {
126 // We now know the size of the function, add a symbol to represent it.
127 ELFWriter::ELFSym FnSym(F.getFunction());
129 // Figure out the binding (linkage) of the symbol.
130 switch (F.getFunction()->getLinkage()) {
132 // appending linkage is illegal for functions.
133 assert(0 && "Unknown linkage type!");
134 case GlobalValue::ExternalLinkage:
135 FnSym.SetBind(ELFWriter::ELFSym::STB_GLOBAL);
137 case GlobalValue::LinkOnceLinkage:
138 case GlobalValue::WeakLinkage:
139 FnSym.SetBind(ELFWriter::ELFSym::STB_WEAK);
141 case GlobalValue::InternalLinkage:
142 FnSym.SetBind(ELFWriter::ELFSym::STB_LOCAL);
146 ES->Size = OutBuffer->size();
148 FnSym.SetType(ELFWriter::ELFSym::STT_FUNC);
149 FnSym.SectionIdx = ES->SectionIdx;
150 FnSym.Value = FnStart; // Value = Offset from start of Section.
151 FnSym.Size = OutBuffer->size()-FnStart;
153 // Finally, add it to the symtab.
154 EW.SymbolTable.push_back(FnSym);
158 //===----------------------------------------------------------------------===//
159 // ELFWriter Implementation
160 //===----------------------------------------------------------------------===//
162 ELFWriter::ELFWriter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) {
163 e_machine = 0; // e_machine defaults to 'No Machine'
164 e_flags = 0; // e_flags defaults to 0, no flags.
166 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
167 isLittleEndian = TM.getTargetData()->isLittleEndian();
169 // Create the machine code emitter object for this target.
170 MCE = new ELFCodeEmitter(*this);
174 ELFWriter::~ELFWriter() {
178 // doInitialization - Emit the file header and all of the global variables for
179 // the module to the ELF file.
180 bool ELFWriter::doInitialization(Module &M) {
181 Mang = new Mangler(M);
183 // Local alias to shortenify coming code.
184 std::vector<unsigned char> &FH = FileHeader;
185 OutputBuffer FHOut(TM, FH);
187 FHOut.outbyte(0x7F); // EI_MAG0
188 FHOut.outbyte('E'); // EI_MAG1
189 FHOut.outbyte('L'); // EI_MAG2
190 FHOut.outbyte('F'); // EI_MAG3
191 FHOut.outbyte(is64Bit ? 2 : 1); // EI_CLASS
192 FHOut.outbyte(isLittleEndian ? 1 : 2); // EI_DATA
193 FHOut.outbyte(1); // EI_VERSION
194 FH.resize(16); // EI_PAD up to 16 bytes.
196 // This should change for shared objects.
197 FHOut.outhalf(1); // e_type = ET_REL
198 FHOut.outhalf(e_machine); // e_machine = whatever the target wants
199 FHOut.outword(1); // e_version = 1
200 FHOut.outaddr(0); // e_entry = 0 -> no entry point in .o file
201 FHOut.outaddr(0); // e_phoff = 0 -> no program header for .o
203 ELFHeader_e_shoff_Offset = FH.size();
204 FHOut.outaddr(0); // e_shoff
205 FHOut.outword(e_flags); // e_flags = whatever the target wants
207 FHOut.outhalf(is64Bit ? 64 : 52); // e_ehsize = ELF header size
208 FHOut.outhalf(0); // e_phentsize = prog header entry size
209 FHOut.outhalf(0); // e_phnum = # prog header entries = 0
210 FHOut.outhalf(is64Bit ? 64 : 40); // e_shentsize = sect hdr entry size
213 ELFHeader_e_shnum_Offset = FH.size();
214 FHOut.outhalf(0); // e_shnum = # of section header ents
215 ELFHeader_e_shstrndx_Offset = FH.size();
216 FHOut.outhalf(0); // e_shstrndx = Section # of '.shstrtab'
218 // Add the null section, which is required to be first in the file.
219 getSection("", 0, 0);
221 // Start up the symbol table. The first entry in the symtab is the null
223 SymbolTable.push_back(ELFSym(0));
228 void ELFWriter::EmitGlobal(GlobalVariable *GV) {
229 // If this is an external global, emit it now. TODO: Note that it would be
230 // better to ignore the symbol here and only add it to the symbol table if
232 if (!GV->hasInitializer()) {
233 ELFSym ExternalSym(GV);
234 ExternalSym.SetBind(ELFSym::STB_GLOBAL);
235 ExternalSym.SetType(ELFSym::STT_NOTYPE);
236 ExternalSym.SectionIdx = ELFSection::SHN_UNDEF;
237 SymbolTable.push_back(ExternalSym);
241 const Type *GVType = (const Type*)GV->getType();
242 unsigned Align = TM.getTargetData()->getTypeAlignment(GVType);
243 unsigned Size = TM.getTargetData()->getTypeSize(GVType);
245 // If this global has a zero initializer, it is part of the .bss or common
247 if (GV->getInitializer()->isNullValue()) {
248 // If this global is part of the common block, add it now. Variables are
249 // part of the common block if they are zero initialized and allowed to be
250 // merged with other symbols.
251 if (GV->hasLinkOnceLinkage() || GV->hasWeakLinkage()) {
252 ELFSym CommonSym(GV);
253 // Value for common symbols is the alignment required.
254 CommonSym.Value = Align;
255 CommonSym.Size = Size;
256 CommonSym.SetBind(ELFSym::STB_GLOBAL);
257 CommonSym.SetType(ELFSym::STT_OBJECT);
258 // TODO SOMEDAY: add ELF visibility.
259 CommonSym.SectionIdx = ELFSection::SHN_COMMON;
260 SymbolTable.push_back(CommonSym);
264 // Otherwise, this symbol is part of the .bss section. Emit it now.
266 // Handle alignment. Ensure section is aligned at least as much as required
268 ELFSection &BSSSection = getBSSSection();
269 BSSSection.Align = std::max(BSSSection.Align, Align);
271 // Within the section, emit enough virtual padding to get us to an alignment
274 BSSSection.Size = (BSSSection.Size + Align - 1) & ~(Align-1);
277 BSSSym.Value = BSSSection.Size;
279 BSSSym.SetType(ELFSym::STT_OBJECT);
281 switch (GV->getLinkage()) {
282 default: // weak/linkonce handled above
283 assert(0 && "Unexpected linkage type!");
284 case GlobalValue::AppendingLinkage: // FIXME: This should be improved!
285 case GlobalValue::ExternalLinkage:
286 BSSSym.SetBind(ELFSym::STB_GLOBAL);
288 case GlobalValue::InternalLinkage:
289 BSSSym.SetBind(ELFSym::STB_LOCAL);
293 // Set the idx of the .bss section
294 BSSSym.SectionIdx = BSSSection.SectionIdx;
295 SymbolTable.push_back(BSSSym);
297 // Reserve space in the .bss section for this symbol.
298 BSSSection.Size += Size;
302 // FIXME: handle .rodata
303 //assert(!GV->isConstant() && "unimp");
305 // FIXME: handle .data
306 //assert(0 && "unimp");
310 bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
311 // Nothing to do here, this is all done through the MCE object above.
315 /// doFinalization - Now that the module has been completely processed, emit
316 /// the ELF file to 'O'.
317 bool ELFWriter::doFinalization(Module &M) {
318 // Okay, the ELF header and .text sections have been completed, build the
319 // .data, .bss, and "common" sections next.
320 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
324 // Emit the symbol table now, if non-empty.
327 // FIXME: Emit the relocations now.
329 // Emit the string table for the sections in the ELF file we have.
330 EmitSectionTableStringTable();
332 // Emit the sections to the .o file, and emit the section table for the file.
333 OutputSectionsAndSectionTable();
335 // We are done with the abstract symbols.
339 // Release the name mangler object.
340 delete Mang; Mang = 0;
344 /// EmitSymbolTable - If the current symbol table is non-empty, emit the string
345 /// table for it and then the symbol table itself.
346 void ELFWriter::EmitSymbolTable() {
347 if (SymbolTable.size() == 1) return; // Only the null entry.
349 // FIXME: compact all local symbols to the start of the symtab.
350 unsigned FirstNonLocalSymbol = 1;
352 ELFSection &StrTab = getSection(".strtab", ELFSection::SHT_STRTAB, 0);
355 DataBuffer &StrTabBuf = StrTab.SectionData;
356 OutputBuffer StrTabOut(TM, StrTabBuf);
358 // Set the zero'th symbol to a null byte, as required.
359 StrTabOut.outbyte(0);
360 SymbolTable[0].NameIdx = 0;
362 for (unsigned i = 1, e = SymbolTable.size(); i != e; ++i) {
363 // Use the name mangler to uniquify the LLVM symbol.
364 std::string Name = Mang->getValueName(SymbolTable[i].GV);
367 SymbolTable[i].NameIdx = 0;
369 SymbolTable[i].NameIdx = Index;
371 // Add the name to the output buffer, including the null terminator.
372 StrTabBuf.insert(StrTabBuf.end(), Name.begin(), Name.end());
374 // Add a null terminator.
375 StrTabBuf.push_back(0);
377 // Keep track of the number of bytes emitted to this section.
378 Index += Name.size()+1;
381 assert(Index == StrTabBuf.size());
384 // Now that we have emitted the string table and know the offset into the
385 // string table of each symbol, emit the symbol table itself.
386 ELFSection &SymTab = getSection(".symtab", ELFSection::SHT_SYMTAB, 0);
387 SymTab.Align = is64Bit ? 8 : 4;
388 SymTab.Link = SymTab.SectionIdx; // Section Index of .strtab.
389 SymTab.Info = FirstNonLocalSymbol; // First non-STB_LOCAL symbol.
390 SymTab.EntSize = 16; // Size of each symtab entry. FIXME: wrong for ELF64
391 DataBuffer &SymTabBuf = SymTab.SectionData;
392 OutputBuffer SymTabOut(TM, SymTabBuf);
394 if (!is64Bit) { // 32-bit and 64-bit formats are shuffled a bit.
395 for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i) {
396 ELFSym &Sym = SymbolTable[i];
397 SymTabOut.outword(Sym.NameIdx);
398 SymTabOut.outaddr32(Sym.Value);
399 SymTabOut.outword(Sym.Size);
400 SymTabOut.outbyte(Sym.Info);
401 SymTabOut.outbyte(Sym.Other);
402 SymTabOut.outhalf(Sym.SectionIdx);
405 for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i) {
406 ELFSym &Sym = SymbolTable[i];
407 SymTabOut.outword(Sym.NameIdx);
408 SymTabOut.outbyte(Sym.Info);
409 SymTabOut.outbyte(Sym.Other);
410 SymTabOut.outhalf(Sym.SectionIdx);
411 SymTabOut.outaddr64(Sym.Value);
412 SymTabOut.outxword(Sym.Size);
416 SymTab.Size = SymTabBuf.size();
419 /// EmitSectionTableStringTable - This method adds and emits a section for the
420 /// ELF Section Table string table: the string table that holds all of the
422 void ELFWriter::EmitSectionTableStringTable() {
423 // First step: add the section for the string table to the list of sections:
424 ELFSection &SHStrTab = getSection(".shstrtab", ELFSection::SHT_STRTAB, 0);
426 // Now that we know which section number is the .shstrtab section, update the
427 // e_shstrndx entry in the ELF header.
428 OutputBuffer FHOut(TM, FileHeader);
429 FHOut.fixhalf(SHStrTab.SectionIdx, ELFHeader_e_shstrndx_Offset);
431 // Set the NameIdx of each section in the string table and emit the bytes for
434 DataBuffer &Buf = SHStrTab.SectionData;
436 for (std::list<ELFSection>::iterator I = SectionList.begin(),
437 E = SectionList.end(); I != E; ++I) {
438 // Set the index into the table. Note if we have lots of entries with
439 // common suffixes, we could memoize them here if we cared.
442 // Add the name to the output buffer, including the null terminator.
443 Buf.insert(Buf.end(), I->Name.begin(), I->Name.end());
445 // Add a null terminator.
448 // Keep track of the number of bytes emitted to this section.
449 Index += I->Name.size()+1;
452 // Set the size of .shstrtab now that we know what it is.
453 assert(Index == Buf.size());
454 SHStrTab.Size = Index;
457 /// OutputSectionsAndSectionTable - Now that we have constructed the file header
458 /// and all of the sections, emit these to the ostream destination and emit the
460 void ELFWriter::OutputSectionsAndSectionTable() {
461 // Pass #1: Compute the file offset for each section.
462 size_t FileOff = FileHeader.size(); // File header first.
464 // Emit all of the section data in order.
465 for (std::list<ELFSection>::iterator I = SectionList.begin(),
466 E = SectionList.end(); I != E; ++I) {
467 // Align FileOff to whatever the alignment restrictions of the section are.
469 FileOff = (FileOff+I->Align-1) & ~(I->Align-1);
471 FileOff += I->SectionData.size();
474 // Align Section Header.
475 unsigned TableAlign = is64Bit ? 8 : 4;
476 FileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
478 // Now that we know where all of the sections will be emitted, set the e_shnum
479 // entry in the ELF header.
480 OutputBuffer FHOut(TM, FileHeader);
481 FHOut.fixhalf(NumSections, ELFHeader_e_shnum_Offset);
483 // Now that we know the offset in the file of the section table, update the
484 // e_shoff address in the ELF header.
485 FHOut.fixaddr(FileOff, ELFHeader_e_shoff_Offset);
487 // Now that we know all of the data in the file header, emit it and all of the
489 O.write((char*)&FileHeader[0], FileHeader.size());
490 FileOff = FileHeader.size();
491 DataBuffer().swap(FileHeader);
494 OutputBuffer TableOut(TM, Table);
496 // Emit all of the section data and build the section table itself.
497 while (!SectionList.empty()) {
498 const ELFSection &S = *SectionList.begin();
500 // Align FileOff to whatever the alignment restrictions of the section are.
502 for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
503 FileOff != NewFileOff; ++FileOff)
505 O.write((char*)&S.SectionData[0], S.SectionData.size());
506 FileOff += S.SectionData.size();
508 TableOut.outword(S.NameIdx); // sh_name - Symbol table name idx
509 TableOut.outword(S.Type); // sh_type - Section contents & semantics
510 TableOut.outword(S.Flags); // sh_flags - Section flags.
511 TableOut.outaddr(S.Addr); // sh_addr - The mem addr this section is in.
512 TableOut.outaddr(S.Offset); // sh_offset - Offset from the file start.
513 TableOut.outword(S.Size); // sh_size - The section size.
514 TableOut.outword(S.Link); // sh_link - Section header table index link.
515 TableOut.outword(S.Info); // sh_info - Auxillary information.
516 TableOut.outword(S.Align); // sh_addralign - Alignment of section.
517 TableOut.outword(S.EntSize); // sh_entsize - Size of entries in the section
519 SectionList.pop_front();
522 // Align output for the section table.
523 for (size_t NewFileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
524 FileOff != NewFileOff; ++FileOff)
527 // Emit the section table itself.
528 O.write((char*)&Table[0], Table.size());