#define DEBUG_TYPE "elfwriter"
#include "ELF.h"
#include "ELFWriter.h"
#include "ELFCodeEmitter.h"
#include "llvm/Constants.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/DerivedTypes.h"
#include "llvm/CodeGen/BinaryObject.h"
#include "llvm/CodeGen/MachineCodeEmitter.h"
#include "llvm/CodeGen/ObjectCodeEmitter.h"
#include "llvm/CodeGen/MachineCodeEmitter.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCSectionELF.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/Target/Mangler.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetELFWriterInfo.h"
#include "llvm/Target/TargetLowering.h"
#include "llvm/Target/TargetLoweringObjectFile.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/SmallString.h"
using namespace llvm;
char ELFWriter::ID = 0;
ELFWriter::ELFWriter(raw_ostream &o, TargetMachine &tm)
: MachineFunctionPass(&ID), O(o), TM(tm),
OutContext(*new MCContext(*TM.getMCAsmInfo())),
TLOF(TM.getTargetLowering()->getObjFileLowering()),
is64Bit(TM.getTargetData()->getPointerSizeInBits() == 64),
isLittleEndian(TM.getTargetData()->isLittleEndian()),
ElfHdr(isLittleEndian, is64Bit) {
MAI = TM.getMCAsmInfo();
TEW = TM.getELFWriterInfo();
ElfCE = new ELFCodeEmitter(*this);
NumSections = 0;
}
ELFWriter::~ELFWriter() {
delete ElfCE;
delete &OutContext;
while(!SymbolList.empty()) {
delete SymbolList.back();
SymbolList.pop_back();
}
while(!PrivateSyms.empty()) {
delete PrivateSyms.back();
PrivateSyms.pop_back();
}
while(!SectionList.empty()) {
delete SectionList.back();
SectionList.pop_back();
}
delete Mang; Mang = 0;
}
bool ELFWriter::doInitialization(Module &M) {
const_cast<TargetLoweringObjectFile&>(TLOF).Initialize(OutContext, TM);
Mang = new Mangler(OutContext, *TM.getTargetData());
ElfHdr.emitByte(0x7f); ElfHdr.emitByte('E'); ElfHdr.emitByte('L'); ElfHdr.emitByte('F');
ElfHdr.emitByte(TEW->getEIClass()); ElfHdr.emitByte(TEW->getEIData()); ElfHdr.emitByte(EV_CURRENT); ElfHdr.emitAlignment(16);
ElfHdr.emitWord16(ET_REL); ElfHdr.emitWord16(TEW->getEMachine()); ElfHdr.emitWord32(EV_CURRENT); ElfHdr.emitWord(0); ElfHdr.emitWord(0); ELFHdr_e_shoff_Offset = ElfHdr.size();
ElfHdr.emitWord(0); ElfHdr.emitWord32(TEW->getEFlags()); ElfHdr.emitWord16(TEW->getHdrSize()); ElfHdr.emitWord16(0); ElfHdr.emitWord16(0);
ElfHdr.emitWord16(TEW->getSHdrSize());
ELFHdr_e_shnum_Offset = ElfHdr.size();
ElfHdr.emitWord16(0);
ELFHdr_e_shstrndx_Offset = ElfHdr.size();
ElfHdr.emitWord16(0);
getNullSection();
SymbolList.push_back(new ELFSym());
SymbolList.push_back(ELFSym::getFileSym());
return false;
}
void ELFWriter::AddPendingGlobalSymbol(const GlobalValue *GV,
bool AddToLookup ) {
PendingGlobals.insert(GV);
if (AddToLookup)
GblSymLookup[GV] = 0;
}
void ELFWriter::AddPendingExternalSymbol(const char *External) {
PendingExternals.insert(External);
ExtSymLookup[External] = 0;
}
ELFSection &ELFWriter::getDataSection() {
const MCSectionELF *Data = (const MCSectionELF *)TLOF.getDataSection();
return getSection(Data->getSectionName(), Data->getType(),
Data->getFlags(), 4);
}
ELFSection &ELFWriter::getBSSSection() {
const MCSectionELF *BSS = (const MCSectionELF *)TLOF.getBSSSection();
return getSection(BSS->getSectionName(), BSS->getType(), BSS->getFlags(), 4);
}
ELFSection &ELFWriter::getCtorSection() {
const MCSectionELF *Ctor = (const MCSectionELF *)TLOF.getStaticCtorSection();
return getSection(Ctor->getSectionName(), Ctor->getType(), Ctor->getFlags());
}
ELFSection &ELFWriter::getDtorSection() {
const MCSectionELF *Dtor = (const MCSectionELF *)TLOF.getStaticDtorSection();
return getSection(Dtor->getSectionName(), Dtor->getType(), Dtor->getFlags());
}
ELFSection &ELFWriter::getTextSection(Function *F) {
const MCSectionELF *Text =
(const MCSectionELF *)TLOF.SectionForGlobal(F, Mang, TM);
return getSection(Text->getSectionName(), Text->getType(), Text->getFlags());
}
ELFSection &ELFWriter::getJumpTableSection() {
const MCSectionELF *JT =
(const MCSectionELF *)TLOF.getSectionForConstant(SectionKind::getReadOnly());
return getSection(JT->getSectionName(), JT->getType(), JT->getFlags(),
TM.getTargetData()->getPointerABIAlignment());
}
ELFSection &ELFWriter::getConstantPoolSection(MachineConstantPoolEntry &CPE) {
SectionKind Kind;
switch (CPE.getRelocationInfo()) {
default: llvm_unreachable("Unknown section kind");
case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
case 1:
Kind = SectionKind::getReadOnlyWithRelLocal();
break;
case 0:
switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
case 4: Kind = SectionKind::getMergeableConst4(); break;
case 8: Kind = SectionKind::getMergeableConst8(); break;
case 16: Kind = SectionKind::getMergeableConst16(); break;
default: Kind = SectionKind::getMergeableConst(); break;
}
}
const MCSectionELF *CPSect =
(const MCSectionELF *)TLOF.getSectionForConstant(Kind);
return getSection(CPSect->getSectionName(), CPSect->getType(),
CPSect->getFlags(), CPE.getAlignment());
}
ELFSection &ELFWriter::getRelocSection(ELFSection &S) {
unsigned SectionType = TEW->hasRelocationAddend() ?
ELFSection::SHT_RELA : ELFSection::SHT_REL;
std::string SectionName(".rel");
if (TEW->hasRelocationAddend())
SectionName.append("a");
SectionName.append(S.getName());
return getSection(SectionName, SectionType, 0, TEW->getPrefELFAlignment());
}
unsigned ELFWriter::getGlobalELFVisibility(const GlobalValue *GV) {
switch (GV->getVisibility()) {
default:
llvm_unreachable("unknown visibility type");
case GlobalValue::DefaultVisibility:
return ELFSym::STV_DEFAULT;
case GlobalValue::HiddenVisibility:
return ELFSym::STV_HIDDEN;
case GlobalValue::ProtectedVisibility:
return ELFSym::STV_PROTECTED;
}
return 0;
}
unsigned ELFWriter::getGlobalELFBinding(const GlobalValue *GV) {
if (GV->hasInternalLinkage())
return ELFSym::STB_LOCAL;
if (GV->isWeakForLinker() && !GV->hasCommonLinkage())
return ELFSym::STB_WEAK;
return ELFSym::STB_GLOBAL;
}
unsigned ELFWriter::getGlobalELFType(const GlobalValue *GV) {
if (GV->isDeclaration())
return ELFSym::STT_NOTYPE;
if (isa<Function>(GV))
return ELFSym::STT_FUNC;
return ELFSym::STT_OBJECT;
}
static bool IsELFUndefSym(const GlobalValue *GV) {
return GV->isDeclaration() || (isa<Function>(GV));
}
void ELFWriter::AddToSymbolList(ELFSym *GblSym) {
assert(GblSym->isGlobalValue() && "Symbol must be a global value");
const GlobalValue *GV = GblSym->getGlobalValue();
if (GV->hasPrivateLinkage()) {
PrivateSyms.push_back(GblSym);
GblSymLookup[GV] = PrivateSyms.size()-1;
} else {
SymbolList.push_back(GblSym);
GblSymLookup[GV] = 0;
}
}
void ELFWriter::EmitGlobal(const GlobalValue *GV) {
if (GblSymLookup.find(GV) != GblSymLookup.end())
return;
unsigned SymBind = getGlobalELFBinding(GV);
unsigned SymType = getGlobalELFType(GV);
bool IsUndefSym = IsELFUndefSym(GV);
ELFSym *GblSym = IsUndefSym ? ELFSym::getUndefGV(GV, SymBind)
: ELFSym::getGV(GV, SymBind, SymType, getGlobalELFVisibility(GV));
if (!IsUndefSym) {
assert(isa<GlobalVariable>(GV) && "GV not a global variable!");
const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
if (EmitSpecialLLVMGlobal(GVar))
return;
const MCSectionELF *S =
(const MCSectionELF *)TLOF.SectionForGlobal(GV, Mang, TM);
ELFSection &ES =
getSection(S->getSectionName(), S->getType(), S->getFlags());
SectionKind Kind = S->getKind();
const TargetData *TD = TM.getTargetData();
unsigned Align = TD->getPreferredAlignment(GVar);
unsigned Size = TD->getTypeAllocSize(GVar->getInitializer()->getType());
GblSym->Size = Size;
if (S->HasCommonSymbols()) { GblSym->SectionIdx = ELFSection::SHN_COMMON;
ES.Align = 1;
GblSym->Value = Align;
} else if (Kind.isBSS() || Kind.isThreadBSS()) { GblSym->SectionIdx = ES.SectionIdx;
if (Align) ES.Size = (ES.Size + Align-1) & ~(Align-1);
ES.Align = std::max(ES.Align, Align);
GblSym->Value = ES.Size;
ES.Size += Size;
} else { GblSym->SectionIdx = ES.SectionIdx;
ES.Align = std::max(ES.Align, Align);
ES.emitAlignment(Align);
GblSym->Value = ES.size();
EmitGlobalConstant(GVar->getInitializer(), ES);
}
}
AddToSymbolList(GblSym);
}
void ELFWriter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
ELFSection &GblS) {
const TargetData *TD = TM.getTargetData();
unsigned Size = TD->getTypeAllocSize(CVS->getType());
const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
uint64_t sizeSoFar = 0;
for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
const Constant* field = CVS->getOperand(i);
uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
- cvsLayout->getElementOffset(i)) - fieldSize;
sizeSoFar += fieldSize + padSize;
EmitGlobalConstant(field, GblS);
GblS.emitZeros(padSize);
}
assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
"Layout of constant struct may be incorrect!");
}
void ELFWriter::EmitGlobalConstant(const Constant *CV, ELFSection &GblS) {
const TargetData *TD = TM.getTargetData();
unsigned Size = TD->getTypeAllocSize(CV->getType());
if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
EmitGlobalConstant(CVA->getOperand(i), GblS);
return;
} else if (isa<ConstantAggregateZero>(CV)) {
GblS.emitZeros(Size);
return;
} else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
EmitGlobalConstantStruct(CVS, GblS);
return;
} else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
APInt Val = CFP->getValueAPF().bitcastToAPInt();
if (CFP->getType()->isDoubleTy())
GblS.emitWord64(Val.getZExtValue());
else if (CFP->getType()->isFloatTy())
GblS.emitWord32(Val.getZExtValue());
else if (CFP->getType()->isX86_FP80Ty()) {
unsigned PadSize = TD->getTypeAllocSize(CFP->getType())-
TD->getTypeStoreSize(CFP->getType());
GblS.emitWordFP80(Val.getRawData(), PadSize);
} else if (CFP->getType()->isPPC_FP128Ty())
llvm_unreachable("PPC_FP128Ty global emission not implemented");
return;
} else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
if (Size == 1)
GblS.emitByte(CI->getZExtValue());
else if (Size == 2)
GblS.emitWord16(CI->getZExtValue());
else if (Size == 4)
GblS.emitWord32(CI->getZExtValue());
else
EmitGlobalConstantLargeInt(CI, GblS);
return;
} else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
const VectorType *PTy = CP->getType();
for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
EmitGlobalConstant(CP->getOperand(I), GblS);
return;
} else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
CstExprResTy Res = ResolveConstantExpr(CE);
const Constant *Op = Res.first;
if (isa<GlobalValue>(Op))
EmitGlobalDataRelocation(cast<const GlobalValue>(Op),
TD->getTypeAllocSize(Op->getType()),
GblS, Res.second);
else
EmitGlobalConstant(Op, GblS);
return;
} else if (CV->getType()->getTypeID() == Type::PointerTyID) {
if (isa<ConstantPointerNull>(CV))
GblS.emitZeros(Size);
else
EmitGlobalDataRelocation(cast<const GlobalValue>(CV),
Size, GblS);
return;
} else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
EmitGlobalDataRelocation(GV, Size, GblS);
return;
}
std::string msg;
raw_string_ostream ErrorMsg(msg);
ErrorMsg << "Constant unimp for type: " << *CV->getType();
llvm_report_error(ErrorMsg.str());
}
CstExprResTy ELFWriter::ResolveConstantExpr(const Constant *CV) {
const TargetData *TD = TM.getTargetData();
if (!isa<ConstantExpr>(CV))
return std::make_pair(CV, 0);
const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
switch (CE->getOpcode()) {
case Instruction::BitCast:
return ResolveConstantExpr(CE->getOperand(0));
case Instruction::GetElementPtr: {
const Constant *ptrVal = CE->getOperand(0);
SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
idxVec.size());
return std::make_pair(ptrVal, Offset);
}
case Instruction::IntToPtr: {
Constant *Op = CE->getOperand(0);
Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
false);
return ResolveConstantExpr(Op);
}
case Instruction::PtrToInt: {
Constant *Op = CE->getOperand(0);
const Type *Ty = CE->getType();
if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
return ResolveConstantExpr(Op);
llvm_unreachable("Integer size less then pointer size");
}
case Instruction::Add:
case Instruction::Sub: {
const Constant *Op0 = CE->getOperand(0);
const Constant *Op1 = CE->getOperand(1);
assert(isa<ConstantInt>(Op1) && "Op1 must be a ConstantInt");
CstExprResTy Res = ResolveConstantExpr(Op0);
assert(isa<GlobalValue>(Res.first) && "Op0 must be a GlobalValue");
const APInt &RHS = cast<ConstantInt>(Op1)->getValue();
switch (CE->getOpcode()) {
case Instruction::Add:
return std::make_pair(Res.first, RHS.getSExtValue());
case Instruction::Sub:
return std::make_pair(Res.first, (-RHS).getSExtValue());
}
}
}
std::string msg(CE->getOpcodeName());
raw_string_ostream ErrorMsg(msg);
ErrorMsg << ": Unsupported ConstantExpr type";
llvm_report_error(ErrorMsg.str());
return std::make_pair(CV, 0); }
void ELFWriter::EmitGlobalDataRelocation(const GlobalValue *GV, unsigned Size,
ELFSection &GblS, int64_t Offset) {
MachineRelocation MR =
MachineRelocation::getGV(GblS.getCurrentPCOffset(),
TEW->getAbsoluteLabelMachineRelTy(),
const_cast<GlobalValue*>(GV),
Offset);
GblS.emitZeros(Size);
GblS.addRelocation(MR);
}
void ELFWriter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
ELFSection &S) {
const TargetData *TD = TM.getTargetData();
unsigned BitWidth = CI->getBitWidth();
assert(isPowerOf2_32(BitWidth) &&
"Non-power-of-2-sized integers not handled!");
const uint64_t *RawData = CI->getValue().getRawData();
uint64_t Val = 0;
for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
Val = (TD->isBigEndian()) ? RawData[e - i - 1] : RawData[i];
S.emitWord64(Val);
}
}
bool ELFWriter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
if (GV->getName() == "llvm.used")
llvm_unreachable("not implemented yet");
if (GV->getSection() == "llvm.metadata" ||
GV->hasAvailableExternallyLinkage())
return true;
if (!GV->hasAppendingLinkage()) return false;
assert(GV->hasInitializer() && "Not a special LLVM global!");
const TargetData *TD = TM.getTargetData();
unsigned Align = TD->getPointerPrefAlignment();
if (GV->getName() == "llvm.global_ctors") {
ELFSection &Ctor = getCtorSection();
Ctor.emitAlignment(Align);
EmitXXStructorList(GV->getInitializer(), Ctor);
return true;
}
if (GV->getName() == "llvm.global_dtors") {
ELFSection &Dtor = getDtorSection();
Dtor.emitAlignment(Align);
EmitXXStructorList(GV->getInitializer(), Dtor);
return true;
}
return false;
}
void ELFWriter::EmitXXStructorList(Constant *List, ELFSection &Xtor) {
if (!isa<ConstantArray>(List)) return;
ConstantArray *InitList = cast<ConstantArray>(List);
for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
if (CS->getNumOperands() != 2) return;
if (CS->getOperand(1)->isNullValue())
return; EmitGlobalConstant(CS->getOperand(1), Xtor);
}
}
bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
return false;
}
bool ELFWriter::doFinalization(Module &M) {
getDataSection();
getBSSSection();
for (Module::global_iterator I = M.global_begin(), E = M.global_end();
I != E; ++I)
EmitGlobal(I);
for (PendingGblsIter I = PendingGlobals.begin(), E = PendingGlobals.end();
I != E; ++I)
EmitGlobal(*I);
for (PendingExtsIter I = PendingExternals.begin(), E = PendingExternals.end();
I != E; ++I)
SymbolList.push_back(ELFSym::getExtSym(*I));
for (unsigned i = 1, e = SectionList.size(); i < e; ++i) {
ELFSection &ES = *SectionList[i];
ELFSym *SectionSym = ELFSym::getSectionSym();
SectionSym->SectionIdx = ES.SectionIdx;
SymbolList.push_back(SectionSym);
ES.Sym = SymbolList.back();
}
EmitStringTable(M.getModuleIdentifier());
EmitSymbolTable();
EmitRelocations();
EmitSectionTableStringTable();
OutputSectionsAndSectionTable();
return false;
}
void ELFWriter::RelocateField(BinaryObject &BO, uint32_t Offset,
int64_t Value, unsigned Size) {
if (Size == 32)
BO.fixWord32(Value, Offset);
else if (Size == 64)
BO.fixWord64(Value, Offset);
else
llvm_unreachable("don't know howto patch relocatable field");
}
void ELFWriter::EmitRelocations() {
bool HasRelA = TEW->hasRelocationAddend();
for (unsigned i=0, e=SectionList.size(); i != e; ++i) {
ELFSection &S = *SectionList[i];
if (!S.hasRelocations()) continue;
ELFSection &RelSec = getRelocSection(S);
ELFSection &SymTab = getSymbolTableSection();
RelSec.Link = SymTab.SectionIdx;
RelSec.Info = S.SectionIdx;
RelSec.EntSize = TEW->getRelocationEntrySize();
std::vector<MachineRelocation> Relos = S.getRelocations();
for (std::vector<MachineRelocation>::iterator MRI = Relos.begin(),
MRE = Relos.end(); MRI != MRE; ++MRI) {
MachineRelocation &MR = *MRI;
unsigned RelOffset = MR.getMachineCodeOffset();
unsigned SymIdx = 0;
unsigned RelType = TEW->getRelocationType(MR.getRelocationType());
unsigned RelTySize = TEW->getRelocationTySize(RelType);
int64_t Addend = 0;
if (MR.isGlobalValue()) {
const GlobalValue *G = MR.getGlobalValue();
int64_t GlobalOffset = MR.getConstantVal();
SymIdx = GblSymLookup[G];
if (G->hasPrivateLinkage()) {
unsigned SectionIdx = PrivateSyms[SymIdx]->SectionIdx;
Addend = PrivateSyms[SymIdx]->Value + GlobalOffset;
SymIdx = SectionList[SectionIdx]->getSymbolTableIndex();
} else {
Addend = TEW->getDefaultAddendForRelTy(RelType, GlobalOffset);
}
} else if (MR.isExternalSymbol()) {
const char *ExtSym = MR.getExternalSymbol();
SymIdx = ExtSymLookup[ExtSym];
Addend = TEW->getDefaultAddendForRelTy(RelType);
} else {
unsigned SectionIdx = MR.getConstantVal();
SymIdx = SectionList[SectionIdx]->getSymbolTableIndex();
int64_t SymOffset = (int64_t)MR.getResultPointer();
if (S.SectionIdx == SectionIdx && TEW->isPCRelativeRel(RelType)) {
int64_t Value = TEW->computeRelocation(SymOffset, RelOffset, RelType);
RelocateField(S, RelOffset, Value, RelTySize);
continue;
}
Addend = TEW->getDefaultAddendForRelTy(RelType, SymOffset);
}
RelocateField(S, RelOffset, HasRelA ? 0 : Addend, RelTySize);
ELFRelocation Rel(RelOffset, SymIdx, RelType, HasRelA, Addend);
EmitRelocation(RelSec, Rel, HasRelA);
}
}
}
void ELFWriter::EmitRelocation(BinaryObject &RelSec, ELFRelocation &Rel,
bool HasRelA) {
RelSec.emitWord(Rel.getOffset());
RelSec.emitWord(Rel.getInfo(is64Bit));
if (HasRelA)
RelSec.emitWord(Rel.getAddend());
}
void ELFWriter::EmitSymbol(BinaryObject &SymbolTable, ELFSym &Sym) {
if (is64Bit) {
SymbolTable.emitWord32(Sym.NameIdx);
SymbolTable.emitByte(Sym.Info);
SymbolTable.emitByte(Sym.Other);
SymbolTable.emitWord16(Sym.SectionIdx);
SymbolTable.emitWord64(Sym.Value);
SymbolTable.emitWord64(Sym.Size);
} else {
SymbolTable.emitWord32(Sym.NameIdx);
SymbolTable.emitWord32(Sym.Value);
SymbolTable.emitWord32(Sym.Size);
SymbolTable.emitByte(Sym.Info);
SymbolTable.emitByte(Sym.Other);
SymbolTable.emitWord16(Sym.SectionIdx);
}
}
void ELFWriter::EmitSectionHeader(BinaryObject &SHdrTab,
const ELFSection &SHdr) {
SHdrTab.emitWord32(SHdr.NameIdx);
SHdrTab.emitWord32(SHdr.Type);
if (is64Bit) {
SHdrTab.emitWord64(SHdr.Flags);
SHdrTab.emitWord(SHdr.Addr);
SHdrTab.emitWord(SHdr.Offset);
SHdrTab.emitWord64(SHdr.Size);
SHdrTab.emitWord32(SHdr.Link);
SHdrTab.emitWord32(SHdr.Info);
SHdrTab.emitWord64(SHdr.Align);
SHdrTab.emitWord64(SHdr.EntSize);
} else {
SHdrTab.emitWord32(SHdr.Flags);
SHdrTab.emitWord(SHdr.Addr);
SHdrTab.emitWord(SHdr.Offset);
SHdrTab.emitWord32(SHdr.Size);
SHdrTab.emitWord32(SHdr.Link);
SHdrTab.emitWord32(SHdr.Info);
SHdrTab.emitWord32(SHdr.Align);
SHdrTab.emitWord32(SHdr.EntSize);
}
}
void ELFWriter::EmitStringTable(const std::string &ModuleName) {
if (!SymbolList.size()) return; ELFSection &StrTab = getStringTableSection();
StrTab.emitByte(0);
unsigned Index = 1;
for (ELFSymIter I=SymbolList.begin(), E=SymbolList.end(); I != E; ++I) {
ELFSym &Sym = *(*I);
std::string Name;
if (Sym.isGlobalValue()) {
SmallString<40> NameStr;
Mang->getNameWithPrefix(NameStr, Sym.getGlobalValue(), false);
Name.append(NameStr.begin(), NameStr.end());
} else if (Sym.isExternalSym())
Name.append(Sym.getExternalSymbol());
else if (Sym.isFileType())
Name.append(ModuleName);
if (Name.empty()) {
Sym.NameIdx = 0;
} else {
Sym.NameIdx = Index;
StrTab.emitString(Name);
Index += Name.size()+1;
}
}
assert(Index == StrTab.size());
StrTab.Size = Index;
}
unsigned ELFWriter::SortSymbols() {
unsigned FirstNonLocalSymbol;
std::vector<ELFSym*> LocalSyms, OtherSyms;
for (ELFSymIter I=SymbolList.begin(), E=SymbolList.end(); I != E; ++I) {
if ((*I)->isLocalBind())
LocalSyms.push_back(*I);
else
OtherSyms.push_back(*I);
}
SymbolList.clear();
FirstNonLocalSymbol = LocalSyms.size();
for (unsigned i = 0; i < FirstNonLocalSymbol; ++i)
SymbolList.push_back(LocalSyms[i]);
for (ELFSymIter I=OtherSyms.begin(), E=OtherSyms.end(); I != E; ++I)
SymbolList.push_back(*I);
LocalSyms.clear();
OtherSyms.clear();
return FirstNonLocalSymbol;
}
void ELFWriter::EmitSymbolTable() {
if (!SymbolList.size()) return;
ELFSection &SymTab = getSymbolTableSection();
SymTab.Align = TEW->getPrefELFAlignment();
SymTab.Link = getStringTableSection().SectionIdx;
SymTab.EntSize = TEW->getSymTabEntrySize();
unsigned FirstNonLocalSymbol = SortSymbols();
for (unsigned i = 0, e = SymbolList.size(); i < e; ++i) {
ELFSym &Sym = *SymbolList[i];
EmitSymbol(SymTab, Sym);
if (Sym.isGlobalValue())
GblSymLookup[Sym.getGlobalValue()] = i;
else if (Sym.isExternalSym())
ExtSymLookup[Sym.getExternalSymbol()] = i;
Sym.SymTabIdx = i;
}
SymTab.Info = FirstNonLocalSymbol;
SymTab.Size = SymTab.size();
}
void ELFWriter::EmitSectionTableStringTable() {
ELFSection &SHStrTab = getSectionHeaderStringTableSection();
ElfHdr.fixWord16(SHStrTab.SectionIdx, ELFHdr_e_shstrndx_Offset);
unsigned Index = 0;
for (ELFSectionIter I=SectionList.begin(), E=SectionList.end(); I != E; ++I) {
ELFSection &S = *(*I);
S.NameIdx = Index;
SHStrTab.emitString(S.getName());
Index += S.getName().size()+1;
}
assert(Index == SHStrTab.size());
SHStrTab.Size = Index;
}
void ELFWriter::OutputSectionsAndSectionTable() {
size_t FileOff = ElfHdr.size();
for (unsigned i=1, e=SectionList.size(); i < e; ++i) {
ELFSection &ES = *SectionList[i];
if (!ES.size()) {
ES.Offset = FileOff;
continue;
}
if (!ES.Size)
ES.Size = ES.size();
if (ES.Align)
FileOff = (FileOff+ES.Align-1) & ~(ES.Align-1);
ES.Offset = FileOff;
FileOff += ES.Size;
}
unsigned TableAlign = TEW->getPrefELFAlignment();
FileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
ElfHdr.fixWord16(NumSections, ELFHdr_e_shnum_Offset);
ElfHdr.fixWord(FileOff, ELFHdr_e_shoff_Offset);
O.write((char *)&ElfHdr.getData()[0], ElfHdr.size());
FileOff = ElfHdr.size();
BinaryObject SHdrTable(isLittleEndian, is64Bit);
for (ELFSectionIter I=SectionList.begin(), E=SectionList.end(); I != E; ++I) {
ELFSection &S = *(*I);
DEBUG(dbgs() << "SectionIdx: " << S.SectionIdx << ", Name: " << S.getName()
<< ", Size: " << S.Size << ", Offset: " << S.Offset
<< ", SectionData Size: " << S.size() << "\n");
if (S.size()) {
if (S.Align) {
for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
FileOff != NewFileOff; ++FileOff)
O << (char)0xAB;
}
O.write((char *)&S.getData()[0], S.Size);
FileOff += S.Size;
}
EmitSectionHeader(SHdrTable, S);
}
for (size_t NewFileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
FileOff != NewFileOff; ++FileOff)
O << (char)0xAB;
O.write((char *)&SHdrTable.getData()[0], SHdrTable.size());
}