From de940dab27eb6e8d8395eedb8ca28bfbc3b7959f Mon Sep 17 00:00:00 2001 From: Faumaray Date: Mon, 20 Oct 2025 21:24:52 +0300 Subject: [PATCH] Agent rewrite Signed-off-by: Faumaray --- CMakeLists.txt | 3 +- include/Agent.hpp | 82 ++++++++++++++ include/Logging/LoggerInternal.hpp | 2 + include/Mods/Loaded.hpp | 29 +++++ include/Mods/Loader.hpp | 32 ++++++ include/Mods/Registry.hpp | 32 ++++++ include/jvmti_handler.h | 23 ---- include/mod_manager.h | 55 --------- src/Agent.cpp | 159 ++++++++++++++++++++++++++ src/Logging/ConsoleSink.cpp | 2 +- src/Logging/FileSink.cpp | 7 +- src/Mods/Loader.cpp | 55 +++++++++ src/Mods/Registry.cpp | 52 +++++++++ src/agent.cpp | 147 ------------------------ src/class_transformer.cpp | 1 - src/jvmti_handler.cpp | 16 --- src/mod_manager.cpp | 175 ----------------------------- 17 files changed, 451 insertions(+), 421 deletions(-) create mode 100644 include/Agent.hpp create mode 100644 include/Mods/Loaded.hpp create mode 100644 include/Mods/Loader.hpp create mode 100644 include/Mods/Registry.hpp delete mode 100644 include/jvmti_handler.h delete mode 100644 include/mod_manager.h create mode 100644 src/Agent.cpp create mode 100644 src/Mods/Loader.cpp create mode 100644 src/Mods/Registry.cpp delete mode 100644 src/agent.cpp delete mode 100644 src/jvmti_handler.cpp delete mode 100644 src/mod_manager.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index ab3e05b..65a2166 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -61,7 +61,7 @@ endif() add_library(${PROJECT_NAME} SHARED ${SOURCES}) target_include_directories(${PROJECT_NAME} PUBLIC ${JNI_INCLUDE_DIRS}) -target_link_libraries(${PROJECT_NAME} PUBLIC JNI::JNI VoidLoaderApi) +target_link_libraries(${PROJECT_NAME} PUBLIC JNI::JNI JNI::JVM VoidLoaderApiInterface) if (CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") target_link_options(${PROJECT_NAME} PRIVATE @@ -79,6 +79,7 @@ endif() # Output name: YourAgent.dll / libYourAgent.so set_target_properties(${PROJECT_NAME} PROPERTIES PREFIX "" + SUFFIX ".vlmod" OUTPUT_NAME "VoidLoader" ) if(UNIX AND NOT APPLE) diff --git a/include/Agent.hpp b/include/Agent.hpp new file mode 100644 index 0000000..550a8d7 --- /dev/null +++ b/include/Agent.hpp @@ -0,0 +1,82 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +extern "C" JNIEXPORT jint JNICALL Java_nativeAgentInit(JNIEnv* env, jclass clazz, jobjectArray args, jobject instrumentation); +extern "C" JNIEXPORT jint JNICALL Java_nativeAgentStart(JNIEnv* env, jclass clazz); +extern "C" JNIEXPORT jint JNICALL Java_ru_faumaray_VoidLoaderAgent_nativeAgentStart(JNIEnv* env, jclass clazz); +extern "C" JNIEXPORT jint JNICALL Java_ru_faumaray_VoidLoaderAgent_nativeAgentInit(JNIEnv* env, jclass jclass, jobject instrumentation, jobjectArray args); + +extern "C" JNIEXPORT void JNICALL Java_ru_faumaray_VoidLoaderAgent_nativeCleanup(JNIEnv* env, jclass clazz); +namespace vl::Agent { + +class Agent { +public: + static void JNICALL vmInit(jvmtiEnv* jvmti, JNIEnv* jni, jthread thread); + static void JNICALL vmDeath(jvmtiEnv* jvmti, JNIEnv* jni); + + static Agent& getInstance(const std::unordered_map& args) { + std::call_once(initFlag_, [&] { + instance_.reset(new Agent(args)); + }); + return *instance_; + } + + // Accessor that just retrieves the existing instance + static Agent& getInstance() { + if (!instance_) { + throw std::runtime_error("Agent not initialized — call getInstance(args) first."); + } + return *instance_; + } + + explicit Agent(std::unordered_map args); + + Agent(const Agent&) = delete; + Agent& operator=(const Agent&) = delete; + Agent(Agent&&) = delete; + Agent& operator=(Agent&&) = delete; + + bool isValid() const noexcept + { + return m_isValid; + } + + +private: + std::unordered_map findMods(const std::string& dir); + friend int JNICALL ::Java_nativeAgentInit(JNIEnv* env, jclass clazz, jobjectArray args, jobject instrumentation); + friend int JNICALL ::Java_nativeAgentInit(JNIEnv* env, jclass clazz, jobjectArray args, jobject instrumentation); + friend int JNICALL ::Java_nativeAgentStart(JNIEnv* env, jclass clazz); + friend int JNICALL ::Java_ru_faumaray_VoidLoaderAgent_nativeAgentStart(JNIEnv* env, jclass clazz); + friend int JNICALL ::Java_ru_faumaray_VoidLoaderAgent_nativeAgentInit(JNIEnv* env, jclass jclass, jobject instrumentation, jobjectArray args); + friend void JNICALL ::Java_ru_faumaray_VoidLoaderAgent_nativeCleanup(JNIEnv* env, jclass clazz); + friend class ClassTransformer; + friend class vl::mod::ModLoader; +private: + std::unordered_map m_mods; + jvmtiEnv* m_jmti = nullptr; + JavaVM* m_jvm = nullptr; + JNIEnv* m_jni = nullptr; + std::unique_ptr m_modloader; + std::unique_ptr m_transformer; + vl::mod::Context m_context; + std::atomic m_isValid; + std::shared_ptr m_logger; + static std::unique_ptr instance_; + static std::once_flag initFlag_; +}; +inline std::unique_ptr Agent::instance_ = nullptr; +inline std::once_flag Agent::initFlag_; +} \ No newline at end of file diff --git a/include/Logging/LoggerInternal.hpp b/include/Logging/LoggerInternal.hpp index a7811d5..48b1988 100644 --- a/include/Logging/LoggerInternal.hpp +++ b/include/Logging/LoggerInternal.hpp @@ -14,6 +14,8 @@ public: std::string_view prefix() const noexcept override { return prefix_; } void setLevel(Level l) noexcept override { level_ = l; } + //FIXME: make possible to override rotation + void setMaxBytes(std::uintmax_t bytes) noexcept override { }; Level level() const noexcept override { return level_; } protected: diff --git a/include/Mods/Loaded.hpp b/include/Mods/Loaded.hpp new file mode 100644 index 0000000..0359d7d --- /dev/null +++ b/include/Mods/Loaded.hpp @@ -0,0 +1,29 @@ +#pragma once +#include +#include +#include + +namespace vl::mod { + +class LoadedMod { +public: + LoadedMod(std::string name, std::string version, + std::unique_ptr instance, void* handle) + : name_(std::move(name)), version_(std::move(version)), + instance_(std::move(instance)), handle_(handle) {} + + Base& mod() { return *instance_; } + const Base& mod() const { return *instance_; } + + const std::string& name() const noexcept { return name_; } + const std::string& version() const noexcept { return version_; } + void* handle() const noexcept { return handle_; } + +private: + std::string name_; + std::string version_; + std::unique_ptr instance_; + void* handle_{}; +}; + +} // namespace vl::log diff --git a/include/Mods/Loader.hpp b/include/Mods/Loader.hpp new file mode 100644 index 0000000..3278b53 --- /dev/null +++ b/include/Mods/Loader.hpp @@ -0,0 +1,32 @@ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace vl::mod { + +// Handles dlopen/dlsym, discovers mod registrations, constructs mods (C2) +class ModLoader { +public: + // Load a module (.so), discover CRTP-registered mod types, instantiate each with Context. + // Returns the number of instances created from this module. + std::size_t loadModule(const std::string& path, const Context& ctx); + + // Start/stop all currently loaded instances. + void startAll(); + void stopAll(); + + // Unload everything (calls stopAll first if not stopped). + void unloadAll(); + + const std::vector& instances() const noexcept { return instances_; } + +private: + std::vector handles_; + std::vector instances_; +}; + +} // namespace vl::log diff --git a/include/Mods/Registry.hpp b/include/Mods/Registry.hpp new file mode 100644 index 0000000..b9dab0e --- /dev/null +++ b/include/Mods/Registry.hpp @@ -0,0 +1,32 @@ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace vl::mod { + +class Registry { +public: + struct Entry { + std::string typeName; + std::string name; // from T::Name() + std::string version; // from T::Version() + std::function(const Context&)> factory; + }; + + // Read registration entries from a loaded module (ELF .so handle) + // Returns number of entries found. + static std::size_t addFromModule(void* soHandle); + + // Enumerate all known entries from all modules loaded so far + static const std::vector& all(); + static std::vector& mutableAll(); + +private: + static std::vector& storage_(); +}; + +} // namespace vl::log diff --git a/include/jvmti_handler.h b/include/jvmti_handler.h deleted file mode 100644 index e8918f5..0000000 --- a/include/jvmti_handler.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once -#include -#include -#include - -class JvmtiHandler { -public: - static void JNICALL vmInit(jvmtiEnv* jvmti, JNIEnv* jni, jthread thread); - static void JNICALL vmDeath(jvmtiEnv* jvmti, JNIEnv* jni); - - // Accessor methods for global variables - static jvmtiEnv* getJvmti(); - static JavaVM* getJavaVM(); - static bool isAgentInitialized(); - - // Setter methods - static void setJvmti(jvmtiEnv* jvmti); - static void setJavaVM(JavaVM* jvm); - static void setAgentInitialized(bool initialized); - -private: - // No global variable declarations here - they'll be in agent.cpp -}; \ No newline at end of file diff --git a/include/mod_manager.h b/include/mod_manager.h deleted file mode 100644 index 15d62e5..0000000 --- a/include/mod_manager.h +++ /dev/null @@ -1,55 +0,0 @@ -#pragma once -#include -#include -#include -#include - -enum class ModType { - JAR, // Java/bytecode mod - NATIVE // Native C++ mod -}; - -struct ModInfo { - std::string name; - std::string version; - std::string file_path; - ModType type; - bool enabled; - - // Mod metadata (from fabric.mod.json or similar) - std::string author; - std::string description; - std::vector dependencies; -}; - -class ModManager { -public: - ModManager(); - ~ModManager(); - - // Discover and load mods from directory - void discoverMods(const std::string& mods_dir); - - // Load a single mod - void loadMod(const std::filesystem::path& mod_path); - - // Apply transformations from all mods to a class - void applyTransformations( - const std::string& class_name, - const unsigned char* class_data, - jint class_data_len - ); - - // Get list of loaded mods - const std::vector& getLoadedMods() const; - - // Enable/disable a mod - void setModEnabled(const std::string& mod_name, bool enabled); - -private: - std::vector loaded_mods; - - // Parse mod metadata - void parseJarMod(const std::filesystem::path& jar_path, ModInfo& mod); - void parseNativeMod(const std::filesystem::path& native_path, ModInfo& mod); -}; \ No newline at end of file diff --git a/src/Agent.cpp b/src/Agent.cpp new file mode 100644 index 0000000..668941a --- /dev/null +++ b/src/Agent.cpp @@ -0,0 +1,159 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +namespace vl::Agent { + + Agent::Agent(std::unordered_map args) : m_modloader(std::make_unique()) + { + auto currentPath = std::filesystem::current_path(); + if (!args.contains("gameDir")) + { + args["gameDir"] = currentPath; + } + auto gameDir = args["gameDir"]; + auto dataDir = args["gameDir"] + std::filesystem::path::preferred_separator + "data"; + auto logDir = args["gameDir"] + std::filesystem::path::preferred_separator + "logs"; + auto modsDir = args["gameDir"] + std::filesystem::path::preferred_separator + "mods"; + m_context = { + .gameDir = std::move(gameDir), + .dataDir = std::move(dataDir), + .logDir = std::move(logDir), + .apiVersion = {1,0,0}, + }; + auto mods = findMods(modsDir); + if (!mods.contains("VoidLoaderApi.vlmod")) + { + std::cerr << "FATAL: Could not locate API: mod loader is not loaded"<< std::endl; + return; + } + + dlopen(mods.at("VoidLoaderApi.vlmod").c_str(), RTLD_NOW | RTLD_GLOBAL); + mods.erase("VoidLoaderApi.vlmod"); + mods.erase("VoidLoader.vlmod"); + + m_mods = mods; + m_isValid = true; + } + + void JNICALL Agent::vmInit(jvmtiEnv* jvmti, JNIEnv* jni, jthread thread) + { + + } + void JNICALL Agent::vmDeath(jvmtiEnv* jvmti, JNIEnv* jni) + { + Agent::getInstance().m_isValid = false; + } + + std::unordered_map Agent::findMods(const std::string& dir) + { + std::unordered_map result; + for (auto& entry : std::filesystem::directory_iterator(dir)) { + if (entry.path().extension() == ".vlmod") { + result.emplace(entry.path().filename(), std::filesystem::absolute(entry.path())); + } + } + return result; + } +} + +extern "C" JNIEXPORT jint JNICALL Java_nativeAgentInit(JNIEnv* env, jclass clazz, jobjectArray args, jobject instrumentation) +{ + int stringCount = env->GetArrayLength(args); + std::unordered_map argsMap; + + for (int i=0; iGetObjectArrayElement(args, i)); + auto arg = std::string(env->GetStringUTFChars(argString, 0)); + arg.erase(0, 2); + jstring valString = (jstring) (env->GetObjectArrayElement(args, i+1)); + const char *val = env->GetStringUTFChars(valString, 0); + argsMap.emplace(arg, val); + } + + auto& instance = vl::Agent::Agent::getInstance(argsMap); + try { + auto coreLogDir = std::string(instance.m_context.logDir) + std::filesystem::path::preferred_separator + "VoidLoader"; + vl::logging::init_voidloader_logger(); + instance.m_logger = vl::logging::LoggerManager::instance().createCombined("VoidLoader", coreLogDir.c_str(), 512'000, vl::logging::Level::Trace); + vl::logging::LoggerManager::instance().createConsole("VoidLoader")->setLevel(vl::logging::Level::Info); + } + catch (const std::exception& ex) { + fprintf(stderr, "[VoidLoaderCore] Logger initialization failed: %s\n", ex.what()); + return 1; + } + + auto error = env->GetJavaVM(&(instance.m_jvm)); + if (error != JNI_OK) { + instance.m_logger->error("Unable to get JavaVM from JNIEnv"); + return 1; + } + jint result = instance.m_jvm->GetEnv(reinterpret_cast(&(instance.m_jmti)), JVMTI_VERSION_21); + if (result != JNI_OK || instance.m_jmti == nullptr) { + instance.m_logger->error("Unable to access JVMTI"); + return JNI_ERR; + } + instance.m_jni = env; + + jvmtiEventCallbacks callbacks = {0}; + callbacks.ClassFileLoadHook = &instance.m_transformer->classFileLoadHook; + callbacks.VMInit = &instance.vmInit; + callbacks.VMDeath = &instance.vmDeath; + + auto cerror = instance.m_jmti->SetEventCallbacks(&callbacks, sizeof(callbacks)); + if (cerror != JVMTI_ERROR_NONE) { + instance.m_logger->error("Unable to set JVMTI callbacks!"); + return JNI_ERR; + } + + // Enable events + instance.m_jmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, nullptr); + instance.m_jmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_INIT, nullptr); + instance.m_jmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_DEATH, nullptr); + + + instance.m_logger->info("VoidLoader loaded"); + instance.m_logger->info("Logging initialized"); + + return 0; +} +extern "C" JNIEXPORT jint JNICALL Java_nativeAgentStart(JNIEnv* env, jclass clazz) +{ + auto& instance = vl::Agent::Agent::getInstance(); + instance.m_logger->info("Loading mods..."); + auto loaded = 0; + + for (auto& [name, path] : instance.m_mods) + { + instance.m_logger->trace("Loading mod: {}", name); + loaded += instance.m_modloader->loadModule(path, instance.m_context); + } + instance.m_logger->info("Mods loaded: {}, Starting", loaded); + + instance.m_modloader->startAll(); + return 0; +} +extern "C" JNIEXPORT jint JNICALL Java_ru_faumaray_VoidLoaderAgent_nativeAgentStart(JNIEnv* env, jclass clazz) +{ + return Java_nativeAgentStart(env, clazz); +} +extern "C" JNIEXPORT jint JNICALL Java_ru_faumaray_VoidLoaderAgent_nativeAgentInit(JNIEnv* env, jclass jclass, jobject instrumentation, jobjectArray args) +{ + return Java_nativeAgentInit(env,jclass,args,instrumentation); +} + +extern "C" JNIEXPORT void JNICALL Java_ru_faumaray_VoidLoaderAgent_nativeCleanup(JNIEnv* env, jclass jclass) +{ + auto& instance = vl::Agent::Agent::getInstance(); + instance.m_logger->info("Clearing up..."); + instance.m_modloader->stopAll(); + instance.m_logger->info("Mods stopped"); +} \ No newline at end of file diff --git a/src/Logging/ConsoleSink.cpp b/src/Logging/ConsoleSink.cpp index e11593d..dfea9c2 100644 --- a/src/Logging/ConsoleSink.cpp +++ b/src/Logging/ConsoleSink.cpp @@ -21,7 +21,7 @@ static std::string formatTimestamp(const std::chrono::system_clock::time_point& } void ConsoleSink::write(const Message& msg) { - const auto line = std::format("{} {} {:>5} {}\n", + const auto line = std::format("{} {} {} {}\n", formatTimestamp(msg.ts), msg.prefix, toString(msg.level), diff --git a/src/Logging/FileSink.cpp b/src/Logging/FileSink.cpp index 00eaa63..3ea8d43 100644 --- a/src/Logging/FileSink.cpp +++ b/src/Logging/FileSink.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include namespace vl::logging { @@ -53,7 +54,9 @@ void FileSink::openCurrent() { out_.close(); out_.clear(); out_.open(name, std::ios::out | std::ios::app | std::ios::binary); - if (!out_) throw std::runtime_error(std::format("FileSink: cannot open '{}'", name)); + if (!out_) { + throw std::runtime_error(std::format("FileSink: cannot open '{}'", name)); + } try { written_ = fs::file_size(name); } catch (...) { written_ = 0; } } @@ -83,7 +86,7 @@ void FileSink::ensureOpen(const Message& msg) { void FileSink::write(const Message& msg) { ensureOpen(msg); - const auto line = std::format("{} {} {:>5} {}\n", + const auto line = std::format("{} {} {} {}\n", formatTimestamp(msg.ts), msg.prefix, toString(msg.level), diff --git a/src/Mods/Loader.cpp b/src/Mods/Loader.cpp new file mode 100644 index 0000000..d9cfff4 --- /dev/null +++ b/src/Mods/Loader.cpp @@ -0,0 +1,55 @@ +#include +#include +#include +#include +#include + +namespace vl::mod { + +std::size_t ModLoader::loadModule(const std::string& path, const Context& ctx) { + void* handle = dlopen(path.c_str(), RTLD_NOW | RTLD_GLOBAL); + if (!handle) throw std::runtime_error(std::string("dlopen failed: ") + dlerror()); + handles_.push_back(handle); + + const std::size_t before = Registry::all().size(); + Registry::addFromModule(handle); + const std::size_t after = Registry::all().size(); + const std::size_t added = after - before; + if (added > 0) { + auto& all = Registry::mutableAll(); + for (std::size_t i = all.size() - added; i < all.size(); ++i) { + auto& e = all[i]; + auto inst = e.factory(ctx); + auto name = std::string(inst->name()); + auto version = std::string(inst->version()); + e.name = std::move(name); + e.version = std::move(version); + instances_.emplace_back(e.name, e.version, std::move(inst), handle); + } + } + return added; +} + +void ModLoader::startAll() { + auto& instance = vl::Agent::Agent::getInstance(); + for (auto& lm : instances_) + { + auto name = std::string(lm.mod().name()); + auto version = std::string(lm.mod().version()); + instance.m_logger->info("Starting {}, Version: {}", name, version); + lm.mod().onStart(); + } +} + +void ModLoader::stopAll() { + for (auto it = instances_.rbegin(); it != instances_.rend(); ++it) it->mod().onStop(); +} + +void ModLoader::unloadAll() { + stopAll(); + instances_.clear(); + for (auto* h : handles_) if (h) dlclose(h); + handles_.clear(); +} + +} // namespace vl::log diff --git a/src/Mods/Registry.cpp b/src/Mods/Registry.cpp new file mode 100644 index 0000000..a5f0931 --- /dev/null +++ b/src/Mods/Registry.cpp @@ -0,0 +1,52 @@ +#include +#include // dlopen/dlsym (ELF) +#include +#include + +namespace vl::mod { + +std::vector& Registry::storage_() { + static std::vector s; + return s; +} + +const std::vector& Registry::all() { + return storage_(); +} + +std::vector& Registry::mutableAll() { + return storage_(); +} + +std::size_t Registry::addFromModule(void* soHandle) { +#if defined(__ELF__) + using BoundPtr = const Registration*; + auto symStart = dlsym(soHandle, "__start_vlmods"); + auto symStop = dlsym(soHandle, "__stop_vlmods"); + if ((symStart == nullptr) || (symStop == nullptr)) + { + return 0; + } + auto* begin = reinterpret_cast(symStart); + auto* end = reinterpret_cast(symStop); + + std::size_t added = 0; + for (auto* it = begin; it && it < end; ++it) { + if (!it->factory || it->magic != kModRegMagic) continue; + + Entry e; + e.typeName = std::string{""}; + e.name = std::string{""}; + e.version = std::string{"0.0.0"}; + e.factory = it->factory; + storage_().push_back(std::move(e)); + ++added; + } + return added; +#else + (void)soHandle; + return 0; +#endif +} + +} // namespace vl::log diff --git a/src/agent.cpp b/src/agent.cpp deleted file mode 100644 index 45a8bb8..0000000 --- a/src/agent.cpp +++ /dev/null @@ -1,147 +0,0 @@ -#include -#include -#include -#include -#include -#include "Logging/LoggerManager.hpp" -#include "jvmti_handler.h" -#include "class_transformer.h" -#include "mod_manager.h" -#include - -// Global variables defined ONLY here -namespace { - jvmtiEnv* g_jvmti = nullptr; - JavaVM* g_jvm = nullptr; - bool g_agent_initialized = false; - ModManager g_modManager; -} - -// Implementation of JvmtiHandler accessors -jvmtiEnv* JvmtiHandler::getJvmti() { - return g_jvmti; -} - -JavaVM* JvmtiHandler::getJavaVM() { - return g_jvm; -} - -bool JvmtiHandler::isAgentInitialized() { - return g_agent_initialized; -} - -void JvmtiHandler::setJvmti(jvmtiEnv* jvmti) { - g_jvmti = jvmti; -} - -void JvmtiHandler::setJavaVM(JavaVM* jvm) { - g_jvm = jvm; -} - -void JvmtiHandler::setAgentInitialized(bool initialized) { - g_agent_initialized = initialized; -} - -// JVMTI Agent Entry Point -extern "C" JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM* vm, char* options, void* reserved) { - std::cout << "[VoidLoader] C++ Agent_OnLoad called!" << std::endl; - - JvmtiHandler::setJavaVM(vm); - - // Get JVMTI environment - jint result = vm->GetEnv(reinterpret_cast(&g_jvmti), JVMTI_VERSION_1_2); - if (result != JNI_OK || g_jvmti == nullptr) { - std::cerr << "[VoidLoader] ERROR: Unable to access JVMTI!" << std::endl; - return JNI_ERR; - } - - JvmtiHandler::setJvmti(g_jvmti); - - // Set JVMTI capabilities - jvmtiCapabilities capabilities = {0}; - capabilities.can_retransform_classes = 1; - capabilities.can_retransform_any_class = 1; - capabilities.can_generate_all_class_hook_events = 1; - capabilities.can_get_bytecodes = 1; - - jvmtiError error = g_jvmti->AddCapabilities(&capabilities); - if (error != JVMTI_ERROR_NONE) { - std::cerr << "[VoidLoader] ERROR: Unable to set JVMTI capabilities!" << std::endl; - return JNI_ERR; - } - - // Set event callbacks - jvmtiEventCallbacks callbacks = {0}; - callbacks.ClassFileLoadHook = &ClassTransformer::classFileLoadHook; - callbacks.VMInit = &JvmtiHandler::vmInit; - callbacks.VMDeath = &JvmtiHandler::vmDeath; - - error = g_jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks)); - if (error != JVMTI_ERROR_NONE) { - std::cerr << "[VoidLoader] ERROR: Unable to set JVMTI callbacks!" << std::endl; - return JNI_ERR; - } - - // Enable events - g_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, nullptr); - g_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_INIT, nullptr); - g_jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_DEATH, nullptr); - - std::cout << "[VoidLoader] C++ Agent loaded successfully!" << std::endl; - return JNI_OK; -} - -// Called from Java agent - NON-BLOCKING -extern "C" JNIEXPORT void JNICALL Java_ru_faumaray_VoidLoaderAgent_nativeAgentStart(JNIEnv* env, jclass clazz) { - std::cout << "[VoidLoader] Native agent started from Java" << std::endl; - // Don't do any heavy work here - just initialization -} - -extern "C" JNIEXPORT void JNICALL Java_ru_faumaray_VoidLoaderAgent_nativeAgentInit(JNIEnv* env, jclass clazz, jstring args, jobject instrumentation) { - try { - // Register logger provider in API singleton - vl::logging::init_voidloader_logger(); - } - catch (const std::exception& ex) { - // If something fails, return an error code, JVM will abort agent load - fprintf(stderr, "[VoidLoaderCore] Logger initialization failed: %s\n", ex.what()); - return; - } - auto logger = vl::logging::LoggerManager::instance().createConsole("[Core]"); - - logger->info("Native agent initialized with Instrumentation"); - - // Initialize mod manager - but don't block - g_modManager.discoverMods("mods"); - JavaVM* vm; - auto error = env->GetJavaVM(&vm); - if (error != JNI_OK) { - logger->error("Unable to get JavaVM from JNIEnv"); - return; - } - Agent_OnLoad(vm, nullptr, nullptr); -} - -extern "C" JNIEXPORT void JNICALL Java_nativeAgentStart(JNIEnv* env, jclass clazz) { - std::cout << "[VoidLoader] Native agent started from Java" << std::endl; - // Don't do any heavy work here - just initialization -} - -extern "C" JNIEXPORT void JNICALL Java_nativeAgentInit(JNIEnv* env, jclass clazz, jstring args, jobject instrumentation) { - std::cout << "[VoidLoader] Native agent initialized with Instrumentation" << std::endl; - // Initialize mod manager - but don't block - g_modManager.discoverMods("mods"); - JavaVM* vm; - auto error = env->GetJavaVM(&vm); - if (error != JNI_OK) { - std::cerr << "[VoidLoader] FATAL: Unable to get JavaVM from JNIEnv!" << std::endl; - return; - } - Agent_OnLoad(vm, nullptr, nullptr); -} - -// Cleanup native resources -extern "C" JNIEXPORT void JNICALL Java_org_faumaray_VoidLoaderAgent_nativeCleanup(JNIEnv* env, jclass clazz) { - std::cout << "[VoidLoader] Native cleanup called" << std::endl; - // Cleanup any native resources if needed -} \ No newline at end of file diff --git a/src/class_transformer.cpp b/src/class_transformer.cpp index 572c57e..5d70270 100644 --- a/src/class_transformer.cpp +++ b/src/class_transformer.cpp @@ -1,5 +1,4 @@ #include "class_transformer.h" -#include "jvmti_handler.h" #include #include #include diff --git a/src/jvmti_handler.cpp b/src/jvmti_handler.cpp deleted file mode 100644 index becee69..0000000 --- a/src/jvmti_handler.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include "jvmti_handler.h" - -void JNICALL JvmtiHandler::vmInit(jvmtiEnv* jvmti, JNIEnv* jni, jthread thread) { - std::cout << "[VoidLoader] VM Initialized - Minecraft starting soon" << std::endl; - - JvmtiHandler::setJvmti(jvmti); - JvmtiHandler::setAgentInitialized(true); - - // The main application is now starting - our agent is ready - std::cout << "[VoidLoader] Agent ready for class transformation" << std::endl; -} - -void JNICALL JvmtiHandler::vmDeath(jvmtiEnv* jvmti, JNIEnv* jni) { - std::cout << "[VoidLoader] VM Shutting down" << std::endl; - JvmtiHandler::setAgentInitialized(false); -} \ No newline at end of file diff --git a/src/mod_manager.cpp b/src/mod_manager.cpp deleted file mode 100644 index caea5ed..0000000 --- a/src/mod_manager.cpp +++ /dev/null @@ -1,175 +0,0 @@ -#include "mod_manager.h" -#include -#include -#include - -ModManager::ModManager() { - std::cout << "[VoidLoader] ModManager initialized" << std::endl; -} - -ModManager::~ModManager() { - std::cout << "[VoidLoader] ModManager destroyed" << std::endl; -} - -// Discover mods in the mods directory -void ModManager::discoverMods(const std::string& mods_dir) { - namespace fs = std::filesystem; - - std::cout << "[VoidLoader] Scanning for mods in: " << mods_dir << std::endl; - - try { - // Create mods directory if it doesn't exist - if (!fs::exists(mods_dir)) { - fs::create_directories(mods_dir); - std::cout << "[VoidLoader] Created mods directory: " << mods_dir << std::endl; - - // Create a README - std::ofstream readme((std::filesystem::path(mods_dir) / "README.txt").string()); - - readme << "VoidLoader Mods Directory\n"; - readme << "=======================\n\n"; - readme << "Place your .jar mod files here.\n"; - readme << "The mod loader will automatically detect and load them.\n"; - readme.close(); - - return; - } - - // Scan for mod files - int mod_count = 0; - for (const auto& entry : fs::directory_iterator(mods_dir)) { - if (entry.is_regular_file()) { - std::string ext = entry.path().extension().string(); - - // Support .jar mods (Java mods) and .dll/.so (native mods) - if (ext == ".jar" || ext == ".dll" || ext == ".so") { - loadMod(entry.path()); - mod_count++; - } - } - } - - std::cout << "[VoidLoader] Discovered " << mod_count << " mod file(s)" << std::endl; - std::cout << "[VoidLoader] Loaded " << loaded_mods.size() << " mod(s) successfully" << std::endl; - - // Print loaded mods - if (!loaded_mods.empty()) { - std::cout << "\n[VoidLoader] Loaded Mods:" << std::endl; - for (const auto& mod : loaded_mods) { - std::cout << " - " << mod.name << " v" << mod.version - << " (" << mod.file_path << ")" << std::endl; - } - std::cout << std::endl; - } - - } catch (const std::exception& e) { - std::cerr << "[VoidLoader] Error discovering mods: " << e.what() << std::endl; - } -} - -// Load a single mod -void ModManager::loadMod(const std::filesystem::path& mod_path) { - std::string filename = mod_path.filename().string(); - std::cout << "[VoidLoader] Loading mod: " << filename << std::endl; - - try { - ModInfo mod; - mod.file_path = mod_path.string(); - mod.name = filename; - mod.version = "unknown"; - mod.enabled = true; - - // Parse mod metadata based on file type - if (mod_path.extension() == ".jar") { - parseJarMod(mod_path, mod); - } else { - // Native mod (.dll/.so) - parseNativeMod(mod_path, mod); - } - - loaded_mods.push_back(mod); - std::cout << "[VoidLoader] Loaded: " << mod.name << " v" << mod.version << std::endl; - - } catch (const std::exception& e) { - std::cerr << "[VoidLoader] Failed to load mod " << filename << ": " << e.what() << std::endl; - } -} - -// Parse JAR mod metadata (fabric.mod.json or similar) -void ModManager::parseJarMod(const std::filesystem::path& jar_path, ModInfo& mod) { - // TODO: Implement JAR parsing - // This would: - // 1. Open the JAR file as a ZIP - // 2. Extract fabric.mod.json or mod.json - // 3. Parse JSON for mod metadata - // 4. Extract transformation rules/mixins - - // For now, extract basic info from filename - std::string filename = jar_path.stem().string(); - - // Try to parse version from filename (e.g., "modname-1.0.0.jar") - size_t dash_pos = filename.find_last_of('-'); - if (dash_pos != std::string::npos) { - mod.name = filename.substr(0, dash_pos); - mod.version = filename.substr(dash_pos + 1); - } else { - mod.name = filename; - } - - mod.type = ModType::JAR; - - std::cout << "[VoidLoader] Parsed JAR mod: " << mod.name << " v" << mod.version << std::endl; -} - -// Parse native mod metadata -void ModManager::parseNativeMod(const std::filesystem::path& native_path, ModInfo& mod) { - mod.name = native_path.stem().string(); - mod.type = ModType::NATIVE; - - // TODO: Load the native library and query for metadata - // This would dlopen/LoadLibrary the .dll/.so and call an exported function - // like "getModInfo()" to retrieve metadata - - std::cout << "[VoidLoader] Parsed native mod: " << mod.name << std::endl; -} - -// Apply transformations from mods to a class -void ModManager::applyTransformations( - const std::string& class_name, - const unsigned char* class_data, - jint class_data_len) { - - // Check each mod for transformations targeting this class - for (const auto& mod : loaded_mods) { - if (!mod.enabled) continue; - - // TODO: Check if mod has transformations for this class - // This would: - // 1. Look up transformation rules from mod metadata - // 2. Check if any mixins target this class - // 3. Queue transformations to be applied - - // For now, just log - if (class_name.find("net/minecraft/client/Minecraft") == 0) { - std::cout << "[VoidLoader] Mod '" << mod.name << "' checking transformations for: " - << class_name << std::endl; - } - } -} - -// Get list of loaded mods -const std::vector& ModManager::getLoadedMods() const { - return loaded_mods; -} - -// Enable/disable a mod -void ModManager::setModEnabled(const std::string& mod_name, bool enabled) { - for (auto& mod : loaded_mods) { - if (mod.name == mod_name) { - mod.enabled = enabled; - std::cout << "[VoidLoader] Mod '" << mod_name << "' " - << (enabled ? "enabled" : "disabled") << std::endl; - return; - } - } -} \ No newline at end of file