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"
34 #include "ELFWriter.h"
35 #include "ELFCodeEmitter.h"
36 #include "llvm/Constants.h"
37 #include "llvm/Module.h"
38 #include "llvm/PassManager.h"
39 #include "llvm/DerivedTypes.h"
40 #include "llvm/CodeGen/BinaryObject.h"
41 #include "llvm/CodeGen/FileWriters.h"
42 #include "llvm/CodeGen/MachineCodeEmitter.h"
43 #include "llvm/CodeGen/ObjectCodeEmitter.h"
44 #include "llvm/CodeGen/MachineCodeEmitter.h"
45 #include "llvm/CodeGen/MachineConstantPool.h"
46 #include "llvm/Target/TargetAsmInfo.h"
47 #include "llvm/Target/TargetData.h"
48 #include "llvm/Target/TargetELFWriterInfo.h"
49 #include "llvm/Target/TargetMachine.h"
50 #include "llvm/Support/Mangler.h"
51 #include "llvm/Support/Streams.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/ErrorHandling.h"
58 char ELFWriter::ID = 0;
60 /// AddELFWriter - Add the ELF writer to the function pass manager
61 ObjectCodeEmitter *llvm::AddELFWriter(PassManagerBase &PM,
64 ELFWriter *EW = new ELFWriter(O, TM);
66 return EW->getObjectCodeEmitter();
69 //===----------------------------------------------------------------------===//
70 // ELFWriter Implementation
71 //===----------------------------------------------------------------------===//
73 ELFWriter::ELFWriter(raw_ostream &o, TargetMachine &tm)
74 : MachineFunctionPass(&ID), O(o), TM(tm),
75 is64Bit(TM.getTargetData()->getPointerSizeInBits() == 64),
76 isLittleEndian(TM.getTargetData()->isLittleEndian()),
77 ElfHdr(isLittleEndian, is64Bit) {
79 TAI = TM.getTargetAsmInfo();
80 TEW = TM.getELFWriterInfo();
82 // Create the object code emitter object for this target.
83 ElfCE = new ELFCodeEmitter(*this);
85 // Inital number of sections
89 ELFWriter::~ELFWriter() {
93 // doInitialization - Emit the file header and all of the global variables for
94 // the module to the ELF file.
95 bool ELFWriter::doInitialization(Module &M) {
96 Mang = new Mangler(M);
100 // Fields e_shnum e_shstrndx are only known after all section have
101 // been emitted. They locations in the ouput buffer are recorded so
102 // to be patched up later.
106 // emitWord method behaves differently for ELF32 and ELF64, writing
107 // 4 bytes in the former and 8 in the last for *_off and *_addr elf types
109 ElfHdr.emitByte(0x7f); // e_ident[EI_MAG0]
110 ElfHdr.emitByte('E'); // e_ident[EI_MAG1]
111 ElfHdr.emitByte('L'); // e_ident[EI_MAG2]
112 ElfHdr.emitByte('F'); // e_ident[EI_MAG3]
114 ElfHdr.emitByte(TEW->getEIClass()); // e_ident[EI_CLASS]
115 ElfHdr.emitByte(TEW->getEIData()); // e_ident[EI_DATA]
116 ElfHdr.emitByte(EV_CURRENT); // e_ident[EI_VERSION]
117 ElfHdr.emitAlignment(16); // e_ident[EI_NIDENT-EI_PAD]
119 ElfHdr.emitWord16(ET_REL); // e_type
120 ElfHdr.emitWord16(TEW->getEMachine()); // e_machine = target
121 ElfHdr.emitWord32(EV_CURRENT); // e_version
122 ElfHdr.emitWord(0); // e_entry, no entry point in .o file
123 ElfHdr.emitWord(0); // e_phoff, no program header for .o
124 ELFHdr_e_shoff_Offset = ElfHdr.size();
125 ElfHdr.emitWord(0); // e_shoff = sec hdr table off in bytes
126 ElfHdr.emitWord32(TEW->getEFlags()); // e_flags = whatever the target wants
127 ElfHdr.emitWord16(TEW->getHdrSize()); // e_ehsize = ELF header size
128 ElfHdr.emitWord16(0); // e_phentsize = prog header entry size
129 ElfHdr.emitWord16(0); // e_phnum = # prog header entries = 0
131 // e_shentsize = Section header entry size
132 ElfHdr.emitWord16(TEW->getSHdrSize());
134 // e_shnum = # of section header ents
135 ELFHdr_e_shnum_Offset = ElfHdr.size();
136 ElfHdr.emitWord16(0); // Placeholder
138 // e_shstrndx = Section # of '.shstrtab'
139 ELFHdr_e_shstrndx_Offset = ElfHdr.size();
140 ElfHdr.emitWord16(0); // Placeholder
142 // Add the null section, which is required to be first in the file.
148 unsigned ELFWriter::getGlobalELFVisibility(const GlobalValue *GV) {
149 switch (GV->getVisibility()) {
151 LLVM_UNREACHABLE("unknown visibility type");
152 case GlobalValue::DefaultVisibility:
153 return ELFSym::STV_DEFAULT;
154 case GlobalValue::HiddenVisibility:
155 return ELFSym::STV_HIDDEN;
156 case GlobalValue::ProtectedVisibility:
157 return ELFSym::STV_PROTECTED;
163 unsigned ELFWriter::getGlobalELFLinkage(const GlobalValue *GV) {
164 if (GV->hasInternalLinkage())
165 return ELFSym::STB_LOCAL;
167 if (GV->hasWeakLinkage())
168 return ELFSym::STB_WEAK;
170 return ELFSym::STB_GLOBAL;
173 // getElfSectionFlags - Get the ELF Section Header based on the
174 // flags defined in ELFTargetAsmInfo.
175 unsigned ELFWriter::getElfSectionFlags(unsigned Flags) {
176 unsigned ElfSectionFlags = ELFSection::SHF_ALLOC;
178 if (Flags & SectionFlags::Code)
179 ElfSectionFlags |= ELFSection::SHF_EXECINSTR;
180 if (Flags & SectionFlags::Writeable)
181 ElfSectionFlags |= ELFSection::SHF_WRITE;
182 if (Flags & SectionFlags::Mergeable)
183 ElfSectionFlags |= ELFSection::SHF_MERGE;
184 if (Flags & SectionFlags::TLS)
185 ElfSectionFlags |= ELFSection::SHF_TLS;
186 if (Flags & SectionFlags::Strings)
187 ElfSectionFlags |= ELFSection::SHF_STRINGS;
189 return ElfSectionFlags;
192 // For global symbols without a section, return the Null section as a
194 ELFSection &ELFWriter::getGlobalSymELFSection(const GlobalVariable *GV,
196 // If this is a declaration, the symbol does not have a section.
197 if (!GV->hasInitializer()) {
198 Sym.SectionIdx = ELFSection::SHN_UNDEF;
199 return getNullSection();
202 // Get the name and flags of the section for the global
203 const Section *S = TAI->SectionForGlobal(GV);
204 unsigned SectionType = ELFSection::SHT_PROGBITS;
205 unsigned SectionFlags = getElfSectionFlags(S->getFlags());
206 DOUT << "Section " << S->getName() << " for global " << GV->getName() << "\n";
208 const TargetData *TD = TM.getTargetData();
209 unsigned Align = TD->getPreferredAlignment(GV);
210 Constant *CV = GV->getInitializer();
212 // If this global has a zero initializer, go to .bss or common section.
213 // Variables are part of the common block if they are zero initialized
214 // and allowed to be merged with other symbols.
215 if (CV->isNullValue() || isa<UndefValue>(CV)) {
216 SectionType = ELFSection::SHT_NOBITS;
217 ELFSection &ElfS = getSection(S->getName(), SectionType, SectionFlags);
218 if (GV->hasLinkOnceLinkage() || GV->hasWeakLinkage() ||
219 GV->hasCommonLinkage()) {
220 Sym.SectionIdx = ELFSection::SHN_COMMON;
226 Sym.SectionIdx = ElfS.SectionIdx;
227 if (Align) ElfS.Size = (ElfS.Size + Align-1) & ~(Align-1);
228 ElfS.Align = std::max(ElfS.Align, Align);
232 Sym.IsConstant = true;
233 ELFSection &ElfS = getSection(S->getName(), SectionType, SectionFlags);
234 Sym.SectionIdx = ElfS.SectionIdx;
235 ElfS.Align = std::max(ElfS.Align, Align);
239 void ELFWriter::EmitFunctionDeclaration(const Function *F) {
241 GblSym.setBind(ELFSym::STB_GLOBAL);
242 GblSym.setType(ELFSym::STT_NOTYPE);
243 GblSym.setVisibility(ELFSym::STV_DEFAULT);
244 GblSym.SectionIdx = ELFSection::SHN_UNDEF;
245 SymbolList.push_back(GblSym);
248 void ELFWriter::EmitGlobalVar(const GlobalVariable *GV) {
249 unsigned SymBind = getGlobalELFLinkage(GV);
250 unsigned Align=0, Size=0;
252 GblSym.setBind(SymBind);
253 GblSym.setVisibility(getGlobalELFVisibility(GV));
255 if (GV->hasInitializer()) {
256 GblSym.setType(ELFSym::STT_OBJECT);
257 const TargetData *TD = TM.getTargetData();
258 Align = TD->getPreferredAlignment(GV);
259 Size = TD->getTypeAllocSize(GV->getInitializer()->getType());
262 GblSym.setType(ELFSym::STT_NOTYPE);
265 ELFSection &GblSection = getGlobalSymELFSection(GV, GblSym);
267 if (GblSym.IsCommon) {
268 GblSym.Value = Align;
269 } else if (GblSym.IsBss) {
270 GblSym.Value = GblSection.Size;
271 GblSection.Size += Size;
272 } else if (GblSym.IsConstant){
273 // GblSym.Value should contain the symbol index inside the section,
274 // and all symbols should start on their required alignment boundary
275 GblSym.Value = (GblSection.size() + (Align-1)) & (-Align);
276 GblSection.emitAlignment(Align);
277 EmitGlobalConstant(GV->getInitializer(), GblSection);
280 // Local symbols should come first on the symbol table.
281 if (!GV->hasPrivateLinkage()) {
282 if (SymBind == ELFSym::STB_LOCAL)
283 SymbolList.push_front(GblSym);
285 SymbolList.push_back(GblSym);
289 void ELFWriter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
292 // Print the fields in successive locations. Pad to align if needed!
293 const TargetData *TD = TM.getTargetData();
294 unsigned Size = TD->getTypeAllocSize(CVS->getType());
295 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
296 uint64_t sizeSoFar = 0;
297 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
298 const Constant* field = CVS->getOperand(i);
300 // Check if padding is needed and insert one or more 0s.
301 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
302 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
303 - cvsLayout->getElementOffset(i)) - fieldSize;
304 sizeSoFar += fieldSize + padSize;
306 // Now print the actual field value.
307 EmitGlobalConstant(field, GblS);
309 // Insert padding - this may include padding to increase the size of the
310 // current field up to the ABI size (if the struct is not packed) as well
311 // as padding to ensure that the next field starts at the right offset.
312 for (unsigned p=0; p < padSize; p++)
315 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
316 "Layout of constant struct may be incorrect!");
319 void ELFWriter::EmitGlobalConstant(const Constant *CV, ELFSection &GblS) {
320 const TargetData *TD = TM.getTargetData();
321 unsigned Size = TD->getTypeAllocSize(CV->getType());
323 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
324 if (CVA->isString()) {
325 std::string GblStr = CVA->getAsString();
326 GblStr.resize(GblStr.size()-1);
327 GblS.emitString(GblStr);
328 } else { // Not a string. Print the values in successive locations
329 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
330 EmitGlobalConstant(CVA->getOperand(i), GblS);
333 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
334 EmitGlobalConstantStruct(CVS, GblS);
336 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
337 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
338 if (CFP->getType() == Type::DoubleTy)
339 GblS.emitWord64(Val);
340 else if (CFP->getType() == Type::FloatTy)
341 GblS.emitWord32(Val);
342 else if (CFP->getType() == Type::X86_FP80Ty) {
343 LLVM_UNREACHABLE("X86_FP80Ty global emission not implemented");
344 } else if (CFP->getType() == Type::PPC_FP128Ty)
345 LLVM_UNREACHABLE("PPC_FP128Ty global emission not implemented");
347 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
349 GblS.emitWord32(CI->getZExtValue());
351 GblS.emitWord64(CI->getZExtValue());
353 LLVM_UNREACHABLE("LargeInt global emission not implemented");
355 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
356 const VectorType *PTy = CP->getType();
357 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
358 EmitGlobalConstant(CP->getOperand(I), GblS);
361 LLVM_UNREACHABLE("unknown global constant");
365 bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
366 // Nothing to do here, this is all done through the ElfCE object above.
370 /// doFinalization - Now that the module has been completely processed, emit
371 /// the ELF file to 'O'.
372 bool ELFWriter::doFinalization(Module &M) {
373 // Emit .data section placeholder
376 // Emit .bss section placeholder
379 // Build and emit data, bss and "common" sections.
380 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
386 // Emit all pending globals
387 // TODO: this should be done only for referenced symbols
388 for (SetVector<GlobalValue*>::const_iterator I = PendingGlobals.begin(),
389 E = PendingGlobals.end(); I != E; ++I) {
391 // No need to emit the symbol again
392 if (GblSymLookup.find(*I) != GblSymLookup.end())
395 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I)) {
397 } else if (Function *F = dyn_cast<Function>(*I)) {
398 // If function is not in GblSymLookup, it doesn't have a body,
399 // so emit the symbol as a function declaration (no section associated)
400 EmitFunctionDeclaration(F);
402 assert("unknown howto handle pending global");
404 GblSymLookup[*I] = 0;
407 // Emit non-executable stack note
408 if (TAI->getNonexecutableStackDirective())
409 getNonExecStackSection();
411 // Emit a symbol for each section created until now
412 for (std::map<std::string, ELFSection*>::iterator I = SectionLookup.begin(),
413 E = SectionLookup.end(); I != E; ++I) {
414 ELFSection *ES = I->second;
417 if (ES->SectionIdx == 0) continue;
419 ELFSym SectionSym(0);
420 SectionSym.SectionIdx = ES->SectionIdx;
422 SectionSym.setBind(ELFSym::STB_LOCAL);
423 SectionSym.setType(ELFSym::STT_SECTION);
424 SectionSym.setVisibility(ELFSym::STV_DEFAULT);
426 // Local symbols go in the list front
427 SymbolList.push_front(SectionSym);
433 // Emit the symbol table now, if non-empty.
436 // Emit the relocation sections.
439 // Emit the sections string table.
440 EmitSectionTableStringTable();
442 // Dump the sections and section table to the .o file.
443 OutputSectionsAndSectionTable();
445 // We are done with the abstract symbols.
449 // Release the name mangler object.
450 delete Mang; Mang = 0;
454 /// EmitRelocations - Emit relocations
455 void ELFWriter::EmitRelocations() {
457 // Create Relocation sections for each section which needs it.
458 for (std::list<ELFSection>::iterator I = SectionList.begin(),
459 E = SectionList.end(); I != E; ++I) {
461 // This section does not have relocations
462 if (!I->hasRelocations()) continue;
464 // Get the relocation section for section 'I'
465 bool HasRelA = TEW->hasRelocationAddend();
466 ELFSection &RelSec = getRelocSection(I->getName(), HasRelA,
467 TEW->getPrefELFAlignment());
469 // 'Link' - Section hdr idx of the associated symbol table
470 // 'Info' - Section hdr idx of the section to which the relocation applies
471 ELFSection &SymTab = getSymbolTableSection();
472 RelSec.Link = SymTab.SectionIdx;
473 RelSec.Info = I->SectionIdx;
474 RelSec.EntSize = TEW->getRelocationEntrySize();
476 // Get the relocations from Section
477 std::vector<MachineRelocation> Relos = I->getRelocations();
478 for (std::vector<MachineRelocation>::iterator MRI = Relos.begin(),
479 MRE = Relos.end(); MRI != MRE; ++MRI) {
480 MachineRelocation &MR = *MRI;
482 // Offset from the start of the section containing the symbol
483 unsigned Offset = MR.getMachineCodeOffset();
485 // Symbol index in the symbol table
488 // Target specific ELF relocation type
489 unsigned RelType = TEW->getRelocationType(MR.getRelocationType());
491 // Constant addend used to compute the value to be stored
492 // into the relocatable field
495 // There are several machine relocations types, and each one of
496 // them needs a different approach to retrieve the symbol table index.
497 if (MR.isGlobalValue()) {
498 const GlobalValue *G = MR.getGlobalValue();
499 SymIdx = GblSymLookup[G];
500 Addend = TEW->getAddendForRelTy(RelType);
502 unsigned SectionIdx = MR.getConstantVal();
503 // TODO: use a map for this.
504 for (std::list<ELFSym>::iterator I = SymbolList.begin(),
505 E = SymbolList.end(); I != E; ++I)
506 if ((SectionIdx == I->SectionIdx) &&
507 (I->getType() == ELFSym::STT_SECTION)) {
508 SymIdx = I->SymTabIdx;
511 Addend = (uint64_t)MR.getResultPointer();
514 // Get the relocation entry and emit to the relocation section
515 ELFRelocation Rel(Offset, SymIdx, RelType, HasRelA, Addend);
516 EmitRelocation(RelSec, Rel, HasRelA);
521 /// EmitRelocation - Write relocation 'Rel' to the relocation section 'Rel'
522 void ELFWriter::EmitRelocation(BinaryObject &RelSec, ELFRelocation &Rel,
524 RelSec.emitWord(Rel.getOffset());
525 RelSec.emitWord(Rel.getInfo(is64Bit));
527 RelSec.emitWord(Rel.getAddend());
530 /// EmitSymbol - Write symbol 'Sym' to the symbol table 'SymbolTable'
531 void ELFWriter::EmitSymbol(BinaryObject &SymbolTable, ELFSym &Sym) {
533 SymbolTable.emitWord32(Sym.NameIdx);
534 SymbolTable.emitByte(Sym.Info);
535 SymbolTable.emitByte(Sym.Other);
536 SymbolTable.emitWord16(Sym.SectionIdx);
537 SymbolTable.emitWord64(Sym.Value);
538 SymbolTable.emitWord64(Sym.Size);
540 SymbolTable.emitWord32(Sym.NameIdx);
541 SymbolTable.emitWord32(Sym.Value);
542 SymbolTable.emitWord32(Sym.Size);
543 SymbolTable.emitByte(Sym.Info);
544 SymbolTable.emitByte(Sym.Other);
545 SymbolTable.emitWord16(Sym.SectionIdx);
549 /// EmitSectionHeader - Write section 'Section' header in 'SHdrTab'
550 /// Section Header Table
551 void ELFWriter::EmitSectionHeader(BinaryObject &SHdrTab,
552 const ELFSection &SHdr) {
553 SHdrTab.emitWord32(SHdr.NameIdx);
554 SHdrTab.emitWord32(SHdr.Type);
556 SHdrTab.emitWord64(SHdr.Flags);
557 SHdrTab.emitWord(SHdr.Addr);
558 SHdrTab.emitWord(SHdr.Offset);
559 SHdrTab.emitWord64(SHdr.Size);
560 SHdrTab.emitWord32(SHdr.Link);
561 SHdrTab.emitWord32(SHdr.Info);
562 SHdrTab.emitWord64(SHdr.Align);
563 SHdrTab.emitWord64(SHdr.EntSize);
565 SHdrTab.emitWord32(SHdr.Flags);
566 SHdrTab.emitWord(SHdr.Addr);
567 SHdrTab.emitWord(SHdr.Offset);
568 SHdrTab.emitWord32(SHdr.Size);
569 SHdrTab.emitWord32(SHdr.Link);
570 SHdrTab.emitWord32(SHdr.Info);
571 SHdrTab.emitWord32(SHdr.Align);
572 SHdrTab.emitWord32(SHdr.EntSize);
576 /// EmitStringTable - If the current symbol table is non-empty, emit the string
578 void ELFWriter::EmitStringTable() {
579 if (!SymbolList.size()) return; // Empty symbol table.
580 ELFSection &StrTab = getStringTableSection();
582 // Set the zero'th symbol to a null byte, as required.
585 // Walk on the symbol list and write symbol names into the
588 for (std::list<ELFSym>::iterator I = SymbolList.begin(),
589 E = SymbolList.end(); I != E; ++I) {
591 // Use the name mangler to uniquify the LLVM symbol.
593 if (I->GV) Name.append(Mang->getValueName(I->GV));
599 StrTab.emitString(Name);
601 // Keep track of the number of bytes emitted to this section.
602 Index += Name.size()+1;
605 assert(Index == StrTab.size());
609 /// EmitSymbolTable - Emit the symbol table itself.
610 void ELFWriter::EmitSymbolTable() {
611 if (!SymbolList.size()) return; // Empty symbol table.
613 unsigned FirstNonLocalSymbol = 1;
614 // Now that we have emitted the string table and know the offset into the
615 // string table of each symbol, emit the symbol table itself.
616 ELFSection &SymTab = getSymbolTableSection();
617 SymTab.Align = TEW->getPrefELFAlignment();
619 // Section Index of .strtab.
620 SymTab.Link = getStringTableSection().SectionIdx;
622 // Size of each symtab entry.
623 SymTab.EntSize = TEW->getSymTabEntrySize();
625 // The first entry in the symtab is the null symbol
626 ELFSym NullSym = ELFSym(0);
627 EmitSymbol(SymTab, NullSym);
629 // Emit all the symbols to the symbol table. Skip the null
630 // symbol, cause it's emitted already
632 for (std::list<ELFSym>::iterator I = SymbolList.begin(),
633 E = SymbolList.end(); I != E; ++I, ++Index) {
634 // Keep track of the first non-local symbol
635 if (I->getBind() == ELFSym::STB_LOCAL)
636 FirstNonLocalSymbol++;
638 // Emit symbol to the symbol table
639 EmitSymbol(SymTab, *I);
641 // Record the symbol table index for each global value
643 GblSymLookup[I->GV] = Index;
645 // Keep track on the symbol index into the symbol table
646 I->SymTabIdx = Index;
649 SymTab.Info = FirstNonLocalSymbol;
650 SymTab.Size = SymTab.size();
653 /// EmitSectionTableStringTable - This method adds and emits a section for the
654 /// ELF Section Table string table: the string table that holds all of the
656 void ELFWriter::EmitSectionTableStringTable() {
657 // First step: add the section for the string table to the list of sections:
658 ELFSection &SHStrTab = getSectionHeaderStringTableSection();
660 // Now that we know which section number is the .shstrtab section, update the
661 // e_shstrndx entry in the ELF header.
662 ElfHdr.fixWord16(SHStrTab.SectionIdx, ELFHdr_e_shstrndx_Offset);
664 // Set the NameIdx of each section in the string table and emit the bytes for
668 for (std::list<ELFSection>::iterator I = SectionList.begin(),
669 E = SectionList.end(); I != E; ++I) {
670 // Set the index into the table. Note if we have lots of entries with
671 // common suffixes, we could memoize them here if we cared.
673 SHStrTab.emitString(I->getName());
675 // Keep track of the number of bytes emitted to this section.
676 Index += I->getName().size()+1;
679 // Set the size of .shstrtab now that we know what it is.
680 assert(Index == SHStrTab.size());
681 SHStrTab.Size = Index;
684 /// OutputSectionsAndSectionTable - Now that we have constructed the file header
685 /// and all of the sections, emit these to the ostream destination and emit the
687 void ELFWriter::OutputSectionsAndSectionTable() {
688 // Pass #1: Compute the file offset for each section.
689 size_t FileOff = ElfHdr.size(); // File header first.
691 // Adjust alignment of all section if needed.
692 for (std::list<ELFSection>::iterator I = SectionList.begin(),
693 E = SectionList.end(); I != E; ++I) {
695 // Section idx 0 has 0 offset
704 // Update Section size
708 // Align FileOff to whatever the alignment restrictions of the section are.
710 FileOff = (FileOff+I->Align-1) & ~(I->Align-1);
716 // Align Section Header.
717 unsigned TableAlign = TEW->getPrefELFAlignment();
718 FileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
720 // Now that we know where all of the sections will be emitted, set the e_shnum
721 // entry in the ELF header.
722 ElfHdr.fixWord16(NumSections, ELFHdr_e_shnum_Offset);
724 // Now that we know the offset in the file of the section table, update the
725 // e_shoff address in the ELF header.
726 ElfHdr.fixWord(FileOff, ELFHdr_e_shoff_Offset);
728 // Now that we know all of the data in the file header, emit it and all of the
730 O.write((char *)&ElfHdr.getData()[0], ElfHdr.size());
731 FileOff = ElfHdr.size();
733 // Section Header Table blob
734 BinaryObject SHdrTable(isLittleEndian, is64Bit);
736 // Emit all of sections to the file and build the section header table.
737 while (!SectionList.empty()) {
738 ELFSection &S = *SectionList.begin();
739 DOUT << "SectionIdx: " << S.SectionIdx << ", Name: " << S.getName()
740 << ", Size: " << S.Size << ", Offset: " << S.Offset
741 << ", SectionData Size: " << S.size() << "\n";
743 // Align FileOff to whatever the alignment restrictions of the section are.
746 for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
747 FileOff != NewFileOff; ++FileOff)
750 O.write((char *)&S.getData()[0], S.Size);
754 EmitSectionHeader(SHdrTable, S);
755 SectionList.pop_front();
758 // Align output for the section table.
759 for (size_t NewFileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
760 FileOff != NewFileOff; ++FileOff)
763 // Emit the section table itself.
764 O.write((char *)&SHdrTable.getData()[0], SHdrTable.size());