1 //===-- ELFWriter.cpp - Target-independent ELF Writer code ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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"
47 #include "llvm/Support/raw_ostream.h"
51 char ELFWriter::ID = 0;
52 /// AddELFWriter - Concrete function to add the ELF writer to the function pass
54 MachineCodeEmitter *llvm::AddELFWriter(PassManagerBase &PM,
57 ELFWriter *EW = new ELFWriter(O, TM);
59 return &EW->getMachineCodeEmitter();
62 //===----------------------------------------------------------------------===//
63 // ELFCodeEmitter Implementation
64 //===----------------------------------------------------------------------===//
67 /// ELFCodeEmitter - This class is used by the ELFWriter to emit the code for
68 /// functions to the ELF file.
69 class ELFCodeEmitter : public MachineCodeEmitter {
72 ELFWriter::ELFSection *ES; // Section to write to.
73 std::vector<unsigned char> *OutBuffer;
76 explicit ELFCodeEmitter(ELFWriter &ew) : EW(ew), TM(EW.TM), OutBuffer(0) {}
78 void startFunction(MachineFunction &F);
79 bool finishFunction(MachineFunction &F);
81 void addRelocation(const MachineRelocation &MR) {
82 assert(0 && "relo not handled yet!");
85 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
88 virtual intptr_t getConstantPoolEntryAddress(unsigned Index) const {
89 assert(0 && "CP not implementated yet!");
92 virtual intptr_t getJumpTableEntryAddress(unsigned Index) const {
93 assert(0 && "JT not implementated yet!");
97 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
98 assert(0 && "JT not implementated yet!");
102 virtual intptr_t getLabelAddress(uint64_t Label) const {
103 assert(0 && "Label address not implementated yet!");
108 virtual void emitLabel(uint64_t LabelID) {
109 assert(0 && "emit Label not implementated yet!");
114 virtual void setModuleInfo(llvm::MachineModuleInfo* MMI) { }
117 /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
118 void startFunctionStub(const GlobalValue* F, unsigned StubSize,
119 unsigned Alignment = 1) {
120 assert(0 && "JIT specific function called!");
123 void *finishFunctionStub(const GlobalValue *F) {
124 assert(0 && "JIT specific function called!");
131 /// startFunction - This callback is invoked when a new machine function is
132 /// about to be emitted.
133 void ELFCodeEmitter::startFunction(MachineFunction &F) {
134 // Align the output buffer to the appropriate alignment.
135 unsigned Align = 16; // FIXME: GENERICIZE!!
136 // Get the ELF Section that this function belongs in.
137 ES = &EW.getSection(".text", ELFWriter::ELFSection::SHT_PROGBITS,
138 ELFWriter::ELFSection::SHF_EXECINSTR |
139 ELFWriter::ELFSection::SHF_ALLOC);
140 OutBuffer = &ES->SectionData;
141 cerr << "FIXME: This code needs to be updated for changes in the "
142 << "CodeEmitter interfaces. In particular, this should set "
143 << "BufferBegin/BufferEnd/CurBufferPtr, not deal with OutBuffer!";
146 // Upgrade the section alignment if required.
147 if (ES->Align < Align) ES->Align = Align;
149 // Add padding zeros to the end of the buffer to make sure that the
150 // function will start on the correct byte alignment within the section.
151 OutputBuffer OB(*OutBuffer,
152 TM.getTargetData()->getPointerSizeInBits() == 64,
153 TM.getTargetData()->isLittleEndian());
155 FnStart = OutBuffer->size();
158 /// finishFunction - This callback is invoked after the function is completely
160 bool ELFCodeEmitter::finishFunction(MachineFunction &F) {
161 // We now know the size of the function, add a symbol to represent it.
162 ELFWriter::ELFSym FnSym(F.getFunction());
164 // Figure out the binding (linkage) of the symbol.
165 switch (F.getFunction()->getLinkage()) {
167 // appending linkage is illegal for functions.
168 assert(0 && "Unknown linkage type!");
169 case GlobalValue::ExternalLinkage:
170 FnSym.SetBind(ELFWriter::ELFSym::STB_GLOBAL);
172 case GlobalValue::LinkOnceLinkage:
173 case GlobalValue::WeakLinkage:
174 FnSym.SetBind(ELFWriter::ELFSym::STB_WEAK);
176 case GlobalValue::InternalLinkage:
177 FnSym.SetBind(ELFWriter::ELFSym::STB_LOCAL);
181 ES->Size = OutBuffer->size();
183 FnSym.SetType(ELFWriter::ELFSym::STT_FUNC);
184 FnSym.SectionIdx = ES->SectionIdx;
185 FnSym.Value = FnStart; // Value = Offset from start of Section.
186 FnSym.Size = OutBuffer->size()-FnStart;
188 // Finally, add it to the symtab.
189 EW.SymbolTable.push_back(FnSym);
193 //===----------------------------------------------------------------------===//
194 // ELFWriter Implementation
195 //===----------------------------------------------------------------------===//
197 ELFWriter::ELFWriter(raw_ostream &o, TargetMachine &tm)
198 : MachineFunctionPass(&ID), O(o), TM(tm) {
199 e_flags = 0; // e_flags defaults to 0, no flags.
201 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
202 isLittleEndian = TM.getTargetData()->isLittleEndian();
204 // Create the machine code emitter object for this target.
205 MCE = new ELFCodeEmitter(*this);
209 ELFWriter::~ELFWriter() {
213 // doInitialization - Emit the file header and all of the global variables for
214 // the module to the ELF file.
215 bool ELFWriter::doInitialization(Module &M) {
216 Mang = new Mangler(M);
218 // Local alias to shortenify coming code.
219 std::vector<unsigned char> &FH = FileHeader;
220 OutputBuffer FHOut(FH, is64Bit, isLittleEndian);
222 FHOut.outbyte(0x7F); // EI_MAG0
223 FHOut.outbyte('E'); // EI_MAG1
224 FHOut.outbyte('L'); // EI_MAG2
225 FHOut.outbyte('F'); // EI_MAG3
226 FHOut.outbyte(is64Bit ? 2 : 1); // EI_CLASS
227 FHOut.outbyte(isLittleEndian ? 1 : 2); // EI_DATA
228 FHOut.outbyte(1); // EI_VERSION
229 FH.resize(16); // EI_PAD up to 16 bytes.
231 // This should change for shared objects.
232 FHOut.outhalf(1); // e_type = ET_REL
233 FHOut.outhalf(TM.getELFWriterInfo()->getEMachine()); // target-defined
234 FHOut.outword(1); // e_version = 1
235 FHOut.outaddr(0); // e_entry = 0 -> no entry point in .o file
236 FHOut.outaddr(0); // e_phoff = 0 -> no program header for .o
238 ELFHeader_e_shoff_Offset = FH.size();
239 FHOut.outaddr(0); // e_shoff
240 FHOut.outword(e_flags); // e_flags = whatever the target wants
242 FHOut.outhalf(is64Bit ? 64 : 52); // e_ehsize = ELF header size
243 FHOut.outhalf(0); // e_phentsize = prog header entry size
244 FHOut.outhalf(0); // e_phnum = # prog header entries = 0
245 FHOut.outhalf(is64Bit ? 64 : 40); // e_shentsize = sect hdr entry size
248 ELFHeader_e_shnum_Offset = FH.size();
249 FHOut.outhalf(0); // e_shnum = # of section header ents
250 ELFHeader_e_shstrndx_Offset = FH.size();
251 FHOut.outhalf(0); // e_shstrndx = Section # of '.shstrtab'
253 // Add the null section, which is required to be first in the file.
254 getSection("", 0, 0);
256 // Start up the symbol table. The first entry in the symtab is the null
258 SymbolTable.push_back(ELFSym(0));
263 void ELFWriter::EmitGlobal(GlobalVariable *GV) {
264 // If this is an external global, emit it now. TODO: Note that it would be
265 // better to ignore the symbol here and only add it to the symbol table if
267 if (!GV->hasInitializer()) {
268 ELFSym ExternalSym(GV);
269 ExternalSym.SetBind(ELFSym::STB_GLOBAL);
270 ExternalSym.SetType(ELFSym::STT_NOTYPE);
271 ExternalSym.SectionIdx = ELFSection::SHN_UNDEF;
272 SymbolTable.push_back(ExternalSym);
276 const Type *GVType = (const Type*)GV->getType();
277 unsigned Align = TM.getTargetData()->getPreferredAlignment(GV);
278 unsigned Size = TM.getTargetData()->getABITypeSize(GVType);
280 // If this global has a zero initializer, it is part of the .bss or common
282 if (GV->getInitializer()->isNullValue()) {
283 // If this global is part of the common block, add it now. Variables are
284 // part of the common block if they are zero initialized and allowed to be
285 // merged with other symbols.
286 if (GV->hasLinkOnceLinkage() || GV->hasWeakLinkage() ||
287 GV->hasCommonLinkage()) {
288 ELFSym CommonSym(GV);
289 // Value for common symbols is the alignment required.
290 CommonSym.Value = Align;
291 CommonSym.Size = Size;
292 CommonSym.SetBind(ELFSym::STB_GLOBAL);
293 CommonSym.SetType(ELFSym::STT_OBJECT);
294 // TODO SOMEDAY: add ELF visibility.
295 CommonSym.SectionIdx = ELFSection::SHN_COMMON;
296 SymbolTable.push_back(CommonSym);
300 // Otherwise, this symbol is part of the .bss section. Emit it now.
302 // Handle alignment. Ensure section is aligned at least as much as required
304 ELFSection &BSSSection = getBSSSection();
305 BSSSection.Align = std::max(BSSSection.Align, Align);
307 // Within the section, emit enough virtual padding to get us to an alignment
310 BSSSection.Size = (BSSSection.Size + Align - 1) & ~(Align-1);
313 BSSSym.Value = BSSSection.Size;
315 BSSSym.SetType(ELFSym::STT_OBJECT);
317 switch (GV->getLinkage()) {
318 default: // weak/linkonce/common handled above
319 assert(0 && "Unexpected linkage type!");
320 case GlobalValue::AppendingLinkage: // FIXME: This should be improved!
321 case GlobalValue::ExternalLinkage:
322 BSSSym.SetBind(ELFSym::STB_GLOBAL);
324 case GlobalValue::InternalLinkage:
325 BSSSym.SetBind(ELFSym::STB_LOCAL);
329 // Set the idx of the .bss section
330 BSSSym.SectionIdx = BSSSection.SectionIdx;
331 SymbolTable.push_back(BSSSym);
333 // Reserve space in the .bss section for this symbol.
334 BSSSection.Size += Size;
338 // FIXME: handle .rodata
339 //assert(!GV->isConstant() && "unimp");
341 // FIXME: handle .data
342 //assert(0 && "unimp");
346 bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
347 // Nothing to do here, this is all done through the MCE object above.
351 /// doFinalization - Now that the module has been completely processed, emit
352 /// the ELF file to 'O'.
353 bool ELFWriter::doFinalization(Module &M) {
354 // Okay, the ELF header and .text sections have been completed, build the
355 // .data, .bss, and "common" sections next.
356 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
360 // Emit the symbol table now, if non-empty.
363 // FIXME: Emit the relocations now.
365 // Emit the string table for the sections in the ELF file we have.
366 EmitSectionTableStringTable();
368 // Emit the sections to the .o file, and emit the section table for the file.
369 OutputSectionsAndSectionTable();
371 // We are done with the abstract symbols.
375 // Release the name mangler object.
376 delete Mang; Mang = 0;
380 /// EmitSymbolTable - If the current symbol table is non-empty, emit the string
381 /// table for it and then the symbol table itself.
382 void ELFWriter::EmitSymbolTable() {
383 if (SymbolTable.size() == 1) return; // Only the null entry.
385 // FIXME: compact all local symbols to the start of the symtab.
386 unsigned FirstNonLocalSymbol = 1;
388 ELFSection &StrTab = getSection(".strtab", ELFSection::SHT_STRTAB, 0);
391 DataBuffer &StrTabBuf = StrTab.SectionData;
392 OutputBuffer StrTabOut(StrTabBuf, is64Bit, isLittleEndian);
394 // Set the zero'th symbol to a null byte, as required.
395 StrTabOut.outbyte(0);
396 SymbolTable[0].NameIdx = 0;
398 for (unsigned i = 1, e = SymbolTable.size(); i != e; ++i) {
399 // Use the name mangler to uniquify the LLVM symbol.
400 std::string Name = Mang->getValueName(SymbolTable[i].GV);
403 SymbolTable[i].NameIdx = 0;
405 SymbolTable[i].NameIdx = Index;
407 // Add the name to the output buffer, including the null terminator.
408 StrTabBuf.insert(StrTabBuf.end(), Name.begin(), Name.end());
410 // Add a null terminator.
411 StrTabBuf.push_back(0);
413 // Keep track of the number of bytes emitted to this section.
414 Index += Name.size()+1;
417 assert(Index == StrTabBuf.size());
420 // Now that we have emitted the string table and know the offset into the
421 // string table of each symbol, emit the symbol table itself.
422 ELFSection &SymTab = getSection(".symtab", ELFSection::SHT_SYMTAB, 0);
423 SymTab.Align = is64Bit ? 8 : 4;
424 SymTab.Link = SymTab.SectionIdx; // Section Index of .strtab.
425 SymTab.Info = FirstNonLocalSymbol; // First non-STB_LOCAL symbol.
426 SymTab.EntSize = 16; // Size of each symtab entry. FIXME: wrong for ELF64
427 DataBuffer &SymTabBuf = SymTab.SectionData;
428 OutputBuffer SymTabOut(SymTabBuf, is64Bit, isLittleEndian);
430 if (!is64Bit) { // 32-bit and 64-bit formats are shuffled a bit.
431 for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i) {
432 ELFSym &Sym = SymbolTable[i];
433 SymTabOut.outword(Sym.NameIdx);
434 SymTabOut.outaddr32(Sym.Value);
435 SymTabOut.outword(Sym.Size);
436 SymTabOut.outbyte(Sym.Info);
437 SymTabOut.outbyte(Sym.Other);
438 SymTabOut.outhalf(Sym.SectionIdx);
441 for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i) {
442 ELFSym &Sym = SymbolTable[i];
443 SymTabOut.outword(Sym.NameIdx);
444 SymTabOut.outbyte(Sym.Info);
445 SymTabOut.outbyte(Sym.Other);
446 SymTabOut.outhalf(Sym.SectionIdx);
447 SymTabOut.outaddr64(Sym.Value);
448 SymTabOut.outxword(Sym.Size);
452 SymTab.Size = SymTabBuf.size();
455 /// EmitSectionTableStringTable - This method adds and emits a section for the
456 /// ELF Section Table string table: the string table that holds all of the
458 void ELFWriter::EmitSectionTableStringTable() {
459 // First step: add the section for the string table to the list of sections:
460 ELFSection &SHStrTab = getSection(".shstrtab", ELFSection::SHT_STRTAB, 0);
462 // Now that we know which section number is the .shstrtab section, update the
463 // e_shstrndx entry in the ELF header.
464 OutputBuffer FHOut(FileHeader, is64Bit, isLittleEndian);
465 FHOut.fixhalf(SHStrTab.SectionIdx, ELFHeader_e_shstrndx_Offset);
467 // Set the NameIdx of each section in the string table and emit the bytes for
470 DataBuffer &Buf = SHStrTab.SectionData;
472 for (std::list<ELFSection>::iterator I = SectionList.begin(),
473 E = SectionList.end(); I != E; ++I) {
474 // Set the index into the table. Note if we have lots of entries with
475 // common suffixes, we could memoize them here if we cared.
478 // Add the name to the output buffer, including the null terminator.
479 Buf.insert(Buf.end(), I->Name.begin(), I->Name.end());
481 // Add a null terminator.
484 // Keep track of the number of bytes emitted to this section.
485 Index += I->Name.size()+1;
488 // Set the size of .shstrtab now that we know what it is.
489 assert(Index == Buf.size());
490 SHStrTab.Size = Index;
493 /// OutputSectionsAndSectionTable - Now that we have constructed the file header
494 /// and all of the sections, emit these to the ostream destination and emit the
496 void ELFWriter::OutputSectionsAndSectionTable() {
497 // Pass #1: Compute the file offset for each section.
498 size_t FileOff = FileHeader.size(); // File header first.
500 // Emit all of the section data in order.
501 for (std::list<ELFSection>::iterator I = SectionList.begin(),
502 E = SectionList.end(); I != E; ++I) {
503 // Align FileOff to whatever the alignment restrictions of the section are.
505 FileOff = (FileOff+I->Align-1) & ~(I->Align-1);
507 FileOff += I->SectionData.size();
510 // Align Section Header.
511 unsigned TableAlign = is64Bit ? 8 : 4;
512 FileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
514 // Now that we know where all of the sections will be emitted, set the e_shnum
515 // entry in the ELF header.
516 OutputBuffer FHOut(FileHeader, is64Bit, isLittleEndian);
517 FHOut.fixhalf(NumSections, ELFHeader_e_shnum_Offset);
519 // Now that we know the offset in the file of the section table, update the
520 // e_shoff address in the ELF header.
521 FHOut.fixaddr(FileOff, ELFHeader_e_shoff_Offset);
523 // Now that we know all of the data in the file header, emit it and all of the
525 O.write((char*)&FileHeader[0], FileHeader.size());
526 FileOff = FileHeader.size();
527 DataBuffer().swap(FileHeader);
530 OutputBuffer TableOut(Table, is64Bit, isLittleEndian);
532 // Emit all of the section data and build the section table itself.
533 while (!SectionList.empty()) {
534 const ELFSection &S = *SectionList.begin();
536 // Align FileOff to whatever the alignment restrictions of the section are.
538 for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
539 FileOff != NewFileOff; ++FileOff)
541 O.write((char*)&S.SectionData[0], S.SectionData.size());
542 FileOff += S.SectionData.size();
544 TableOut.outword(S.NameIdx); // sh_name - Symbol table name idx
545 TableOut.outword(S.Type); // sh_type - Section contents & semantics
546 TableOut.outword(S.Flags); // sh_flags - Section flags.
547 TableOut.outaddr(S.Addr); // sh_addr - The mem addr this section is in.
548 TableOut.outaddr(S.Offset); // sh_offset - Offset from the file start.
549 TableOut.outword(S.Size); // sh_size - The section size.
550 TableOut.outword(S.Link); // sh_link - Section header table index link.
551 TableOut.outword(S.Info); // sh_info - Auxillary information.
552 TableOut.outword(S.Align); // sh_addralign - Alignment of section.
553 TableOut.outword(S.EntSize); // sh_entsize - Size of entries in the section
555 SectionList.pop_front();
558 // Align output for the section table.
559 for (size_t NewFileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
560 FileOff != NewFileOff; ++FileOff)
563 // Emit the section table itself.
564 O.write((char*)&Table[0], Table.size());