impr: Get rid of cimgui shared library by hooking pinvoke handler

This commit is contained in:
WerWolv
2024-03-12 23:17:49 +01:00
parent 876f091244
commit fdf01dfb50
15 changed files with 135 additions and 57 deletions

View File

@@ -15,6 +15,8 @@
#include <nethost.h>
#include <coreclr_delegates.h>
#include <hostfxr.h>
#include <imgui.h>
#include <hex/api/plugin_manager.hpp>
#include <hex/helpers/fs.hpp>
#include <wolv/io/fs.hpp>
@@ -22,6 +24,9 @@
#include <wolv/utils/string.hpp>
#include <hex/helpers/fmt.hpp>
#include <hex/helpers/logger.hpp>
#include <hex/helpers/utils.hpp>
extern "C" void igSetCurrentContext(ImGuiContext* ctx);
namespace hex::script::loader {
@@ -64,6 +69,20 @@ namespace hex::script::loader {
hostfxr_initialize_for_runtime_config_fn hostfxr_initialize_for_runtime_config = nullptr;
hostfxr_get_runtime_delegate_fn hostfxr_get_runtime_delegate = nullptr;
hostfxr_close_fn hostfxr_close = nullptr;
hostfxr_set_runtime_property_value_fn hostfxr_set_runtime_property_value = nullptr;
hostfxr_set_error_writer_fn hostfxr_set_error_writer = nullptr;
void* pInvokeOverride(const char *libraryName, const char *symbolName) {
auto library = std::string_view(libraryName);
if (library == "cimgui") {
return getExport<void*>(ImHexApi::System::getLibImHexModuleHandle(), symbolName);
} else if (library == "ImHex") {
auto address = getExport<void*>(hex::getContainingModule((void*)&pInvokeOverride), symbolName);
return address;
}
return nullptr;
}
bool loadHostfxr() {
#if defined(OS_WINDOWS)
@@ -108,13 +127,26 @@ namespace hex::script::loader {
= getExport<hostfxr_get_runtime_delegate_fn>(hostfxrLibrary, "hostfxr_get_runtime_delegate");
hostfxr_close
= getExport<hostfxr_close_fn>(hostfxrLibrary, "hostfxr_close");
hostfxr_set_runtime_property_value
= getExport<hostfxr_set_runtime_property_value_fn>(hostfxrLibrary, "hostfxr_set_runtime_property_value");
hostfxr_set_error_writer
= getExport<hostfxr_set_error_writer_fn>(hostfxrLibrary, "hostfxr_set_error_writer");
}
hostfxr_set_error_writer([] HOSTFXR_CALLTYPE (const char_t *message) {
if constexpr (std::same_as<char_t, wchar_t>) {
log::error("{}", utf16ToUtf8(message));
} else {
log::error("{}", message);
}
});
return
hostfxr_initialize_for_runtime_config != nullptr &&
hostfxr_get_runtime_delegate != nullptr &&
hostfxr_close != nullptr;
hostfxr_close != nullptr &&
hostfxr_set_runtime_property_value != nullptr &&
hostfxr_set_error_writer != nullptr;
}
load_assembly_and_get_function_pointer_fn getLoadAssemblyFunction(const std::fs::path &path) {
@@ -131,6 +163,8 @@ namespace hex::script::loader {
throw std::runtime_error(hex::format("Failed to initialize command line {:X}", result));
}
hostfxr_set_runtime_property_value(ctx, STRING("PINVOKE_OVERRIDE"), utf8ToUtf16(hex::format("{}", (void*)pInvokeOverride)).c_str());
result = hostfxr_get_runtime_delegate(
ctx,
hostfxr_delegate_type::hdt_load_assembly_and_get_function_pointer,
@@ -237,4 +271,4 @@ namespace hex::script::loader {
return true;
}
}
}