#include "llvm/ExecutionEngine/RuntimeDyld.h"
#include "RuntimeDyldCOFF.h"
#include "RuntimeDyldELF.h"
#include "RuntimeDyldImpl.h"
#include "RuntimeDyldMachO.h"
#include "llvm/Object/COFF.h"
#include "llvm/Object/ELFObjectFile.h"
#include "llvm/Support/Alignment.h"
#include "llvm/Support/MSVCErrorWorkarounds.h"
#include "llvm/Support/MathExtras.h"
#include <mutex>
#include <future>
using namespace llvm;
using namespace llvm::object;
#define DEBUG_TYPE "dyld"
namespace {
enum RuntimeDyldErrorCode {
GenericRTDyldError = 1
};
class RuntimeDyldErrorCategory : public std::error_category {
public:
const char *name() const noexcept override { return "runtimedyld"; }
std::string message(int Condition) const override {
switch (static_cast<RuntimeDyldErrorCode>(Condition)) {
case GenericRTDyldError: return "Generic RuntimeDyld error";
}
llvm_unreachable("Unrecognized RuntimeDyldErrorCode");
}
};
}
char RuntimeDyldError::ID = 0;
void RuntimeDyldError::log(raw_ostream &OS) const {
OS << ErrMsg << "\n";
}
std::error_code RuntimeDyldError::convertToErrorCode() const {
static RuntimeDyldErrorCategory RTDyldErrorCategory;
return std::error_code(GenericRTDyldError, RTDyldErrorCategory);
}
RuntimeDyldImpl::~RuntimeDyldImpl() = default;
void RuntimeDyld::LoadedObjectInfo::anchor() {}
namespace llvm {
void RuntimeDyldImpl::registerEHFrames() {}
void RuntimeDyldImpl::deregisterEHFrames() {
MemMgr.deregisterEHFrames();
}
#ifndef NDEBUG
static void dumpSectionMemory(const SectionEntry &S, StringRef State) {
dbgs() << "----- Contents of section " << S.getName() << " " << State
<< " -----";
if (S.getAddress() == nullptr) {
dbgs() << "\n <section not emitted>\n";
return;
}
const unsigned ColsPerRow = 16;
uint8_t *DataAddr = S.getAddress();
uint64_t LoadAddr = S.getLoadAddress();
unsigned StartPadding = LoadAddr & (ColsPerRow - 1);
unsigned BytesRemaining = S.getSize();
if (StartPadding) {
dbgs() << "\n" << format("0x%016" PRIx64,
LoadAddr & ~(uint64_t)(ColsPerRow - 1)) << ":";
while (StartPadding--)
dbgs() << " ";
}
while (BytesRemaining > 0) {
if ((LoadAddr & (ColsPerRow - 1)) == 0)
dbgs() << "\n" << format("0x%016" PRIx64, LoadAddr) << ":";
dbgs() << " " << format("%02x", *DataAddr);
++DataAddr;
++LoadAddr;
--BytesRemaining;
}
dbgs() << "\n";
}
#endif
void RuntimeDyldImpl::resolveRelocations() {
std::lock_guard<sys::Mutex> locked(lock);
LLVM_DEBUG({
for (SectionEntry &S : Sections)
dumpSectionMemory(S, "before relocations");
});
if (auto Err = resolveExternalSymbols()) {
HasError = true;
ErrorStr = toString(std::move(Err));
}
resolveLocalRelocations();
LLVM_DEBUG({
for (SectionEntry &S : Sections)
dumpSectionMemory(S, "after relocations");
});
}
void RuntimeDyldImpl::resolveLocalRelocations() {
for (const auto &Rel : Relocations) {
unsigned Idx = Rel.first;
uint64_t Addr = getSectionLoadAddress(Idx);
LLVM_DEBUG(dbgs() << "Resolving relocations Section #" << Idx << "\t"
<< format("%p", (uintptr_t)Addr) << "\n");
resolveRelocationList(Rel.second, Addr);
}
Relocations.clear();
}
void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
uint64_t TargetAddress) {
std::lock_guard<sys::Mutex> locked(lock);
for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
if (Sections[i].getAddress() == LocalAddress) {
reassignSectionAddress(i, TargetAddress);
return;
}
}
llvm_unreachable("Attempting to remap address of unknown section!");
}
static Error getOffset(const SymbolRef &Sym, SectionRef Sec,
uint64_t &Result) {
Expected<uint64_t> AddressOrErr = Sym.getAddress();
if (!AddressOrErr)
return AddressOrErr.takeError();
Result = *AddressOrErr - Sec.getAddress();
return Error::success();
}
Expected<RuntimeDyldImpl::ObjSectionToIDMap>
RuntimeDyldImpl::loadObjectImpl(const object::ObjectFile &Obj) {
std::lock_guard<sys::Mutex> locked(lock);
Arch = (Triple::ArchType)Obj.getArch();
IsTargetLittleEndian = Obj.isLittleEndian();
setMipsABI(Obj);
if (MemMgr.needsToReserveAllocationSpace()) {
uint64_t CodeSize = 0, RODataSize = 0, RWDataSize = 0;
uint32_t CodeAlign = 1, RODataAlign = 1, RWDataAlign = 1;
if (auto Err = computeTotalAllocSize(Obj,
CodeSize, CodeAlign,
RODataSize, RODataAlign,
RWDataSize, RWDataAlign))
return std::move(Err);
MemMgr.reserveAllocationSpace(CodeSize, CodeAlign, RODataSize, RODataAlign,
RWDataSize, RWDataAlign);
}
ObjSectionToIDMap LocalSections;
CommonSymbolList CommonSymbolsToAllocate;
uint64_t CommonSize = 0;
uint32_t CommonAlign = 0;
JITSymbolResolver::LookupSet ResponsibilitySet;
{
JITSymbolResolver::LookupSet Symbols;
for (auto &Sym : Obj.symbols()) {
Expected<uint32_t> FlagsOrErr = Sym.getFlags();
if (!FlagsOrErr)
return FlagsOrErr.takeError();
if ((*FlagsOrErr & SymbolRef::SF_Common) ||
(*FlagsOrErr & SymbolRef::SF_Weak)) {
if (auto NameOrErr = Sym.getName())
Symbols.insert(*NameOrErr);
else
return NameOrErr.takeError();
}
}
if (auto ResultOrErr = Resolver.getResponsibilitySet(Symbols))
ResponsibilitySet = std::move(*ResultOrErr);
else
return ResultOrErr.takeError();
}
LLVM_DEBUG(dbgs() << "Parse symbols:\n");
for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
++I) {
Expected<uint32_t> FlagsOrErr = I->getFlags();
if (!FlagsOrErr)
return FlagsOrErr.takeError();
if (*FlagsOrErr & SymbolRef::SF_Undefined)
continue;
object::SymbolRef::Type SymType;
if (auto SymTypeOrErr = I->getType())
SymType = *SymTypeOrErr;
else
return SymTypeOrErr.takeError();
StringRef Name;
if (auto NameOrErr = I->getName())
Name = *NameOrErr;
else
return NameOrErr.takeError();
auto JITSymFlags = getJITSymbolFlags(*I);
if (!JITSymFlags)
return JITSymFlags.takeError();
if (JITSymFlags->isWeak() || JITSymFlags->isCommon()) {
if (GlobalSymbolTable.count(Name))
continue;
if (!ResponsibilitySet.count(Name))
continue;
if (JITSymFlags->isWeak())
*JITSymFlags &= ~JITSymbolFlags::Weak;
if (JITSymFlags->isCommon()) {
*JITSymFlags &= ~JITSymbolFlags::Common;
uint32_t Align = I->getAlignment();
uint64_t Size = I->getCommonSize();
if (!CommonAlign)
CommonAlign = Align;
CommonSize = alignTo(CommonSize, Align) + Size;
CommonSymbolsToAllocate.push_back(*I);
}
}
if (*FlagsOrErr & SymbolRef::SF_Absolute &&
SymType != object::SymbolRef::ST_File) {
uint64_t Addr = 0;
if (auto AddrOrErr = I->getAddress())
Addr = *AddrOrErr;
else
return AddrOrErr.takeError();
unsigned SectionID = AbsoluteSymbolSection;
LLVM_DEBUG(dbgs() << "\tType: " << SymType << " (absolute) Name: " << Name
<< " SID: " << SectionID
<< " Offset: " << format("%p", (uintptr_t)Addr)
<< " flags: " << *FlagsOrErr << "\n");
if (!Name.empty()) GlobalSymbolTable[Name] =
SymbolTableEntry(SectionID, Addr, *JITSymFlags);
} else if (SymType == object::SymbolRef::ST_Function ||
SymType == object::SymbolRef::ST_Data ||
SymType == object::SymbolRef::ST_Unknown ||
SymType == object::SymbolRef::ST_Other) {
section_iterator SI = Obj.section_end();
if (auto SIOrErr = I->getSection())
SI = *SIOrErr;
else
return SIOrErr.takeError();
if (SI == Obj.section_end())
continue;
uint64_t SectOffset;
if (auto Err = getOffset(*I, *SI, SectOffset))
return std::move(Err);
bool IsCode = SI->isText();
unsigned SectionID;
if (auto SectionIDOrErr =
findOrEmitSection(Obj, *SI, IsCode, LocalSections))
SectionID = *SectionIDOrErr;
else
return SectionIDOrErr.takeError();
LLVM_DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name
<< " SID: " << SectionID
<< " Offset: " << format("%p", (uintptr_t)SectOffset)
<< " flags: " << *FlagsOrErr << "\n");
if (!Name.empty()) GlobalSymbolTable[Name] =
SymbolTableEntry(SectionID, SectOffset, *JITSymFlags);
}
}
if (auto Err = emitCommonSymbols(Obj, CommonSymbolsToAllocate, CommonSize,
CommonAlign))
return std::move(Err);
LLVM_DEBUG(dbgs() << "Parse relocations:\n");
for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
SI != SE; ++SI) {
StubMap Stubs;
Expected<section_iterator> RelSecOrErr = SI->getRelocatedSection();
if (!RelSecOrErr)
return RelSecOrErr.takeError();
section_iterator RelocatedSection = *RelSecOrErr;
if (RelocatedSection == SE)
continue;
relocation_iterator I = SI->relocation_begin();
relocation_iterator E = SI->relocation_end();
if (I == E && !ProcessAllSections)
continue;
bool IsCode = RelocatedSection->isText();
unsigned SectionID = 0;
if (auto SectionIDOrErr = findOrEmitSection(Obj, *RelocatedSection, IsCode,
LocalSections))
SectionID = *SectionIDOrErr;
else
return SectionIDOrErr.takeError();
LLVM_DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
for (; I != E;)
if (auto IOrErr = processRelocationRef(SectionID, I, Obj, LocalSections, Stubs))
I = *IOrErr;
else
return IOrErr.takeError();
if (NotifyStubEmitted) {
StringRef FileName = Obj.getFileName();
StringRef SectionName = Sections[SectionID].getName();
for (auto &KV : Stubs) {
auto &VR = KV.first;
uint64_t StubAddr = KV.second;
if (VR.SymbolName) {
NotifyStubEmitted(FileName, SectionName, VR.SymbolName, SectionID,
StubAddr);
continue;
}
for (auto &GSTMapEntry : GlobalSymbolTable) {
StringRef SymbolName = GSTMapEntry.first();
auto &GSTEntry = GSTMapEntry.second;
if (GSTEntry.getSectionID() == VR.SectionID &&
GSTEntry.getOffset() == VR.Offset) {
NotifyStubEmitted(FileName, SectionName, SymbolName, SectionID,
StubAddr);
break;
}
}
}
}
}
if (ProcessAllSections) {
LLVM_DEBUG(dbgs() << "Process remaining sections:\n");
for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
SI != SE; ++SI) {
if (LocalSections.find(*SI) != LocalSections.end())
continue;
bool IsCode = SI->isText();
if (auto SectionIDOrErr =
findOrEmitSection(Obj, *SI, IsCode, LocalSections))
LLVM_DEBUG(dbgs() << "\tSectionID: " << (*SectionIDOrErr) << "\n");
else
return SectionIDOrErr.takeError();
}
}
if (auto Err = finalizeLoad(Obj, LocalSections))
return std::move(Err);
return LocalSections;
}
static uint64_t
computeAllocationSizeForSections(std::vector<uint64_t> &SectionSizes,
uint64_t Alignment) {
uint64_t TotalSize = 0;
for (uint64_t SectionSize : SectionSizes) {
uint64_t AlignedSize =
(SectionSize + Alignment - 1) / Alignment * Alignment;
TotalSize += AlignedSize;
}
return TotalSize;
}
static bool isRequiredForExecution(const SectionRef Section) {
const ObjectFile *Obj = Section.getObject();
if (isa<object::ELFObjectFileBase>(Obj))
return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC;
if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj)) {
const coff_section *CoffSection = COFFObj->getCOFFSection(Section);
bool HasContent =
(CoffSection->VirtualSize > 0) || (CoffSection->SizeOfRawData > 0);
bool IsDiscardable =
CoffSection->Characteristics &
(COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_LNK_INFO);
return HasContent && !IsDiscardable;
}
assert(isa<MachOObjectFile>(Obj));
return true;
}
static bool isReadOnlyData(const SectionRef Section) {
const ObjectFile *Obj = Section.getObject();
if (isa<object::ELFObjectFileBase>(Obj))
return !(ELFSectionRef(Section).getFlags() &
(ELF::SHF_WRITE | ELF::SHF_EXECINSTR));
if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj))
return ((COFFObj->getCOFFSection(Section)->Characteristics &
(COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
| COFF::IMAGE_SCN_MEM_READ
| COFF::IMAGE_SCN_MEM_WRITE))
==
(COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
| COFF::IMAGE_SCN_MEM_READ));
assert(isa<MachOObjectFile>(Obj));
return false;
}
static bool isZeroInit(const SectionRef Section) {
const ObjectFile *Obj = Section.getObject();
if (isa<object::ELFObjectFileBase>(Obj))
return ELFSectionRef(Section).getType() == ELF::SHT_NOBITS;
if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj))
return COFFObj->getCOFFSection(Section)->Characteristics &
COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
auto *MachO = cast<MachOObjectFile>(Obj);
unsigned SectionType = MachO->getSectionType(Section);
return SectionType == MachO::S_ZEROFILL ||
SectionType == MachO::S_GB_ZEROFILL;
}
static bool isTLS(const SectionRef Section) {
const ObjectFile *Obj = Section.getObject();
if (isa<object::ELFObjectFileBase>(Obj))
return ELFSectionRef(Section).getFlags() & ELF::SHF_TLS;
return false;
}
Error RuntimeDyldImpl::computeTotalAllocSize(const ObjectFile &Obj,
uint64_t &CodeSize,
uint32_t &CodeAlign,
uint64_t &RODataSize,
uint32_t &RODataAlign,
uint64_t &RWDataSize,
uint32_t &RWDataAlign) {
std::vector<uint64_t> CodeSectionSizes;
std::vector<uint64_t> ROSectionSizes;
std::vector<uint64_t> RWSectionSizes;
for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
SI != SE; ++SI) {
const SectionRef &Section = *SI;
bool IsRequired = isRequiredForExecution(Section) || ProcessAllSections;
if (IsRequired) {
uint64_t DataSize = Section.getSize();
uint64_t Alignment64 = Section.getAlignment();
unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
bool IsCode = Section.isText();
bool IsReadOnly = isReadOnlyData(Section);
bool IsTLS = isTLS(Section);
Expected<StringRef> NameOrErr = Section.getName();
if (!NameOrErr)
return NameOrErr.takeError();
StringRef Name = *NameOrErr;
uint64_t StubBufSize = computeSectionStubBufSize(Obj, Section);
uint64_t PaddingSize = 0;
if (Name == ".eh_frame")
PaddingSize += 4;
if (StubBufSize != 0)
PaddingSize += getStubAlignment() - 1;
uint64_t SectionSize = DataSize + PaddingSize + StubBufSize;
if (Name == ".eh_frame")
SectionSize += 4;
if (!SectionSize)
SectionSize = 1;
if (IsCode) {
CodeAlign = std::max(CodeAlign, Alignment);
CodeSectionSizes.push_back(SectionSize);
} else if (IsReadOnly) {
RODataAlign = std::max(RODataAlign, Alignment);
ROSectionSizes.push_back(SectionSize);
} else if (!IsTLS) {
RWDataAlign = std::max(RWDataAlign, Alignment);
RWSectionSizes.push_back(SectionSize);
}
}
}
if (unsigned GotSize = computeGOTSize(Obj)) {
RWSectionSizes.push_back(GotSize);
RWDataAlign = std::max<uint32_t>(RWDataAlign, getGOTEntrySize());
}
uint64_t CommonSize = 0;
uint32_t CommonAlign = 1;
for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
++I) {
Expected<uint32_t> FlagsOrErr = I->getFlags();
if (!FlagsOrErr)
return FlagsOrErr.takeError();
if (*FlagsOrErr & SymbolRef::SF_Common) {
uint64_t Size = I->getCommonSize();
uint32_t Align = I->getAlignment();
if (CommonSize == 0)
CommonAlign = Align;
CommonSize = alignTo(CommonSize, Align) + Size;
}
}
if (CommonSize != 0) {
RWSectionSizes.push_back(CommonSize);
RWDataAlign = std::max(RWDataAlign, CommonAlign);
}
CodeSize = computeAllocationSizeForSections(CodeSectionSizes, CodeAlign);
RODataSize = computeAllocationSizeForSections(ROSectionSizes, RODataAlign);
RWDataSize = computeAllocationSizeForSections(RWSectionSizes, RWDataAlign);
return Error::success();
}
unsigned RuntimeDyldImpl::computeGOTSize(const ObjectFile &Obj) {
size_t GotEntrySize = getGOTEntrySize();
if (!GotEntrySize)
return 0;
size_t GotSize = 0;
for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
SI != SE; ++SI) {
for (const RelocationRef &Reloc : SI->relocations())
if (relocationNeedsGot(Reloc))
GotSize += GotEntrySize;
}
return GotSize;
}
unsigned RuntimeDyldImpl::computeSectionStubBufSize(const ObjectFile &Obj,
const SectionRef &Section) {
if (!MemMgr.allowStubAllocation()) {
return 0;
}
unsigned StubSize = getMaxStubSize();
if (StubSize == 0) {
return 0;
}
unsigned StubBufSize = 0;
for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
SI != SE; ++SI) {
Expected<section_iterator> RelSecOrErr = SI->getRelocatedSection();
if (!RelSecOrErr)
report_fatal_error(Twine(toString(RelSecOrErr.takeError())));
section_iterator RelSecI = *RelSecOrErr;
if (!(RelSecI == Section))
continue;
for (const RelocationRef &Reloc : SI->relocations())
if (relocationNeedsStub(Reloc))
StubBufSize += StubSize;
}
uint64_t DataSize = Section.getSize();
uint64_t Alignment64 = Section.getAlignment();
unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
unsigned StubAlignment = getStubAlignment();
unsigned EndAlignment = (DataSize | Alignment) & -(DataSize | Alignment);
if (StubAlignment > EndAlignment)
StubBufSize += StubAlignment - EndAlignment;
return StubBufSize;
}
uint64_t RuntimeDyldImpl::readBytesUnaligned(uint8_t *Src,
unsigned Size) const {
uint64_t Result = 0;
if (IsTargetLittleEndian) {
Src += Size - 1;
while (Size--)
Result = (Result << 8) | *Src--;
} else
while (Size--)
Result = (Result << 8) | *Src++;
return Result;
}
void RuntimeDyldImpl::writeBytesUnaligned(uint64_t Value, uint8_t *Dst,
unsigned Size) const {
if (IsTargetLittleEndian) {
while (Size--) {
*Dst++ = Value & 0xFF;
Value >>= 8;
}
} else {
Dst += Size - 1;
while (Size--) {
*Dst-- = Value & 0xFF;
Value >>= 8;
}
}
}
Expected<JITSymbolFlags>
RuntimeDyldImpl::getJITSymbolFlags(const SymbolRef &SR) {
return JITSymbolFlags::fromObjectSymbol(SR);
}
Error RuntimeDyldImpl::emitCommonSymbols(const ObjectFile &Obj,
CommonSymbolList &SymbolsToAllocate,
uint64_t CommonSize,
uint32_t CommonAlign) {
if (SymbolsToAllocate.empty())
return Error::success();
unsigned SectionID = Sections.size();
uint8_t *Addr = MemMgr.allocateDataSection(CommonSize, CommonAlign, SectionID,
"<common symbols>", false);
if (!Addr)
report_fatal_error("Unable to allocate memory for common symbols!");
uint64_t Offset = 0;
Sections.push_back(
SectionEntry("<common symbols>", Addr, CommonSize, CommonSize, 0));
memset(Addr, 0, CommonSize);
LLVM_DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
<< " new addr: " << format("%p", Addr)
<< " DataSize: " << CommonSize << "\n");
for (auto &Sym : SymbolsToAllocate) {
uint32_t Alignment = Sym.getAlignment();
uint64_t Size = Sym.getCommonSize();
StringRef Name;
if (auto NameOrErr = Sym.getName())
Name = *NameOrErr;
else
return NameOrErr.takeError();
if (Alignment) {
uint64_t AlignOffset =
offsetToAlignment((uint64_t)Addr, Align(Alignment));
Addr += AlignOffset;
Offset += AlignOffset;
}
auto JITSymFlags = getJITSymbolFlags(Sym);
if (!JITSymFlags)
return JITSymFlags.takeError();
LLVM_DEBUG(dbgs() << "Allocating common symbol " << Name << " address "
<< format("%p", Addr) << "\n");
if (!Name.empty()) GlobalSymbolTable[Name] =
SymbolTableEntry(SectionID, Offset, std::move(*JITSymFlags));
Offset += Size;
Addr += Size;
}
return Error::success();
}
Expected<unsigned>
RuntimeDyldImpl::emitSection(const ObjectFile &Obj,
const SectionRef &Section,
bool IsCode) {
StringRef data;
uint64_t Alignment64 = Section.getAlignment();
unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
unsigned PaddingSize = 0;
unsigned StubBufSize = 0;
bool IsRequired = isRequiredForExecution(Section);
bool IsVirtual = Section.isVirtual();
bool IsZeroInit = isZeroInit(Section);
bool IsReadOnly = isReadOnlyData(Section);
bool IsTLS = isTLS(Section);
uint64_t DataSize = Section.getSize();
Alignment = std::max(1u, Alignment);
Expected<StringRef> NameOrErr = Section.getName();
if (!NameOrErr)
return NameOrErr.takeError();
StringRef Name = *NameOrErr;
StubBufSize = computeSectionStubBufSize(Obj, Section);
if (Name == ".eh_frame")
PaddingSize = 4;
uintptr_t Allocate;
unsigned SectionID = Sections.size();
uint8_t *Addr;
uint64_t LoadAddress = 0;
const char *pData = nullptr;
if (!IsVirtual && !IsZeroInit) {
if (Expected<StringRef> E = Section.getContents())
data = *E;
else
return E.takeError();
pData = data.data();
}
if (StubBufSize != 0) {
Alignment = std::max(Alignment, getStubAlignment());
PaddingSize += getStubAlignment() - 1;
}
if (IsRequired || ProcessAllSections) {
Allocate = DataSize + PaddingSize + StubBufSize;
if (!Allocate)
Allocate = 1;
if (IsTLS) {
auto TLSSection =
MemMgr.allocateTLSSection(Allocate, Alignment, SectionID, Name);
Addr = TLSSection.InitializationImage;
LoadAddress = TLSSection.Offset;
} else if (IsCode) {
Addr = MemMgr.allocateCodeSection(Allocate, Alignment, SectionID, Name);
} else {
Addr = MemMgr.allocateDataSection(Allocate, Alignment, SectionID, Name,
IsReadOnly);
}
if (!Addr)
report_fatal_error("Unable to allocate section memory!");
if (IsZeroInit || IsVirtual)
memset(Addr, 0, DataSize);
else
memcpy(Addr, pData, DataSize);
if (PaddingSize != 0) {
memset(Addr + DataSize, 0, PaddingSize);
DataSize += PaddingSize;
if (StubBufSize > 0)
DataSize &= -(uint64_t)getStubAlignment();
}
LLVM_DEBUG(dbgs() << "emitSection SectionID: " << SectionID << " Name: "
<< Name << " obj addr: " << format("%p", pData)
<< " new addr: " << format("%p", Addr) << " DataSize: "
<< DataSize << " StubBufSize: " << StubBufSize
<< " Allocate: " << Allocate << "\n");
} else {
Allocate = 0;
Addr = nullptr;
LLVM_DEBUG(
dbgs() << "emitSection SectionID: " << SectionID << " Name: " << Name
<< " obj addr: " << format("%p", data.data()) << " new addr: 0"
<< " DataSize: " << DataSize << " StubBufSize: " << StubBufSize
<< " Allocate: " << Allocate << "\n");
}
Sections.push_back(
SectionEntry(Name, Addr, DataSize, Allocate, (uintptr_t)pData));
if (IsTLS)
Sections.back().setLoadAddress(LoadAddress);
if (!IsRequired)
Sections.back().setLoadAddress(0);
return SectionID;
}
Expected<unsigned>
RuntimeDyldImpl::findOrEmitSection(const ObjectFile &Obj,
const SectionRef &Section,
bool IsCode,
ObjSectionToIDMap &LocalSections) {
unsigned SectionID = 0;
ObjSectionToIDMap::iterator i = LocalSections.find(Section);
if (i != LocalSections.end())
SectionID = i->second;
else {
if (auto SectionIDOrErr = emitSection(Obj, Section, IsCode))
SectionID = *SectionIDOrErr;
else
return SectionIDOrErr.takeError();
LocalSections[Section] = SectionID;
}
return SectionID;
}
void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
unsigned SectionID) {
Relocations[SectionID].push_back(RE);
}
void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
StringRef SymbolName) {
RTDyldSymbolTable::const_iterator Loc = GlobalSymbolTable.find(SymbolName);
if (Loc == GlobalSymbolTable.end()) {
ExternalSymbolRelocations[SymbolName].push_back(RE);
} else {
assert(!SymbolName.empty() &&
"Empty symbol should not be in GlobalSymbolTable");
RelocationEntry RECopy = RE;
const auto &SymInfo = Loc->second;
RECopy.Addend += SymInfo.getOffset();
Relocations[SymInfo.getSectionID()].push_back(RECopy);
}
}
uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr,
unsigned AbiVariant) {
if (Arch == Triple::aarch64 || Arch == Triple::aarch64_be ||
Arch == Triple::aarch64_32) {
writeBytesUnaligned(0xd2e00010, Addr, 4); writeBytesUnaligned(0xf2c00010, Addr+4, 4); writeBytesUnaligned(0xf2a00010, Addr+8, 4); writeBytesUnaligned(0xf2800010, Addr+12, 4); writeBytesUnaligned(0xd61f0200, Addr+16, 4);
return Addr;
} else if (Arch == Triple::arm || Arch == Triple::armeb) {
writeBytesUnaligned(0xe51ff004, Addr, 4); return Addr + 4;
} else if (IsMipsO32ABI || IsMipsN32ABI) {
const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
const unsigned NopInstr = 0x0;
unsigned JrT9Instr = 0x03200008;
if ((AbiVariant & ELF::EF_MIPS_ARCH) == ELF::EF_MIPS_ARCH_32R6 ||
(AbiVariant & ELF::EF_MIPS_ARCH) == ELF::EF_MIPS_ARCH_64R6)
JrT9Instr = 0x03200009;
writeBytesUnaligned(LuiT9Instr, Addr, 4);
writeBytesUnaligned(AdduiT9Instr, Addr + 4, 4);
writeBytesUnaligned(JrT9Instr, Addr + 8, 4);
writeBytesUnaligned(NopInstr, Addr + 12, 4);
return Addr;
} else if (IsMipsN64ABI) {
const unsigned LuiT9Instr = 0x3c190000, DaddiuT9Instr = 0x67390000,
DsllT9Instr = 0x19CC38;
const unsigned NopInstr = 0x0;
unsigned JrT9Instr = 0x03200008;
if ((AbiVariant & ELF::EF_MIPS_ARCH) == ELF::EF_MIPS_ARCH_64R6)
JrT9Instr = 0x03200009;
writeBytesUnaligned(LuiT9Instr, Addr, 4);
writeBytesUnaligned(DaddiuT9Instr, Addr + 4, 4);
writeBytesUnaligned(DsllT9Instr, Addr + 8, 4);
writeBytesUnaligned(DaddiuT9Instr, Addr + 12, 4);
writeBytesUnaligned(DsllT9Instr, Addr + 16, 4);
writeBytesUnaligned(DaddiuT9Instr, Addr + 20, 4);
writeBytesUnaligned(JrT9Instr, Addr + 24, 4);
writeBytesUnaligned(NopInstr, Addr + 28, 4);
return Addr;
} else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
writeInt32BE(Addr, 0x3D800000); writeInt32BE(Addr+4, 0x618C0000); writeInt32BE(Addr+8, 0x798C07C6); writeInt32BE(Addr+12, 0x658C0000); writeInt32BE(Addr+16, 0x618C0000); if (AbiVariant == 2) {
writeInt32BE(Addr+20, 0xF8410018); writeInt32BE(Addr+24, 0x7D8903A6); writeInt32BE(Addr+28, 0x4E800420); } else {
writeInt32BE(Addr+20, 0xF8410028); writeInt32BE(Addr+24, 0xE96C0000); writeInt32BE(Addr+28, 0xE84C0008); writeInt32BE(Addr+32, 0x7D6903A6); writeInt32BE(Addr+36, 0xE96C0010); writeInt32BE(Addr+40, 0x4E800420); }
return Addr;
} else if (Arch == Triple::systemz) {
writeInt16BE(Addr, 0xC418); writeInt16BE(Addr+2, 0x0000);
writeInt16BE(Addr+4, 0x0004);
writeInt16BE(Addr+6, 0x07F1); return Addr;
} else if (Arch == Triple::x86_64) {
*Addr = 0xFF; *(Addr+1) = 0x25; } else if (Arch == Triple::x86) {
*Addr = 0xE9; }
return Addr;
}
void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
uint64_t Addr) {
LLVM_DEBUG(
dbgs() << "Reassigning address for section " << SectionID << " ("
<< Sections[SectionID].getName() << "): "
<< format("0x%016" PRIx64, Sections[SectionID].getLoadAddress())
<< " -> " << format("0x%016" PRIx64, Addr) << "\n");
Sections[SectionID].setLoadAddress(Addr);
}
void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
uint64_t Value) {
for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
const RelocationEntry &RE = Relocs[i];
if (RE.SectionID != AbsoluteSymbolSection &&
Sections[RE.SectionID].getAddress() == nullptr)
continue;
resolveRelocation(RE, Value);
}
}
void RuntimeDyldImpl::applyExternalSymbolRelocations(
const StringMap<JITEvaluatedSymbol> ExternalSymbolMap) {
for (auto &RelocKV : ExternalSymbolRelocations) {
StringRef Name = RelocKV.first();
RelocationList &Relocs = RelocKV.second;
if (Name.size() == 0) {
LLVM_DEBUG(dbgs() << "Resolving absolute relocations."
<< "\n");
resolveRelocationList(Relocs, 0);
} else {
uint64_t Addr = 0;
JITSymbolFlags Flags;
RTDyldSymbolTable::const_iterator Loc = GlobalSymbolTable.find(Name);
if (Loc == GlobalSymbolTable.end()) {
auto RRI = ExternalSymbolMap.find(Name);
assert(RRI != ExternalSymbolMap.end() && "No result for symbol");
Addr = RRI->second.getAddress();
Flags = RRI->second.getFlags();
} else {
const auto &SymInfo = Loc->second;
Addr = getSectionLoadAddress(SymInfo.getSectionID()) +
SymInfo.getOffset();
Flags = SymInfo.getFlags();
}
if (!Addr && !Resolver.allowsZeroSymbols())
report_fatal_error(Twine("Program used external function '") + Name +
"' which could not be resolved!");
if (Addr != UINT64_MAX) {
Addr = modifyAddressBasedOnFlags(Addr, Flags);
LLVM_DEBUG(dbgs() << "Resolving relocations Name: " << Name << "\t"
<< format("0x%lx", Addr) << "\n");
resolveRelocationList(Relocs, Addr);
}
}
}
ExternalSymbolRelocations.clear();
}
Error RuntimeDyldImpl::resolveExternalSymbols() {
StringMap<JITEvaluatedSymbol> ExternalSymbolMap;
{
JITSymbolResolver::LookupSet ResolvedSymbols;
while (true) {
JITSymbolResolver::LookupSet NewSymbols;
for (auto &RelocKV : ExternalSymbolRelocations) {
StringRef Name = RelocKV.first();
if (!Name.empty() && !GlobalSymbolTable.count(Name) &&
!ResolvedSymbols.count(Name))
NewSymbols.insert(Name);
}
if (NewSymbols.empty())
break;
#ifdef _MSC_VER
using ExpectedLookupResult =
MSVCPExpected<JITSymbolResolver::LookupResult>;
#else
using ExpectedLookupResult = Expected<JITSymbolResolver::LookupResult>;
#endif
auto NewSymbolsP = std::make_shared<std::promise<ExpectedLookupResult>>();
auto NewSymbolsF = NewSymbolsP->get_future();
Resolver.lookup(NewSymbols,
[=](Expected<JITSymbolResolver::LookupResult> Result) {
NewSymbolsP->set_value(std::move(Result));
});
auto NewResolverResults = NewSymbolsF.get();
if (!NewResolverResults)
return NewResolverResults.takeError();
assert(NewResolverResults->size() == NewSymbols.size() &&
"Should have errored on unresolved symbols");
for (auto &RRKV : *NewResolverResults) {
assert(!ResolvedSymbols.count(RRKV.first) && "Redundant resolution?");
ExternalSymbolMap.insert(RRKV);
ResolvedSymbols.insert(RRKV.first);
}
}
}
applyExternalSymbolRelocations(ExternalSymbolMap);
return Error::success();
}
void RuntimeDyldImpl::finalizeAsync(
std::unique_ptr<RuntimeDyldImpl> This,
unique_function<void(object::OwningBinary<object::ObjectFile>,
std::unique_ptr<RuntimeDyld::LoadedObjectInfo>, Error)>
OnEmitted,
object::OwningBinary<object::ObjectFile> O,
std::unique_ptr<RuntimeDyld::LoadedObjectInfo> Info) {
auto SharedThis = std::shared_ptr<RuntimeDyldImpl>(std::move(This));
auto PostResolveContinuation =
[SharedThis, OnEmitted = std::move(OnEmitted), O = std::move(O),
Info = std::move(Info)](
Expected<JITSymbolResolver::LookupResult> Result) mutable {
if (!Result) {
OnEmitted(std::move(O), std::move(Info), Result.takeError());
return;
}
StringMap<JITEvaluatedSymbol> Resolved;
for (auto &KV : *Result)
Resolved[KV.first] = KV.second;
SharedThis->applyExternalSymbolRelocations(Resolved);
SharedThis->resolveLocalRelocations();
SharedThis->registerEHFrames();
std::string ErrMsg;
if (SharedThis->MemMgr.finalizeMemory(&ErrMsg))
OnEmitted(std::move(O), std::move(Info),
make_error<StringError>(std::move(ErrMsg),
inconvertibleErrorCode()));
else
OnEmitted(std::move(O), std::move(Info), Error::success());
};
JITSymbolResolver::LookupSet Symbols;
for (auto &RelocKV : SharedThis->ExternalSymbolRelocations) {
StringRef Name = RelocKV.first();
if (Name.empty()) continue;
assert(!SharedThis->GlobalSymbolTable.count(Name) &&
"Name already processed. RuntimeDyld instances can not be re-used "
"when finalizing with finalizeAsync.");
Symbols.insert(Name);
}
if (!Symbols.empty()) {
SharedThis->Resolver.lookup(Symbols, std::move(PostResolveContinuation));
} else
PostResolveContinuation(std::map<StringRef, JITEvaluatedSymbol>());
}
uint64_t RuntimeDyld::LoadedObjectInfo::getSectionLoadAddress(
const object::SectionRef &Sec) const {
auto I = ObjSecToIDMap.find(Sec);
if (I != ObjSecToIDMap.end())
return RTDyld.Sections[I->second].getLoadAddress();
return 0;
}
RuntimeDyld::MemoryManager::TLSSection
RuntimeDyld::MemoryManager::allocateTLSSection(uintptr_t Size,
unsigned Alignment,
unsigned SectionID,
StringRef SectionName) {
report_fatal_error("allocation of TLS not implemented");
}
void RuntimeDyld::MemoryManager::anchor() {}
void JITSymbolResolver::anchor() {}
void LegacyJITSymbolResolver::anchor() {}
RuntimeDyld::RuntimeDyld(RuntimeDyld::MemoryManager &MemMgr,
JITSymbolResolver &Resolver)
: MemMgr(MemMgr), Resolver(Resolver) {
Dyld = nullptr;
ProcessAllSections = false;
}
RuntimeDyld::~RuntimeDyld() = default;
static std::unique_ptr<RuntimeDyldCOFF>
createRuntimeDyldCOFF(
Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
JITSymbolResolver &Resolver, bool ProcessAllSections,
RuntimeDyld::NotifyStubEmittedFunction NotifyStubEmitted) {
std::unique_ptr<RuntimeDyldCOFF> Dyld =
RuntimeDyldCOFF::create(Arch, MM, Resolver);
Dyld->setProcessAllSections(ProcessAllSections);
Dyld->setNotifyStubEmitted(std::move(NotifyStubEmitted));
return Dyld;
}
static std::unique_ptr<RuntimeDyldELF>
createRuntimeDyldELF(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
JITSymbolResolver &Resolver, bool ProcessAllSections,
RuntimeDyld::NotifyStubEmittedFunction NotifyStubEmitted) {
std::unique_ptr<RuntimeDyldELF> Dyld =
RuntimeDyldELF::create(Arch, MM, Resolver);
Dyld->setProcessAllSections(ProcessAllSections);
Dyld->setNotifyStubEmitted(std::move(NotifyStubEmitted));
return Dyld;
}
static std::unique_ptr<RuntimeDyldMachO>
createRuntimeDyldMachO(
Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
JITSymbolResolver &Resolver,
bool ProcessAllSections,
RuntimeDyld::NotifyStubEmittedFunction NotifyStubEmitted) {
std::unique_ptr<RuntimeDyldMachO> Dyld =
RuntimeDyldMachO::create(Arch, MM, Resolver);
Dyld->setProcessAllSections(ProcessAllSections);
Dyld->setNotifyStubEmitted(std::move(NotifyStubEmitted));
return Dyld;
}
std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
RuntimeDyld::loadObject(const ObjectFile &Obj) {
if (!Dyld) {
if (Obj.isELF())
Dyld =
createRuntimeDyldELF(static_cast<Triple::ArchType>(Obj.getArch()),
MemMgr, Resolver, ProcessAllSections,
std::move(NotifyStubEmitted));
else if (Obj.isMachO())
Dyld = createRuntimeDyldMachO(
static_cast<Triple::ArchType>(Obj.getArch()), MemMgr, Resolver,
ProcessAllSections, std::move(NotifyStubEmitted));
else if (Obj.isCOFF())
Dyld = createRuntimeDyldCOFF(
static_cast<Triple::ArchType>(Obj.getArch()), MemMgr, Resolver,
ProcessAllSections, std::move(NotifyStubEmitted));
else
report_fatal_error("Incompatible object format!");
}
if (!Dyld->isCompatibleFile(Obj))
report_fatal_error("Incompatible object format!");
auto LoadedObjInfo = Dyld->loadObject(Obj);
MemMgr.notifyObjectLoaded(*this, Obj);
return LoadedObjInfo;
}
void *RuntimeDyld::getSymbolLocalAddress(StringRef Name) const {
if (!Dyld)
return nullptr;
return Dyld->getSymbolLocalAddress(Name);
}
unsigned RuntimeDyld::getSymbolSectionID(StringRef Name) const {
assert(Dyld && "No RuntimeDyld instance attached");
return Dyld->getSymbolSectionID(Name);
}
JITEvaluatedSymbol RuntimeDyld::getSymbol(StringRef Name) const {
if (!Dyld)
return nullptr;
return Dyld->getSymbol(Name);
}
std::map<StringRef, JITEvaluatedSymbol> RuntimeDyld::getSymbolTable() const {
if (!Dyld)
return std::map<StringRef, JITEvaluatedSymbol>();
return Dyld->getSymbolTable();
}
void RuntimeDyld::resolveRelocations() { Dyld->resolveRelocations(); }
void RuntimeDyld::reassignSectionAddress(unsigned SectionID, uint64_t Addr) {
Dyld->reassignSectionAddress(SectionID, Addr);
}
void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
uint64_t TargetAddress) {
Dyld->mapSectionAddress(LocalAddress, TargetAddress);
}
bool RuntimeDyld::hasError() { return Dyld->hasError(); }
StringRef RuntimeDyld::getErrorString() { return Dyld->getErrorString(); }
void RuntimeDyld::finalizeWithMemoryManagerLocking() {
bool MemoryFinalizationLocked = MemMgr.FinalizationLocked;
MemMgr.FinalizationLocked = true;
resolveRelocations();
registerEHFrames();
if (!MemoryFinalizationLocked) {
MemMgr.finalizeMemory();
MemMgr.FinalizationLocked = false;
}
}
StringRef RuntimeDyld::getSectionContent(unsigned SectionID) const {
assert(Dyld && "No Dyld instance attached");
return Dyld->getSectionContent(SectionID);
}
uint64_t RuntimeDyld::getSectionLoadAddress(unsigned SectionID) const {
assert(Dyld && "No Dyld instance attached");
return Dyld->getSectionLoadAddress(SectionID);
}
void RuntimeDyld::registerEHFrames() {
if (Dyld)
Dyld->registerEHFrames();
}
void RuntimeDyld::deregisterEHFrames() {
if (Dyld)
Dyld->deregisterEHFrames();
}
void jitLinkForORC(
object::OwningBinary<object::ObjectFile> O,
RuntimeDyld::MemoryManager &MemMgr, JITSymbolResolver &Resolver,
bool ProcessAllSections,
unique_function<Error(const object::ObjectFile &Obj,
RuntimeDyld::LoadedObjectInfo &LoadedObj,
std::map<StringRef, JITEvaluatedSymbol>)>
OnLoaded,
unique_function<void(object::OwningBinary<object::ObjectFile>,
std::unique_ptr<RuntimeDyld::LoadedObjectInfo>, Error)>
OnEmitted) {
RuntimeDyld RTDyld(MemMgr, Resolver);
RTDyld.setProcessAllSections(ProcessAllSections);
auto Info = RTDyld.loadObject(*O.getBinary());
if (RTDyld.hasError()) {
OnEmitted(std::move(O), std::move(Info),
make_error<StringError>(RTDyld.getErrorString(),
inconvertibleErrorCode()));
return;
}
if (auto Err = OnLoaded(*O.getBinary(), *Info, RTDyld.getSymbolTable()))
OnEmitted(std::move(O), std::move(Info), std::move(Err));
RuntimeDyldImpl::finalizeAsync(std::move(RTDyld.Dyld), std::move(OnEmitted),
std::move(O), std::move(Info));
}
}