Agent rewrite

Signed-off-by: Faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2025-10-20 21:24:52 +03:00
1 parent 65b91ff8b2
commit de940dab27
17 files changed
+451 -421

No files matched your search

+2 -1
View File
@@ -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)
+82
View File
@@ -0,0 +1,82 @@
#pragma once
#include <class_transformer.h>
#include <Logging/Logger.hpp>
#include <Mod/Context.hpp>
#include <Mods/Loader.hpp>
#include <atomic>
#include <filesystem>
#include <jvmti.h>
#include <jni.h>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
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<std::string, std::string>& 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<std::string, std::string> 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<std::string, std::filesystem::path> 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<std::string, std::filesystem::path> m_mods;
jvmtiEnv* m_jmti = nullptr;
JavaVM* m_jvm = nullptr;
JNIEnv* m_jni = nullptr;
std::unique_ptr<vl::mod::ModLoader> m_modloader;
std::unique_ptr<ClassTransformer> m_transformer;
vl::mod::Context m_context;
std::atomic<bool> m_isValid;
std::shared_ptr<vl::logging::Logger> m_logger;
static std::unique_ptr<Agent> instance_;
static std::once_flag initFlag_;
};
inline std::unique_ptr<Agent> Agent::instance_ = nullptr;
inline std::once_flag Agent::initFlag_;
}
+2
View File
@@ -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:
+29
View File
@@ -0,0 +1,29 @@
#pragma once
#include <Mod/Base.hpp>
#include <memory>
#include <string>
namespace vl::mod {
class LoadedMod {
public:
LoadedMod(std::string name, std::string version,
std::unique_ptr<Base> 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<Base> instance_;
void* handle_{};
};
} // namespace vl::log
+32
View File
@@ -0,0 +1,32 @@
#pragma once
#include <Mod/Context.hpp>
#include <Mods/Loaded.hpp>
#include <Mods/Registry.hpp>
#include <memory>
#include <string>
#include <vector>
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<LoadedMod>& instances() const noexcept { return instances_; }
private:
std::vector<void*> handles_;
std::vector<LoadedMod> instances_;
};
} // namespace vl::log
+32
View File
@@ -0,0 +1,32 @@
#pragma once
#include <Mod/Registration.hpp>
#include <functional>
#include <memory>
#include <string>
#include <string_view>
#include <vector>
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<std::unique_ptr<Base>(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<Entry>& all();
static std::vector<Entry>& mutableAll();
private:
static std::vector<Entry>& storage_();
};
} // namespace vl::log
-23
View File
@@ -1,23 +0,0 @@
#pragma once
#include <jvmti.h>
#include <jni.h>
#include <iostream>
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
};
-55
View File
@@ -1,55 +0,0 @@
#pragma once
#include <string>
#include <vector>
#include <filesystem>
#include <jvmti.h>
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<std::string> 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<ModInfo>& getLoadedMods() const;
// Enable/disable a mod
void setModEnabled(const std::string& mod_name, bool enabled);
private:
std::vector<ModInfo> 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);
};
+159
View File
@@ -0,0 +1,159 @@
#include <Logging/Level.hpp>
#include <Logging/Logger.hpp>
#include <Logging/LoggerManager.hpp>
#include <Logging/LoggerRegister.hpp>
#include <Mods/Loader.hpp>
#include <Agent.hpp>
#include <dlfcn.h>
#include <filesystem>
#include <iostream>
namespace vl::Agent {
Agent::Agent(std::unordered_map<std::string, std::string> args) : m_modloader(std::make_unique<vl::mod::ModLoader>())
{
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<std::string, std::filesystem::path> Agent::findMods(const std::string& dir)
{
std::unordered_map<std::string, std::filesystem::path> 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<std::string, std::string> argsMap;
for (int i=0; i<stringCount; i+=2) {
jstring argString = (jstring) (env->GetObjectArrayElement(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<void**>(&(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");
}
+1 -1
View File
@@ -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),
+5 -2
View File
@@ -4,6 +4,7 @@
#include <ctime>
#include <filesystem>
#include <format>
#include <iostream>
#include <stdexcept>
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),
+55
View File
@@ -0,0 +1,55 @@
#include <Mods/Loader.hpp>
#include <Agent.hpp>
#include <dlfcn.h>
#include <iostream>
#include <stdexcept>
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
+52
View File
@@ -0,0 +1,52 @@
#include <Mods/Registry.hpp>
#include <dlfcn.h> // dlopen/dlsym (ELF)
#include <iostream>
#include <stdexcept>
namespace vl::mod {
std::vector<Registry::Entry>& Registry::storage_() {
static std::vector<Entry> s;
return s;
}
const std::vector<Registry::Entry>& Registry::all() {
return storage_();
}
std::vector<Registry::Entry>& 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<BoundPtr>(symStart);
auto* end = reinterpret_cast<BoundPtr>(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{"<unknown>"};
e.name = std::string{"<unnamed>"};
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
-147
View File
@@ -1,147 +0,0 @@
#include <jvmti.h>
#include <jni.h>
#include <iostream>
#include <vector>
#include <string>
#include "Logging/LoggerManager.hpp"
#include "jvmti_handler.h"
#include "class_transformer.h"
#include "mod_manager.h"
#include <Logging/LoggerRegister.hpp>
// 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<void**>(&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
}
-1
View File
@@ -1,5 +1,4 @@
#include "class_transformer.h"
#include "jvmti_handler.h"
#include <iostream>
#include <string>
#include <vector>
-16
View File
@@ -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);
}
-175
View File
@@ -1,175 +0,0 @@
#include "mod_manager.h"
#include <iostream>
#include <fstream>
#include <sstream>
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<ModInfo>& 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;
}
}
}