Files
carbon-lang/compiler-rt/lib/orc/macho_platform.cpp
T
Lang Hames bb5f97e3ad [ORC][ORC-RT] Introduce ORC-runtime based MachO-Platform.
Adds support for MachO static initializers/deinitializers and eh-frame
registration via the ORC runtime.

This commit introduces cooperative support code into the ORC runtime and ORC
LLVM libraries (especially the MachOPlatform class) to support macho runtime
features for JIT'd code. This commit introduces support for static
initializers, static destructors (via cxa_atexit interposition), and eh-frame
registration. Near-future commits will add support for MachO native
thread-local variables, and language runtime registration (e.g. for Objective-C
and Swift).

The llvm-jitlink tool is updated to use the ORC runtime where available, and
regression tests for the new MachOPlatform support are added to compiler-rt.

Notable changes on the ORC runtime side:

1. The new macho_platform.h / macho_platform.cpp files contain the bulk of the
runtime-side support. This includes eh-frame registration; jit versions of
dlopen, dlsym, and dlclose; a cxa_atexit interpose to record static destructors,
and an '__orc_rt_macho_run_program' function that defines running a JIT'd MachO
program in terms of the jit- dlopen/dlsym/dlclose functions.

2. Replaces JITTargetAddress (and casting operations) with ExecutorAddress
(copied from LLVM) to improve type-safety of address management.

3. Adds serialization support for ExecutorAddress and unordered_map types to
the runtime-side Simple Packed Serialization code.

4. Adds orc-runtime regression tests to ensure that static initializers and
cxa-atexit interposes work as expected.

Notable changes on the LLVM side:

1. The MachOPlatform class is updated to:

  1.1. Load the ORC runtime into the ExecutionSession.
  1.2. Set up standard aliases for macho-specific runtime functions. E.g.
       ___cxa_atexit -> ___orc_rt_macho_cxa_atexit.
  1.3. Install the MachOPlatformPlugin to scrape LinkGraphs for information
       needed to support MachO features (e.g. eh-frames, mod-inits), and
       communicate this information to the runtime.
  1.4. Provide entry-points that the runtime can call to request initializers,
       perform symbol lookup, and request deinitialiers (the latter is
       implemented as an empty placeholder as macho object deinits are rarely
       used).
  1.5. Create a MachO header object for each JITDylib (defining the __mh_header
       and __dso_handle symbols).

2. The llvm-jitlink tool (and llvm-jitlink-executor) are updated to use the
runtime when available.

3. A `lookupInitSymbolsAsync` method is added to the Platform base class. This
can be used to issue an async lookup for initializer symbols. The existing
`lookupInitSymbols` method is retained (the GenericIRPlatform code is still
using it), but is deprecated and will be removed soon.

4. JIT-dispatch support code is added to ExecutorProcessControl.

The JIT-dispatch system allows handlers in the JIT process to be associated with
'tag' symbols in the executor, and allows the executor to make remote procedure
calls back to the JIT process (via __orc_rt_jit_dispatch) using those tags.

The primary use case is ORC runtime code that needs to call bakc to handlers in
orc::Platform subclasses. E.g. __orc_rt_macho_jit_dlopen calling back to
MachOPlatform::rt_getInitializers using __orc_rt_macho_get_initializers_tag.
(The system is generic however, and could be used by non-runtime code).

The new ExecutorProcessControl::JITDispatchInfo struct provides the address
(in the executor) of the jit-dispatch function and a jit-dispatch context
object, and implementations of the dispatch function are added to
SelfExecutorProcessControl and OrcRPCExecutorProcessControl.

5. OrcRPCTPCServer is updated to support JIT-dispatch calls over ORC-RPC.

6. Serialization support for StringMap is added to the LLVM-side Simple Packed
Serialization code.

7. A JITLink::allocateBuffer operation is introduced to allocate writable memory
attached to the graph. This is used by the MachO header synthesis code, and will
be generically useful for other clients who want to create new graph content
from scratch.
2021-07-19 19:50:16 +10:00

476 lines
15 KiB
C++

