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();
182 const TargetLoweringObjectFile &TLOF =
183 TM.getTargetLowering()->getObjFileLowering();
185 return getSection(TLOF.getSectionForConstant(SectionKind::getReadOnly())
187 ELFSection::SHT_PROGBITS,
188 ELFSection::SHF_ALLOC, Align);
191 // Get a constant pool section based on the section name returned by TAI
192 ELFSection &ELFWriter::getConstantPoolSection(MachineConstantPoolEntry &CPE) {
194 switch (CPE.getRelocationInfo()) {
195 default: llvm_unreachable("Unknown section kind");
196 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
198 Kind = SectionKind::getReadOnlyWithRelLocal();
201 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
202 case 4: Kind = SectionKind::getMergeableConst4(); break;
203 case 8: Kind = SectionKind::getMergeableConst8(); break;
204 case 16: Kind = SectionKind::getMergeableConst16(); break;
205 default: Kind = SectionKind::getMergeableConst(); break;
209 const TargetLoweringObjectFile &TLOF =
210 TM.getTargetLowering()->getObjFileLowering();
212 return getSection(TLOF.getSectionForConstant(Kind)->getName(),
213 ELFSection::SHT_PROGBITS,
214 ELFSection::SHF_MERGE | ELFSection::SHF_ALLOC,
218 // Return the relocation section of section 'S'. 'RelA' is true
219 // if the relocation section contains entries with addends.
220 ELFSection &ELFWriter::getRelocSection(ELFSection &S) {
221 unsigned SectionHeaderTy = TEW->hasRelocationAddend() ?
222 ELFSection::SHT_RELA : ELFSection::SHT_REL;
223 std::string RelSName(".rel");
224 if (TEW->hasRelocationAddend())
225 RelSName.append("a");
226 RelSName.append(S.getName());
228 return getSection(RelSName, SectionHeaderTy, 0, TEW->getPrefELFAlignment());
231 // getGlobalELFVisibility - Returns the ELF specific visibility type
232 unsigned ELFWriter::getGlobalELFVisibility(const GlobalValue *GV) {
233 switch (GV->getVisibility()) {
235 llvm_unreachable("unknown visibility type");
236 case GlobalValue::DefaultVisibility:
237 return ELFSym::STV_DEFAULT;
238 case GlobalValue::HiddenVisibility:
239 return ELFSym::STV_HIDDEN;
240 case GlobalValue::ProtectedVisibility:
241 return ELFSym::STV_PROTECTED;
246 // getGlobalELFBinding - Returns the ELF specific binding type
247 unsigned ELFWriter::getGlobalELFBinding(const GlobalValue *GV) {
248 if (GV->hasInternalLinkage())
249 return ELFSym::STB_LOCAL;
251 if (GV->hasWeakLinkage())
252 return ELFSym::STB_WEAK;
254 return ELFSym::STB_GLOBAL;
257 // getGlobalELFType - Returns the ELF specific type for a global
258 unsigned ELFWriter::getGlobalELFType(const GlobalValue *GV) {
259 if (GV->isDeclaration())
260 return ELFSym::STT_NOTYPE;
262 if (isa<Function>(GV))
263 return ELFSym::STT_FUNC;
265 return ELFSym::STT_OBJECT;
268 // getElfSectionFlags - Get the ELF Section Header flags based
269 // on the flags defined in ELFTargetAsmInfo.
270 unsigned ELFWriter::getElfSectionFlags(SectionKind Kind) {
271 unsigned ElfSectionFlags = ELFSection::SHF_ALLOC;
274 ElfSectionFlags |= ELFSection::SHF_EXECINSTR;
275 if (Kind.isWriteable())
276 ElfSectionFlags |= ELFSection::SHF_WRITE;
277 if (Kind.isMergeableConst())
278 ElfSectionFlags |= ELFSection::SHF_MERGE;
279 if (Kind.isThreadLocal())
280 ElfSectionFlags |= ELFSection::SHF_TLS;
281 if (Kind.isMergeableCString())
282 ElfSectionFlags |= ELFSection::SHF_STRINGS;
284 return ElfSectionFlags;
287 // isELFUndefSym - the symbol has no section and must be placed in
288 // the symbol table with a reference to the null section.
289 static bool isELFUndefSym(const GlobalValue *GV) {
290 return GV->isDeclaration();
293 // isELFBssSym - for an undef or null value, the symbol must go to a bss
294 // section if it's not weak for linker, otherwise it's a common sym.
295 static bool isELFBssSym(const GlobalVariable *GV) {
296 const Constant *CV = GV->getInitializer();
297 return ((CV->isNullValue() || isa<UndefValue>(CV)) && !GV->isWeakForLinker());
300 // isELFCommonSym - for an undef or null value, the symbol must go to a
301 // common section if it's weak for linker, otherwise bss.
302 static bool isELFCommonSym(const GlobalVariable *GV) {
303 const Constant *CV = GV->getInitializer();
304 return ((CV->isNullValue() || isa<UndefValue>(CV)) && GV->isWeakForLinker());
307 // isELFDataSym - if the symbol is an initialized but no null constant
308 // it must go to some kind of data section gathered from TAI
309 static bool isELFDataSym(const Constant *CV) {
310 return (!(CV->isNullValue() || isa<UndefValue>(CV)));
313 // EmitGlobal - Choose the right section for global and emit it
314 void ELFWriter::EmitGlobal(const GlobalValue *GV) {
316 // Check if the referenced symbol is already emitted
317 if (GblSymLookup.find(GV) != GblSymLookup.end())
320 // If the global is a function already emited in the text section
321 // just add it to the global symbol lookup with a zero index to be
323 if (isa<Function>(GV) && !GV->isDeclaration()) {
324 GblSymLookup[GV] = 0;
328 // Handle ELF Bind, Visibility and Type for the current symbol
329 unsigned SymBind = getGlobalELFBinding(GV);
330 ELFSym *GblSym = ELFSym::getGV(GV, SymBind, getGlobalELFType(GV),
331 getGlobalELFVisibility(GV));
333 if (isELFUndefSym(GV)) {
334 GblSym->SectionIdx = ELFSection::SHN_UNDEF;
336 assert(isa<GlobalVariable>(GV) && "GV not a global variable!");
337 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
339 const TargetLoweringObjectFile &TLOF =
340 TM.getTargetLowering()->getObjFileLowering();
342 // Get the ELF section where this global belongs from TLOF
343 const MCSection *S = TLOF.SectionForGlobal(GV, Mang, TM);
344 unsigned SectionFlags = getElfSectionFlags(((MCSectionELF*)S)->getKind());
346 // The symbol align should update the section alignment if needed
347 const TargetData *TD = TM.getTargetData();
348 unsigned Align = TD->getPreferredAlignment(GVar);
349 unsigned Size = TD->getTypeAllocSize(GVar->getInitializer()->getType());
352 if (isELFCommonSym(GVar)) {
353 GblSym->SectionIdx = ELFSection::SHN_COMMON;
354 getSection(S->getName(), ELFSection::SHT_NOBITS, SectionFlags, 1);
356 // A new linkonce section is created for each global in the
357 // common section, the default alignment is 1 and the symbol
358 // value contains its alignment.
359 GblSym->Value = Align;
361 } else if (isELFBssSym(GVar)) {
363 getSection(S->getName(), ELFSection::SHT_NOBITS, SectionFlags);
364 GblSym->SectionIdx = ES.SectionIdx;
366 // Update the size with alignment and the next object can
367 // start in the right offset in the section
368 if (Align) ES.Size = (ES.Size + Align-1) & ~(Align-1);
369 ES.Align = std::max(ES.Align, Align);
371 // GblSym->Value should contain the virtual offset inside the section.
372 // Virtual because the BSS space is not allocated on ELF objects
373 GblSym->Value = ES.Size;
376 } else if (isELFDataSym(GV)) {
378 getSection(S->getName(), ELFSection::SHT_PROGBITS, SectionFlags);
379 GblSym->SectionIdx = ES.SectionIdx;
381 // GblSym->Value should contain the symbol offset inside the section,
382 // and all symbols should start on their required alignment boundary
383 ES.Align = std::max(ES.Align, Align);
384 GblSym->Value = (ES.size() + (Align-1)) & (-Align);
385 ES.emitAlignment(ES.Align);
387 // Emit the global to the data section 'ES'
388 EmitGlobalConstant(GVar->getInitializer(), ES);
392 if (GV->hasPrivateLinkage()) {
393 // For a private symbols, keep track of the index inside the
394 // private list since it will never go to the symbol table and
395 // won't be patched up later.
396 PrivateSyms.push_back(GblSym);
397 GblSymLookup[GV] = PrivateSyms.size()-1;
399 // Non private symbol are left with zero indices until they are patched
400 // up during the symbol table emition (where the indicies are created).
401 SymbolList.push_back(GblSym);
402 GblSymLookup[GV] = 0;
406 void ELFWriter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
409 // Print the fields in successive locations. Pad to align if needed!
410 const TargetData *TD = TM.getTargetData();
411 unsigned Size = TD->getTypeAllocSize(CVS->getType());
412 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
413 uint64_t sizeSoFar = 0;
414 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
415 const Constant* field = CVS->getOperand(i);
417 // Check if padding is needed and insert one or more 0s.
418 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
419 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
420 - cvsLayout->getElementOffset(i)) - fieldSize;
421 sizeSoFar += fieldSize + padSize;
423 // Now print the actual field value.
424 EmitGlobalConstant(field, GblS);
426 // Insert padding - this may include padding to increase the size of the
427 // current field up to the ABI size (if the struct is not packed) as well
428 // as padding to ensure that the next field starts at the right offset.
429 for (unsigned p=0; p < padSize; p++)
432 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
433 "Layout of constant struct may be incorrect!");
436 void ELFWriter::EmitGlobalConstant(const Constant *CV, ELFSection &GblS) {
437 const TargetData *TD = TM.getTargetData();
438 unsigned Size = TD->getTypeAllocSize(CV->getType());
440 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
441 if (CVA->isString()) {
442 std::string GblStr = CVA->getAsString();
443 GblStr.resize(GblStr.size()-1);
444 GblS.emitString(GblStr);
445 } else { // Not a string. Print the values in successive locations
446 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
447 EmitGlobalConstant(CVA->getOperand(i), GblS);
450 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
451 EmitGlobalConstantStruct(CVS, GblS);
453 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
454 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
455 if (CFP->getType() == Type::DoubleTy)
456 GblS.emitWord64(Val);
457 else if (CFP->getType() == Type::FloatTy)
458 GblS.emitWord32(Val);
459 else if (CFP->getType() == Type::X86_FP80Ty) {
460 llvm_unreachable("X86_FP80Ty global emission not implemented");
461 } else if (CFP->getType() == Type::PPC_FP128Ty)
462 llvm_unreachable("PPC_FP128Ty global emission not implemented");
464 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
466 GblS.emitWord32(CI->getZExtValue());
468 GblS.emitWord64(CI->getZExtValue());
470 llvm_unreachable("LargeInt global emission not implemented");
472 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
473 const VectorType *PTy = CP->getType();
474 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
475 EmitGlobalConstant(CP->getOperand(I), GblS);
477 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
478 // This is a constant address for a global variable or function and
479 // therefore must be referenced using a relocation entry.
481 // Check if the referenced symbol is already emitted
482 if (GblSymLookup.find(GV) == GblSymLookup.end())
485 // Create the relocation entry for the global value
486 MachineRelocation MR =
487 MachineRelocation::getGV(GblS.getCurrentPCOffset(),
488 TEW->getAbsoluteLabelMachineRelTy(),
489 const_cast<GlobalValue*>(GV));
491 // Fill the data entry with zeros
492 for (unsigned i=0; i < Size; ++i)
495 // Add the relocation entry for the current data section
496 GblS.addRelocation(MR);
498 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
499 if (CE->getOpcode() == Instruction::BitCast) {
500 EmitGlobalConstant(CE->getOperand(0), GblS);
503 // See AsmPrinter::EmitConstantValueOnly for other ConstantExpr types
504 llvm_unreachable("Unsupported ConstantExpr type");
507 llvm_unreachable("Unknown global constant type");
511 bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
512 // Nothing to do here, this is all done through the ElfCE object above.
516 /// doFinalization - Now that the module has been completely processed, emit
517 /// the ELF file to 'O'.
518 bool ELFWriter::doFinalization(Module &M) {
519 // Emit .data section placeholder
522 // Emit .bss section placeholder
525 // Build and emit data, bss and "common" sections.
526 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
530 // Emit all pending globals
531 for (PendingGblsIter I = PendingGlobals.begin(), E = PendingGlobals.end();
535 // Emit all pending externals
536 for (PendingExtsIter I = PendingExternals.begin(), E = PendingExternals.end();
538 SymbolList.push_back(ELFSym::getExtSym(*I));
540 // Emit non-executable stack note
541 if (TAI->getNonexecutableStackDirective())
542 getNonExecStackSection();
544 // Emit a symbol for each section created until now, skip null section
545 for (unsigned i = 1, e = SectionList.size(); i < e; ++i) {
546 ELFSection &ES = *SectionList[i];
547 ELFSym *SectionSym = ELFSym::getSectionSym();
548 SectionSym->SectionIdx = ES.SectionIdx;
549 SymbolList.push_back(SectionSym);
550 ES.Sym = SymbolList.back();
554 EmitStringTable(M.getModuleIdentifier());
556 // Emit the symbol table now, if non-empty.
559 // Emit the relocation sections.
562 // Emit the sections string table.
563 EmitSectionTableStringTable();
565 // Dump the sections and section table to the .o file.
566 OutputSectionsAndSectionTable();
568 // We are done with the abstract symbols.
573 // Release the name mangler object.
574 delete Mang; Mang = 0;
578 // RelocateField - Patch relocatable field with 'Offset' in 'BO'
579 // using a 'Value' of known 'Size'
580 void ELFWriter::RelocateField(BinaryObject &BO, uint32_t Offset,
581 int64_t Value, unsigned Size) {
583 BO.fixWord32(Value, Offset);
585 BO.fixWord64(Value, Offset);
587 llvm_unreachable("don't know howto patch relocatable field");
590 /// EmitRelocations - Emit relocations
591 void ELFWriter::EmitRelocations() {
593 // True if the target uses the relocation entry to hold the addend,
594 // otherwise the addend is written directly to the relocatable field.
595 bool HasRelA = TEW->hasRelocationAddend();
597 // Create Relocation sections for each section which needs it.
598 for (unsigned i=0, e=SectionList.size(); i != e; ++i) {
599 ELFSection &S = *SectionList[i];
601 // This section does not have relocations
602 if (!S.hasRelocations()) continue;
603 ELFSection &RelSec = getRelocSection(S);
605 // 'Link' - Section hdr idx of the associated symbol table
606 // 'Info' - Section hdr idx of the section to which the relocation applies
607 ELFSection &SymTab = getSymbolTableSection();
608 RelSec.Link = SymTab.SectionIdx;
609 RelSec.Info = S.SectionIdx;
610 RelSec.EntSize = TEW->getRelocationEntrySize();
612 // Get the relocations from Section
613 std::vector<MachineRelocation> Relos = S.getRelocations();
614 for (std::vector<MachineRelocation>::iterator MRI = Relos.begin(),
615 MRE = Relos.end(); MRI != MRE; ++MRI) {
616 MachineRelocation &MR = *MRI;
618 // Relocatable field offset from the section start
619 unsigned RelOffset = MR.getMachineCodeOffset();
621 // Symbol index in the symbol table
624 // Target specific relocation field type and size
625 unsigned RelType = TEW->getRelocationType(MR.getRelocationType());
626 unsigned RelTySize = TEW->getRelocationTySize(RelType);
629 // There are several machine relocations types, and each one of
630 // them needs a different approach to retrieve the symbol table index.
631 if (MR.isGlobalValue()) {
632 const GlobalValue *G = MR.getGlobalValue();
633 SymIdx = GblSymLookup[G];
634 if (G->hasPrivateLinkage()) {
635 // If the target uses a section offset in the relocation:
636 // SymIdx + Addend = section sym for global + section offset
637 unsigned SectionIdx = PrivateSyms[SymIdx]->SectionIdx;
638 Addend = PrivateSyms[SymIdx]->Value;
639 SymIdx = SectionList[SectionIdx]->getSymbolTableIndex();
641 Addend = TEW->getDefaultAddendForRelTy(RelType);
643 } else if (MR.isExternalSymbol()) {
644 const char *ExtSym = MR.getExternalSymbol();
645 SymIdx = ExtSymLookup[ExtSym];
646 Addend = TEW->getDefaultAddendForRelTy(RelType);
648 // Get the symbol index for the section symbol
649 unsigned SectionIdx = MR.getConstantVal();
650 SymIdx = SectionList[SectionIdx]->getSymbolTableIndex();
651 Addend = (uint64_t)MR.getResultPointer();
653 // For pc relative relocations where symbols are defined in the same
654 // section they are referenced, ignore the relocation entry and patch
655 // the relocatable field with the symbol offset directly.
656 if (S.SectionIdx == SectionIdx && TEW->isPCRelativeRel(RelType)) {
657 int64_t Value = TEW->computeRelocation(Addend, RelOffset, RelType);
658 RelocateField(S, RelOffset, Value, RelTySize);
662 // Handle Jump Table Index relocation
663 if ((SectionIdx == getJumpTableSection().SectionIdx) &&
664 TEW->hasCustomJumpTableIndexRelTy()) {
665 RelType = TEW->getJumpTableIndexRelTy();
666 RelTySize = TEW->getRelocationTySize(RelType);
670 // The target without addend on the relocation symbol must be
671 // patched in the relocation place itself to contain the addend
673 RelocateField(S, RelOffset, Addend, RelTySize);
675 // Get the relocation entry and emit to the relocation section
676 ELFRelocation Rel(RelOffset, SymIdx, RelType, HasRelA, Addend);
677 EmitRelocation(RelSec, Rel, HasRelA);
682 /// EmitRelocation - Write relocation 'Rel' to the relocation section 'Rel'
683 void ELFWriter::EmitRelocation(BinaryObject &RelSec, ELFRelocation &Rel,
685 RelSec.emitWord(Rel.getOffset());
686 RelSec.emitWord(Rel.getInfo(is64Bit));
688 RelSec.emitWord(Rel.getAddend());
691 /// EmitSymbol - Write symbol 'Sym' to the symbol table 'SymbolTable'
692 void ELFWriter::EmitSymbol(BinaryObject &SymbolTable, ELFSym &Sym) {
694 SymbolTable.emitWord32(Sym.NameIdx);
695 SymbolTable.emitByte(Sym.Info);
696 SymbolTable.emitByte(Sym.Other);
697 SymbolTable.emitWord16(Sym.SectionIdx);
698 SymbolTable.emitWord64(Sym.Value);
699 SymbolTable.emitWord64(Sym.Size);
701 SymbolTable.emitWord32(Sym.NameIdx);
702 SymbolTable.emitWord32(Sym.Value);
703 SymbolTable.emitWord32(Sym.Size);
704 SymbolTable.emitByte(Sym.Info);
705 SymbolTable.emitByte(Sym.Other);
706 SymbolTable.emitWord16(Sym.SectionIdx);
710 /// EmitSectionHeader - Write section 'Section' header in 'SHdrTab'
711 /// Section Header Table
712 void ELFWriter::EmitSectionHeader(BinaryObject &SHdrTab,
713 const ELFSection &SHdr) {
714 SHdrTab.emitWord32(SHdr.NameIdx);
715 SHdrTab.emitWord32(SHdr.Type);
717 SHdrTab.emitWord64(SHdr.Flags);
718 SHdrTab.emitWord(SHdr.Addr);
719 SHdrTab.emitWord(SHdr.Offset);
720 SHdrTab.emitWord64(SHdr.Size);
721 SHdrTab.emitWord32(SHdr.Link);
722 SHdrTab.emitWord32(SHdr.Info);
723 SHdrTab.emitWord64(SHdr.Align);
724 SHdrTab.emitWord64(SHdr.EntSize);
726 SHdrTab.emitWord32(SHdr.Flags);
727 SHdrTab.emitWord(SHdr.Addr);
728 SHdrTab.emitWord(SHdr.Offset);
729 SHdrTab.emitWord32(SHdr.Size);
730 SHdrTab.emitWord32(SHdr.Link);
731 SHdrTab.emitWord32(SHdr.Info);
732 SHdrTab.emitWord32(SHdr.Align);
733 SHdrTab.emitWord32(SHdr.EntSize);
737 /// EmitStringTable - If the current symbol table is non-empty, emit the string
739 void ELFWriter::EmitStringTable(const std::string &ModuleName) {
740 if (!SymbolList.size()) return; // Empty symbol table.
741 ELFSection &StrTab = getStringTableSection();
743 // Set the zero'th symbol to a null byte, as required.
746 // Walk on the symbol list and write symbol names into the string table.
748 for (ELFSymIter I=SymbolList.begin(), E=SymbolList.end(); I != E; ++I) {
752 if (Sym.isGlobalValue())
753 // Use the name mangler to uniquify the LLVM symbol.
754 Name.append(Mang->getMangledName(Sym.getGlobalValue()));
755 else if (Sym.isExternalSym())
756 Name.append(Sym.getExternalSymbol());
757 else if (Sym.isFileType())
758 Name.append(ModuleName);
764 StrTab.emitString(Name);
766 // Keep track of the number of bytes emitted to this section.
767 Index += Name.size()+1;
770 assert(Index == StrTab.size());
774 // SortSymbols - On the symbol table local symbols must come before
775 // all other symbols with non-local bindings. The return value is
776 // the position of the first non local symbol.
777 unsigned ELFWriter::SortSymbols() {
778 unsigned FirstNonLocalSymbol;
779 std::vector<ELFSym*> LocalSyms, OtherSyms;
781 for (ELFSymIter I=SymbolList.begin(), E=SymbolList.end(); I != E; ++I) {
782 if ((*I)->isLocalBind())
783 LocalSyms.push_back(*I);
785 OtherSyms.push_back(*I);
788 FirstNonLocalSymbol = LocalSyms.size();
790 for (unsigned i = 0; i < FirstNonLocalSymbol; ++i)
791 SymbolList.push_back(LocalSyms[i]);
793 for (ELFSymIter I=OtherSyms.begin(), E=OtherSyms.end(); I != E; ++I)
794 SymbolList.push_back(*I);
799 return FirstNonLocalSymbol;
802 /// EmitSymbolTable - Emit the symbol table itself.
803 void ELFWriter::EmitSymbolTable() {
804 if (!SymbolList.size()) return; // Empty symbol table.
806 // Now that we have emitted the string table and know the offset into the
807 // string table of each symbol, emit the symbol table itself.
808 ELFSection &SymTab = getSymbolTableSection();
809 SymTab.Align = TEW->getPrefELFAlignment();
811 // Section Index of .strtab.
812 SymTab.Link = getStringTableSection().SectionIdx;
814 // Size of each symtab entry.
815 SymTab.EntSize = TEW->getSymTabEntrySize();
817 // Reorder the symbol table with local symbols first!
818 unsigned FirstNonLocalSymbol = SortSymbols();
820 // Emit all the symbols to the symbol table.
821 for (unsigned i = 0, e = SymbolList.size(); i < e; ++i) {
822 ELFSym &Sym = *SymbolList[i];
824 // Emit symbol to the symbol table
825 EmitSymbol(SymTab, Sym);
827 // Record the symbol table index for each symbol
828 if (Sym.isGlobalValue())
829 GblSymLookup[Sym.getGlobalValue()] = i;
830 else if (Sym.isExternalSym())
831 ExtSymLookup[Sym.getExternalSymbol()] = i;
833 // Keep track on the symbol index into the symbol table
837 // One greater than the symbol table index of the last local symbol
838 SymTab.Info = FirstNonLocalSymbol;
839 SymTab.Size = SymTab.size();
842 /// EmitSectionTableStringTable - This method adds and emits a section for the
843 /// ELF Section Table string table: the string table that holds all of the
845 void ELFWriter::EmitSectionTableStringTable() {
846 // First step: add the section for the string table to the list of sections:
847 ELFSection &SHStrTab = getSectionHeaderStringTableSection();
849 // Now that we know which section number is the .shstrtab section, update the
850 // e_shstrndx entry in the ELF header.
851 ElfHdr.fixWord16(SHStrTab.SectionIdx, ELFHdr_e_shstrndx_Offset);
853 // Set the NameIdx of each section in the string table and emit the bytes for
857 for (ELFSectionIter I=SectionList.begin(), E=SectionList.end(); I != E; ++I) {
858 ELFSection &S = *(*I);
859 // Set the index into the table. Note if we have lots of entries with
860 // common suffixes, we could memoize them here if we cared.
862 SHStrTab.emitString(S.getName());
864 // Keep track of the number of bytes emitted to this section.
865 Index += S.getName().size()+1;
868 // Set the size of .shstrtab now that we know what it is.
869 assert(Index == SHStrTab.size());
870 SHStrTab.Size = Index;
873 /// OutputSectionsAndSectionTable - Now that we have constructed the file header
874 /// and all of the sections, emit these to the ostream destination and emit the
876 void ELFWriter::OutputSectionsAndSectionTable() {
877 // Pass #1: Compute the file offset for each section.
878 size_t FileOff = ElfHdr.size(); // File header first.
880 // Adjust alignment of all section if needed, skip the null section.
881 for (unsigned i=1, e=SectionList.size(); i < e; ++i) {
882 ELFSection &ES = *SectionList[i];
888 // Update Section size
892 // Align FileOff to whatever the alignment restrictions of the section are.
894 FileOff = (FileOff+ES.Align-1) & ~(ES.Align-1);
900 // Align Section Header.
901 unsigned TableAlign = TEW->getPrefELFAlignment();
902 FileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
904 // Now that we know where all of the sections will be emitted, set the e_shnum
905 // entry in the ELF header.
906 ElfHdr.fixWord16(NumSections, ELFHdr_e_shnum_Offset);
908 // Now that we know the offset in the file of the section table, update the
909 // e_shoff address in the ELF header.
910 ElfHdr.fixWord(FileOff, ELFHdr_e_shoff_Offset);
912 // Now that we know all of the data in the file header, emit it and all of the
914 O.write((char *)&ElfHdr.getData()[0], ElfHdr.size());
915 FileOff = ElfHdr.size();
917 // Section Header Table blob
918 BinaryObject SHdrTable(isLittleEndian, is64Bit);
920 // Emit all of sections to the file and build the section header table.
921 for (ELFSectionIter I=SectionList.begin(), E=SectionList.end(); I != E; ++I) {
922 ELFSection &S = *(*I);
923 DOUT << "SectionIdx: " << S.SectionIdx << ", Name: " << S.getName()
924 << ", Size: " << S.Size << ", Offset: " << S.Offset
925 << ", SectionData Size: " << S.size() << "\n";
927 // Align FileOff to whatever the alignment restrictions of the section are.
930 for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
931 FileOff != NewFileOff; ++FileOff)
934 O.write((char *)&S.getData()[0], S.Size);
938 EmitSectionHeader(SHdrTable, S);
941 // Align output for the section table.
942 for (size_t NewFileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
943 FileOff != NewFileOff; ++FileOff)
946 // Emit the section table itself.
947 O.write((char *)&SHdrTable.getData()[0], SHdrTable.size());