blob: d054adb9de6f9566bfb547f31ef2e5175bf5a8ad [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- ELFWriter.cpp - Target-independent ELF Writer code ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the target-independent ELF writer. This file writes out
11// the ELF file in the following order:
12//
13// #1. ELF Header
14// #2. '.text' section
15// #3. '.data' section
16// #4. '.bss' section (conceptual position in file)
17// ...
18// #X. '.shstrtab' section
19// #Y. Section Table
20//
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 ]
26// ...
27// #N. ".shstrtab" entry - String table for the section names.
28//
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!
31//
32//===----------------------------------------------------------------------===//
33
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 <list>
48using namespace llvm;
49
50char ELFWriter::ID = 0;
51/// AddELFWriter - Concrete function to add the ELF writer to the function pass
52/// manager.
53MachineCodeEmitter *llvm::AddELFWriter(FunctionPassManager &FPM,
54 std::ostream &O,
55 TargetMachine &TM) {
56 ELFWriter *EW = new ELFWriter(O, TM);
57 FPM.add(EW);
58 return &EW->getMachineCodeEmitter();
59}
60
61//===----------------------------------------------------------------------===//
62// ELFCodeEmitter Implementation
63//===----------------------------------------------------------------------===//
64
65namespace llvm {
66 /// ELFCodeEmitter - This class is used by the ELFWriter to emit the code for
67 /// functions to the ELF file.
68 class ELFCodeEmitter : public MachineCodeEmitter {
69 ELFWriter &EW;
70 TargetMachine &TM;
71 ELFWriter::ELFSection *ES; // Section to write to.
72 std::vector<unsigned char> *OutBuffer;
73 size_t FnStart;
74 public:
Dan Gohmanc43c7f42007-12-14 15:41:34 +000075 explicit ELFCodeEmitter(ELFWriter &ew) : EW(ew), TM(EW.TM), OutBuffer(0) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000076
77 void startFunction(MachineFunction &F);
78 bool finishFunction(MachineFunction &F);
79
80 void addRelocation(const MachineRelocation &MR) {
81 assert(0 && "relo not handled yet!");
82 }
83
84 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
85 }
86
87 virtual intptr_t getConstantPoolEntryAddress(unsigned Index) const {
88 assert(0 && "CP not implementated yet!");
89 return 0;
90 }
91 virtual intptr_t getJumpTableEntryAddress(unsigned Index) const {
92 assert(0 && "JT not implementated yet!");
93 return 0;
94 }
95
96 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
97 assert(0 && "JT not implementated yet!");
98 return 0;
99 }
100
101 /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
102 void startFunctionStub(unsigned StubSize, unsigned Alignment = 1) {
103 assert(0 && "JIT specific function called!");
104 abort();
105 }
106 void *finishFunctionStub(const Function *F) {
107 assert(0 && "JIT specific function called!");
108 abort();
109 return 0;
110 }
111 };
112}
113
114/// startFunction - This callback is invoked when a new machine function is
115/// about to be emitted.
116void ELFCodeEmitter::startFunction(MachineFunction &F) {
117 // Align the output buffer to the appropriate alignment.
118 unsigned Align = 16; // FIXME: GENERICIZE!!
119 // Get the ELF Section that this function belongs in.
120 ES = &EW.getSection(".text", ELFWriter::ELFSection::SHT_PROGBITS,
121 ELFWriter::ELFSection::SHF_EXECINSTR |
122 ELFWriter::ELFSection::SHF_ALLOC);
123 OutBuffer = &ES->SectionData;
124 cerr << "FIXME: This code needs to be updated for changes in the "
125 << "CodeEmitter interfaces. In particular, this should set "
126 << "BufferBegin/BufferEnd/CurBufferPtr, not deal with OutBuffer!";
127 abort();
128
129 // Upgrade the section alignment if required.
130 if (ES->Align < Align) ES->Align = Align;
131
132 // Add padding zeros to the end of the buffer to make sure that the
133 // function will start on the correct byte alignment within the section.
134 OutputBuffer OB(*OutBuffer,
135 TM.getTargetData()->getPointerSizeInBits() == 64,
136 TM.getTargetData()->isLittleEndian());
137 OB.align(Align);
138 FnStart = OutBuffer->size();
139}
140
141/// finishFunction - This callback is invoked after the function is completely
142/// finished.
143bool ELFCodeEmitter::finishFunction(MachineFunction &F) {
144 // We now know the size of the function, add a symbol to represent it.
145 ELFWriter::ELFSym FnSym(F.getFunction());
146
147 // Figure out the binding (linkage) of the symbol.
148 switch (F.getFunction()->getLinkage()) {
149 default:
150 // appending linkage is illegal for functions.
151 assert(0 && "Unknown linkage type!");
152 case GlobalValue::ExternalLinkage:
153 FnSym.SetBind(ELFWriter::ELFSym::STB_GLOBAL);
154 break;
155 case GlobalValue::LinkOnceLinkage:
156 case GlobalValue::WeakLinkage:
157 FnSym.SetBind(ELFWriter::ELFSym::STB_WEAK);
158 break;
159 case GlobalValue::InternalLinkage:
160 FnSym.SetBind(ELFWriter::ELFSym::STB_LOCAL);
161 break;
162 }
163
164 ES->Size = OutBuffer->size();
165
166 FnSym.SetType(ELFWriter::ELFSym::STT_FUNC);
167 FnSym.SectionIdx = ES->SectionIdx;
168 FnSym.Value = FnStart; // Value = Offset from start of Section.
169 FnSym.Size = OutBuffer->size()-FnStart;
170
171 // Finally, add it to the symtab.
172 EW.SymbolTable.push_back(FnSym);
173 return false;
174}
175
176//===----------------------------------------------------------------------===//
177// ELFWriter Implementation
178//===----------------------------------------------------------------------===//
179
180ELFWriter::ELFWriter(std::ostream &o, TargetMachine &tm)
181 : MachineFunctionPass((intptr_t)&ID), O(o), TM(tm) {
182 e_flags = 0; // e_flags defaults to 0, no flags.
183
184 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
185 isLittleEndian = TM.getTargetData()->isLittleEndian();
186
187 // Create the machine code emitter object for this target.
188 MCE = new ELFCodeEmitter(*this);
189 NumSections = 0;
190}
191
192ELFWriter::~ELFWriter() {
193 delete MCE;
194}
195
196// doInitialization - Emit the file header and all of the global variables for
197// the module to the ELF file.
198bool ELFWriter::doInitialization(Module &M) {
199 Mang = new Mangler(M);
200
201 // Local alias to shortenify coming code.
202 std::vector<unsigned char> &FH = FileHeader;
203 OutputBuffer FHOut(FH, is64Bit, isLittleEndian);
204
205 FHOut.outbyte(0x7F); // EI_MAG0
206 FHOut.outbyte('E'); // EI_MAG1
207 FHOut.outbyte('L'); // EI_MAG2
208 FHOut.outbyte('F'); // EI_MAG3
209 FHOut.outbyte(is64Bit ? 2 : 1); // EI_CLASS
210 FHOut.outbyte(isLittleEndian ? 1 : 2); // EI_DATA
211 FHOut.outbyte(1); // EI_VERSION
212 FH.resize(16); // EI_PAD up to 16 bytes.
213
214 // This should change for shared objects.
215 FHOut.outhalf(1); // e_type = ET_REL
216 FHOut.outword(TM.getELFWriterInfo()->getEMachine()); // target-defined
217 FHOut.outword(1); // e_version = 1
218 FHOut.outaddr(0); // e_entry = 0 -> no entry point in .o file
219 FHOut.outaddr(0); // e_phoff = 0 -> no program header for .o
220
221 ELFHeader_e_shoff_Offset = FH.size();
222 FHOut.outaddr(0); // e_shoff
223 FHOut.outword(e_flags); // e_flags = whatever the target wants
224
225 FHOut.outhalf(is64Bit ? 64 : 52); // e_ehsize = ELF header size
226 FHOut.outhalf(0); // e_phentsize = prog header entry size
227 FHOut.outhalf(0); // e_phnum = # prog header entries = 0
228 FHOut.outhalf(is64Bit ? 64 : 40); // e_shentsize = sect hdr entry size
229
230
231 ELFHeader_e_shnum_Offset = FH.size();
232 FHOut.outhalf(0); // e_shnum = # of section header ents
233 ELFHeader_e_shstrndx_Offset = FH.size();
234 FHOut.outhalf(0); // e_shstrndx = Section # of '.shstrtab'
235
236 // Add the null section, which is required to be first in the file.
237 getSection("", 0, 0);
238
239 // Start up the symbol table. The first entry in the symtab is the null
240 // entry.
241 SymbolTable.push_back(ELFSym(0));
242
243 return false;
244}
245
246void ELFWriter::EmitGlobal(GlobalVariable *GV) {
247 // If this is an external global, emit it now. TODO: Note that it would be
248 // better to ignore the symbol here and only add it to the symbol table if
249 // referenced.
250 if (!GV->hasInitializer()) {
251 ELFSym ExternalSym(GV);
252 ExternalSym.SetBind(ELFSym::STB_GLOBAL);
253 ExternalSym.SetType(ELFSym::STT_NOTYPE);
254 ExternalSym.SectionIdx = ELFSection::SHN_UNDEF;
255 SymbolTable.push_back(ExternalSym);
256 return;
257 }
258
259 const Type *GVType = (const Type*)GV->getType();
260 unsigned Align = TM.getTargetData()->getPrefTypeAlignment(GVType);
Duncan Sands8157ef42007-11-05 00:04:43 +0000261 unsigned Size = TM.getTargetData()->getABITypeSize(GVType);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262
263 // If this global has a zero initializer, it is part of the .bss or common
264 // section.
265 if (GV->getInitializer()->isNullValue()) {
266 // If this global is part of the common block, add it now. Variables are
267 // part of the common block if they are zero initialized and allowed to be
268 // merged with other symbols.
269 if (GV->hasLinkOnceLinkage() || GV->hasWeakLinkage()) {
270 ELFSym CommonSym(GV);
271 // Value for common symbols is the alignment required.
272 CommonSym.Value = Align;
273 CommonSym.Size = Size;
274 CommonSym.SetBind(ELFSym::STB_GLOBAL);
275 CommonSym.SetType(ELFSym::STT_OBJECT);
276 // TODO SOMEDAY: add ELF visibility.
277 CommonSym.SectionIdx = ELFSection::SHN_COMMON;
278 SymbolTable.push_back(CommonSym);
279 return;
280 }
281
282 // Otherwise, this symbol is part of the .bss section. Emit it now.
283
284 // Handle alignment. Ensure section is aligned at least as much as required
285 // by this symbol.
286 ELFSection &BSSSection = getBSSSection();
287 BSSSection.Align = std::max(BSSSection.Align, Align);
288
289 // Within the section, emit enough virtual padding to get us to an alignment
290 // boundary.
291 if (Align)
292 BSSSection.Size = (BSSSection.Size + Align - 1) & ~(Align-1);
293
294 ELFSym BSSSym(GV);
295 BSSSym.Value = BSSSection.Size;
296 BSSSym.Size = Size;
297 BSSSym.SetType(ELFSym::STT_OBJECT);
298
299 switch (GV->getLinkage()) {
300 default: // weak/linkonce handled above
301 assert(0 && "Unexpected linkage type!");
302 case GlobalValue::AppendingLinkage: // FIXME: This should be improved!
303 case GlobalValue::ExternalLinkage:
304 BSSSym.SetBind(ELFSym::STB_GLOBAL);
305 break;
306 case GlobalValue::InternalLinkage:
307 BSSSym.SetBind(ELFSym::STB_LOCAL);
308 break;
309 }
310
311 // Set the idx of the .bss section
312 BSSSym.SectionIdx = BSSSection.SectionIdx;
313 SymbolTable.push_back(BSSSym);
314
315 // Reserve space in the .bss section for this symbol.
316 BSSSection.Size += Size;
317 return;
318 }
319
320 // FIXME: handle .rodata
321 //assert(!GV->isConstant() && "unimp");
322
323 // FIXME: handle .data
324 //assert(0 && "unimp");
325}
326
327
328bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
329 // Nothing to do here, this is all done through the MCE object above.
330 return false;
331}
332
333/// doFinalization - Now that the module has been completely processed, emit
334/// the ELF file to 'O'.
335bool ELFWriter::doFinalization(Module &M) {
336 // Okay, the ELF header and .text sections have been completed, build the
337 // .data, .bss, and "common" sections next.
338 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
339 I != E; ++I)
340 EmitGlobal(I);
341
342 // Emit the symbol table now, if non-empty.
343 EmitSymbolTable();
344
345 // FIXME: Emit the relocations now.
346
347 // Emit the string table for the sections in the ELF file we have.
348 EmitSectionTableStringTable();
349
350 // Emit the sections to the .o file, and emit the section table for the file.
351 OutputSectionsAndSectionTable();
352
353 // We are done with the abstract symbols.
354 SectionList.clear();
355 NumSections = 0;
356
357 // Release the name mangler object.
358 delete Mang; Mang = 0;
359 return false;
360}
361
362/// EmitSymbolTable - If the current symbol table is non-empty, emit the string
363/// table for it and then the symbol table itself.
364void ELFWriter::EmitSymbolTable() {
365 if (SymbolTable.size() == 1) return; // Only the null entry.
366
367 // FIXME: compact all local symbols to the start of the symtab.
368 unsigned FirstNonLocalSymbol = 1;
369
370 ELFSection &StrTab = getSection(".strtab", ELFSection::SHT_STRTAB, 0);
371 StrTab.Align = 1;
372
373 DataBuffer &StrTabBuf = StrTab.SectionData;
374 OutputBuffer StrTabOut(StrTabBuf, is64Bit, isLittleEndian);
375
376 // Set the zero'th symbol to a null byte, as required.
377 StrTabOut.outbyte(0);
378 SymbolTable[0].NameIdx = 0;
379 unsigned Index = 1;
380 for (unsigned i = 1, e = SymbolTable.size(); i != e; ++i) {
381 // Use the name mangler to uniquify the LLVM symbol.
382 std::string Name = Mang->getValueName(SymbolTable[i].GV);
383
384 if (Name.empty()) {
385 SymbolTable[i].NameIdx = 0;
386 } else {
387 SymbolTable[i].NameIdx = Index;
388
389 // Add the name to the output buffer, including the null terminator.
390 StrTabBuf.insert(StrTabBuf.end(), Name.begin(), Name.end());
391
392 // Add a null terminator.
393 StrTabBuf.push_back(0);
394
395 // Keep track of the number of bytes emitted to this section.
396 Index += Name.size()+1;
397 }
398 }
399 assert(Index == StrTabBuf.size());
400 StrTab.Size = Index;
401
402 // Now that we have emitted the string table and know the offset into the
403 // string table of each symbol, emit the symbol table itself.
404 ELFSection &SymTab = getSection(".symtab", ELFSection::SHT_SYMTAB, 0);
405 SymTab.Align = is64Bit ? 8 : 4;
406 SymTab.Link = SymTab.SectionIdx; // Section Index of .strtab.
407 SymTab.Info = FirstNonLocalSymbol; // First non-STB_LOCAL symbol.
408 SymTab.EntSize = 16; // Size of each symtab entry. FIXME: wrong for ELF64
409 DataBuffer &SymTabBuf = SymTab.SectionData;
410 OutputBuffer SymTabOut(SymTabBuf, is64Bit, isLittleEndian);
411
412 if (!is64Bit) { // 32-bit and 64-bit formats are shuffled a bit.
413 for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i) {
414 ELFSym &Sym = SymbolTable[i];
415 SymTabOut.outword(Sym.NameIdx);
416 SymTabOut.outaddr32(Sym.Value);
417 SymTabOut.outword(Sym.Size);
418 SymTabOut.outbyte(Sym.Info);
419 SymTabOut.outbyte(Sym.Other);
420 SymTabOut.outhalf(Sym.SectionIdx);
421 }
422 } else {
423 for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i) {
424 ELFSym &Sym = SymbolTable[i];
425 SymTabOut.outword(Sym.NameIdx);
426 SymTabOut.outbyte(Sym.Info);
427 SymTabOut.outbyte(Sym.Other);
428 SymTabOut.outhalf(Sym.SectionIdx);
429 SymTabOut.outaddr64(Sym.Value);
430 SymTabOut.outxword(Sym.Size);
431 }
432 }
433
434 SymTab.Size = SymTabBuf.size();
435}
436
437/// EmitSectionTableStringTable - This method adds and emits a section for the
438/// ELF Section Table string table: the string table that holds all of the
439/// section names.
440void ELFWriter::EmitSectionTableStringTable() {
441 // First step: add the section for the string table to the list of sections:
442 ELFSection &SHStrTab = getSection(".shstrtab", ELFSection::SHT_STRTAB, 0);
443
444 // Now that we know which section number is the .shstrtab section, update the
445 // e_shstrndx entry in the ELF header.
446 OutputBuffer FHOut(FileHeader, is64Bit, isLittleEndian);
447 FHOut.fixhalf(SHStrTab.SectionIdx, ELFHeader_e_shstrndx_Offset);
448
449 // Set the NameIdx of each section in the string table and emit the bytes for
450 // the string table.
451 unsigned Index = 0;
452 DataBuffer &Buf = SHStrTab.SectionData;
453
454 for (std::list<ELFSection>::iterator I = SectionList.begin(),
455 E = SectionList.end(); I != E; ++I) {
456 // Set the index into the table. Note if we have lots of entries with
457 // common suffixes, we could memoize them here if we cared.
458 I->NameIdx = Index;
459
460 // Add the name to the output buffer, including the null terminator.
461 Buf.insert(Buf.end(), I->Name.begin(), I->Name.end());
462
463 // Add a null terminator.
464 Buf.push_back(0);
465
466 // Keep track of the number of bytes emitted to this section.
467 Index += I->Name.size()+1;
468 }
469
470 // Set the size of .shstrtab now that we know what it is.
471 assert(Index == Buf.size());
472 SHStrTab.Size = Index;
473}
474
475/// OutputSectionsAndSectionTable - Now that we have constructed the file header
476/// and all of the sections, emit these to the ostream destination and emit the
477/// SectionTable.
478void ELFWriter::OutputSectionsAndSectionTable() {
479 // Pass #1: Compute the file offset for each section.
480 size_t FileOff = FileHeader.size(); // File header first.
481
482 // Emit all of the section data in order.
483 for (std::list<ELFSection>::iterator I = SectionList.begin(),
484 E = SectionList.end(); I != E; ++I) {
485 // Align FileOff to whatever the alignment restrictions of the section are.
486 if (I->Align)
487 FileOff = (FileOff+I->Align-1) & ~(I->Align-1);
488 I->Offset = FileOff;
489 FileOff += I->SectionData.size();
490 }
491
492 // Align Section Header.
493 unsigned TableAlign = is64Bit ? 8 : 4;
494 FileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
495
496 // Now that we know where all of the sections will be emitted, set the e_shnum
497 // entry in the ELF header.
498 OutputBuffer FHOut(FileHeader, is64Bit, isLittleEndian);
499 FHOut.fixhalf(NumSections, ELFHeader_e_shnum_Offset);
500
501 // Now that we know the offset in the file of the section table, update the
502 // e_shoff address in the ELF header.
503 FHOut.fixaddr(FileOff, ELFHeader_e_shoff_Offset);
504
505 // Now that we know all of the data in the file header, emit it and all of the
506 // sections!
507 O.write((char*)&FileHeader[0], FileHeader.size());
508 FileOff = FileHeader.size();
509 DataBuffer().swap(FileHeader);
510
511 DataBuffer Table;
512 OutputBuffer TableOut(Table, is64Bit, isLittleEndian);
513
514 // Emit all of the section data and build the section table itself.
515 while (!SectionList.empty()) {
516 const ELFSection &S = *SectionList.begin();
517
518 // Align FileOff to whatever the alignment restrictions of the section are.
519 if (S.Align)
520 for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
521 FileOff != NewFileOff; ++FileOff)
522 O.put((char)0xAB);
523 O.write((char*)&S.SectionData[0], S.SectionData.size());
524 FileOff += S.SectionData.size();
525
526 TableOut.outword(S.NameIdx); // sh_name - Symbol table name idx
527 TableOut.outword(S.Type); // sh_type - Section contents & semantics
528 TableOut.outword(S.Flags); // sh_flags - Section flags.
529 TableOut.outaddr(S.Addr); // sh_addr - The mem addr this section is in.
530 TableOut.outaddr(S.Offset); // sh_offset - Offset from the file start.
531 TableOut.outword(S.Size); // sh_size - The section size.
532 TableOut.outword(S.Link); // sh_link - Section header table index link.
533 TableOut.outword(S.Info); // sh_info - Auxillary information.
534 TableOut.outword(S.Align); // sh_addralign - Alignment of section.
535 TableOut.outword(S.EntSize); // sh_entsize - Size of entries in the section
536
537 SectionList.pop_front();
538 }
539
540 // Align output for the section table.
541 for (size_t NewFileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
542 FileOff != NewFileOff; ++FileOff)
543 O.put((char)0xAB);
544
545 // Emit the section table itself.
546 O.write((char*)&Table[0], Table.size());
547}