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/MC/MCContext.h"
46 #include "llvm/MC/MCSection.h"
47 #include "llvm/Target/TargetAsmInfo.h"
48 #include "llvm/Target/TargetData.h"
49 #include "llvm/Target/TargetELFWriterInfo.h"
50 #include "llvm/Target/TargetLowering.h"
51 #include "llvm/Target/TargetLoweringObjectFile.h"
52 #include "llvm/Target/TargetMachine.h"
53 #include "llvm/Support/Mangler.h"
54 #include "llvm/Support/Streams.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/ErrorHandling.h"
61 char ELFWriter::ID = 0;
63 /// AddELFWriter - Add the ELF writer to the function pass manager
64 ObjectCodeEmitter *llvm::AddELFWriter(PassManagerBase &PM,
67 ELFWriter *EW = new ELFWriter(O, TM);
69 return EW->getObjectCodeEmitter();
72 //===----------------------------------------------------------------------===//
73 // ELFWriter Implementation
74 //===----------------------------------------------------------------------===//
76 ELFWriter::ELFWriter(raw_ostream &o, TargetMachine &tm)
77 : MachineFunctionPass(&ID), O(o), TM(tm),
78 OutContext(*new MCContext()),
79 is64Bit(TM.getTargetData()->getPointerSizeInBits() == 64),
80 isLittleEndian(TM.getTargetData()->isLittleEndian()),
81 ElfHdr(isLittleEndian, is64Bit) {
83 TAI = TM.getTargetAsmInfo();
84 TEW = TM.getELFWriterInfo();
86 // Create the object code emitter object for this target.
87 ElfCE = new ELFCodeEmitter(*this);
89 // Inital number of sections
93 ELFWriter::~ELFWriter() {
98 // doInitialization - Emit the file header and all of the global variables for
99 // the module to the ELF file.
100 bool ELFWriter::doInitialization(Module &M) {
101 // Initialize TargetLoweringObjectFile.
102 const TargetLoweringObjectFile &TLOF =
103 TM.getTargetLowering()->getObjFileLowering();
104 const_cast<TargetLoweringObjectFile&>(TLOF).Initialize(OutContext, TM);
106 Mang = new Mangler(M);
110 // Fields e_shnum e_shstrndx are only known after all section have
111 // been emitted. They locations in the ouput buffer are recorded so
112 // to be patched up later.
116 // emitWord method behaves differently for ELF32 and ELF64, writing
117 // 4 bytes in the former and 8 in the last for *_off and *_addr elf types
119 ElfHdr.emitByte(0x7f); // e_ident[EI_MAG0]
120 ElfHdr.emitByte('E'); // e_ident[EI_MAG1]
121 ElfHdr.emitByte('L'); // e_ident[EI_MAG2]
122 ElfHdr.emitByte('F'); // e_ident[EI_MAG3]
124 ElfHdr.emitByte(TEW->getEIClass()); // e_ident[EI_CLASS]
125 ElfHdr.emitByte(TEW->getEIData()); // e_ident[EI_DATA]
126 ElfHdr.emitByte(EV_CURRENT); // e_ident[EI_VERSION]
127 ElfHdr.emitAlignment(16); // e_ident[EI_NIDENT-EI_PAD]
129 ElfHdr.emitWord16(ET_REL); // e_type
130 ElfHdr.emitWord16(TEW->getEMachine()); // e_machine = target
131 ElfHdr.emitWord32(EV_CURRENT); // e_version
132 ElfHdr.emitWord(0); // e_entry, no entry point in .o file
133 ElfHdr.emitWord(0); // e_phoff, no program header for .o
134 ELFHdr_e_shoff_Offset = ElfHdr.size();
135 ElfHdr.emitWord(0); // e_shoff = sec hdr table off in bytes
136 ElfHdr.emitWord32(TEW->getEFlags()); // e_flags = whatever the target wants
137 ElfHdr.emitWord16(TEW->getHdrSize()); // e_ehsize = ELF header size
138 ElfHdr.emitWord16(0); // e_phentsize = prog header entry size
139 ElfHdr.emitWord16(0); // e_phnum = # prog header entries = 0
141 // e_shentsize = Section header entry size
142 ElfHdr.emitWord16(TEW->getSHdrSize());
144 // e_shnum = # of section header ents
145 ELFHdr_e_shnum_Offset = ElfHdr.size();
146 ElfHdr.emitWord16(0); // Placeholder
148 // e_shstrndx = Section # of '.shstrtab'
149 ELFHdr_e_shstrndx_Offset = ElfHdr.size();
150 ElfHdr.emitWord16(0); // Placeholder
152 // Add the null section, which is required to be first in the file.
155 // The first entry in the symtab is the null symbol and the second
156 // is a local symbol containing the module/file name
157 SymbolList.push_back(new ELFSym());
158 SymbolList.push_back(ELFSym::getFileSym());
163 // addGlobalSymbol - Add a global to be processed and to the
164 // global symbol lookup, use a zero index for non private symbols
165 // because the table index will be determined later.
166 void ELFWriter::addGlobalSymbol(const GlobalValue *GV) {
167 PendingGlobals.insert(GV);
170 // addExternalSymbol - Add the external to be processed and to the
171 // external symbol lookup, use a zero index because the symbol
172 // table index will be determined later
173 void ELFWriter::addExternalSymbol(const char *External) {
174 PendingExternals.insert(External);
175 ExtSymLookup[External] = 0;
178 // Get jump table section on the section name returned by TAI
179 ELFSection &ELFWriter::getJumpTableSection() {
180 unsigned Align = TM.getTargetData()->getPointerABIAlignment();
181 return getSection(TAI->getJumpTableDataSection(),
182 ELFSection::SHT_PROGBITS,
183 ELFSection::SHF_ALLOC, Align);
186 // Get a constant pool section based on the section name returned by TAI
187 ELFSection &ELFWriter::getConstantPoolSection(MachineConstantPoolEntry &CPE) {
189 switch (CPE.getRelocationInfo()) {
190 default: llvm_unreachable("Unknown section kind");
191 case 2: Kind = SectionKind::get(SectionKind::ReadOnlyWithRel,false); break;
193 Kind = SectionKind::get(SectionKind::ReadOnlyWithRelLocal,false);
196 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
197 case 4: Kind = SectionKind::get(SectionKind::MergeableConst4,false); break;
198 case 8: Kind = SectionKind::get(SectionKind::MergeableConst8,false); break;
199 case 16: Kind = SectionKind::get(SectionKind::MergeableConst16,false);break;
200 default: Kind = SectionKind::get(SectionKind::MergeableConst,false); break;
204 const TargetLoweringObjectFile &TLOF =
205 TM.getTargetLowering()->getObjFileLowering();
207 return getSection(TLOF.getSectionForMergeableConstant(Kind)->getName(),
208 ELFSection::SHT_PROGBITS,
209 ELFSection::SHF_MERGE | ELFSection::SHF_ALLOC,
213 // Return the relocation section of section 'S'. 'RelA' is true
214 // if the relocation section contains entries with addends.
215 ELFSection &ELFWriter::getRelocSection(ELFSection &S) {
216 unsigned SectionHeaderTy = TEW->hasRelocationAddend() ?
217 ELFSection::SHT_RELA : ELFSection::SHT_REL;
218 std::string RelSName(".rel");
219 if (TEW->hasRelocationAddend())
220 RelSName.append("a");
221 RelSName.append(S.getName());
223 return getSection(RelSName, SectionHeaderTy, 0, TEW->getPrefELFAlignment());
226 // getGlobalELFVisibility - Returns the ELF specific visibility type
227 unsigned ELFWriter::getGlobalELFVisibility(const GlobalValue *GV) {
228 switch (GV->getVisibility()) {
230 llvm_unreachable("unknown visibility type");
231 case GlobalValue::DefaultVisibility:
232 return ELFSym::STV_DEFAULT;
233 case GlobalValue::HiddenVisibility:
234 return ELFSym::STV_HIDDEN;
235 case GlobalValue::ProtectedVisibility:
236 return ELFSym::STV_PROTECTED;
241 // getGlobalELFBinding - Returns the ELF specific binding type
242 unsigned ELFWriter::getGlobalELFBinding(const GlobalValue *GV) {
243 if (GV->hasInternalLinkage())
244 return ELFSym::STB_LOCAL;
246 if (GV->hasWeakLinkage())
247 return ELFSym::STB_WEAK;
249 return ELFSym::STB_GLOBAL;
252 // getGlobalELFType - Returns the ELF specific type for a global
253 unsigned ELFWriter::getGlobalELFType(const GlobalValue *GV) {
254 if (GV->isDeclaration())
255 return ELFSym::STT_NOTYPE;
257 if (isa<Function>(GV))
258 return ELFSym::STT_FUNC;
260 return ELFSym::STT_OBJECT;
263 // getElfSectionFlags - Get the ELF Section Header flags based
264 // on the flags defined in ELFTargetAsmInfo.
265 unsigned ELFWriter::getElfSectionFlags(SectionKind Kind) {
266 unsigned ElfSectionFlags = ELFSection::SHF_ALLOC;
269 ElfSectionFlags |= ELFSection::SHF_EXECINSTR;
270 if (Kind.isWriteable())
271 ElfSectionFlags |= ELFSection::SHF_WRITE;
272 if (Kind.isMergeableConst())
273 ElfSectionFlags |= ELFSection::SHF_MERGE;
274 if (Kind.isThreadLocal())
275 ElfSectionFlags |= ELFSection::SHF_TLS;
276 if (Kind.isMergeableCString())
277 ElfSectionFlags |= ELFSection::SHF_STRINGS;
279 return ElfSectionFlags;
282 // isELFUndefSym - the symbol has no section and must be placed in
283 // the symbol table with a reference to the null section.
284 static bool isELFUndefSym(const GlobalValue *GV) {
285 return GV->isDeclaration();
288 // isELFBssSym - for an undef or null value, the symbol must go to a bss
289 // section if it's not weak for linker, otherwise it's a common sym.
290 static bool isELFBssSym(const GlobalVariable *GV) {
291 const Constant *CV = GV->getInitializer();
292 return ((CV->isNullValue() || isa<UndefValue>(CV)) && !GV->isWeakForLinker());
295 // isELFCommonSym - for an undef or null value, the symbol must go to a
296 // common section if it's weak for linker, otherwise bss.
297 static bool isELFCommonSym(const GlobalVariable *GV) {
298 const Constant *CV = GV->getInitializer();
299 return ((CV->isNullValue() || isa<UndefValue>(CV)) && GV->isWeakForLinker());
302 // isELFDataSym - if the symbol is an initialized but no null constant
303 // it must go to some kind of data section gathered from TAI
304 static bool isELFDataSym(const Constant *CV) {
305 return (!(CV->isNullValue() || isa<UndefValue>(CV)));
308 // EmitGlobal - Choose the right section for global and emit it
309 void ELFWriter::EmitGlobal(const GlobalValue *GV) {
311 // Check if the referenced symbol is already emitted
312 if (GblSymLookup.find(GV) != GblSymLookup.end())
315 // If the global is a function already emited in the text section
316 // just add it to the global symbol lookup with a zero index to be
318 if (isa<Function>(GV) && !GV->isDeclaration()) {
319 GblSymLookup[GV] = 0;
323 // Handle ELF Bind, Visibility and Type for the current symbol
324 unsigned SymBind = getGlobalELFBinding(GV);
325 ELFSym *GblSym = ELFSym::getGV(GV, SymBind, getGlobalELFType(GV),
326 getGlobalELFVisibility(GV));
328 if (isELFUndefSym(GV)) {
329 GblSym->SectionIdx = ELFSection::SHN_UNDEF;
331 assert(isa<GlobalVariable>(GV) && "GV not a global variable!");
332 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
334 const TargetLoweringObjectFile &TLOF =
335 TM.getTargetLowering()->getObjFileLowering();
337 // Get the ELF section where this global belongs from TLOF
338 const MCSection *S = TLOF.SectionForGlobal(GV, Mang, TM);
339 unsigned SectionFlags = getElfSectionFlags(((MCSectionELF*)S)->getKind());
341 // The symbol align should update the section alignment if needed
342 const TargetData *TD = TM.getTargetData();
343 unsigned Align = TD->getPreferredAlignment(GVar);
344 unsigned Size = TD->getTypeAllocSize(GVar->getInitializer()->getType());
347 if (isELFCommonSym(GVar)) {
348 GblSym->SectionIdx = ELFSection::SHN_COMMON;
349 getSection(S->getName(), ELFSection::SHT_NOBITS, SectionFlags, 1);
351 // A new linkonce section is created for each global in the
352 // common section, the default alignment is 1 and the symbol
353 // value contains its alignment.
354 GblSym->Value = Align;
356 } else if (isELFBssSym(GVar)) {
358 getSection(S->getName(), ELFSection::SHT_NOBITS, SectionFlags);
359 GblSym->SectionIdx = ES.SectionIdx;
361 // Update the size with alignment and the next object can
362 // start in the right offset in the section
363 if (Align) ES.Size = (ES.Size + Align-1) & ~(Align-1);
364 ES.Align = std::max(ES.Align, Align);
366 // GblSym->Value should contain the virtual offset inside the section.
367 // Virtual because the BSS space is not allocated on ELF objects
368 GblSym->Value = ES.Size;
371 } else if (isELFDataSym(GV)) {
373 getSection(S->getName(), ELFSection::SHT_PROGBITS, SectionFlags);
374 GblSym->SectionIdx = ES.SectionIdx;
376 // GblSym->Value should contain the symbol offset inside the section,
377 // and all symbols should start on their required alignment boundary
378 ES.Align = std::max(ES.Align, Align);
379 GblSym->Value = (ES.size() + (Align-1)) & (-Align);
380 ES.emitAlignment(ES.Align);
382 // Emit the global to the data section 'ES'
383 EmitGlobalConstant(GVar->getInitializer(), ES);
387 if (GV->hasPrivateLinkage()) {
388 // For a private symbols, keep track of the index inside the
389 // private list since it will never go to the symbol table and
390 // won't be patched up later.
391 PrivateSyms.push_back(GblSym);
392 GblSymLookup[GV] = PrivateSyms.size()-1;
394 // Non private symbol are left with zero indices until they are patched
395 // up during the symbol table emition (where the indicies are created).
396 SymbolList.push_back(GblSym);
397 GblSymLookup[GV] = 0;
401 void ELFWriter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
404 // Print the fields in successive locations. Pad to align if needed!
405 const TargetData *TD = TM.getTargetData();
406 unsigned Size = TD->getTypeAllocSize(CVS->getType());
407 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
408 uint64_t sizeSoFar = 0;
409 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
410 const Constant* field = CVS->getOperand(i);
412 // Check if padding is needed and insert one or more 0s.
413 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
414 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
415 - cvsLayout->getElementOffset(i)) - fieldSize;
416 sizeSoFar += fieldSize + padSize;
418 // Now print the actual field value.
419 EmitGlobalConstant(field, GblS);
421 // Insert padding - this may include padding to increase the size of the
422 // current field up to the ABI size (if the struct is not packed) as well
423 // as padding to ensure that the next field starts at the right offset.
424 for (unsigned p=0; p < padSize; p++)
427 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
428 "Layout of constant struct may be incorrect!");
431 void ELFWriter::EmitGlobalConstant(const Constant *CV, ELFSection &GblS) {
432 const TargetData *TD = TM.getTargetData();
433 unsigned Size = TD->getTypeAllocSize(CV->getType());
435 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
436 if (CVA->isString()) {
437 std::string GblStr = CVA->getAsString();
438 GblStr.resize(GblStr.size()-1);
439 GblS.emitString(GblStr);
440 } else { // Not a string. Print the values in successive locations
441 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
442 EmitGlobalConstant(CVA->getOperand(i), GblS);
445 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
446 EmitGlobalConstantStruct(CVS, GblS);
448 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
449 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
450 if (CFP->getType() == Type::DoubleTy)
451 GblS.emitWord64(Val);
452 else if (CFP->getType() == Type::FloatTy)
453 GblS.emitWord32(Val);
454 else if (CFP->getType() == Type::X86_FP80Ty) {
455 llvm_unreachable("X86_FP80Ty global emission not implemented");
456 } else if (CFP->getType() == Type::PPC_FP128Ty)
457 llvm_unreachable("PPC_FP128Ty global emission not implemented");
459 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
461 GblS.emitWord32(CI->getZExtValue());
463 GblS.emitWord64(CI->getZExtValue());
465 llvm_unreachable("LargeInt global emission not implemented");
467 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
468 const VectorType *PTy = CP->getType();
469 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
470 EmitGlobalConstant(CP->getOperand(I), GblS);
472 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
473 // This is a constant address for a global variable or function and
474 // therefore must be referenced using a relocation entry.
476 // Check if the referenced symbol is already emitted
477 if (GblSymLookup.find(GV) == GblSymLookup.end())
480 // Create the relocation entry for the global value
481 MachineRelocation MR =
482 MachineRelocation::getGV(GblS.getCurrentPCOffset(),
483 TEW->getAbsoluteLabelMachineRelTy(),
484 const_cast<GlobalValue*>(GV));
486 // Fill the data entry with zeros
487 for (unsigned i=0; i < Size; ++i)
490 // Add the relocation entry for the current data section
491 GblS.addRelocation(MR);
493 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
494 if (CE->getOpcode() == Instruction::BitCast) {
495 EmitGlobalConstant(CE->getOperand(0), GblS);
498 // See AsmPrinter::EmitConstantValueOnly for other ConstantExpr types
499 llvm_unreachable("Unsupported ConstantExpr type");
502 llvm_unreachable("Unknown global constant type");
506 bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
507 // Nothing to do here, this is all done through the ElfCE object above.
511 /// doFinalization - Now that the module has been completely processed, emit
512 /// the ELF file to 'O'.
513 bool ELFWriter::doFinalization(Module &M) {
514 // Emit .data section placeholder
517 // Emit .bss section placeholder
520 // Build and emit data, bss and "common" sections.
521 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
525 // Emit all pending globals
526 for (PendingGblsIter I = PendingGlobals.begin(), E = PendingGlobals.end();
530 // Emit all pending externals
531 for (PendingExtsIter I = PendingExternals.begin(), E = PendingExternals.end();
533 SymbolList.push_back(ELFSym::getExtSym(*I));
535 // Emit non-executable stack note
536 if (TAI->getNonexecutableStackDirective())
537 getNonExecStackSection();
539 // Emit a symbol for each section created until now, skip null section
540 for (unsigned i = 1, e = SectionList.size(); i < e; ++i) {
541 ELFSection &ES = *SectionList[i];
542 ELFSym *SectionSym = ELFSym::getSectionSym();
543 SectionSym->SectionIdx = ES.SectionIdx;
544 SymbolList.push_back(SectionSym);
545 ES.Sym = SymbolList.back();
549 EmitStringTable(M.getModuleIdentifier());
551 // Emit the symbol table now, if non-empty.
554 // Emit the relocation sections.
557 // Emit the sections string table.
558 EmitSectionTableStringTable();
560 // Dump the sections and section table to the .o file.
561 OutputSectionsAndSectionTable();
563 // We are done with the abstract symbols.
568 // Release the name mangler object.
569 delete Mang; Mang = 0;
573 // RelocateField - Patch relocatable field with 'Offset' in 'BO'
574 // using a 'Value' of known 'Size'
575 void ELFWriter::RelocateField(BinaryObject &BO, uint32_t Offset,
576 int64_t Value, unsigned Size) {
578 BO.fixWord32(Value, Offset);
580 BO.fixWord64(Value, Offset);
582 llvm_unreachable("don't know howto patch relocatable field");
585 /// EmitRelocations - Emit relocations
586 void ELFWriter::EmitRelocations() {
588 // True if the target uses the relocation entry to hold the addend,
589 // otherwise the addend is written directly to the relocatable field.
590 bool HasRelA = TEW->hasRelocationAddend();
592 // Create Relocation sections for each section which needs it.
593 for (unsigned i=0, e=SectionList.size(); i != e; ++i) {
594 ELFSection &S = *SectionList[i];
596 // This section does not have relocations
597 if (!S.hasRelocations()) continue;
598 ELFSection &RelSec = getRelocSection(S);
600 // 'Link' - Section hdr idx of the associated symbol table
601 // 'Info' - Section hdr idx of the section to which the relocation applies
602 ELFSection &SymTab = getSymbolTableSection();
603 RelSec.Link = SymTab.SectionIdx;
604 RelSec.Info = S.SectionIdx;
605 RelSec.EntSize = TEW->getRelocationEntrySize();
607 // Get the relocations from Section
608 std::vector<MachineRelocation> Relos = S.getRelocations();
609 for (std::vector<MachineRelocation>::iterator MRI = Relos.begin(),
610 MRE = Relos.end(); MRI != MRE; ++MRI) {
611 MachineRelocation &MR = *MRI;
613 // Relocatable field offset from the section start
614 unsigned RelOffset = MR.getMachineCodeOffset();
616 // Symbol index in the symbol table
619 // Target specific relocation field type and size
620 unsigned RelType = TEW->getRelocationType(MR.getRelocationType());
621 unsigned RelTySize = TEW->getRelocationTySize(RelType);
624 // There are several machine relocations types, and each one of
625 // them needs a different approach to retrieve the symbol table index.
626 if (MR.isGlobalValue()) {
627 const GlobalValue *G = MR.getGlobalValue();
628 SymIdx = GblSymLookup[G];
629 if (G->hasPrivateLinkage()) {
630 // If the target uses a section offset in the relocation:
631 // SymIdx + Addend = section sym for global + section offset
632 unsigned SectionIdx = PrivateSyms[SymIdx]->SectionIdx;
633 Addend = PrivateSyms[SymIdx]->Value;
634 SymIdx = SectionList[SectionIdx]->getSymbolTableIndex();
636 Addend = TEW->getDefaultAddendForRelTy(RelType);
638 } else if (MR.isExternalSymbol()) {
639 const char *ExtSym = MR.getExternalSymbol();
640 SymIdx = ExtSymLookup[ExtSym];
641 Addend = TEW->getDefaultAddendForRelTy(RelType);
643 // Get the symbol index for the section symbol
644 unsigned SectionIdx = MR.getConstantVal();
645 SymIdx = SectionList[SectionIdx]->getSymbolTableIndex();
646 Addend = (uint64_t)MR.getResultPointer();
648 // For pc relative relocations where symbols are defined in the same
649 // section they are referenced, ignore the relocation entry and patch
650 // the relocatable field with the symbol offset directly.
651 if (S.SectionIdx == SectionIdx && TEW->isPCRelativeRel(RelType)) {
652 int64_t Value = TEW->computeRelocation(Addend, RelOffset, RelType);
653 RelocateField(S, RelOffset, Value, RelTySize);
657 // Handle Jump Table Index relocation
658 if ((SectionIdx == getJumpTableSection().SectionIdx) &&
659 TEW->hasCustomJumpTableIndexRelTy()) {
660 RelType = TEW->getJumpTableIndexRelTy();
661 RelTySize = TEW->getRelocationTySize(RelType);
665 // The target without addend on the relocation symbol must be
666 // patched in the relocation place itself to contain the addend
668 RelocateField(S, RelOffset, Addend, RelTySize);
670 // Get the relocation entry and emit to the relocation section
671 ELFRelocation Rel(RelOffset, SymIdx, RelType, HasRelA, Addend);
672 EmitRelocation(RelSec, Rel, HasRelA);
677 /// EmitRelocation - Write relocation 'Rel' to the relocation section 'Rel'
678 void ELFWriter::EmitRelocation(BinaryObject &RelSec, ELFRelocation &Rel,
680 RelSec.emitWord(Rel.getOffset());
681 RelSec.emitWord(Rel.getInfo(is64Bit));
683 RelSec.emitWord(Rel.getAddend());
686 /// EmitSymbol - Write symbol 'Sym' to the symbol table 'SymbolTable'
687 void ELFWriter::EmitSymbol(BinaryObject &SymbolTable, ELFSym &Sym) {
689 SymbolTable.emitWord32(Sym.NameIdx);
690 SymbolTable.emitByte(Sym.Info);
691 SymbolTable.emitByte(Sym.Other);
692 SymbolTable.emitWord16(Sym.SectionIdx);
693 SymbolTable.emitWord64(Sym.Value);
694 SymbolTable.emitWord64(Sym.Size);
696 SymbolTable.emitWord32(Sym.NameIdx);
697 SymbolTable.emitWord32(Sym.Value);
698 SymbolTable.emitWord32(Sym.Size);
699 SymbolTable.emitByte(Sym.Info);
700 SymbolTable.emitByte(Sym.Other);
701 SymbolTable.emitWord16(Sym.SectionIdx);
705 /// EmitSectionHeader - Write section 'Section' header in 'SHdrTab'
706 /// Section Header Table
707 void ELFWriter::EmitSectionHeader(BinaryObject &SHdrTab,
708 const ELFSection &SHdr) {
709 SHdrTab.emitWord32(SHdr.NameIdx);
710 SHdrTab.emitWord32(SHdr.Type);
712 SHdrTab.emitWord64(SHdr.Flags);
713 SHdrTab.emitWord(SHdr.Addr);
714 SHdrTab.emitWord(SHdr.Offset);
715 SHdrTab.emitWord64(SHdr.Size);
716 SHdrTab.emitWord32(SHdr.Link);
717 SHdrTab.emitWord32(SHdr.Info);
718 SHdrTab.emitWord64(SHdr.Align);
719 SHdrTab.emitWord64(SHdr.EntSize);
721 SHdrTab.emitWord32(SHdr.Flags);
722 SHdrTab.emitWord(SHdr.Addr);
723 SHdrTab.emitWord(SHdr.Offset);
724 SHdrTab.emitWord32(SHdr.Size);
725 SHdrTab.emitWord32(SHdr.Link);
726 SHdrTab.emitWord32(SHdr.Info);
727 SHdrTab.emitWord32(SHdr.Align);
728 SHdrTab.emitWord32(SHdr.EntSize);
732 /// EmitStringTable - If the current symbol table is non-empty, emit the string
734 void ELFWriter::EmitStringTable(const std::string &ModuleName) {
735 if (!SymbolList.size()) return; // Empty symbol table.
736 ELFSection &StrTab = getStringTableSection();
738 // Set the zero'th symbol to a null byte, as required.
741 // Walk on the symbol list and write symbol names into the string table.
743 for (ELFSymIter I=SymbolList.begin(), E=SymbolList.end(); I != E; ++I) {
747 if (Sym.isGlobalValue())
748 // Use the name mangler to uniquify the LLVM symbol.
749 Name.append(Mang->getMangledName(Sym.getGlobalValue()));
750 else if (Sym.isExternalSym())
751 Name.append(Sym.getExternalSymbol());
752 else if (Sym.isFileType())
753 Name.append(ModuleName);
759 StrTab.emitString(Name);
761 // Keep track of the number of bytes emitted to this section.
762 Index += Name.size()+1;
765 assert(Index == StrTab.size());
769 // SortSymbols - On the symbol table local symbols must come before
770 // all other symbols with non-local bindings. The return value is
771 // the position of the first non local symbol.
772 unsigned ELFWriter::SortSymbols() {
773 unsigned FirstNonLocalSymbol;
774 std::vector<ELFSym*> LocalSyms, OtherSyms;
776 for (ELFSymIter I=SymbolList.begin(), E=SymbolList.end(); I != E; ++I) {
777 if ((*I)->isLocalBind())
778 LocalSyms.push_back(*I);
780 OtherSyms.push_back(*I);
783 FirstNonLocalSymbol = LocalSyms.size();
785 for (unsigned i = 0; i < FirstNonLocalSymbol; ++i)
786 SymbolList.push_back(LocalSyms[i]);
788 for (ELFSymIter I=OtherSyms.begin(), E=OtherSyms.end(); I != E; ++I)
789 SymbolList.push_back(*I);
794 return FirstNonLocalSymbol;
797 /// EmitSymbolTable - Emit the symbol table itself.
798 void ELFWriter::EmitSymbolTable() {
799 if (!SymbolList.size()) return; // Empty symbol table.
801 // Now that we have emitted the string table and know the offset into the
802 // string table of each symbol, emit the symbol table itself.
803 ELFSection &SymTab = getSymbolTableSection();
804 SymTab.Align = TEW->getPrefELFAlignment();
806 // Section Index of .strtab.
807 SymTab.Link = getStringTableSection().SectionIdx;
809 // Size of each symtab entry.
810 SymTab.EntSize = TEW->getSymTabEntrySize();
812 // Reorder the symbol table with local symbols first!
813 unsigned FirstNonLocalSymbol = SortSymbols();
815 // Emit all the symbols to the symbol table.
816 for (unsigned i = 0, e = SymbolList.size(); i < e; ++i) {
817 ELFSym &Sym = *SymbolList[i];
819 // Emit symbol to the symbol table
820 EmitSymbol(SymTab, Sym);
822 // Record the symbol table index for each symbol
823 if (Sym.isGlobalValue())
824 GblSymLookup[Sym.getGlobalValue()] = i;
825 else if (Sym.isExternalSym())
826 ExtSymLookup[Sym.getExternalSymbol()] = i;
828 // Keep track on the symbol index into the symbol table
832 // One greater than the symbol table index of the last local symbol
833 SymTab.Info = FirstNonLocalSymbol;
834 SymTab.Size = SymTab.size();
837 /// EmitSectionTableStringTable - This method adds and emits a section for the
838 /// ELF Section Table string table: the string table that holds all of the
840 void ELFWriter::EmitSectionTableStringTable() {
841 // First step: add the section for the string table to the list of sections:
842 ELFSection &SHStrTab = getSectionHeaderStringTableSection();
844 // Now that we know which section number is the .shstrtab section, update the
845 // e_shstrndx entry in the ELF header.
846 ElfHdr.fixWord16(SHStrTab.SectionIdx, ELFHdr_e_shstrndx_Offset);
848 // Set the NameIdx of each section in the string table and emit the bytes for
852 for (ELFSectionIter I=SectionList.begin(), E=SectionList.end(); I != E; ++I) {
853 ELFSection &S = *(*I);
854 // Set the index into the table. Note if we have lots of entries with
855 // common suffixes, we could memoize them here if we cared.
857 SHStrTab.emitString(S.getName());
859 // Keep track of the number of bytes emitted to this section.
860 Index += S.getName().size()+1;
863 // Set the size of .shstrtab now that we know what it is.
864 assert(Index == SHStrTab.size());
865 SHStrTab.Size = Index;
868 /// OutputSectionsAndSectionTable - Now that we have constructed the file header
869 /// and all of the sections, emit these to the ostream destination and emit the
871 void ELFWriter::OutputSectionsAndSectionTable() {
872 // Pass #1: Compute the file offset for each section.
873 size_t FileOff = ElfHdr.size(); // File header first.
875 // Adjust alignment of all section if needed, skip the null section.
876 for (unsigned i=1, e=SectionList.size(); i < e; ++i) {
877 ELFSection &ES = *SectionList[i];
883 // Update Section size
887 // Align FileOff to whatever the alignment restrictions of the section are.
889 FileOff = (FileOff+ES.Align-1) & ~(ES.Align-1);
895 // Align Section Header.
896 unsigned TableAlign = TEW->getPrefELFAlignment();
897 FileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
899 // Now that we know where all of the sections will be emitted, set the e_shnum
900 // entry in the ELF header.
901 ElfHdr.fixWord16(NumSections, ELFHdr_e_shnum_Offset);
903 // Now that we know the offset in the file of the section table, update the
904 // e_shoff address in the ELF header.
905 ElfHdr.fixWord(FileOff, ELFHdr_e_shoff_Offset);
907 // Now that we know all of the data in the file header, emit it and all of the
909 O.write((char *)&ElfHdr.getData()[0], ElfHdr.size());
910 FileOff = ElfHdr.size();
912 // Section Header Table blob
913 BinaryObject SHdrTable(isLittleEndian, is64Bit);
915 // Emit all of sections to the file and build the section header table.
916 for (ELFSectionIter I=SectionList.begin(), E=SectionList.end(); I != E; ++I) {
917 ELFSection &S = *(*I);
918 DOUT << "SectionIdx: " << S.SectionIdx << ", Name: " << S.getName()
919 << ", Size: " << S.Size << ", Offset: " << S.Offset
920 << ", SectionData Size: " << S.size() << "\n";
922 // Align FileOff to whatever the alignment restrictions of the section are.
925 for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
926 FileOff != NewFileOff; ++FileOff)
929 O.write((char *)&S.getData()[0], S.Size);
933 EmitSectionHeader(SHdrTable, S);
936 // Align output for the section table.
937 for (size_t NewFileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
938 FileOff != NewFileOff; ++FileOff)
941 // Emit the section table itself.
942 O.write((char *)&SHdrTable.getData()[0], SHdrTable.size());