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 "ELFCodeEmitter.h"
36 #include "llvm/Module.h"
37 #include "llvm/PassManager.h"
38 #include "llvm/DerivedTypes.h"
39 #include "llvm/CodeGen/FileWriters.h"
40 #include "llvm/CodeGen/MachineCodeEmitter.h"
41 #include "llvm/CodeGen/MachineConstantPool.h"
42 #include "llvm/CodeGen/MachineFunctionPass.h"
43 #include "llvm/Target/TargetData.h"
44 #include "llvm/Target/TargetELFWriterInfo.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include "llvm/Support/Mangler.h"
47 #include "llvm/Support/OutputBuffer.h"
48 #include "llvm/Support/Streams.h"
49 #include "llvm/Support/raw_ostream.h"
53 char ELFWriter::ID = 0;
54 /// AddELFWriter - Concrete function to add the ELF writer to the function pass
56 MachineCodeEmitter *llvm::AddELFWriter(PassManagerBase &PM,
59 ELFWriter *EW = new ELFWriter(O, TM);
61 return &EW->getMachineCodeEmitter();
64 //===----------------------------------------------------------------------===//
65 // ELFWriter Implementation
66 //===----------------------------------------------------------------------===//
68 ELFWriter::ELFWriter(raw_ostream &o, TargetMachine &tm)
69 : MachineFunctionPass(&ID), O(o), TM(tm) {
70 e_flags = 0; // e_flags defaults to 0, no flags.
72 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
73 isLittleEndian = TM.getTargetData()->isLittleEndian();
75 // Create the machine code emitter object for this target.
76 MCE = new ELFCodeEmitter(*this);
80 ELFWriter::~ELFWriter() {
84 // doInitialization - Emit the file header and all of the global variables for
85 // the module to the ELF file.
86 bool ELFWriter::doInitialization(Module &M) {
87 Mang = new Mangler(M);
89 // Local alias to shortenify coming code.
90 std::vector<unsigned char> &FH = FileHeader;
91 OutputBuffer FHOut(FH, is64Bit, isLittleEndian);
93 FHOut.outbyte(0x7F); // EI_MAG0
94 FHOut.outbyte('E'); // EI_MAG1
95 FHOut.outbyte('L'); // EI_MAG2
96 FHOut.outbyte('F'); // EI_MAG3
97 FHOut.outbyte(is64Bit ? 2 : 1); // EI_CLASS
98 FHOut.outbyte(isLittleEndian ? 1 : 2); // EI_DATA
99 FHOut.outbyte(1); // EI_VERSION
100 FH.resize(16); // EI_PAD up to 16 bytes.
102 // This should change for shared objects.
103 FHOut.outhalf(1); // e_type = ET_REL
104 FHOut.outhalf(TM.getELFWriterInfo()->getEMachine()); // target-defined
105 FHOut.outword(1); // e_version = 1
106 FHOut.outaddr(0); // e_entry = 0 -> no entry point in .o file
107 FHOut.outaddr(0); // e_phoff = 0 -> no program header for .o
109 ELFHeader_e_shoff_Offset = FH.size();
110 FHOut.outaddr(0); // e_shoff
111 FHOut.outword(e_flags); // e_flags = whatever the target wants
113 FHOut.outhalf(is64Bit ? 64 : 52); // e_ehsize = ELF header size
114 FHOut.outhalf(0); // e_phentsize = prog header entry size
115 FHOut.outhalf(0); // e_phnum = # prog header entries = 0
116 FHOut.outhalf(is64Bit ? 64 : 40); // e_shentsize = sect hdr entry size
119 ELFHeader_e_shnum_Offset = FH.size();
120 FHOut.outhalf(0); // e_shnum = # of section header ents
121 ELFHeader_e_shstrndx_Offset = FH.size();
122 FHOut.outhalf(0); // e_shstrndx = Section # of '.shstrtab'
124 // Add the null section, which is required to be first in the file.
125 getSection("", 0, 0);
127 // Start up the symbol table. The first entry in the symtab is the null
129 SymbolTable.push_back(ELFSym(0));
134 void ELFWriter::EmitGlobal(GlobalVariable *GV) {
135 // If this is an external global, emit it now. TODO: Note that it would be
136 // better to ignore the symbol here and only add it to the symbol table if
138 if (!GV->hasInitializer()) {
139 ELFSym ExternalSym(GV);
140 ExternalSym.SetBind(ELFSym::STB_GLOBAL);
141 ExternalSym.SetType(ELFSym::STT_NOTYPE);
142 ExternalSym.SectionIdx = ELFSection::SHN_UNDEF;
143 SymbolTable.push_back(ExternalSym);
147 unsigned Align = TM.getTargetData()->getPreferredAlignment(GV);
149 TM.getTargetData()->getTypeAllocSize(GV->getType()->getElementType());
151 // If this global has a zero initializer, it is part of the .bss or common
153 if (GV->getInitializer()->isNullValue()) {
154 // If this global is part of the common block, add it now. Variables are
155 // part of the common block if they are zero initialized and allowed to be
156 // merged with other symbols.
157 if (GV->hasLinkOnceLinkage() || GV->hasWeakLinkage() ||
158 GV->hasCommonLinkage()) {
159 ELFSym CommonSym(GV);
160 // Value for common symbols is the alignment required.
161 CommonSym.Value = Align;
162 CommonSym.Size = Size;
163 CommonSym.SetBind(ELFSym::STB_GLOBAL);
164 CommonSym.SetType(ELFSym::STT_OBJECT);
165 // TODO SOMEDAY: add ELF visibility.
166 CommonSym.SectionIdx = ELFSection::SHN_COMMON;
167 SymbolTable.push_back(CommonSym);
171 // Otherwise, this symbol is part of the .bss section. Emit it now.
173 // Handle alignment. Ensure section is aligned at least as much as required
175 ELFSection &BSSSection = getBSSSection();
176 BSSSection.Align = std::max(BSSSection.Align, Align);
178 // Within the section, emit enough virtual padding to get us to an alignment
181 BSSSection.Size = (BSSSection.Size + Align - 1) & ~(Align-1);
184 BSSSym.Value = BSSSection.Size;
186 BSSSym.SetType(ELFSym::STT_OBJECT);
188 switch (GV->getLinkage()) {
189 default: // weak/linkonce/common handled above
190 assert(0 && "Unexpected linkage type!");
191 case GlobalValue::AppendingLinkage: // FIXME: This should be improved!
192 case GlobalValue::ExternalLinkage:
193 BSSSym.SetBind(ELFSym::STB_GLOBAL);
195 case GlobalValue::InternalLinkage:
196 BSSSym.SetBind(ELFSym::STB_LOCAL);
200 // Set the idx of the .bss section
201 BSSSym.SectionIdx = BSSSection.SectionIdx;
202 if (!GV->hasPrivateLinkage())
203 SymbolTable.push_back(BSSSym);
205 // Reserve space in the .bss section for this symbol.
206 BSSSection.Size += Size;
210 // FIXME: handle .rodata
211 //assert(!GV->isConstant() && "unimp");
213 // FIXME: handle .data
214 //assert(0 && "unimp");
218 bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
219 // Nothing to do here, this is all done through the MCE object above.
223 /// doFinalization - Now that the module has been completely processed, emit
224 /// the ELF file to 'O'.
225 bool ELFWriter::doFinalization(Module &M) {
226 // Okay, the ELF header and .text sections have been completed, build the
227 // .data, .bss, and "common" sections next.
228 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
232 // Emit the symbol table now, if non-empty.
235 // FIXME: Emit the relocations now.
237 // Emit the string table for the sections in the ELF file we have.
238 EmitSectionTableStringTable();
240 // Emit the sections to the .o file, and emit the section table for the file.
241 OutputSectionsAndSectionTable();
243 // We are done with the abstract symbols.
247 // Release the name mangler object.
248 delete Mang; Mang = 0;
252 /// EmitSymbolTable - If the current symbol table is non-empty, emit the string
253 /// table for it and then the symbol table itself.
254 void ELFWriter::EmitSymbolTable() {
255 if (SymbolTable.size() == 1) return; // Only the null entry.
257 // FIXME: compact all local symbols to the start of the symtab.
258 unsigned FirstNonLocalSymbol = 1;
260 ELFSection &StrTab = getSection(".strtab", ELFSection::SHT_STRTAB, 0);
263 DataBuffer &StrTabBuf = StrTab.SectionData;
264 OutputBuffer StrTabOut(StrTabBuf, is64Bit, isLittleEndian);
266 // Set the zero'th symbol to a null byte, as required.
267 StrTabOut.outbyte(0);
268 SymbolTable[0].NameIdx = 0;
270 for (unsigned i = 1, e = SymbolTable.size(); i != e; ++i) {
271 // Use the name mangler to uniquify the LLVM symbol.
272 std::string Name = Mang->getValueName(SymbolTable[i].GV);
275 SymbolTable[i].NameIdx = 0;
277 SymbolTable[i].NameIdx = Index;
279 // Add the name to the output buffer, including the null terminator.
280 StrTabBuf.insert(StrTabBuf.end(), Name.begin(), Name.end());
282 // Add a null terminator.
283 StrTabBuf.push_back(0);
285 // Keep track of the number of bytes emitted to this section.
286 Index += Name.size()+1;
289 assert(Index == StrTabBuf.size());
292 // Now that we have emitted the string table and know the offset into the
293 // string table of each symbol, emit the symbol table itself.
294 ELFSection &SymTab = getSection(".symtab", ELFSection::SHT_SYMTAB, 0);
295 SymTab.Align = is64Bit ? 8 : 4;
296 SymTab.Link = SymTab.SectionIdx; // Section Index of .strtab.
297 SymTab.Info = FirstNonLocalSymbol; // First non-STB_LOCAL symbol.
298 SymTab.EntSize = 16; // Size of each symtab entry. FIXME: wrong for ELF64
299 DataBuffer &SymTabBuf = SymTab.SectionData;
300 OutputBuffer SymTabOut(SymTabBuf, is64Bit, isLittleEndian);
302 if (!is64Bit) { // 32-bit and 64-bit formats are shuffled a bit.
303 for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i) {
304 ELFSym &Sym = SymbolTable[i];
305 SymTabOut.outword(Sym.NameIdx);
306 SymTabOut.outaddr32(Sym.Value);
307 SymTabOut.outword(Sym.Size);
308 SymTabOut.outbyte(Sym.Info);
309 SymTabOut.outbyte(Sym.Other);
310 SymTabOut.outhalf(Sym.SectionIdx);
313 for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i) {
314 ELFSym &Sym = SymbolTable[i];
315 SymTabOut.outword(Sym.NameIdx);
316 SymTabOut.outbyte(Sym.Info);
317 SymTabOut.outbyte(Sym.Other);
318 SymTabOut.outhalf(Sym.SectionIdx);
319 SymTabOut.outaddr64(Sym.Value);
320 SymTabOut.outxword(Sym.Size);
324 SymTab.Size = SymTabBuf.size();
327 /// EmitSectionTableStringTable - This method adds and emits a section for the
328 /// ELF Section Table string table: the string table that holds all of the
330 void ELFWriter::EmitSectionTableStringTable() {
331 // First step: add the section for the string table to the list of sections:
332 ELFSection &SHStrTab = getSection(".shstrtab", ELFSection::SHT_STRTAB, 0);
334 // Now that we know which section number is the .shstrtab section, update the
335 // e_shstrndx entry in the ELF header.
336 OutputBuffer FHOut(FileHeader, is64Bit, isLittleEndian);
337 FHOut.fixhalf(SHStrTab.SectionIdx, ELFHeader_e_shstrndx_Offset);
339 // Set the NameIdx of each section in the string table and emit the bytes for
342 DataBuffer &Buf = SHStrTab.SectionData;
344 for (std::list<ELFSection>::iterator I = SectionList.begin(),
345 E = SectionList.end(); I != E; ++I) {
346 // Set the index into the table. Note if we have lots of entries with
347 // common suffixes, we could memoize them here if we cared.
350 // Add the name to the output buffer, including the null terminator.
351 Buf.insert(Buf.end(), I->Name.begin(), I->Name.end());
353 // Add a null terminator.
356 // Keep track of the number of bytes emitted to this section.
357 Index += I->Name.size()+1;
360 // Set the size of .shstrtab now that we know what it is.
361 assert(Index == Buf.size());
362 SHStrTab.Size = Index;
365 /// OutputSectionsAndSectionTable - Now that we have constructed the file header
366 /// and all of the sections, emit these to the ostream destination and emit the
368 void ELFWriter::OutputSectionsAndSectionTable() {
369 // Pass #1: Compute the file offset for each section.
370 size_t FileOff = FileHeader.size(); // File header first.
372 // Emit all of the section data in order.
373 for (std::list<ELFSection>::iterator I = SectionList.begin(),
374 E = SectionList.end(); I != E; ++I) {
375 // Align FileOff to whatever the alignment restrictions of the section are.
377 FileOff = (FileOff+I->Align-1) & ~(I->Align-1);
379 FileOff += I->SectionData.size();
382 // Align Section Header.
383 unsigned TableAlign = is64Bit ? 8 : 4;
384 FileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
386 // Now that we know where all of the sections will be emitted, set the e_shnum
387 // entry in the ELF header.
388 OutputBuffer FHOut(FileHeader, is64Bit, isLittleEndian);
389 FHOut.fixhalf(NumSections, ELFHeader_e_shnum_Offset);
391 // Now that we know the offset in the file of the section table, update the
392 // e_shoff address in the ELF header.
393 FHOut.fixaddr(FileOff, ELFHeader_e_shoff_Offset);
395 // Now that we know all of the data in the file header, emit it and all of the
397 O.write((char*)&FileHeader[0], FileHeader.size());
398 FileOff = FileHeader.size();
399 DataBuffer().swap(FileHeader);
402 OutputBuffer TableOut(Table, is64Bit, isLittleEndian);
404 // Emit all of the section data and build the section table itself.
405 while (!SectionList.empty()) {
406 const ELFSection &S = *SectionList.begin();
408 // Align FileOff to whatever the alignment restrictions of the section are.
410 for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
411 FileOff != NewFileOff; ++FileOff)
413 O.write((char*)&S.SectionData[0], S.SectionData.size());
414 FileOff += S.SectionData.size();
416 TableOut.outword(S.NameIdx); // sh_name - Symbol table name idx
417 TableOut.outword(S.Type); // sh_type - Section contents & semantics
418 TableOut.outword(S.Flags); // sh_flags - Section flags.
419 TableOut.outaddr(S.Addr); // sh_addr - The mem addr this section is in.
420 TableOut.outaddr(S.Offset); // sh_offset - Offset from the file start.
421 TableOut.outword(S.Size); // sh_size - The section size.
422 TableOut.outword(S.Link); // sh_link - Section header table index link.
423 TableOut.outword(S.Info); // sh_info - Auxillary information.
424 TableOut.outword(S.Align); // sh_addralign - Alignment of section.
425 TableOut.outword(S.EntSize); // sh_entsize - Size of entries in the section
427 SectionList.pop_front();
430 // Align output for the section table.
431 for (size_t NewFileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
432 FileOff != NewFileOff; ++FileOff)
435 // Emit the section table itself.
436 O.write((char*)&Table[0], Table.size());