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/MCSectionELF.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/Debug.h"
54 #include "llvm/Support/ErrorHandling.h"
55 #include "llvm/Support/Mangler.h"
56 #include "llvm/Support/raw_ostream.h"
60 char ELFWriter::ID = 0;
62 /// AddELFWriter - Add the ELF writer to the function pass manager
63 ObjectCodeEmitter *llvm::AddELFWriter(PassManagerBase &PM,
66 ELFWriter *EW = new ELFWriter(O, TM);
68 return EW->getObjectCodeEmitter();
71 //===----------------------------------------------------------------------===//
72 // ELFWriter Implementation
73 //===----------------------------------------------------------------------===//
75 ELFWriter::ELFWriter(raw_ostream &o, TargetMachine &tm)
76 : MachineFunctionPass(&ID), O(o), TM(tm),
77 OutContext(*new MCContext()),
78 TLOF(TM.getTargetLowering()->getObjFileLowering()),
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_cast<TargetLoweringObjectFile&>(TLOF).Initialize(OutContext, TM);
104 Mang = new Mangler(M);
108 // Fields e_shnum e_shstrndx are only known after all section have
109 // been emitted. They locations in the ouput buffer are recorded so
110 // to be patched up later.
114 // emitWord method behaves differently for ELF32 and ELF64, writing
115 // 4 bytes in the former and 8 in the last for *_off and *_addr elf types
117 ElfHdr.emitByte(0x7f); // e_ident[EI_MAG0]
118 ElfHdr.emitByte('E'); // e_ident[EI_MAG1]
119 ElfHdr.emitByte('L'); // e_ident[EI_MAG2]
120 ElfHdr.emitByte('F'); // e_ident[EI_MAG3]
122 ElfHdr.emitByte(TEW->getEIClass()); // e_ident[EI_CLASS]
123 ElfHdr.emitByte(TEW->getEIData()); // e_ident[EI_DATA]
124 ElfHdr.emitByte(EV_CURRENT); // e_ident[EI_VERSION]
125 ElfHdr.emitAlignment(16); // e_ident[EI_NIDENT-EI_PAD]
127 ElfHdr.emitWord16(ET_REL); // e_type
128 ElfHdr.emitWord16(TEW->getEMachine()); // e_machine = target
129 ElfHdr.emitWord32(EV_CURRENT); // e_version
130 ElfHdr.emitWord(0); // e_entry, no entry point in .o file
131 ElfHdr.emitWord(0); // e_phoff, no program header for .o
132 ELFHdr_e_shoff_Offset = ElfHdr.size();
133 ElfHdr.emitWord(0); // e_shoff = sec hdr table off in bytes
134 ElfHdr.emitWord32(TEW->getEFlags()); // e_flags = whatever the target wants
135 ElfHdr.emitWord16(TEW->getHdrSize()); // e_ehsize = ELF header size
136 ElfHdr.emitWord16(0); // e_phentsize = prog header entry size
137 ElfHdr.emitWord16(0); // e_phnum = # prog header entries = 0
139 // e_shentsize = Section header entry size
140 ElfHdr.emitWord16(TEW->getSHdrSize());
142 // e_shnum = # of section header ents
143 ELFHdr_e_shnum_Offset = ElfHdr.size();
144 ElfHdr.emitWord16(0); // Placeholder
146 // e_shstrndx = Section # of '.shstrtab'
147 ELFHdr_e_shstrndx_Offset = ElfHdr.size();
148 ElfHdr.emitWord16(0); // Placeholder
150 // Add the null section, which is required to be first in the file.
153 // The first entry in the symtab is the null symbol and the second
154 // is a local symbol containing the module/file name
155 SymbolList.push_back(new ELFSym());
156 SymbolList.push_back(ELFSym::getFileSym());
161 // AddPendingGlobalSymbol - Add a global to be processed and to
162 // the global symbol lookup, use a zero index because the table
163 // index will be determined later.
164 void ELFWriter::AddPendingGlobalSymbol(const GlobalValue *GV,
165 bool AddToLookup /* = false */) {
166 PendingGlobals.insert(GV);
168 GblSymLookup[GV] = 0;
171 // AddPendingExternalSymbol - Add the external to be processed
172 // and to the external symbol lookup, use a zero index because
173 // the symbol table index will be determined later.
174 void ELFWriter::AddPendingExternalSymbol(const char *External) {
175 PendingExternals.insert(External);
176 ExtSymLookup[External] = 0;
179 ELFSection &ELFWriter::getDataSection() {
180 const MCSectionELF *Data = (const MCSectionELF *)TLOF.getDataSection();
181 return getSection(Data->getSectionName(), Data->getType(),
182 Data->getFlags(), 4);
185 ELFSection &ELFWriter::getBSSSection() {
186 const MCSectionELF *BSS = (const MCSectionELF *)TLOF.getBSSSection();
187 return getSection(BSS->getSectionName(), BSS->getType(), BSS->getFlags(), 4);
190 // getCtorSection - Get the static constructor section
191 ELFSection &ELFWriter::getCtorSection() {
192 const MCSectionELF *Ctor = (const MCSectionELF *)TLOF.getStaticCtorSection();
193 return getSection(Ctor->getSectionName(), Ctor->getType(), Ctor->getFlags());
196 // getDtorSection - Get the static destructor section
197 ELFSection &ELFWriter::getDtorSection() {
198 const MCSectionELF *Dtor = (const MCSectionELF *)TLOF.getStaticDtorSection();
199 return getSection(Dtor->getSectionName(), Dtor->getType(), Dtor->getFlags());
202 // getTextSection - Get the text section for the specified function
203 ELFSection &ELFWriter::getTextSection(Function *F) {
204 const MCSectionELF *Text =
205 (const MCSectionELF *)TLOF.SectionForGlobal(F, Mang, TM);
206 return getSection(Text->getSectionName(), Text->getType(), Text->getFlags());
209 // getJumpTableSection - Get a read only section for constants when
210 // emitting jump tables. TODO: add PIC support
211 ELFSection &ELFWriter::getJumpTableSection() {
212 const MCSectionELF *JT =
213 (const MCSectionELF *)TLOF.getSectionForConstant(SectionKind::getReadOnly());
214 return getSection(JT->getSectionName(), JT->getType(), JT->getFlags(),
215 TM.getTargetData()->getPointerABIAlignment());
218 // getConstantPoolSection - Get a constant pool section based on the machine
219 // constant pool entry type and relocation info.
220 ELFSection &ELFWriter::getConstantPoolSection(MachineConstantPoolEntry &CPE) {
222 switch (CPE.getRelocationInfo()) {
223 default: llvm_unreachable("Unknown section kind");
224 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
226 Kind = SectionKind::getReadOnlyWithRelLocal();
229 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
230 case 4: Kind = SectionKind::getMergeableConst4(); break;
231 case 8: Kind = SectionKind::getMergeableConst8(); break;
232 case 16: Kind = SectionKind::getMergeableConst16(); break;
233 default: Kind = SectionKind::getMergeableConst(); break;
237 const MCSectionELF *CPSect =
238 (const MCSectionELF *)TLOF.getSectionForConstant(Kind);
239 return getSection(CPSect->getSectionName(), CPSect->getType(),
240 CPSect->getFlags(), CPE.getAlignment());
243 // getRelocSection - Return the relocation section of section 'S'. 'RelA'
244 // is true if the relocation section contains entries with addends.
245 ELFSection &ELFWriter::getRelocSection(ELFSection &S) {
246 unsigned SectionType = TEW->hasRelocationAddend() ?
247 ELFSection::SHT_RELA : ELFSection::SHT_REL;
249 std::string SectionName(".rel");
250 if (TEW->hasRelocationAddend())
251 SectionName.append("a");
252 SectionName.append(S.getName());
254 return getSection(SectionName, SectionType, 0, TEW->getPrefELFAlignment());
257 // getGlobalELFVisibility - Returns the ELF specific visibility type
258 unsigned ELFWriter::getGlobalELFVisibility(const GlobalValue *GV) {
259 switch (GV->getVisibility()) {
261 llvm_unreachable("unknown visibility type");
262 case GlobalValue::DefaultVisibility:
263 return ELFSym::STV_DEFAULT;
264 case GlobalValue::HiddenVisibility:
265 return ELFSym::STV_HIDDEN;
266 case GlobalValue::ProtectedVisibility:
267 return ELFSym::STV_PROTECTED;
272 // getGlobalELFBinding - Returns the ELF specific binding type
273 unsigned ELFWriter::getGlobalELFBinding(const GlobalValue *GV) {
274 if (GV->hasInternalLinkage())
275 return ELFSym::STB_LOCAL;
277 if (GV->isWeakForLinker() && !GV->hasCommonLinkage())
278 return ELFSym::STB_WEAK;
280 return ELFSym::STB_GLOBAL;
283 // getGlobalELFType - Returns the ELF specific type for a global
284 unsigned ELFWriter::getGlobalELFType(const GlobalValue *GV) {
285 if (GV->isDeclaration())
286 return ELFSym::STT_NOTYPE;
288 if (isa<Function>(GV))
289 return ELFSym::STT_FUNC;
291 return ELFSym::STT_OBJECT;
294 // IsELFUndefSym - True if the global value must be marked as a symbol
295 // which points to a SHN_UNDEF section. This means that the symbol has
296 // no definition on the module.
297 static bool IsELFUndefSym(const GlobalValue *GV) {
298 return GV->isDeclaration() || (isa<Function>(GV));
301 // AddToSymbolList - Update the symbol lookup and If the symbol is
302 // private add it to PrivateSyms list, otherwise to SymbolList.
303 void ELFWriter::AddToSymbolList(ELFSym *GblSym) {
304 assert(GblSym->isGlobalValue() && "Symbol must be a global value");
306 const GlobalValue *GV = GblSym->getGlobalValue();
307 if (GV->hasPrivateLinkage()) {
308 // For a private symbols, keep track of the index inside
309 // the private list since it will never go to the symbol
310 // table and won't be patched up later.
311 PrivateSyms.push_back(GblSym);
312 GblSymLookup[GV] = PrivateSyms.size()-1;
314 // Non private symbol are left with zero indices until
315 // they are patched up during the symbol table emition
316 // (where the indicies are created).
317 SymbolList.push_back(GblSym);
318 GblSymLookup[GV] = 0;
322 // EmitGlobal - Choose the right section for global and emit it
323 void ELFWriter::EmitGlobal(const GlobalValue *GV) {
325 // Check if the referenced symbol is already emitted
326 if (GblSymLookup.find(GV) != GblSymLookup.end())
329 // Handle ELF Bind, Visibility and Type for the current symbol
330 unsigned SymBind = getGlobalELFBinding(GV);
331 unsigned SymType = getGlobalELFType(GV);
332 bool IsUndefSym = IsELFUndefSym(GV);
334 ELFSym *GblSym = IsUndefSym ? ELFSym::getUndefGV(GV, SymBind)
335 : ELFSym::getGV(GV, SymBind, SymType, getGlobalELFVisibility(GV));
338 assert(isa<GlobalVariable>(GV) && "GV not a global variable!");
339 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
341 // Handle special llvm globals
342 if (EmitSpecialLLVMGlobal(GVar))
345 // Get the ELF section where this global belongs from TLOF
346 const MCSectionELF *S =
347 (const MCSectionELF *)TLOF.SectionForGlobal(GV, Mang, TM);
349 getSection(S->getSectionName(), S->getType(), S->getFlags());
350 SectionKind Kind = S->getKind();
352 // The symbol align should update the section alignment if needed
353 const TargetData *TD = TM.getTargetData();
354 unsigned Align = TD->getPreferredAlignment(GVar);
355 unsigned Size = TD->getTypeAllocSize(GVar->getInitializer()->getType());
358 if (S->HasCommonSymbols()) { // Symbol must go to a common section
359 GblSym->SectionIdx = ELFSection::SHN_COMMON;
361 // A new linkonce section is created for each global in the
362 // common section, the default alignment is 1 and the symbol
363 // value contains its alignment.
365 GblSym->Value = Align;
367 } else if (Kind.isBSS() || Kind.isThreadBSS()) { // Symbol goes to BSS.
368 GblSym->SectionIdx = ES.SectionIdx;
370 // Update the size with alignment and the next object can
371 // start in the right offset in the section
372 if (Align) ES.Size = (ES.Size + Align-1) & ~(Align-1);
373 ES.Align = std::max(ES.Align, Align);
375 // GblSym->Value should contain the virtual offset inside the section.
376 // Virtual because the BSS space is not allocated on ELF objects
377 GblSym->Value = ES.Size;
380 } else { // The symbol must go to some kind of data section
381 GblSym->SectionIdx = ES.SectionIdx;
383 // GblSym->Value should contain the symbol offset inside the section,
384 // and all symbols should start on their required alignment boundary
385 ES.Align = std::max(ES.Align, Align);
386 ES.emitAlignment(Align);
387 GblSym->Value = ES.size();
389 // Emit the global to the data section 'ES'
390 EmitGlobalConstant(GVar->getInitializer(), ES);
394 AddToSymbolList(GblSym);
397 void ELFWriter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
400 // Print the fields in successive locations. Pad to align if needed!
401 const TargetData *TD = TM.getTargetData();
402 unsigned Size = TD->getTypeAllocSize(CVS->getType());
403 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
404 uint64_t sizeSoFar = 0;
405 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
406 const Constant* field = CVS->getOperand(i);
408 // Check if padding is needed and insert one or more 0s.
409 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
410 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
411 - cvsLayout->getElementOffset(i)) - fieldSize;
412 sizeSoFar += fieldSize + padSize;
414 // Now print the actual field value.
415 EmitGlobalConstant(field, GblS);
417 // Insert padding - this may include padding to increase the size of the
418 // current field up to the ABI size (if the struct is not packed) as well
419 // as padding to ensure that the next field starts at the right offset.
420 GblS.emitZeros(padSize);
422 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
423 "Layout of constant struct may be incorrect!");
426 void ELFWriter::EmitGlobalConstant(const Constant *CV, ELFSection &GblS) {
427 const TargetData *TD = TM.getTargetData();
428 unsigned Size = TD->getTypeAllocSize(CV->getType());
430 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
431 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
432 EmitGlobalConstant(CVA->getOperand(i), GblS);
434 } else if (isa<ConstantAggregateZero>(CV)) {
435 GblS.emitZeros(Size);
437 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
438 EmitGlobalConstantStruct(CVS, GblS);
440 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
441 APInt Val = CFP->getValueAPF().bitcastToAPInt();
442 if (CFP->getType() == Type::getDoubleTy(CV->getContext()))
443 GblS.emitWord64(Val.getZExtValue());
444 else if (CFP->getType() == Type::getFloatTy(CV->getContext()))
445 GblS.emitWord32(Val.getZExtValue());
446 else if (CFP->getType() == Type::getX86_FP80Ty(CV->getContext())) {
448 TD->getTypeAllocSize(Type::getX86_FP80Ty(CV->getContext()))-
449 TD->getTypeStoreSize(Type::getX86_FP80Ty(CV->getContext()));
450 GblS.emitWordFP80(Val.getRawData(), PadSize);
451 } else if (CFP->getType() == Type::getPPC_FP128Ty(CV->getContext()))
452 llvm_unreachable("PPC_FP128Ty global emission not implemented");
454 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
456 GblS.emitByte(CI->getZExtValue());
458 GblS.emitWord16(CI->getZExtValue());
460 GblS.emitWord32(CI->getZExtValue());
462 EmitGlobalConstantLargeInt(CI, GblS);
464 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
465 const VectorType *PTy = CP->getType();
466 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
467 EmitGlobalConstant(CP->getOperand(I), GblS);
469 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
470 // Resolve a constant expression which returns a (Constant, Offset)
471 // pair. If 'Res.first' is a GlobalValue, emit a relocation with
472 // the offset 'Res.second', otherwise emit a global constant like
473 // it is always done for not contant expression types.
474 CstExprResTy Res = ResolveConstantExpr(CE);
475 const Constant *Op = Res.first;
477 if (isa<GlobalValue>(Op))
478 EmitGlobalDataRelocation(cast<const GlobalValue>(Op),
479 TD->getTypeAllocSize(Op->getType()),
482 EmitGlobalConstant(Op, GblS);
485 } else if (CV->getType()->getTypeID() == Type::PointerTyID) {
486 // Fill the data entry with zeros or emit a relocation entry
487 if (isa<ConstantPointerNull>(CV))
488 GblS.emitZeros(Size);
490 EmitGlobalDataRelocation(cast<const GlobalValue>(CV),
493 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
494 // This is a constant address for a global variable or function and
495 // therefore must be referenced using a relocation entry.
496 EmitGlobalDataRelocation(GV, Size, GblS);
501 raw_string_ostream ErrorMsg(msg);
502 ErrorMsg << "Constant unimp for type: " << *CV->getType();
503 llvm_report_error(ErrorMsg.str());
506 // ResolveConstantExpr - Resolve the constant expression until it stop
507 // yielding other constant expressions.
508 CstExprResTy ELFWriter::ResolveConstantExpr(const Constant *CV) {
509 const TargetData *TD = TM.getTargetData();
511 // There ins't constant expression inside others anymore
512 if (!isa<ConstantExpr>(CV))
513 return std::make_pair(CV, 0);
515 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
516 switch (CE->getOpcode()) {
517 case Instruction::BitCast:
518 return ResolveConstantExpr(CE->getOperand(0));
520 case Instruction::GetElementPtr: {
521 const Constant *ptrVal = CE->getOperand(0);
522 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
523 int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
525 return std::make_pair(ptrVal, Offset);
527 case Instruction::IntToPtr: {
528 Constant *Op = CE->getOperand(0);
529 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
531 return ResolveConstantExpr(Op);
533 case Instruction::PtrToInt: {
534 Constant *Op = CE->getOperand(0);
535 const Type *Ty = CE->getType();
537 // We can emit the pointer value into this slot if the slot is an
538 // integer slot greater or equal to the size of the pointer.
539 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
540 return ResolveConstantExpr(Op);
542 llvm_unreachable("Integer size less then pointer size");
544 case Instruction::Add:
545 case Instruction::Sub: {
546 // Only handle cases where there's a constant expression with GlobalValue
547 // as first operand and ConstantInt as second, which are the cases we can
548 // solve direclty using a relocation entry. GlobalValue=Op0, CstInt=Op1
549 // 1) Instruction::Add => (global) + CstInt
550 // 2) Instruction::Sub => (global) + -CstInt
551 const Constant *Op0 = CE->getOperand(0);
552 const Constant *Op1 = CE->getOperand(1);
553 assert(isa<ConstantInt>(Op1) && "Op1 must be a ConstantInt");
555 CstExprResTy Res = ResolveConstantExpr(Op0);
556 assert(isa<GlobalValue>(Res.first) && "Op0 must be a GlobalValue");
558 const APInt &RHS = cast<ConstantInt>(Op1)->getValue();
559 switch (CE->getOpcode()) {
560 case Instruction::Add:
561 return std::make_pair(Res.first, RHS.getSExtValue());
562 case Instruction::Sub:
563 return std::make_pair(Res.first, (-RHS).getSExtValue());
568 std::string msg(CE->getOpcodeName());
569 raw_string_ostream ErrorMsg(msg);
570 ErrorMsg << ": Unsupported ConstantExpr type";
571 llvm_report_error(ErrorMsg.str());
573 return std::make_pair(CV, 0); // silence warning
576 void ELFWriter::EmitGlobalDataRelocation(const GlobalValue *GV, unsigned Size,
577 ELFSection &GblS, int64_t Offset) {
578 // Create the relocation entry for the global value
579 MachineRelocation MR =
580 MachineRelocation::getGV(GblS.getCurrentPCOffset(),
581 TEW->getAbsoluteLabelMachineRelTy(),
582 const_cast<GlobalValue*>(GV),
585 // Fill the data entry with zeros
586 GblS.emitZeros(Size);
588 // Add the relocation entry for the current data section
589 GblS.addRelocation(MR);
592 void ELFWriter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
594 const TargetData *TD = TM.getTargetData();
595 unsigned BitWidth = CI->getBitWidth();
596 assert(isPowerOf2_32(BitWidth) &&
597 "Non-power-of-2-sized integers not handled!");
599 const uint64_t *RawData = CI->getValue().getRawData();
601 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
602 Val = (TD->isBigEndian()) ? RawData[e - i - 1] : RawData[i];
607 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
608 /// special global used by LLVM. If so, emit it and return true, otherwise
609 /// do nothing and return false.
610 bool ELFWriter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
611 if (GV->getName() == "llvm.used")
612 llvm_unreachable("not implemented yet");
614 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
615 if (GV->getSection() == "llvm.metadata" ||
616 GV->hasAvailableExternallyLinkage())
619 if (!GV->hasAppendingLinkage()) return false;
621 assert(GV->hasInitializer() && "Not a special LLVM global!");
623 const TargetData *TD = TM.getTargetData();
624 unsigned Align = TD->getPointerPrefAlignment();
625 if (GV->getName() == "llvm.global_ctors") {
626 ELFSection &Ctor = getCtorSection();
627 Ctor.emitAlignment(Align);
628 EmitXXStructorList(GV->getInitializer(), Ctor);
632 if (GV->getName() == "llvm.global_dtors") {
633 ELFSection &Dtor = getDtorSection();
634 Dtor.emitAlignment(Align);
635 EmitXXStructorList(GV->getInitializer(), Dtor);
642 /// EmitXXStructorList - Emit the ctor or dtor list. This just emits out the
643 /// function pointers, ignoring the init priority.
644 void ELFWriter::EmitXXStructorList(Constant *List, ELFSection &Xtor) {
645 // Should be an array of '{ int, void ()* }' structs. The first value is the
646 // init priority, which we ignore.
647 if (!isa<ConstantArray>(List)) return;
648 ConstantArray *InitList = cast<ConstantArray>(List);
649 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
650 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
651 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
653 if (CS->getOperand(1)->isNullValue())
654 return; // Found a null terminator, exit printing.
655 // Emit the function pointer.
656 EmitGlobalConstant(CS->getOperand(1), Xtor);
660 bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
661 // Nothing to do here, this is all done through the ElfCE object above.
665 /// doFinalization - Now that the module has been completely processed, emit
666 /// the ELF file to 'O'.
667 bool ELFWriter::doFinalization(Module &M) {
668 // Emit .data section placeholder
671 // Emit .bss section placeholder
674 // Build and emit data, bss and "common" sections.
675 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
679 // Emit all pending globals
680 for (PendingGblsIter I = PendingGlobals.begin(), E = PendingGlobals.end();
684 // Emit all pending externals
685 for (PendingExtsIter I = PendingExternals.begin(), E = PendingExternals.end();
687 SymbolList.push_back(ELFSym::getExtSym(*I));
689 // Emit non-executable stack note
690 if (TAI->getNonexecutableStackDirective())
691 getNonExecStackSection();
693 // Emit a symbol for each section created until now, skip null section
694 for (unsigned i = 1, e = SectionList.size(); i < e; ++i) {
695 ELFSection &ES = *SectionList[i];
696 ELFSym *SectionSym = ELFSym::getSectionSym();
697 SectionSym->SectionIdx = ES.SectionIdx;
698 SymbolList.push_back(SectionSym);
699 ES.Sym = SymbolList.back();
703 EmitStringTable(M.getModuleIdentifier());
705 // Emit the symbol table now, if non-empty.
708 // Emit the relocation sections.
711 // Emit the sections string table.
712 EmitSectionTableStringTable();
714 // Dump the sections and section table to the .o file.
715 OutputSectionsAndSectionTable();
717 // We are done with the abstract symbols.
722 // Release the name mangler object.
723 delete Mang; Mang = 0;
727 // RelocateField - Patch relocatable field with 'Offset' in 'BO'
728 // using a 'Value' of known 'Size'
729 void ELFWriter::RelocateField(BinaryObject &BO, uint32_t Offset,
730 int64_t Value, unsigned Size) {
732 BO.fixWord32(Value, Offset);
734 BO.fixWord64(Value, Offset);
736 llvm_unreachable("don't know howto patch relocatable field");
739 /// EmitRelocations - Emit relocations
740 void ELFWriter::EmitRelocations() {
742 // True if the target uses the relocation entry to hold the addend,
743 // otherwise the addend is written directly to the relocatable field.
744 bool HasRelA = TEW->hasRelocationAddend();
746 // Create Relocation sections for each section which needs it.
747 for (unsigned i=0, e=SectionList.size(); i != e; ++i) {
748 ELFSection &S = *SectionList[i];
750 // This section does not have relocations
751 if (!S.hasRelocations()) continue;
752 ELFSection &RelSec = getRelocSection(S);
754 // 'Link' - Section hdr idx of the associated symbol table
755 // 'Info' - Section hdr idx of the section to which the relocation applies
756 ELFSection &SymTab = getSymbolTableSection();
757 RelSec.Link = SymTab.SectionIdx;
758 RelSec.Info = S.SectionIdx;
759 RelSec.EntSize = TEW->getRelocationEntrySize();
761 // Get the relocations from Section
762 std::vector<MachineRelocation> Relos = S.getRelocations();
763 for (std::vector<MachineRelocation>::iterator MRI = Relos.begin(),
764 MRE = Relos.end(); MRI != MRE; ++MRI) {
765 MachineRelocation &MR = *MRI;
767 // Relocatable field offset from the section start
768 unsigned RelOffset = MR.getMachineCodeOffset();
770 // Symbol index in the symbol table
773 // Target specific relocation field type and size
774 unsigned RelType = TEW->getRelocationType(MR.getRelocationType());
775 unsigned RelTySize = TEW->getRelocationTySize(RelType);
778 // There are several machine relocations types, and each one of
779 // them needs a different approach to retrieve the symbol table index.
780 if (MR.isGlobalValue()) {
781 const GlobalValue *G = MR.getGlobalValue();
782 int64_t GlobalOffset = MR.getConstantVal();
783 SymIdx = GblSymLookup[G];
784 if (G->hasPrivateLinkage()) {
785 // If the target uses a section offset in the relocation:
786 // SymIdx + Addend = section sym for global + section offset
787 unsigned SectionIdx = PrivateSyms[SymIdx]->SectionIdx;
788 Addend = PrivateSyms[SymIdx]->Value + GlobalOffset;
789 SymIdx = SectionList[SectionIdx]->getSymbolTableIndex();
791 Addend = TEW->getDefaultAddendForRelTy(RelType, GlobalOffset);
793 } else if (MR.isExternalSymbol()) {
794 const char *ExtSym = MR.getExternalSymbol();
795 SymIdx = ExtSymLookup[ExtSym];
796 Addend = TEW->getDefaultAddendForRelTy(RelType);
798 // Get the symbol index for the section symbol
799 unsigned SectionIdx = MR.getConstantVal();
800 SymIdx = SectionList[SectionIdx]->getSymbolTableIndex();
802 // The symbol offset inside the section
803 int64_t SymOffset = (int64_t)MR.getResultPointer();
805 // For pc relative relocations where symbols are defined in the same
806 // section they are referenced, ignore the relocation entry and patch
807 // the relocatable field with the symbol offset directly.
808 if (S.SectionIdx == SectionIdx && TEW->isPCRelativeRel(RelType)) {
809 int64_t Value = TEW->computeRelocation(SymOffset, RelOffset, RelType);
810 RelocateField(S, RelOffset, Value, RelTySize);
814 Addend = TEW->getDefaultAddendForRelTy(RelType, SymOffset);
817 // The target without addend on the relocation symbol must be
818 // patched in the relocation place itself to contain the addend
819 // otherwise write zeros to make sure there is no garbage there
820 RelocateField(S, RelOffset, HasRelA ? 0 : Addend, RelTySize);
822 // Get the relocation entry and emit to the relocation section
823 ELFRelocation Rel(RelOffset, SymIdx, RelType, HasRelA, Addend);
824 EmitRelocation(RelSec, Rel, HasRelA);
829 /// EmitRelocation - Write relocation 'Rel' to the relocation section 'Rel'
830 void ELFWriter::EmitRelocation(BinaryObject &RelSec, ELFRelocation &Rel,
832 RelSec.emitWord(Rel.getOffset());
833 RelSec.emitWord(Rel.getInfo(is64Bit));
835 RelSec.emitWord(Rel.getAddend());
838 /// EmitSymbol - Write symbol 'Sym' to the symbol table 'SymbolTable'
839 void ELFWriter::EmitSymbol(BinaryObject &SymbolTable, ELFSym &Sym) {
841 SymbolTable.emitWord32(Sym.NameIdx);
842 SymbolTable.emitByte(Sym.Info);
843 SymbolTable.emitByte(Sym.Other);
844 SymbolTable.emitWord16(Sym.SectionIdx);
845 SymbolTable.emitWord64(Sym.Value);
846 SymbolTable.emitWord64(Sym.Size);
848 SymbolTable.emitWord32(Sym.NameIdx);
849 SymbolTable.emitWord32(Sym.Value);
850 SymbolTable.emitWord32(Sym.Size);
851 SymbolTable.emitByte(Sym.Info);
852 SymbolTable.emitByte(Sym.Other);
853 SymbolTable.emitWord16(Sym.SectionIdx);
857 /// EmitSectionHeader - Write section 'Section' header in 'SHdrTab'
858 /// Section Header Table
859 void ELFWriter::EmitSectionHeader(BinaryObject &SHdrTab,
860 const ELFSection &SHdr) {
861 SHdrTab.emitWord32(SHdr.NameIdx);
862 SHdrTab.emitWord32(SHdr.Type);
864 SHdrTab.emitWord64(SHdr.Flags);
865 SHdrTab.emitWord(SHdr.Addr);
866 SHdrTab.emitWord(SHdr.Offset);
867 SHdrTab.emitWord64(SHdr.Size);
868 SHdrTab.emitWord32(SHdr.Link);
869 SHdrTab.emitWord32(SHdr.Info);
870 SHdrTab.emitWord64(SHdr.Align);
871 SHdrTab.emitWord64(SHdr.EntSize);
873 SHdrTab.emitWord32(SHdr.Flags);
874 SHdrTab.emitWord(SHdr.Addr);
875 SHdrTab.emitWord(SHdr.Offset);
876 SHdrTab.emitWord32(SHdr.Size);
877 SHdrTab.emitWord32(SHdr.Link);
878 SHdrTab.emitWord32(SHdr.Info);
879 SHdrTab.emitWord32(SHdr.Align);
880 SHdrTab.emitWord32(SHdr.EntSize);
884 /// EmitStringTable - If the current symbol table is non-empty, emit the string
886 void ELFWriter::EmitStringTable(const std::string &ModuleName) {
887 if (!SymbolList.size()) return; // Empty symbol table.
888 ELFSection &StrTab = getStringTableSection();
890 // Set the zero'th symbol to a null byte, as required.
893 // Walk on the symbol list and write symbol names into the string table.
895 for (ELFSymIter I=SymbolList.begin(), E=SymbolList.end(); I != E; ++I) {
899 if (Sym.isGlobalValue())
900 Name.append(Mang->getMangledName(Sym.getGlobalValue()));
901 else if (Sym.isExternalSym())
902 Name.append(Sym.getExternalSymbol());
903 else if (Sym.isFileType())
904 Name.append(ModuleName);
910 StrTab.emitString(Name);
912 // Keep track of the number of bytes emitted to this section.
913 Index += Name.size()+1;
916 assert(Index == StrTab.size());
920 // SortSymbols - On the symbol table local symbols must come before
921 // all other symbols with non-local bindings. The return value is
922 // the position of the first non local symbol.
923 unsigned ELFWriter::SortSymbols() {
924 unsigned FirstNonLocalSymbol;
925 std::vector<ELFSym*> LocalSyms, OtherSyms;
927 for (ELFSymIter I=SymbolList.begin(), E=SymbolList.end(); I != E; ++I) {
928 if ((*I)->isLocalBind())
929 LocalSyms.push_back(*I);
931 OtherSyms.push_back(*I);
934 FirstNonLocalSymbol = LocalSyms.size();
936 for (unsigned i = 0; i < FirstNonLocalSymbol; ++i)
937 SymbolList.push_back(LocalSyms[i]);
939 for (ELFSymIter I=OtherSyms.begin(), E=OtherSyms.end(); I != E; ++I)
940 SymbolList.push_back(*I);
945 return FirstNonLocalSymbol;
948 /// EmitSymbolTable - Emit the symbol table itself.
949 void ELFWriter::EmitSymbolTable() {
950 if (!SymbolList.size()) return; // Empty symbol table.
952 // Now that we have emitted the string table and know the offset into the
953 // string table of each symbol, emit the symbol table itself.
954 ELFSection &SymTab = getSymbolTableSection();
955 SymTab.Align = TEW->getPrefELFAlignment();
957 // Section Index of .strtab.
958 SymTab.Link = getStringTableSection().SectionIdx;
960 // Size of each symtab entry.
961 SymTab.EntSize = TEW->getSymTabEntrySize();
963 // Reorder the symbol table with local symbols first!
964 unsigned FirstNonLocalSymbol = SortSymbols();
966 // Emit all the symbols to the symbol table.
967 for (unsigned i = 0, e = SymbolList.size(); i < e; ++i) {
968 ELFSym &Sym = *SymbolList[i];
970 // Emit symbol to the symbol table
971 EmitSymbol(SymTab, Sym);
973 // Record the symbol table index for each symbol
974 if (Sym.isGlobalValue())
975 GblSymLookup[Sym.getGlobalValue()] = i;
976 else if (Sym.isExternalSym())
977 ExtSymLookup[Sym.getExternalSymbol()] = i;
979 // Keep track on the symbol index into the symbol table
983 // One greater than the symbol table index of the last local symbol
984 SymTab.Info = FirstNonLocalSymbol;
985 SymTab.Size = SymTab.size();
988 /// EmitSectionTableStringTable - This method adds and emits a section for the
989 /// ELF Section Table string table: the string table that holds all of the
991 void ELFWriter::EmitSectionTableStringTable() {
992 // First step: add the section for the string table to the list of sections:
993 ELFSection &SHStrTab = getSectionHeaderStringTableSection();
995 // Now that we know which section number is the .shstrtab section, update the
996 // e_shstrndx entry in the ELF header.
997 ElfHdr.fixWord16(SHStrTab.SectionIdx, ELFHdr_e_shstrndx_Offset);
999 // Set the NameIdx of each section in the string table and emit the bytes for
1000 // the string table.
1003 for (ELFSectionIter I=SectionList.begin(), E=SectionList.end(); I != E; ++I) {
1004 ELFSection &S = *(*I);
1005 // Set the index into the table. Note if we have lots of entries with
1006 // common suffixes, we could memoize them here if we cared.
1008 SHStrTab.emitString(S.getName());
1010 // Keep track of the number of bytes emitted to this section.
1011 Index += S.getName().size()+1;
1014 // Set the size of .shstrtab now that we know what it is.
1015 assert(Index == SHStrTab.size());
1016 SHStrTab.Size = Index;
1019 /// OutputSectionsAndSectionTable - Now that we have constructed the file header
1020 /// and all of the sections, emit these to the ostream destination and emit the
1022 void ELFWriter::OutputSectionsAndSectionTable() {
1023 // Pass #1: Compute the file offset for each section.
1024 size_t FileOff = ElfHdr.size(); // File header first.
1026 // Adjust alignment of all section if needed, skip the null section.
1027 for (unsigned i=1, e=SectionList.size(); i < e; ++i) {
1028 ELFSection &ES = *SectionList[i];
1030 ES.Offset = FileOff;
1034 // Update Section size
1036 ES.Size = ES.size();
1038 // Align FileOff to whatever the alignment restrictions of the section are.
1040 FileOff = (FileOff+ES.Align-1) & ~(ES.Align-1);
1042 ES.Offset = FileOff;
1046 // Align Section Header.
1047 unsigned TableAlign = TEW->getPrefELFAlignment();
1048 FileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
1050 // Now that we know where all of the sections will be emitted, set the e_shnum
1051 // entry in the ELF header.
1052 ElfHdr.fixWord16(NumSections, ELFHdr_e_shnum_Offset);
1054 // Now that we know the offset in the file of the section table, update the
1055 // e_shoff address in the ELF header.
1056 ElfHdr.fixWord(FileOff, ELFHdr_e_shoff_Offset);
1058 // Now that we know all of the data in the file header, emit it and all of the
1060 O.write((char *)&ElfHdr.getData()[0], ElfHdr.size());
1061 FileOff = ElfHdr.size();
1063 // Section Header Table blob
1064 BinaryObject SHdrTable(isLittleEndian, is64Bit);
1066 // Emit all of sections to the file and build the section header table.
1067 for (ELFSectionIter I=SectionList.begin(), E=SectionList.end(); I != E; ++I) {
1068 ELFSection &S = *(*I);
1069 DEBUG(errs() << "SectionIdx: " << S.SectionIdx << ", Name: " << S.getName()
1070 << ", Size: " << S.Size << ", Offset: " << S.Offset
1071 << ", SectionData Size: " << S.size() << "\n");
1073 // Align FileOff to whatever the alignment restrictions of the section are.
1076 for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
1077 FileOff != NewFileOff; ++FileOff)
1080 O.write((char *)&S.getData()[0], S.Size);
1084 EmitSectionHeader(SHdrTable, S);
1087 // Align output for the section table.
1088 for (size_t NewFileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
1089 FileOff != NewFileOff; ++FileOff)
1092 // Emit the section table itself.
1093 O.write((char *)&SHdrTable.getData()[0], SHdrTable.size());