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 //===----------------------------------------------------------------------===//
31 #define DEBUG_TYPE "elfwriter"
33 #include "ELFWriter.h"
34 #include "ELFCodeEmitter.h"
35 #include "llvm/Constants.h"
36 #include "llvm/Module.h"
37 #include "llvm/PassManager.h"
38 #include "llvm/DerivedTypes.h"
39 #include "llvm/CodeGen/BinaryObject.h"
40 #include "llvm/CodeGen/FileWriters.h"
41 #include "llvm/CodeGen/MachineCodeEmitter.h"
42 #include "llvm/CodeGen/ObjectCodeEmitter.h"
43 #include "llvm/CodeGen/MachineCodeEmitter.h"
44 #include "llvm/CodeGen/MachineConstantPool.h"
45 #include "llvm/Target/TargetAsmInfo.h"
46 #include "llvm/Target/TargetData.h"
47 #include "llvm/Target/TargetELFWriterInfo.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include "llvm/Support/Mangler.h"
50 #include "llvm/Support/Streams.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/ErrorHandling.h"
57 char ELFWriter::ID = 0;
59 /// AddELFWriter - Add the ELF writer to the function pass manager
60 ObjectCodeEmitter *llvm::AddELFWriter(PassManagerBase &PM,
63 ELFWriter *EW = new ELFWriter(O, TM);
65 return EW->getObjectCodeEmitter();
68 //===----------------------------------------------------------------------===//
69 // ELFWriter Implementation
70 //===----------------------------------------------------------------------===//
72 ELFWriter::ELFWriter(raw_ostream &o, TargetMachine &tm)
73 : MachineFunctionPass(&ID), O(o), TM(tm),
74 is64Bit(TM.getTargetData()->getPointerSizeInBits() == 64),
75 isLittleEndian(TM.getTargetData()->isLittleEndian()),
76 ElfHdr(isLittleEndian, is64Bit) {
78 TAI = TM.getTargetAsmInfo();
79 TEW = TM.getELFWriterInfo();
81 // Create the object code emitter object for this target.
82 ElfCE = new ELFCodeEmitter(*this);
84 // Inital number of sections
88 ELFWriter::~ELFWriter() {
92 // doInitialization - Emit the file header and all of the global variables for
93 // the module to the ELF file.
94 bool ELFWriter::doInitialization(Module &M) {
95 Mang = new Mangler(M);
99 // Fields e_shnum e_shstrndx are only known after all section have
100 // been emitted. They locations in the ouput buffer are recorded so
101 // to be patched up later.
105 // emitWord method behaves differently for ELF32 and ELF64, writing
106 // 4 bytes in the former and 8 in the last for *_off and *_addr elf types
108 ElfHdr.emitByte(0x7f); // e_ident[EI_MAG0]
109 ElfHdr.emitByte('E'); // e_ident[EI_MAG1]
110 ElfHdr.emitByte('L'); // e_ident[EI_MAG2]
111 ElfHdr.emitByte('F'); // e_ident[EI_MAG3]
113 ElfHdr.emitByte(TEW->getEIClass()); // e_ident[EI_CLASS]
114 ElfHdr.emitByte(TEW->getEIData()); // e_ident[EI_DATA]
115 ElfHdr.emitByte(EV_CURRENT); // e_ident[EI_VERSION]
116 ElfHdr.emitAlignment(16); // e_ident[EI_NIDENT-EI_PAD]
118 ElfHdr.emitWord16(ET_REL); // e_type
119 ElfHdr.emitWord16(TEW->getEMachine()); // e_machine = target
120 ElfHdr.emitWord32(EV_CURRENT); // e_version
121 ElfHdr.emitWord(0); // e_entry, no entry point in .o file
122 ElfHdr.emitWord(0); // e_phoff, no program header for .o
123 ELFHdr_e_shoff_Offset = ElfHdr.size();
124 ElfHdr.emitWord(0); // e_shoff = sec hdr table off in bytes
125 ElfHdr.emitWord32(TEW->getEFlags()); // e_flags = whatever the target wants
126 ElfHdr.emitWord16(TEW->getHdrSize()); // e_ehsize = ELF header size
127 ElfHdr.emitWord16(0); // e_phentsize = prog header entry size
128 ElfHdr.emitWord16(0); // e_phnum = # prog header entries = 0
130 // e_shentsize = Section header entry size
131 ElfHdr.emitWord16(TEW->getSHdrSize());
133 // e_shnum = # of section header ents
134 ELFHdr_e_shnum_Offset = ElfHdr.size();
135 ElfHdr.emitWord16(0); // Placeholder
137 // e_shstrndx = Section # of '.shstrtab'
138 ELFHdr_e_shstrndx_Offset = ElfHdr.size();
139 ElfHdr.emitWord16(0); // Placeholder
141 // Add the null section, which is required to be first in the file.
147 // Get jump table section on the section name returned by TAI
148 ELFSection &ELFWriter::getJumpTableSection() {
149 unsigned Align = TM.getTargetData()->getPointerABIAlignment();
150 return getSection(TAI->getJumpTableDataSection(),
151 ELFSection::SHT_PROGBITS,
152 ELFSection::SHF_ALLOC, Align);
155 // Get a constant pool section based on the section name returned by TAI
156 ELFSection &ELFWriter::getConstantPoolSection(MachineConstantPoolEntry &CPE) {
158 switch (CPE.getRelocationInfo()) {
159 default: llvm_unreachable("Unknown section kind");
160 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
161 case 1: Kind = SectionKind::getReadOnlyWithRelLocal(); break;
163 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
164 case 4: Kind = SectionKind::getMergableConst4(); break;
165 case 8: Kind = SectionKind::getMergableConst8(); break;
166 case 16: Kind = SectionKind::getMergableConst16(); break;
167 default: Kind = SectionKind::getMergableConst(); break;
171 std::string CstPoolName = TAI->getSectionForMergableConstant(Kind)->getName();
172 return getSection(CstPoolName,
173 ELFSection::SHT_PROGBITS,
174 ELFSection::SHF_MERGE | ELFSection::SHF_ALLOC,
178 // Return the relocation section of section 'S'. 'RelA' is true
179 // if the relocation section contains entries with addends.
180 ELFSection &ELFWriter::getRelocSection(ELFSection &S) {
181 unsigned SectionHeaderTy = TEW->hasRelocationAddend() ?
182 ELFSection::SHT_RELA : ELFSection::SHT_REL;
183 std::string RelSName(".rel");
184 if (TEW->hasRelocationAddend())
185 RelSName.append("a");
186 RelSName.append(S.getName());
188 return getSection(RelSName, SectionHeaderTy, 0, TEW->getPrefELFAlignment());
191 // getGlobalELFVisibility - Returns the ELF specific visibility type
192 unsigned ELFWriter::getGlobalELFVisibility(const GlobalValue *GV) {
193 switch (GV->getVisibility()) {
195 llvm_unreachable("unknown visibility type");
196 case GlobalValue::DefaultVisibility:
197 return ELFSym::STV_DEFAULT;
198 case GlobalValue::HiddenVisibility:
199 return ELFSym::STV_HIDDEN;
200 case GlobalValue::ProtectedVisibility:
201 return ELFSym::STV_PROTECTED;
206 // getGlobalELFBinding - Returns the ELF specific binding type
207 unsigned ELFWriter::getGlobalELFBinding(const GlobalValue *GV) {
208 if (GV->hasInternalLinkage())
209 return ELFSym::STB_LOCAL;
211 if (GV->hasWeakLinkage())
212 return ELFSym::STB_WEAK;
214 return ELFSym::STB_GLOBAL;
217 // getGlobalELFType - Returns the ELF specific type for a global
218 unsigned ELFWriter::getGlobalELFType(const GlobalValue *GV) {
219 if (GV->isDeclaration())
220 return ELFSym::STT_NOTYPE;
222 if (isa<Function>(GV))
223 return ELFSym::STT_FUNC;
225 return ELFSym::STT_OBJECT;
228 // getElfSectionFlags - Get the ELF Section Header flags based
229 // on the flags defined in ELFTargetAsmInfo.
230 unsigned ELFWriter::getElfSectionFlags(unsigned Flags) {
231 unsigned ElfSectionFlags = ELFSection::SHF_ALLOC;
233 if (Flags & SectionFlags::Code)
234 ElfSectionFlags |= ELFSection::SHF_EXECINSTR;
235 if (Flags & SectionFlags::Writable)
236 ElfSectionFlags |= ELFSection::SHF_WRITE;
237 if (Flags & SectionFlags::Mergeable)
238 ElfSectionFlags |= ELFSection::SHF_MERGE;
239 if (Flags & SectionFlags::TLS)
240 ElfSectionFlags |= ELFSection::SHF_TLS;
241 if (Flags & SectionFlags::Strings)
242 ElfSectionFlags |= ELFSection::SHF_STRINGS;
244 return ElfSectionFlags;
247 // isELFUndefSym - the symbol has no section and must be placed in
248 // the symbol table with a reference to the null section.
249 static bool isELFUndefSym(const GlobalValue *GV) {
250 return GV->isDeclaration();
253 // isELFBssSym - for an undef or null value, the symbol must go to a bss
254 // section if it's not weak for linker, otherwise it's a common sym.
255 static bool isELFBssSym(const GlobalVariable *GV) {
256 const Constant *CV = GV->getInitializer();
257 return ((CV->isNullValue() || isa<UndefValue>(CV)) && !GV->isWeakForLinker());
260 // isELFCommonSym - for an undef or null value, the symbol must go to a
261 // common section if it's weak for linker, otherwise bss.
262 static bool isELFCommonSym(const GlobalVariable *GV) {
263 const Constant *CV = GV->getInitializer();
264 return ((CV->isNullValue() || isa<UndefValue>(CV)) && GV->isWeakForLinker());
267 // isELFDataSym - if the symbol is an initialized but no null constant
268 // it must go to some kind of data section gathered from TAI
269 static bool isELFDataSym(const Constant *CV) {
270 return (!(CV->isNullValue() || isa<UndefValue>(CV)));
273 // EmitGlobal - Choose the right section for global and emit it
274 void ELFWriter::EmitGlobal(const GlobalValue *GV) {
276 // Check if the referenced symbol is already emitted
277 if (GblSymLookup.find(GV) != GblSymLookup.end())
280 // Handle ELF Bind, Visibility and Type for the current symbol
281 unsigned SymBind = getGlobalELFBinding(GV);
282 ELFSym *GblSym = new ELFSym(GV);
283 GblSym->setBind(SymBind);
284 GblSym->setVisibility(getGlobalELFVisibility(GV));
285 GblSym->setType(getGlobalELFType(GV));
287 if (isELFUndefSym(GV)) {
288 GblSym->SectionIdx = ELFSection::SHN_UNDEF;
290 assert(isa<GlobalVariable>(GV) && "GV not a global variable!");
291 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
293 // Get ELF section from TAI
294 const Section *S = TAI->SectionForGlobal(GV);
295 unsigned SectionFlags = getElfSectionFlags(S->getFlags());
297 // The symbol align should update the section alignment if needed
298 const TargetData *TD = TM.getTargetData();
299 unsigned Align = TD->getPreferredAlignment(GVar);
300 unsigned Size = TD->getTypeAllocSize(GVar->getInitializer()->getType());
303 if (isELFCommonSym(GVar)) {
304 GblSym->SectionIdx = ELFSection::SHN_COMMON;
305 getSection(S->getName(), ELFSection::SHT_NOBITS, SectionFlags, 1);
307 // A new linkonce section is created for each global in the
308 // common section, the default alignment is 1 and the symbol
309 // value contains its alignment.
310 GblSym->Value = Align;
312 } else if (isELFBssSym(GVar)) {
314 getSection(S->getName(), ELFSection::SHT_NOBITS, SectionFlags);
315 GblSym->SectionIdx = ES.SectionIdx;
317 // Update the size with alignment and the next object can
318 // start in the right offset in the section
319 if (Align) ES.Size = (ES.Size + Align-1) & ~(Align-1);
320 ES.Align = std::max(ES.Align, Align);
322 // GblSym->Value should contain the virtual offset inside the section.
323 // Virtual because the BSS space is not allocated on ELF objects
324 GblSym->Value = ES.Size;
327 } else if (isELFDataSym(GV)) {
329 getSection(S->getName(), ELFSection::SHT_PROGBITS, SectionFlags);
330 GblSym->SectionIdx = ES.SectionIdx;
332 // GblSym->Value should contain the symbol offset inside the section,
333 // and all symbols should start on their required alignment boundary
334 ES.Align = std::max(ES.Align, Align);
335 GblSym->Value = (ES.size() + (Align-1)) & (-Align);
336 ES.emitAlignment(ES.Align);
338 // Emit the global to the data section 'ES'
339 EmitGlobalConstant(GVar->getInitializer(), ES);
343 // Private symbols must never go to the symbol table.
345 if (GV->hasPrivateLinkage()) {
346 PrivateSyms.push_back(GblSym);
347 SymIdx = PrivateSyms.size()-1;
349 SymbolList.push_back(GblSym);
352 setGlobalSymLookup(GV, SymIdx);
355 void ELFWriter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
358 // Print the fields in successive locations. Pad to align if needed!
359 const TargetData *TD = TM.getTargetData();
360 unsigned Size = TD->getTypeAllocSize(CVS->getType());
361 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
362 uint64_t sizeSoFar = 0;
363 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
364 const Constant* field = CVS->getOperand(i);
366 // Check if padding is needed and insert one or more 0s.
367 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
368 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
369 - cvsLayout->getElementOffset(i)) - fieldSize;
370 sizeSoFar += fieldSize + padSize;
372 // Now print the actual field value.
373 EmitGlobalConstant(field, GblS);
375 // Insert padding - this may include padding to increase the size of the
376 // current field up to the ABI size (if the struct is not packed) as well
377 // as padding to ensure that the next field starts at the right offset.
378 for (unsigned p=0; p < padSize; p++)
381 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
382 "Layout of constant struct may be incorrect!");
385 void ELFWriter::EmitGlobalConstant(const Constant *CV, ELFSection &GblS) {
386 const TargetData *TD = TM.getTargetData();
387 unsigned Size = TD->getTypeAllocSize(CV->getType());
389 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
390 if (CVA->isString()) {
391 std::string GblStr = CVA->getAsString();
392 GblStr.resize(GblStr.size()-1);
393 GblS.emitString(GblStr);
394 } else { // Not a string. Print the values in successive locations
395 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
396 EmitGlobalConstant(CVA->getOperand(i), GblS);
399 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
400 EmitGlobalConstantStruct(CVS, GblS);
402 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
403 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
404 if (CFP->getType() == Type::DoubleTy)
405 GblS.emitWord64(Val);
406 else if (CFP->getType() == Type::FloatTy)
407 GblS.emitWord32(Val);
408 else if (CFP->getType() == Type::X86_FP80Ty) {
409 llvm_unreachable("X86_FP80Ty global emission not implemented");
410 } else if (CFP->getType() == Type::PPC_FP128Ty)
411 llvm_unreachable("PPC_FP128Ty global emission not implemented");
413 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
415 GblS.emitWord32(CI->getZExtValue());
417 GblS.emitWord64(CI->getZExtValue());
419 llvm_unreachable("LargeInt global emission not implemented");
421 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
422 const VectorType *PTy = CP->getType();
423 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
424 EmitGlobalConstant(CP->getOperand(I), GblS);
426 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
427 // This is a constant address for a global variable or function and
428 // therefore must be referenced using a relocation entry.
430 // Check if the referenced symbol is already emitted
431 if (GblSymLookup.find(GV) == GblSymLookup.end())
434 // Create the relocation entry for the global value
435 MachineRelocation MR =
436 MachineRelocation::getGV(GblS.getCurrentPCOffset(),
437 TEW->getAbsoluteLabelMachineRelTy(),
438 const_cast<GlobalValue*>(GV));
440 // Fill the data entry with zeros
441 for (unsigned i=0; i < Size; ++i)
444 // Add the relocation entry for the current data section
445 GblS.addRelocation(MR);
447 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
448 if (CE->getOpcode() == Instruction::BitCast) {
449 EmitGlobalConstant(CE->getOperand(0), GblS);
452 // See AsmPrinter::EmitConstantValueOnly for other ConstantExpr types
453 llvm_unreachable("Unsupported ConstantExpr type");
456 llvm_unreachable("Unknown global constant type");
460 bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
461 // Nothing to do here, this is all done through the ElfCE object above.
465 /// doFinalization - Now that the module has been completely processed, emit
466 /// the ELF file to 'O'.
467 bool ELFWriter::doFinalization(Module &M) {
468 // Emit .data section placeholder
471 // Emit .bss section placeholder
474 // Build and emit data, bss and "common" sections.
475 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
479 // Emit all pending globals
480 for (SetVector<GlobalValue*>::const_iterator I = PendingGlobals.begin(),
481 E = PendingGlobals.end(); I != E; ++I)
484 // Emit non-executable stack note
485 if (TAI->getNonexecutableStackDirective())
486 getNonExecStackSection();
488 // Emit a symbol for each section created until now, skip null section
489 for (unsigned i = 1, e = SectionList.size(); i < e; ++i) {
490 ELFSection &ES = *SectionList[i];
491 ELFSym *SectionSym = new ELFSym(0);
492 SectionSym->SectionIdx = ES.SectionIdx;
493 SectionSym->Size = 0;
494 SectionSym->setBind(ELFSym::STB_LOCAL);
495 SectionSym->setType(ELFSym::STT_SECTION);
496 SectionSym->setVisibility(ELFSym::STV_DEFAULT);
497 SymbolList.push_back(SectionSym);
498 ES.Sym = SymbolList.back();
504 // Emit the symbol table now, if non-empty.
507 // Emit the relocation sections.
510 // Emit the sections string table.
511 EmitSectionTableStringTable();
513 // Dump the sections and section table to the .o file.
514 OutputSectionsAndSectionTable();
516 // We are done with the abstract symbols.
521 // Release the name mangler object.
522 delete Mang; Mang = 0;
526 // RelocateField - Patch relocatable field with 'Offset' in 'BO'
527 // using a 'Value' of known 'Size'
528 void ELFWriter::RelocateField(BinaryObject &BO, uint32_t Offset,
529 int64_t Value, unsigned Size) {
531 BO.fixWord32(Value, Offset);
533 BO.fixWord64(Value, Offset);
535 llvm_unreachable("don't know howto patch relocatable field");
538 /// EmitRelocations - Emit relocations
539 void ELFWriter::EmitRelocations() {
541 // True if the target uses the relocation entry to hold the addend,
542 // otherwise the addend is written directly to the relocatable field.
543 bool HasRelA = TEW->hasRelocationAddend();
545 // Create Relocation sections for each section which needs it.
546 for (unsigned i=0, e=SectionList.size(); i != e; ++i) {
547 ELFSection &S = *SectionList[i];
549 // This section does not have relocations
550 if (!S.hasRelocations()) continue;
551 ELFSection &RelSec = getRelocSection(S);
553 // 'Link' - Section hdr idx of the associated symbol table
554 // 'Info' - Section hdr idx of the section to which the relocation applies
555 ELFSection &SymTab = getSymbolTableSection();
556 RelSec.Link = SymTab.SectionIdx;
557 RelSec.Info = S.SectionIdx;
558 RelSec.EntSize = TEW->getRelocationEntrySize();
560 // Get the relocations from Section
561 std::vector<MachineRelocation> Relos = S.getRelocations();
562 for (std::vector<MachineRelocation>::iterator MRI = Relos.begin(),
563 MRE = Relos.end(); MRI != MRE; ++MRI) {
564 MachineRelocation &MR = *MRI;
566 // Relocatable field offset from the section start
567 unsigned RelOffset = MR.getMachineCodeOffset();
569 // Symbol index in the symbol table
572 // Target specific relocation field type and size
573 unsigned RelType = TEW->getRelocationType(MR.getRelocationType());
574 unsigned RelTySize = TEW->getRelocationTySize(RelType);
577 // There are several machine relocations types, and each one of
578 // them needs a different approach to retrieve the symbol table index.
579 if (MR.isGlobalValue()) {
580 const GlobalValue *G = MR.getGlobalValue();
581 SymIdx = GblSymLookup[G];
582 if (G->hasPrivateLinkage()) {
583 // If the target uses a section offset in the relocation:
584 // SymIdx + Addend = section sym for global + section offset
585 unsigned SectionIdx = PrivateSyms[SymIdx]->SectionIdx;
586 Addend = PrivateSyms[SymIdx]->Value;
587 SymIdx = SectionList[SectionIdx]->getSymbolTableIndex();
589 Addend = TEW->getDefaultAddendForRelTy(RelType);
592 // Get the symbol index for the section symbol
593 unsigned SectionIdx = MR.getConstantVal();
594 SymIdx = SectionList[SectionIdx]->getSymbolTableIndex();
595 Addend = (uint64_t)MR.getResultPointer();
597 // For pc relative relocations where symbols are defined in the same
598 // section they are referenced, ignore the relocation entry and patch
599 // the relocatable field with the symbol offset directly.
600 if (S.SectionIdx == SectionIdx && TEW->isPCRelativeRel(RelType)) {
601 int64_t Value = TEW->computeRelocation(Addend, RelOffset, RelType);
602 RelocateField(S, RelOffset, Value, RelTySize);
606 // Handle Jump Table Index relocation
607 if ((SectionIdx == getJumpTableSection().SectionIdx) &&
608 TEW->hasCustomJumpTableIndexRelTy()) {
609 RelType = TEW->getJumpTableIndexRelTy();
610 RelTySize = TEW->getRelocationTySize(RelType);
614 // The target without addend on the relocation symbol must be
615 // patched in the relocation place itself to contain the addend
617 RelocateField(S, RelOffset, Addend, RelTySize);
619 // Get the relocation entry and emit to the relocation section
620 ELFRelocation Rel(RelOffset, SymIdx, RelType, HasRelA, Addend);
621 EmitRelocation(RelSec, Rel, HasRelA);
626 /// EmitRelocation - Write relocation 'Rel' to the relocation section 'Rel'
627 void ELFWriter::EmitRelocation(BinaryObject &RelSec, ELFRelocation &Rel,
629 RelSec.emitWord(Rel.getOffset());
630 RelSec.emitWord(Rel.getInfo(is64Bit));
632 RelSec.emitWord(Rel.getAddend());
635 /// EmitSymbol - Write symbol 'Sym' to the symbol table 'SymbolTable'
636 void ELFWriter::EmitSymbol(BinaryObject &SymbolTable, ELFSym &Sym) {
638 SymbolTable.emitWord32(Sym.NameIdx);
639 SymbolTable.emitByte(Sym.Info);
640 SymbolTable.emitByte(Sym.Other);
641 SymbolTable.emitWord16(Sym.SectionIdx);
642 SymbolTable.emitWord64(Sym.Value);
643 SymbolTable.emitWord64(Sym.Size);
645 SymbolTable.emitWord32(Sym.NameIdx);
646 SymbolTable.emitWord32(Sym.Value);
647 SymbolTable.emitWord32(Sym.Size);
648 SymbolTable.emitByte(Sym.Info);
649 SymbolTable.emitByte(Sym.Other);
650 SymbolTable.emitWord16(Sym.SectionIdx);
654 /// EmitSectionHeader - Write section 'Section' header in 'SHdrTab'
655 /// Section Header Table
656 void ELFWriter::EmitSectionHeader(BinaryObject &SHdrTab,
657 const ELFSection &SHdr) {
658 SHdrTab.emitWord32(SHdr.NameIdx);
659 SHdrTab.emitWord32(SHdr.Type);
661 SHdrTab.emitWord64(SHdr.Flags);
662 SHdrTab.emitWord(SHdr.Addr);
663 SHdrTab.emitWord(SHdr.Offset);
664 SHdrTab.emitWord64(SHdr.Size);
665 SHdrTab.emitWord32(SHdr.Link);
666 SHdrTab.emitWord32(SHdr.Info);
667 SHdrTab.emitWord64(SHdr.Align);
668 SHdrTab.emitWord64(SHdr.EntSize);
670 SHdrTab.emitWord32(SHdr.Flags);
671 SHdrTab.emitWord(SHdr.Addr);
672 SHdrTab.emitWord(SHdr.Offset);
673 SHdrTab.emitWord32(SHdr.Size);
674 SHdrTab.emitWord32(SHdr.Link);
675 SHdrTab.emitWord32(SHdr.Info);
676 SHdrTab.emitWord32(SHdr.Align);
677 SHdrTab.emitWord32(SHdr.EntSize);
681 /// EmitStringTable - If the current symbol table is non-empty, emit the string
683 void ELFWriter::EmitStringTable() {
684 if (!SymbolList.size()) return; // Empty symbol table.
685 ELFSection &StrTab = getStringTableSection();
687 // Set the zero'th symbol to a null byte, as required.
690 // Walk on the symbol list and write symbol names into the string table.
692 for (ELFSymIter I=SymbolList.begin(), E=SymbolList.end(); I != E; ++I) {
695 // Use the name mangler to uniquify the LLVM symbol.
697 if (Sym.GV) Name.append(Mang->getMangledName(Sym.GV));
703 StrTab.emitString(Name);
705 // Keep track of the number of bytes emitted to this section.
706 Index += Name.size()+1;
709 assert(Index == StrTab.size());
713 // SortSymbols - On the symbol table local symbols must come before
714 // all other symbols with non-local bindings. The return value is
715 // the position of the first non local symbol.
716 unsigned ELFWriter::SortSymbols() {
717 unsigned FirstNonLocalSymbol;
718 std::vector<ELFSym*> LocalSyms, OtherSyms;
720 for (ELFSymIter I=SymbolList.begin(), E=SymbolList.end(); I != E; ++I) {
721 if ((*I)->isLocalBind())
722 LocalSyms.push_back(*I);
724 OtherSyms.push_back(*I);
727 FirstNonLocalSymbol = LocalSyms.size();
729 for (unsigned i = 0; i < FirstNonLocalSymbol; ++i)
730 SymbolList.push_back(LocalSyms[i]);
732 for (ELFSymIter I=OtherSyms.begin(), E=OtherSyms.end(); I != E; ++I)
733 SymbolList.push_back(*I);
738 return FirstNonLocalSymbol;
741 /// EmitSymbolTable - Emit the symbol table itself.
742 void ELFWriter::EmitSymbolTable() {
743 if (!SymbolList.size()) return; // Empty symbol table.
745 // Now that we have emitted the string table and know the offset into the
746 // string table of each symbol, emit the symbol table itself.
747 ELFSection &SymTab = getSymbolTableSection();
748 SymTab.Align = TEW->getPrefELFAlignment();
750 // Section Index of .strtab.
751 SymTab.Link = getStringTableSection().SectionIdx;
753 // Size of each symtab entry.
754 SymTab.EntSize = TEW->getSymTabEntrySize();
756 // The first entry in the symtab is the null symbol
757 SymbolList.insert(SymbolList.begin(), new ELFSym(0));
759 // Reorder the symbol table with local symbols first!
760 unsigned FirstNonLocalSymbol = SortSymbols();
762 // Emit all the symbols to the symbol table.
763 for (unsigned i = 0, e = SymbolList.size(); i < e; ++i) {
764 ELFSym &Sym = *SymbolList[i];
766 // Emit symbol to the symbol table
767 EmitSymbol(SymTab, Sym);
769 // Record the symbol table index for each global value
770 if (Sym.GV) setGlobalSymLookup(Sym.GV, i);
772 // Keep track on the symbol index into the symbol table
776 // One greater than the symbol table index of the last local symbol
777 SymTab.Info = FirstNonLocalSymbol;
778 SymTab.Size = SymTab.size();
781 /// EmitSectionTableStringTable - This method adds and emits a section for the
782 /// ELF Section Table string table: the string table that holds all of the
784 void ELFWriter::EmitSectionTableStringTable() {
785 // First step: add the section for the string table to the list of sections:
786 ELFSection &SHStrTab = getSectionHeaderStringTableSection();
788 // Now that we know which section number is the .shstrtab section, update the
789 // e_shstrndx entry in the ELF header.
790 ElfHdr.fixWord16(SHStrTab.SectionIdx, ELFHdr_e_shstrndx_Offset);
792 // Set the NameIdx of each section in the string table and emit the bytes for
796 for (ELFSectionIter I=SectionList.begin(), E=SectionList.end(); I != E; ++I) {
797 ELFSection &S = *(*I);
798 // Set the index into the table. Note if we have lots of entries with
799 // common suffixes, we could memoize them here if we cared.
801 SHStrTab.emitString(S.getName());
803 // Keep track of the number of bytes emitted to this section.
804 Index += S.getName().size()+1;
807 // Set the size of .shstrtab now that we know what it is.
808 assert(Index == SHStrTab.size());
809 SHStrTab.Size = Index;
812 /// OutputSectionsAndSectionTable - Now that we have constructed the file header
813 /// and all of the sections, emit these to the ostream destination and emit the
815 void ELFWriter::OutputSectionsAndSectionTable() {
816 // Pass #1: Compute the file offset for each section.
817 size_t FileOff = ElfHdr.size(); // File header first.
819 // Adjust alignment of all section if needed, skip the null section.
820 for (unsigned i=1, e=SectionList.size(); i < e; ++i) {
821 ELFSection &ES = *SectionList[i];
827 // Update Section size
831 // Align FileOff to whatever the alignment restrictions of the section are.
833 FileOff = (FileOff+ES.Align-1) & ~(ES.Align-1);
839 // Align Section Header.
840 unsigned TableAlign = TEW->getPrefELFAlignment();
841 FileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
843 // Now that we know where all of the sections will be emitted, set the e_shnum
844 // entry in the ELF header.
845 ElfHdr.fixWord16(NumSections, ELFHdr_e_shnum_Offset);
847 // Now that we know the offset in the file of the section table, update the
848 // e_shoff address in the ELF header.
849 ElfHdr.fixWord(FileOff, ELFHdr_e_shoff_Offset);
851 // Now that we know all of the data in the file header, emit it and all of the
853 O.write((char *)&ElfHdr.getData()[0], ElfHdr.size());
854 FileOff = ElfHdr.size();
856 // Section Header Table blob
857 BinaryObject SHdrTable(isLittleEndian, is64Bit);
859 // Emit all of sections to the file and build the section header table.
860 for (ELFSectionIter I=SectionList.begin(), E=SectionList.end(); I != E; ++I) {
861 ELFSection &S = *(*I);
862 DOUT << "SectionIdx: " << S.SectionIdx << ", Name: " << S.getName()
863 << ", Size: " << S.Size << ", Offset: " << S.Offset
864 << ", SectionData Size: " << S.size() << "\n";
866 // Align FileOff to whatever the alignment restrictions of the section are.
869 for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
870 FileOff != NewFileOff; ++FileOff)
873 O.write((char *)&S.getData()[0], S.Size);
877 EmitSectionHeader(SHdrTable, S);
880 // Align output for the section table.
881 for (size_t NewFileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
882 FileOff != NewFileOff; ++FileOff)
885 // Emit the section table itself.
886 O.write((char *)&SHdrTable.getData()[0], SHdrTable.size());