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/DerivedTypes.h"
38 #include "llvm/CodeGen/FileWriters.h"
39 #include "llvm/CodeGen/MachineCodeEmitter.h"
40 #include "llvm/CodeGen/MachineConstantPool.h"
41 #include "llvm/CodeGen/MachineFunctionPass.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Target/TargetELFWriterInfo.h"
44 #include "llvm/Target/TargetMachine.h"
45 #include "llvm/Support/Mangler.h"
46 #include "llvm/Support/OutputBuffer.h"
47 #include "llvm/Support/Streams.h"
48 #include "llvm/Support/raw_ostream.h"
52 char ELFWriter::ID = 0;
53 /// AddELFWriter - Concrete function to add the ELF writer to the function pass
55 MachineCodeEmitter *llvm::AddELFWriter(PassManagerBase &PM,
58 ELFWriter *EW = new ELFWriter(O, TM);
60 return &EW->getMachineCodeEmitter();
63 //===----------------------------------------------------------------------===//
64 // ELFCodeEmitter Implementation
65 //===----------------------------------------------------------------------===//
68 /// ELFCodeEmitter - This class is used by the ELFWriter to emit the code for
69 /// functions to the ELF file.
70 class ELFCodeEmitter : public MachineCodeEmitter {
73 ELFWriter::ELFSection *ES; // Section to write to.
74 std::vector<unsigned char> *OutBuffer;
77 explicit ELFCodeEmitter(ELFWriter &ew) : EW(ew), TM(EW.TM), OutBuffer(0) {}
79 void startFunction(MachineFunction &F);
80 bool finishFunction(MachineFunction &F);
82 void addRelocation(const MachineRelocation &MR) {
83 assert(0 && "relo not handled yet!");
86 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
89 virtual uintptr_t getConstantPoolEntryAddress(unsigned Index) const {
90 assert(0 && "CP not implementated yet!");
93 virtual uintptr_t getJumpTableEntryAddress(unsigned Index) const {
94 assert(0 && "JT not implementated yet!");
98 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
99 assert(0 && "JT not implementated yet!");
103 virtual uintptr_t getLabelAddress(uint64_t Label) const {
104 assert(0 && "Label address not implementated yet!");
109 virtual void emitLabel(uint64_t LabelID) {
110 assert(0 && "emit Label not implementated yet!");
115 virtual void setModuleInfo(llvm::MachineModuleInfo* MMI) { }
118 /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
119 void startGVStub(const GlobalValue* F, unsigned StubSize,
120 unsigned Alignment = 1) {
121 assert(0 && "JIT specific function called!");
124 void startGVStub(const GlobalValue* F, void *Buffer, unsigned StubSize) {
125 assert(0 && "JIT specific function called!");
128 void *finishGVStub(const GlobalValue *F) {
129 assert(0 && "JIT specific function called!");
136 /// startFunction - This callback is invoked when a new machine function is
137 /// about to be emitted.
138 void ELFCodeEmitter::startFunction(MachineFunction &F) {
139 // Align the output buffer to the appropriate alignment.
140 unsigned Align = 16; // FIXME: GENERICIZE!!
141 // Get the ELF Section that this function belongs in.
142 ES = &EW.getSection(".text", ELFWriter::ELFSection::SHT_PROGBITS,
143 ELFWriter::ELFSection::SHF_EXECINSTR |
144 ELFWriter::ELFSection::SHF_ALLOC);
145 OutBuffer = &ES->SectionData;
146 cerr << "FIXME: This code needs to be updated for changes in the "
147 << "CodeEmitter interfaces. In particular, this should set "
148 << "BufferBegin/BufferEnd/CurBufferPtr, not deal with OutBuffer!";
151 // Upgrade the section alignment if required.
152 if (ES->Align < Align) ES->Align = Align;
154 // Add padding zeros to the end of the buffer to make sure that the
155 // function will start on the correct byte alignment within the section.
156 OutputBuffer OB(*OutBuffer,
157 TM.getTargetData()->getPointerSizeInBits() == 64,
158 TM.getTargetData()->isLittleEndian());
160 FnStart = OutBuffer->size();
163 /// finishFunction - This callback is invoked after the function is completely
165 bool ELFCodeEmitter::finishFunction(MachineFunction &F) {
166 // We now know the size of the function, add a symbol to represent it.
167 ELFWriter::ELFSym FnSym(F.getFunction());
169 // Figure out the binding (linkage) of the symbol.
170 switch (F.getFunction()->getLinkage()) {
172 // appending linkage is illegal for functions.
173 assert(0 && "Unknown linkage type!");
174 case GlobalValue::ExternalLinkage:
175 FnSym.SetBind(ELFWriter::ELFSym::STB_GLOBAL);
177 case GlobalValue::LinkOnceLinkage:
178 case GlobalValue::WeakLinkage:
179 FnSym.SetBind(ELFWriter::ELFSym::STB_WEAK);
181 case GlobalValue::PrivateLinkage:
182 assert (0 && "PrivateLinkage should not be in the symbol table.");
183 case GlobalValue::InternalLinkage:
184 FnSym.SetBind(ELFWriter::ELFSym::STB_LOCAL);
188 ES->Size = OutBuffer->size();
190 FnSym.SetType(ELFWriter::ELFSym::STT_FUNC);
191 FnSym.SectionIdx = ES->SectionIdx;
192 FnSym.Value = FnStart; // Value = Offset from start of Section.
193 FnSym.Size = OutBuffer->size()-FnStart;
195 // Finally, add it to the symtab.
196 EW.SymbolTable.push_back(FnSym);
200 //===----------------------------------------------------------------------===//
201 // ELFWriter Implementation
202 //===----------------------------------------------------------------------===//
204 ELFWriter::ELFWriter(raw_ostream &o, TargetMachine &tm)
205 : MachineFunctionPass(&ID), O(o), TM(tm) {
206 e_flags = 0; // e_flags defaults to 0, no flags.
208 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
209 isLittleEndian = TM.getTargetData()->isLittleEndian();
211 // Create the machine code emitter object for this target.
212 MCE = new ELFCodeEmitter(*this);
216 ELFWriter::~ELFWriter() {
220 // doInitialization - Emit the file header and all of the global variables for
221 // the module to the ELF file.
222 bool ELFWriter::doInitialization(Module &M) {
223 Mang = new Mangler(M);
225 // Local alias to shortenify coming code.
226 std::vector<unsigned char> &FH = FileHeader;
227 OutputBuffer FHOut(FH, is64Bit, isLittleEndian);
229 FHOut.outbyte(0x7F); // EI_MAG0
230 FHOut.outbyte('E'); // EI_MAG1
231 FHOut.outbyte('L'); // EI_MAG2
232 FHOut.outbyte('F'); // EI_MAG3
233 FHOut.outbyte(is64Bit ? 2 : 1); // EI_CLASS
234 FHOut.outbyte(isLittleEndian ? 1 : 2); // EI_DATA
235 FHOut.outbyte(1); // EI_VERSION
236 FH.resize(16); // EI_PAD up to 16 bytes.
238 // This should change for shared objects.
239 FHOut.outhalf(1); // e_type = ET_REL
240 FHOut.outhalf(TM.getELFWriterInfo()->getEMachine()); // target-defined
241 FHOut.outword(1); // e_version = 1
242 FHOut.outaddr(0); // e_entry = 0 -> no entry point in .o file
243 FHOut.outaddr(0); // e_phoff = 0 -> no program header for .o
245 ELFHeader_e_shoff_Offset = FH.size();
246 FHOut.outaddr(0); // e_shoff
247 FHOut.outword(e_flags); // e_flags = whatever the target wants
249 FHOut.outhalf(is64Bit ? 64 : 52); // e_ehsize = ELF header size
250 FHOut.outhalf(0); // e_phentsize = prog header entry size
251 FHOut.outhalf(0); // e_phnum = # prog header entries = 0
252 FHOut.outhalf(is64Bit ? 64 : 40); // e_shentsize = sect hdr entry size
255 ELFHeader_e_shnum_Offset = FH.size();
256 FHOut.outhalf(0); // e_shnum = # of section header ents
257 ELFHeader_e_shstrndx_Offset = FH.size();
258 FHOut.outhalf(0); // e_shstrndx = Section # of '.shstrtab'
260 // Add the null section, which is required to be first in the file.
261 getSection("", 0, 0);
263 // Start up the symbol table. The first entry in the symtab is the null
265 SymbolTable.push_back(ELFSym(0));
270 void ELFWriter::EmitGlobal(GlobalVariable *GV) {
271 // If this is an external global, emit it now. TODO: Note that it would be
272 // better to ignore the symbol here and only add it to the symbol table if
274 if (!GV->hasInitializer()) {
275 ELFSym ExternalSym(GV);
276 ExternalSym.SetBind(ELFSym::STB_GLOBAL);
277 ExternalSym.SetType(ELFSym::STT_NOTYPE);
278 ExternalSym.SectionIdx = ELFSection::SHN_UNDEF;
279 SymbolTable.push_back(ExternalSym);
283 unsigned Align = TM.getTargetData()->getPreferredAlignment(GV);
285 TM.getTargetData()->getTypePaddedSize(GV->getType()->getElementType());
287 // If this global has a zero initializer, it is part of the .bss or common
289 if (GV->getInitializer()->isNullValue()) {
290 // If this global is part of the common block, add it now. Variables are
291 // part of the common block if they are zero initialized and allowed to be
292 // merged with other symbols.
293 if (GV->hasLinkOnceLinkage() || GV->hasWeakLinkage() ||
294 GV->hasCommonLinkage()) {
295 ELFSym CommonSym(GV);
296 // Value for common symbols is the alignment required.
297 CommonSym.Value = Align;
298 CommonSym.Size = Size;
299 CommonSym.SetBind(ELFSym::STB_GLOBAL);
300 CommonSym.SetType(ELFSym::STT_OBJECT);
301 // TODO SOMEDAY: add ELF visibility.
302 CommonSym.SectionIdx = ELFSection::SHN_COMMON;
303 SymbolTable.push_back(CommonSym);
307 // Otherwise, this symbol is part of the .bss section. Emit it now.
309 // Handle alignment. Ensure section is aligned at least as much as required
311 ELFSection &BSSSection = getBSSSection();
312 BSSSection.Align = std::max(BSSSection.Align, Align);
314 // Within the section, emit enough virtual padding to get us to an alignment
317 BSSSection.Size = (BSSSection.Size + Align - 1) & ~(Align-1);
320 BSSSym.Value = BSSSection.Size;
322 BSSSym.SetType(ELFSym::STT_OBJECT);
324 switch (GV->getLinkage()) {
325 default: // weak/linkonce/common handled above
326 assert(0 && "Unexpected linkage type!");
327 case GlobalValue::AppendingLinkage: // FIXME: This should be improved!
328 case GlobalValue::ExternalLinkage:
329 BSSSym.SetBind(ELFSym::STB_GLOBAL);
331 case GlobalValue::InternalLinkage:
332 BSSSym.SetBind(ELFSym::STB_LOCAL);
336 // Set the idx of the .bss section
337 BSSSym.SectionIdx = BSSSection.SectionIdx;
338 if (!GV->hasPrivateLinkage())
339 SymbolTable.push_back(BSSSym);
341 // Reserve space in the .bss section for this symbol.
342 BSSSection.Size += Size;
346 // FIXME: handle .rodata
347 //assert(!GV->isConstant() && "unimp");
349 // FIXME: handle .data
350 //assert(0 && "unimp");
354 bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
355 // Nothing to do here, this is all done through the MCE object above.
359 /// doFinalization - Now that the module has been completely processed, emit
360 /// the ELF file to 'O'.
361 bool ELFWriter::doFinalization(Module &M) {
362 // Okay, the ELF header and .text sections have been completed, build the
363 // .data, .bss, and "common" sections next.
364 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
368 // Emit the symbol table now, if non-empty.
371 // FIXME: Emit the relocations now.
373 // Emit the string table for the sections in the ELF file we have.
374 EmitSectionTableStringTable();
376 // Emit the sections to the .o file, and emit the section table for the file.
377 OutputSectionsAndSectionTable();
379 // We are done with the abstract symbols.
383 // Release the name mangler object.
384 delete Mang; Mang = 0;
388 /// EmitSymbolTable - If the current symbol table is non-empty, emit the string
389 /// table for it and then the symbol table itself.
390 void ELFWriter::EmitSymbolTable() {
391 if (SymbolTable.size() == 1) return; // Only the null entry.
393 // FIXME: compact all local symbols to the start of the symtab.
394 unsigned FirstNonLocalSymbol = 1;
396 ELFSection &StrTab = getSection(".strtab", ELFSection::SHT_STRTAB, 0);
399 DataBuffer &StrTabBuf = StrTab.SectionData;
400 OutputBuffer StrTabOut(StrTabBuf, is64Bit, isLittleEndian);
402 // Set the zero'th symbol to a null byte, as required.
403 StrTabOut.outbyte(0);
404 SymbolTable[0].NameIdx = 0;
406 for (unsigned i = 1, e = SymbolTable.size(); i != e; ++i) {
407 // Use the name mangler to uniquify the LLVM symbol.
408 std::string Name = Mang->getValueName(SymbolTable[i].GV);
411 SymbolTable[i].NameIdx = 0;
413 SymbolTable[i].NameIdx = Index;
415 // Add the name to the output buffer, including the null terminator.
416 StrTabBuf.insert(StrTabBuf.end(), Name.begin(), Name.end());
418 // Add a null terminator.
419 StrTabBuf.push_back(0);
421 // Keep track of the number of bytes emitted to this section.
422 Index += Name.size()+1;
425 assert(Index == StrTabBuf.size());
428 // Now that we have emitted the string table and know the offset into the
429 // string table of each symbol, emit the symbol table itself.
430 ELFSection &SymTab = getSection(".symtab", ELFSection::SHT_SYMTAB, 0);
431 SymTab.Align = is64Bit ? 8 : 4;
432 SymTab.Link = SymTab.SectionIdx; // Section Index of .strtab.
433 SymTab.Info = FirstNonLocalSymbol; // First non-STB_LOCAL symbol.
434 SymTab.EntSize = 16; // Size of each symtab entry. FIXME: wrong for ELF64
435 DataBuffer &SymTabBuf = SymTab.SectionData;
436 OutputBuffer SymTabOut(SymTabBuf, is64Bit, isLittleEndian);
438 if (!is64Bit) { // 32-bit and 64-bit formats are shuffled a bit.
439 for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i) {
440 ELFSym &Sym = SymbolTable[i];
441 SymTabOut.outword(Sym.NameIdx);
442 SymTabOut.outaddr32(Sym.Value);
443 SymTabOut.outword(Sym.Size);
444 SymTabOut.outbyte(Sym.Info);
445 SymTabOut.outbyte(Sym.Other);
446 SymTabOut.outhalf(Sym.SectionIdx);
449 for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i) {
450 ELFSym &Sym = SymbolTable[i];
451 SymTabOut.outword(Sym.NameIdx);
452 SymTabOut.outbyte(Sym.Info);
453 SymTabOut.outbyte(Sym.Other);
454 SymTabOut.outhalf(Sym.SectionIdx);
455 SymTabOut.outaddr64(Sym.Value);
456 SymTabOut.outxword(Sym.Size);
460 SymTab.Size = SymTabBuf.size();
463 /// EmitSectionTableStringTable - This method adds and emits a section for the
464 /// ELF Section Table string table: the string table that holds all of the
466 void ELFWriter::EmitSectionTableStringTable() {
467 // First step: add the section for the string table to the list of sections:
468 ELFSection &SHStrTab = getSection(".shstrtab", ELFSection::SHT_STRTAB, 0);
470 // Now that we know which section number is the .shstrtab section, update the
471 // e_shstrndx entry in the ELF header.
472 OutputBuffer FHOut(FileHeader, is64Bit, isLittleEndian);
473 FHOut.fixhalf(SHStrTab.SectionIdx, ELFHeader_e_shstrndx_Offset);
475 // Set the NameIdx of each section in the string table and emit the bytes for
478 DataBuffer &Buf = SHStrTab.SectionData;
480 for (std::list<ELFSection>::iterator I = SectionList.begin(),
481 E = SectionList.end(); I != E; ++I) {
482 // Set the index into the table. Note if we have lots of entries with
483 // common suffixes, we could memoize them here if we cared.
486 // Add the name to the output buffer, including the null terminator.
487 Buf.insert(Buf.end(), I->Name.begin(), I->Name.end());
489 // Add a null terminator.
492 // Keep track of the number of bytes emitted to this section.
493 Index += I->Name.size()+1;
496 // Set the size of .shstrtab now that we know what it is.
497 assert(Index == Buf.size());
498 SHStrTab.Size = Index;
501 /// OutputSectionsAndSectionTable - Now that we have constructed the file header
502 /// and all of the sections, emit these to the ostream destination and emit the
504 void ELFWriter::OutputSectionsAndSectionTable() {
505 // Pass #1: Compute the file offset for each section.
506 size_t FileOff = FileHeader.size(); // File header first.
508 // Emit all of the section data in order.
509 for (std::list<ELFSection>::iterator I = SectionList.begin(),
510 E = SectionList.end(); I != E; ++I) {
511 // Align FileOff to whatever the alignment restrictions of the section are.
513 FileOff = (FileOff+I->Align-1) & ~(I->Align-1);
515 FileOff += I->SectionData.size();
518 // Align Section Header.
519 unsigned TableAlign = is64Bit ? 8 : 4;
520 FileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
522 // Now that we know where all of the sections will be emitted, set the e_shnum
523 // entry in the ELF header.
524 OutputBuffer FHOut(FileHeader, is64Bit, isLittleEndian);
525 FHOut.fixhalf(NumSections, ELFHeader_e_shnum_Offset);
527 // Now that we know the offset in the file of the section table, update the
528 // e_shoff address in the ELF header.
529 FHOut.fixaddr(FileOff, ELFHeader_e_shoff_Offset);
531 // Now that we know all of the data in the file header, emit it and all of the
533 O.write((char*)&FileHeader[0], FileHeader.size());
534 FileOff = FileHeader.size();
535 DataBuffer().swap(FileHeader);
538 OutputBuffer TableOut(Table, is64Bit, isLittleEndian);
540 // Emit all of the section data and build the section table itself.
541 while (!SectionList.empty()) {
542 const ELFSection &S = *SectionList.begin();
544 // Align FileOff to whatever the alignment restrictions of the section are.
546 for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
547 FileOff != NewFileOff; ++FileOff)
549 O.write((char*)&S.SectionData[0], S.SectionData.size());
550 FileOff += S.SectionData.size();
552 TableOut.outword(S.NameIdx); // sh_name - Symbol table name idx
553 TableOut.outword(S.Type); // sh_type - Section contents & semantics
554 TableOut.outword(S.Flags); // sh_flags - Section flags.
555 TableOut.outaddr(S.Addr); // sh_addr - The mem addr this section is in.
556 TableOut.outaddr(S.Offset); // sh_offset - Offset from the file start.
557 TableOut.outword(S.Size); // sh_size - The section size.
558 TableOut.outword(S.Link); // sh_link - Section header table index link.
559 TableOut.outword(S.Info); // sh_info - Auxillary information.
560 TableOut.outword(S.Align); // sh_addralign - Alignment of section.
561 TableOut.outword(S.EntSize); // sh_entsize - Size of entries in the section
563 SectionList.pop_front();
566 // Align output for the section table.
567 for (size_t NewFileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
568 FileOff != NewFileOff; ++FileOff)
571 // Emit the section table itself.
572 O.write((char*)&Table[0], Table.size());