//===- macho_platform.cpp -------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file contains code required to load the rest of the MachO runtime.
//
//===----------------------------------------------------------------------===//
#include "macho_platform.h"
#include "common.h"
#include "error.h"
#include "wrapper_function_utils.h"
#include <map>
#include <mutex>
#include <sstream>
#include <unordered_map>
#include <vector>
using namespace __orc_rt;
using namespace __orc_rt::macho;
// Declare function tags for functions in the JIT process.
extern "C" char __orc_rt_macho_get_initializers_tag = 0;
extern "C" char __orc_rt_macho_get_deinitializers_tag = 0;
extern "C" char __orc_rt_macho_symbol_lookup_tag = 0;
// eh-frame registration functions.
// We expect these to be available for all processes.
extern "C" void __register_frame(const void *);
extern "C" void __deregister_frame(const void *);
namespace {
template <typename HandleFDEFn>
void walkEHFrameSection(span<const char> EHFrameSection,
HandleFDEFn HandleFDE) {
const char *CurCFIRecord = EHFrameSection.data();
uint64_t Size = *reinterpret_cast<const uint32_t *>(CurCFIRecord);
while (CurCFIRecord != EHFrameSection.end() && Size != 0) {
const char *OffsetField = CurCFIRecord + (Size == 0xffffffff ? 12 : 4);
if (Size == 0xffffffff)
Size = *reinterpret_cast<const uint64_t *>(CurCFIRecord + 4) + 12;
else
Size += 4;
uint32_t Offset = *reinterpret_cast<const uint32_t *>(OffsetField);
if (Offset != 0)
HandleFDE(CurCFIRecord);
CurCFIRecord += Size;
Size = *reinterpret_cast<const uint32_t *>(CurCFIRecord);
}
}
Error validatePointerSectionExtent(const char *SectionName,
const ExecutorAddressRange &SE) {
if (SE.size().getValue() % sizeof(uintptr_t)) {
std::ostringstream ErrMsg;
ErrMsg << std::hex << "Size of " << SectionName << " 0x"
<< SE.StartAddress.getValue() << " -- 0x" << SE.EndAddress.getValue()
<< " is not a pointer multiple";
return make_error<StringError>(ErrMsg.str());
}
return Error::success();
}
Error runModInits(const std::vector<ExecutorAddressRange> &ModInitsSections,
const MachOJITDylibInitializers &MOJDIs) {
for (const auto &ModInits : ModInitsSections) {
if (auto Err = validatePointerSectionExtent("__mod_inits", ModInits))
return Err;
using InitFunc = void (*)();
for (auto *Init : ModInits.toSpan<InitFunc>())
(*Init)();
}
return Error::success();
}
class MachOPlatformRuntimeState {
private:
struct AtExitEntry {
void (*Func)(void *);
void *Arg;
};
using AtExitsVector = std::vector<AtExitEntry>;
struct PerJITDylibState {
void *Header = nullptr;
size_t RefCount = 0;
bool AllowReinitialization = false;
AtExitsVector AtExits;
};
public:
static void initialize();
static MachOPlatformRuntimeState &get();
static void destroy();
MachOPlatformRuntimeState() = default;
// Delete copy and move constructors.
MachOPlatformRuntimeState(const MachOPlatformRuntimeState &) = delete;
MachOPlatformRuntimeState &
operator=(const MachOPlatformRuntimeState &) = delete;
MachOPlatformRuntimeState(MachOPlatformRuntimeState &&) = delete;
MachOPlatformRuntimeState &operator=(MachOPlatformRuntimeState &&) = delete;
Error registerObjectSections(MachOPerObjectSectionsToRegister POSR);
Error deregisterObjectSections(MachOPerObjectSectionsToRegister POSR);
const char *dlerror();
void *dlopen(string_view Name, int Mode);
int dlclose(void *DSOHandle);
void *dlsym(void *DSOHandle, string_view Symbol);
int registerAtExit(void (*F)(void *), void *Arg, void *DSOHandle);
void runAtExits(void *DSOHandle);
private:
PerJITDylibState *getJITDylibStateByHeaderAddr(void *DSOHandle);
PerJITDylibState *getJITDylibStateByName(string_view Path);
PerJITDylibState &getOrCreateJITDylibState(MachOJITDylibInitializers &MOJDIs);
Expected<ExecutorAddress> lookupSymbolInJITDylib(void *DSOHandle,
string_view Symbol);
Expected<MachOJITDylibInitializerSequence>
getJITDylibInitializersByName(string_view Path);
Expected<void *> dlopenInitialize(string_view Path, int Mode);
Error initializeJITDylib(MachOJITDylibInitializers &MOJDIs);
static MachOPlatformRuntimeState *MOPS;
using InitSectionHandler =
Error (*)(const std::vector<ExecutorAddressRange> &Sections,
const MachOJITDylibInitializers &MOJDIs);
const std::vector<std::pair<string_view, InitSectionHandler>> InitSections = {
{"__DATA,__mod_init_func", runModInits}};
// FIXME: Move to thread-state.
std::string DLFcnError;
std::recursive_mutex JDStatesMutex;
std::unordered_map<void *, PerJITDylibState> JDStates;
std::unordered_map<std::string, void *> JDNameToHeader;
};
MachOPlatformRuntimeState *MachOPlatformRuntimeState::MOPS = nullptr;
void MachOPlatformRuntimeState::initialize() {
assert(!MOPS && "MachOPlatformRuntimeState should be null");
MOPS = new MachOPlatformRuntimeState();
}
MachOPlatformRuntimeState &MachOPlatformRuntimeState::get() {
assert(MOPS && "MachOPlatformRuntimeState not initialized");
return *MOPS;
}
void MachOPlatformRuntimeState::destroy() {
assert(MOPS && "MachOPlatformRuntimeState not initialized");
delete MOPS;
}
Error MachOPlatformRuntimeState::registerObjectSections(
MachOPerObjectSectionsToRegister POSR) {
if (POSR.EHFrameSection.StartAddress)
walkEHFrameSection(POSR.EHFrameSection.toSpan<const char>(),
__register_frame);
return Error::success();
}
Error MachOPlatformRuntimeState::deregisterObjectSections(
MachOPerObjectSectionsToRegister POSR) {
if (POSR.EHFrameSection.StartAddress)
walkEHFrameSection(POSR.EHFrameSection.toSpan<const char>(),
__deregister_frame);
return Error::success();
}
const char *MachOPlatformRuntimeState::dlerror() { return DLFcnError.c_str(); }
void *MachOPlatformRuntimeState::dlopen(string_view Path, int Mode) {
std::lock_guard<std::recursive_mutex> Lock(JDStatesMutex);
// Use fast path if all JITDylibs are already loaded and don't require
// re-running initializers.
if (auto *JDS = getJITDylibStateByName(Path)) {
if (!JDS->AllowReinitialization) {
++JDS->RefCount;
return JDS->Header;
}
}
auto H = dlopenInitialize(Path, Mode);
if (!H) {
DLFcnError = toString(H.takeError());
return nullptr;
}
return *H;
}
int MachOPlatformRuntimeState::dlclose(void *DSOHandle) {
runAtExits(DSOHandle);
return 0;
}
void *MachOPlatformRuntimeState::dlsym(void *DSOHandle, string_view Symbol) {
auto Addr = lookupSymbolInJITDylib(DSOHandle, Symbol);
if (!Addr) {
DLFcnError = toString(Addr.takeError());
return 0;
}
return Addr->toPtr<void *>();
}
int MachOPlatformRuntimeState::registerAtExit(void (*F)(void *), void *Arg,
void *DSOHandle) {
// FIXME: Handle out-of-memory errors, returning -1 if OOM.
std::lock_guard<std::recursive_mutex> Lock(JDStatesMutex);
auto *JDS = getJITDylibStateByHeaderAddr(DSOHandle);
assert(JDS && "JITDylib state not initialized");
JDS->AtExits.push_back({F, Arg});
return 0;
}
void MachOPlatformRuntimeState::runAtExits(void *DSOHandle) {
// FIXME: Should atexits be allowed to run concurrently with access to
// JDState?
AtExitsVector V;
{
std::lock_guard<std::recursive_mutex> Lock(JDStatesMutex);
auto *JDS = getJITDylibStateByHeaderAddr(DSOHandle);
assert(JDS && "JITDlybi state not initialized");
std::swap(V, JDS->AtExits);
}
while (!V.empty()) {
auto &AE = V.back();
AE.Func(AE.Arg);
V.pop_back();
}
}
MachOPlatformRuntimeState::PerJITDylibState *
MachOPlatformRuntimeState::getJITDylibStateByHeaderAddr(void *DSOHandle) {
auto I = JDStates.find(DSOHandle);
if (I == JDStates.end())
return nullptr;
return &I->second;
}
MachOPlatformRuntimeState::PerJITDylibState *
MachOPlatformRuntimeState::getJITDylibStateByName(string_view Name) {
// FIXME: Avoid creating string copy here.
auto I = JDNameToHeader.find(std::string(Name.data(), Name.size()));
if (I == JDNameToHeader.end())
return nullptr;
void *H = I->second;
auto J = JDStates.find(H);
assert(J != JDStates.end() &&
"JITDylib has name map entry but no header map entry");
return &J->second;
}
MachOPlatformRuntimeState::PerJITDylibState &
MachOPlatformRuntimeState::getOrCreateJITDylibState(
MachOJITDylibInitializers &MOJDIs) {
void *Header = MOJDIs.MachOHeaderAddress.toPtr<void *>();
auto &JDS = JDStates[Header];
// If this entry hasn't been created yet.
if (!JDS.Header) {
assert(!JDNameToHeader.count(MOJDIs.Name) &&
"JITDylib has header map entry but no name map entry");
JDNameToHeader[MOJDIs.Name] = Header;
JDS.Header = Header;
}
return JDS;
}
Expected<ExecutorAddress>
MachOPlatformRuntimeState::lookupSymbolInJITDylib(void *DSOHandle,
string_view Sym) {
Expected<ExecutorAddress> Result((ExecutorAddress()));
if (auto Err = WrapperFunction<SPSExpected<SPSExecutorAddress>(
SPSExecutorAddress,
SPSString)>::call(&__orc_rt_macho_symbol_lookup_tag, Result,
ExecutorAddress::fromPtr(DSOHandle), Sym))
return std::move(Err);
return Result;
}
Expected<MachOJITDylibInitializerSequence>
MachOPlatformRuntimeState::getJITDylibInitializersByName(string_view Path) {
Expected<MachOJITDylibInitializerSequence> Result(
(MachOJITDylibInitializerSequence()));
std::string PathStr(Path.data(), Path.size());
if (auto Err =
WrapperFunction<SPSExpected<SPSMachOJITDylibInitializerSequence>(
SPSString)>::call(&__orc_rt_macho_get_initializers_tag, Result,
Path))
return std::move(Err);
return Result;
}
Expected<void *> MachOPlatformRuntimeState::dlopenInitialize(string_view Path,
int Mode) {
// Either our JITDylib wasn't loaded, or it or one of its dependencies allows
// reinitialization. We need to call in to the JIT to see if there's any new
// work pending.
auto InitSeq = getJITDylibInitializersByName(Path);
if (!InitSeq)
return InitSeq.takeError();
// Init sequences should be non-empty.
if (InitSeq->empty())
return make_error<StringError>(
"__orc_rt_macho_get_initializers returned an "
"empty init sequence");
// Otherwise register and run initializers for each JITDylib.
for (auto &MOJDIs : *InitSeq)
if (auto Err = initializeJITDylib(MOJDIs))
return std::move(Err);
// Return the header for the last item in the list.
auto *JDS = getJITDylibStateByHeaderAddr(
InitSeq->back().MachOHeaderAddress.toPtr<void *>());
assert(JDS && "Missing state entry for JD");
return JDS->Header;
}
Error MachOPlatformRuntimeState::initializeJITDylib(
MachOJITDylibInitializers &MOJDIs) {
auto &JDS = getOrCreateJITDylibState(MOJDIs);
++JDS.RefCount;
for (auto &KV : InitSections) {
const auto &Name = KV.first;
const auto &Handler = KV.second;
// FIXME: Remove copy once we have C++17.
auto I = MOJDIs.InitSections.find(to_string(Name));
if (I != MOJDIs.InitSections.end()) {
if (auto Err = Handler(I->second, MOJDIs))
return Err;
}
}
return Error::success();
}
} // end anonymous namespace
//------------------------------------------------------------------------------
// JIT entry points
//------------------------------------------------------------------------------
ORC_RT_INTERFACE __orc_rt_CWrapperFunctionResult
__orc_rt_macho_platform_bootstrap(char *ArgData, size_t ArgSize) {
MachOPlatformRuntimeState::initialize();
return WrapperFunctionResult().release();
}
ORC_RT_INTERFACE __orc_rt_CWrapperFunctionResult
__orc_rt_macho_platform_shutdown(char *ArgData, size_t ArgSize) {
MachOPlatformRuntimeState::destroy();
return WrapperFunctionResult().release();
}
/// Wrapper function for registering metadata on a per-object basis.
ORC_RT_INTERFACE __orc_rt_CWrapperFunctionResult
__orc_rt_macho_register_object_sections(char *ArgData, size_t ArgSize) {
return WrapperFunction<SPSError(SPSMachOPerObjectSectionsToRegister)>::handle(
ArgData, ArgSize,
[](MachOPerObjectSectionsToRegister &POSR) {
return MachOPlatformRuntimeState::get().registerObjectSections(
std::move(POSR));
})
.release();
}
/// Wrapper for releasing per-object metadat.
ORC_RT_INTERFACE __orc_rt_CWrapperFunctionResult
__orc_rt_macho_deregister_object_sections(char *ArgData, size_t ArgSize) {
return WrapperFunction<SPSError(SPSMachOPerObjectSectionsToRegister)>::handle(
ArgData, ArgSize,
[](MachOPerObjectSectionsToRegister &POSR) {
return MachOPlatformRuntimeState::get().deregisterObjectSections(
std::move(POSR));
})
.release();
}
//------------------------------------------------------------------------------
// cxa_atexit support
//------------------------------------------------------------------------------
int __orc_rt_macho_cxa_atexit(void (*func)(void *), void *arg,
void *dso_handle) {
return MachOPlatformRuntimeState::get().registerAtExit(func, arg, dso_handle);
}
void __orc_rt_macho_cxa_finalize(void *dso_handle) {
MachOPlatformRuntimeState::get().runAtExits(dso_handle);
}
//------------------------------------------------------------------------------
// JIT'd dlfcn alternatives.
//------------------------------------------------------------------------------
const char *__orc_rt_macho_jit_dlerror() {
return MachOPlatformRuntimeState::get().dlerror();
}
void *__orc_rt_macho_jit_dlopen(const char *path, int mode) {
return MachOPlatformRuntimeState::get().dlopen(path, mode);
}
int __orc_rt_macho_jit_dlclose(void *dso_handle) {
return MachOPlatformRuntimeState::get().dlclose(dso_handle);
}
void *__orc_rt_macho_jit_dlsym(void *dso_handle, const char *symbol) {
return MachOPlatformRuntimeState::get().dlsym(dso_handle, symbol);
}
//------------------------------------------------------------------------------
// MachO Run Program
//------------------------------------------------------------------------------
ORC_RT_INTERFACE int64_t __orc_rt_macho_run_program(const char *JITDylibName,
const char *EntrySymbolName,
int argc, char *argv[]) {
using MainTy = int (*)(int, char *[]);
void *H = __orc_rt_macho_jit_dlopen(JITDylibName,
__orc_rt::macho::ORC_RT_RTLD_LAZY);
if (!H) {
__orc_rt_log_error(__orc_rt_macho_jit_dlerror());
return -1;
}
auto *Main =
reinterpret_cast<MainTy>(__orc_rt_macho_jit_dlsym(H, EntrySymbolName));
if (!Main) {
__orc_rt_log_error(__orc_rt_macho_jit_dlerror());
return -1;
}
int Result = Main(argc, argv);
if (__orc_rt_macho_jit_dlclose(H) == -1)
__orc_rt_log_error(__orc_rt_macho_jit_dlerror());
return Result;
}