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/Target/TargetObjInfo.h"
41 #include "llvm/Support/Mangler.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 {
54 ELFWriter::ELFSection *ES; // Section to write to.
55 std::vector<unsigned char> *OutBuffer;
58 /// Target machine description.
62 /// Target object writer info.
64 const TargetObjInfo *TOI;
66 ELFCodeEmitter(ELFWriter &ew, TargetMachine &tm)
67 : EW(ew), OutBuffer(0), TM(tm) {
68 // Create the target object info object for this target.
69 TOI = TM.getTargetObjInfo();
72 void startFunction(MachineFunction &F);
73 bool finishFunction(MachineFunction &F);
75 void addRelocation(const MachineRelocation &MR) {
76 assert(0 && "relo not handled yet!");
79 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
82 virtual intptr_t getConstantPoolEntryAddress(unsigned Index) const {
83 assert(0 && "CP not implementated yet!");
86 virtual intptr_t getJumpTableEntryAddress(unsigned Index) const {
87 assert(0 && "JT not implementated yet!");
91 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
92 assert(0 && "JT not implementated yet!");
96 /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
97 void startFunctionStub(unsigned StubSize, unsigned Alignment = 1) {
98 assert(0 && "JIT specific function called!");
101 void *finishFunctionStub(const Function *F) {
102 assert(0 && "JIT specific function called!");
109 /// startFunction - This callback is invoked when a new machine function is
110 /// about to be emitted.
111 void ELFCodeEmitter::startFunction(MachineFunction &F) {
112 // Align the output buffer to the appropriate alignment.
113 unsigned Align = 16; // FIXME: GENERICIZE!!
114 // Get the ELF Section that this function belongs in.
115 ES = &EW.getSection(".text", ELFWriter::ELFSection::SHT_PROGBITS,
116 ELFWriter::ELFSection::SHF_EXECINSTR |
117 ELFWriter::ELFSection::SHF_ALLOC);
118 OutBuffer = &ES->SectionData;
119 cerr << "FIXME: This code needs to be updated for changes in the"
120 << " CodeEmitter interfaces. In particular, this should set "
121 << "BufferBegin/BufferEnd/CurBufferPtr, not deal with OutBuffer!";
124 // Upgrade the section alignment if required.
125 if (ES->Align < Align) ES->Align = Align;
127 // Add padding zeros to the end of the buffer to make sure that the
128 // function will start on the correct byte alignment within the section.
129 TOI->align(*OutBuffer, Align);
131 FnStart = OutBuffer->size();
134 /// finishFunction - This callback is invoked after the function is completely
136 bool ELFCodeEmitter::finishFunction(MachineFunction &F) {
137 // We now know the size of the function, add a symbol to represent it.
138 ELFWriter::ELFSym FnSym(F.getFunction());
140 // Figure out the binding (linkage) of the symbol.
141 switch (F.getFunction()->getLinkage()) {
143 // appending linkage is illegal for functions.
144 assert(0 && "Unknown linkage type!");
145 case GlobalValue::ExternalLinkage:
146 FnSym.SetBind(ELFWriter::ELFSym::STB_GLOBAL);
148 case GlobalValue::LinkOnceLinkage:
149 case GlobalValue::WeakLinkage:
150 FnSym.SetBind(ELFWriter::ELFSym::STB_WEAK);
152 case GlobalValue::InternalLinkage:
153 FnSym.SetBind(ELFWriter::ELFSym::STB_LOCAL);
157 ES->Size = OutBuffer->size();
159 FnSym.SetType(ELFWriter::ELFSym::STT_FUNC);
160 FnSym.SectionIdx = ES->SectionIdx;
161 FnSym.Value = FnStart; // Value = Offset from start of Section.
162 FnSym.Size = OutBuffer->size()-FnStart;
164 // Finally, add it to the symtab.
165 EW.SymbolTable.push_back(FnSym);
169 //===----------------------------------------------------------------------===//
170 // ELFWriter Implementation
171 //===----------------------------------------------------------------------===//
173 ELFWriter::ELFWriter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) {
174 e_machine = 0; // e_machine defaults to 'No Machine'
175 e_flags = 0; // e_flags defaults to 0, no flags.
177 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
178 isLittleEndian = TM.getTargetData()->isLittleEndian();
180 // Create the machine code emitter object for this target.
181 MCE = new ELFCodeEmitter(*this, TM);
184 // Create the target object info object for this target.
185 TOI = TM.getTargetObjInfo();
188 ELFWriter::~ELFWriter() {
192 // doInitialization - Emit the file header and all of the global variables for
193 // the module to the ELF file.
194 bool ELFWriter::doInitialization(Module &M) {
195 Mang = new Mangler(M);
197 // Local alias to shortenify coming code.
198 std::vector<unsigned char> &FH = FileHeader;
200 TOI->outbyte(FH, 0x7F); // EI_MAG0
201 TOI->outbyte(FH, 'E'); // EI_MAG1
202 TOI->outbyte(FH, 'L'); // EI_MAG2
203 TOI->outbyte(FH, 'F'); // EI_MAG3
204 TOI->outbyte(FH, is64Bit ? 2 : 1); // EI_CLASS
205 TOI->outbyte(FH, isLittleEndian ? 1 : 2); // EI_DATA
206 TOI->outbyte(FH, 1); // EI_VERSION
207 FH.resize(16); // EI_PAD up to 16 bytes.
209 // This should change for shared objects.
210 TOI->outhalf(FH, 1); // e_type = ET_REL
211 TOI->outhalf(FH, e_machine); // e_machine = whatever the target wants
212 TOI->outword(FH, 1); // e_version = 1
213 TOI->outaddr(FH, 0); // e_entry = 0 -> no entry point in .o file
214 TOI->outaddr(FH, 0); // e_phoff = 0 -> no program header for .o
216 ELFHeader_e_shoff_Offset = FH.size();
217 TOI->outaddr(FH, 0); // e_shoff
218 TOI->outword(FH, e_flags); // e_flags = whatever the target wants
220 TOI->outhalf(FH, is64Bit ? 64 : 52); // e_ehsize = ELF header size
221 TOI->outhalf(FH, 0); // e_phentsize = prog header entry size
222 TOI->outhalf(FH, 0); // e_phnum = # prog header entries=0
223 TOI->outhalf(FH, is64Bit ? 64 : 40); // e_shentsize = sect hdr entry size
226 ELFHeader_e_shnum_Offset = FH.size();
227 TOI->outhalf(FH, 0); // e_shnum = # of section header ents
228 ELFHeader_e_shstrndx_Offset = FH.size();
229 TOI->outhalf(FH, 0); // e_shstrndx = Section # of '.shstrtab'
231 // Add the null section, which is required to be first in the file.
232 getSection("", 0, 0);
234 // Start up the symbol table. The first entry in the symtab is the null
236 SymbolTable.push_back(ELFSym(0));
241 void ELFWriter::EmitGlobal(GlobalVariable *GV) {
242 // If this is an external global, emit it now. TODO: Note that it would be
243 // better to ignore the symbol here and only add it to the symbol table if
245 if (!GV->hasInitializer()) {
246 ELFSym ExternalSym(GV);
247 ExternalSym.SetBind(ELFSym::STB_GLOBAL);
248 ExternalSym.SetType(ELFSym::STT_NOTYPE);
249 ExternalSym.SectionIdx = ELFSection::SHN_UNDEF;
250 SymbolTable.push_back(ExternalSym);
254 const Type *GVType = (const Type*)GV->getType();
255 unsigned Align = TM.getTargetData()->getTypeAlignment(GVType);
256 unsigned Size = TM.getTargetData()->getTypeSize(GVType);
258 // If this global has a zero initializer, it is part of the .bss or common
260 if (GV->getInitializer()->isNullValue()) {
261 // If this global is part of the common block, add it now. Variables are
262 // part of the common block if they are zero initialized and allowed to be
263 // merged with other symbols.
264 if (GV->hasLinkOnceLinkage() || GV->hasWeakLinkage()) {
265 ELFSym CommonSym(GV);
266 // Value for common symbols is the alignment required.
267 CommonSym.Value = Align;
268 CommonSym.Size = Size;
269 CommonSym.SetBind(ELFSym::STB_GLOBAL);
270 CommonSym.SetType(ELFSym::STT_OBJECT);
271 // TODO SOMEDAY: add ELF visibility.
272 CommonSym.SectionIdx = ELFSection::SHN_COMMON;
273 SymbolTable.push_back(CommonSym);
277 // Otherwise, this symbol is part of the .bss section. Emit it now.
279 // Handle alignment. Ensure section is aligned at least as much as required
281 ELFSection &BSSSection = getBSSSection();
282 BSSSection.Align = std::max(BSSSection.Align, Align);
284 // Within the section, emit enough virtual padding to get us to an alignment
287 BSSSection.Size = (BSSSection.Size + Align - 1) & ~(Align-1);
290 BSSSym.Value = BSSSection.Size;
292 BSSSym.SetType(ELFSym::STT_OBJECT);
294 switch (GV->getLinkage()) {
295 default: // weak/linkonce handled above
296 assert(0 && "Unexpected linkage type!");
297 case GlobalValue::AppendingLinkage: // FIXME: This should be improved!
298 case GlobalValue::ExternalLinkage:
299 BSSSym.SetBind(ELFSym::STB_GLOBAL);
301 case GlobalValue::InternalLinkage:
302 BSSSym.SetBind(ELFSym::STB_LOCAL);
306 // Set the idx of the .bss section
307 BSSSym.SectionIdx = BSSSection.SectionIdx;
308 SymbolTable.push_back(BSSSym);
310 // Reserve space in the .bss section for this symbol.
311 BSSSection.Size += Size;
315 // FIXME: handle .rodata
316 //assert(!GV->isConstant() && "unimp");
318 // FIXME: handle .data
319 //assert(0 && "unimp");
323 bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
324 // Nothing to do here, this is all done through the MCE object above.
328 /// doFinalization - Now that the module has been completely processed, emit
329 /// the ELF file to 'O'.
330 bool ELFWriter::doFinalization(Module &M) {
331 // Okay, the ELF header and .text sections have been completed, build the
332 // .data, .bss, and "common" sections next.
333 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
337 // Emit the symbol table now, if non-empty.
340 // FIXME: Emit the relocations now.
342 // Emit the string table for the sections in the ELF file we have.
343 EmitSectionTableStringTable();
345 // Emit the sections to the .o file, and emit the section table for the file.
346 OutputSectionsAndSectionTable();
348 // We are done with the abstract symbols.
352 // Release the name mangler object.
353 delete Mang; Mang = 0;
357 /// EmitSymbolTable - If the current symbol table is non-empty, emit the string
358 /// table for it and then the symbol table itself.
359 void ELFWriter::EmitSymbolTable() {
360 if (SymbolTable.size() == 1) return; // Only the null entry.
362 // FIXME: compact all local symbols to the start of the symtab.
363 unsigned FirstNonLocalSymbol = 1;
365 ELFSection &StrTab = getSection(".strtab", ELFSection::SHT_STRTAB, 0);
368 DataBuffer &StrTabBuf = StrTab.SectionData;
370 // Set the zero'th symbol to a null byte, as required.
371 TOI->outbyte(StrTabBuf, 0);
372 SymbolTable[0].NameIdx = 0;
374 for (unsigned i = 1, e = SymbolTable.size(); i != e; ++i) {
375 // Use the name mangler to uniquify the LLVM symbol.
376 std::string Name = Mang->getValueName(SymbolTable[i].GV);
379 SymbolTable[i].NameIdx = 0;
381 SymbolTable[i].NameIdx = Index;
383 // Add the name to the output buffer, including the null terminator.
384 StrTabBuf.insert(StrTabBuf.end(), Name.begin(), Name.end());
386 // Add a null terminator.
387 StrTabBuf.push_back(0);
389 // Keep track of the number of bytes emitted to this section.
390 Index += Name.size()+1;
393 assert(Index == StrTabBuf.size());
396 // Now that we have emitted the string table and know the offset into the
397 // string table of each symbol, emit the symbol table itself.
398 ELFSection &SymTab = getSection(".symtab", ELFSection::SHT_SYMTAB, 0);
399 SymTab.Align = is64Bit ? 8 : 4;
400 SymTab.Link = SymTab.SectionIdx; // Section Index of .strtab.
401 SymTab.Info = FirstNonLocalSymbol; // First non-STB_LOCAL symbol.
402 SymTab.EntSize = 16; // Size of each symtab entry. FIXME: wrong for ELF64
403 DataBuffer &SymTabBuf = SymTab.SectionData;
405 if (!is64Bit) { // 32-bit and 64-bit formats are shuffled a bit.
406 for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i) {
407 ELFSym &Sym = SymbolTable[i];
408 TOI->outword(SymTabBuf, Sym.NameIdx);
409 TOI->outaddr32(SymTabBuf, Sym.Value);
410 TOI->outword(SymTabBuf, Sym.Size);
411 TOI->outbyte(SymTabBuf, Sym.Info);
412 TOI->outbyte(SymTabBuf, Sym.Other);
413 TOI->outhalf(SymTabBuf, Sym.SectionIdx);
416 for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i) {
417 ELFSym &Sym = SymbolTable[i];
418 TOI->outword(SymTabBuf, Sym.NameIdx);
419 TOI->outbyte(SymTabBuf, Sym.Info);
420 TOI->outbyte(SymTabBuf, Sym.Other);
421 TOI->outhalf(SymTabBuf, Sym.SectionIdx);
422 TOI->outaddr64(SymTabBuf, Sym.Value);
423 TOI->outxword(SymTabBuf, Sym.Size);
427 SymTab.Size = SymTabBuf.size();
430 /// EmitSectionTableStringTable - This method adds and emits a section for the
431 /// ELF Section Table string table: the string table that holds all of the
433 void ELFWriter::EmitSectionTableStringTable() {
434 // First step: add the section for the string table to the list of sections:
435 ELFSection &SHStrTab = getSection(".shstrtab", ELFSection::SHT_STRTAB, 0);
437 // Now that we know which section number is the .shstrtab section, update the
438 // e_shstrndx entry in the ELF header.
439 TOI->fixhalf(FileHeader, SHStrTab.SectionIdx, ELFHeader_e_shstrndx_Offset);
441 // Set the NameIdx of each section in the string table and emit the bytes for
444 DataBuffer &Buf = SHStrTab.SectionData;
446 for (std::list<ELFSection>::iterator I = SectionList.begin(),
447 E = SectionList.end(); I != E; ++I) {
448 // Set the index into the table. Note if we have lots of entries with
449 // common suffixes, we could memoize them here if we cared.
452 // Add the name to the output buffer, including the null terminator.
453 Buf.insert(Buf.end(), I->Name.begin(), I->Name.end());
455 // Add a null terminator.
458 // Keep track of the number of bytes emitted to this section.
459 Index += I->Name.size()+1;
462 // Set the size of .shstrtab now that we know what it is.
463 assert(Index == Buf.size());
464 SHStrTab.Size = Index;
467 /// OutputSectionsAndSectionTable - Now that we have constructed the file header
468 /// and all of the sections, emit these to the ostream destination and emit the
470 void ELFWriter::OutputSectionsAndSectionTable() {
471 // Pass #1: Compute the file offset for each section.
472 size_t FileOff = FileHeader.size(); // File header first.
474 // Emit all of the section data in order.
475 for (std::list<ELFSection>::iterator I = SectionList.begin(),
476 E = SectionList.end(); I != E; ++I) {
477 // Align FileOff to whatever the alignment restrictions of the section are.
479 FileOff = (FileOff+I->Align-1) & ~(I->Align-1);
481 FileOff += I->SectionData.size();
484 // Align Section Header.
485 unsigned TableAlign = is64Bit ? 8 : 4;
486 FileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
488 // Now that we know where all of the sections will be emitted, set the e_shnum
489 // entry in the ELF header.
490 TOI->fixhalf(FileHeader, NumSections, ELFHeader_e_shnum_Offset);
492 // Now that we know the offset in the file of the section table, update the
493 // e_shoff address in the ELF header.
494 TOI->fixaddr(FileHeader, FileOff, ELFHeader_e_shoff_Offset);
496 // Now that we know all of the data in the file header, emit it and all of the
498 O.write((char*)&FileHeader[0], FileHeader.size());
499 FileOff = FileHeader.size();
500 DataBuffer().swap(FileHeader);
504 // Emit all of the section data and build the section table itself.
505 while (!SectionList.empty()) {
506 const ELFSection &S = *SectionList.begin();
508 // Align FileOff to whatever the alignment restrictions of the section are.
510 for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
511 FileOff != NewFileOff; ++FileOff)
513 O.write((char*)&S.SectionData[0], S.SectionData.size());
514 FileOff += S.SectionData.size();
516 TOI->outword(Table, S.NameIdx); // sh_name - Symbol table name idx
517 TOI->outword(Table, S.Type); // sh_type - Section contents & semantics
518 TOI->outword(Table, S.Flags); // sh_flags - Section flags
519 TOI->outaddr(Table, S.Addr); // sh_addr - The mem addr this section is in
520 TOI->outaddr(Table, S.Offset); // sh_offset - Offset from the file start
521 TOI->outword(Table, S.Size); // sh_size - The section size
522 TOI->outword(Table, S.Link); // sh_link - Section header table index link
523 TOI->outword(Table, S.Info); // sh_info - Auxillary information
524 TOI->outword(Table, S.Align); // sh_addralign - Alignment of section
525 TOI->outword(Table, S.EntSize); // sh_entsize - Size of entries in the sect
527 SectionList.pop_front();
530 // Align output for the section table.
531 for (size_t NewFileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
532 FileOff != NewFileOff; ++FileOff)
535 // Emit the section table itself.
536 O.write((char*)&Table[0], Table.size());