commit a78c6a3bb60ed819145c3da7c3bb3d94caa275ef Author: Faumaray Date: Wed Oct 15 17:41:37 2025 +0300 init commit Signed-off-by: Faumaray diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..f91f646 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,12 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# Linux start script should use lf +/gradlew text eol=lf + +# These are Windows script files and should use crlf +*.bat text eol=crlf + +# Binary files should be left untouched +*.jar binary + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1b6985c --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +# Ignore Gradle project-specific cache directory +.gradle + +# Ignore Gradle build output directory +build diff --git a/CppAgent/build.gradle.kts b/CppAgent/build.gradle.kts new file mode 100644 index 0000000..3adc6aa --- /dev/null +++ b/CppAgent/build.gradle.kts @@ -0,0 +1,14 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * This project uses @Incubating APIs which are subject to change. + */ + +plugins { + `cpp-library` +} +library { + targetMachines.add(machines.linux.x86_64) + baseName.set(rootProject.name) +} +version = "1.0.0" \ No newline at end of file diff --git a/CppAgent/src/main/cpp/agent.cpp b/CppAgent/src/main/cpp/agent.cpp new file mode 100644 index 0000000..1c4510c --- /dev/null +++ b/CppAgent/src/main/cpp/agent.cpp @@ -0,0 +1,115 @@ +#include +#include +#include +#include +#include +#include "jvmti_handler.h" +#include "class_transformer.h" +#include "mod_manager.h" + +// 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 << "[FabricPP] 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 << "[FabricPP] 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 << "[FabricPP] 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 << "[FabricPP] 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 << "[FabricPP] C++ Agent loaded successfully!" << std::endl; + return JNI_OK; +} + +// Called from Java agent - NON-BLOCKING +extern "C" JNIEXPORT void JNICALL Java_org_faumaray_FabricPPAgent_nativeAgentStart(JNIEnv* env, jclass clazz) { + std::cout << "[FabricPP] Native agent started from Java" << std::endl; + // Don't do any heavy work here - just initialization +} + +extern "C" JNIEXPORT void JNICALL Java_org_faumaray_FabricPPAgent_nativeAgentInit(JNIEnv* env, jclass clazz, jstring args, jobject instrumentation) { + std::cout << "[FabricPP] 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 << "[FabricPP] 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_FabricPPAgent_nativeCleanup(JNIEnv* env, jclass clazz) { + std::cout << "[FabricPP] Native cleanup called" << std::endl; + // Cleanup any native resources if needed +} \ No newline at end of file diff --git a/CppAgent/src/main/cpp/class_transformer.cpp b/CppAgent/src/main/cpp/class_transformer.cpp new file mode 100644 index 0000000..457ad9f --- /dev/null +++ b/CppAgent/src/main/cpp/class_transformer.cpp @@ -0,0 +1,83 @@ +#include "class_transformer.h" +#include "jvmti_handler.h" +#include +#include +#include +#include +#include + +// Only target specific Minecraft classes, exclude everything else +static const std::set TARGET_CLASSES = { + "net/minecraft/client/Minecraft", + "net/minecraft/client/main/Main", + "net/minecraft/server/MinecraftServer" +}; + +// Exclude all launcher and system classes +static const std::set EXCLUDED_PREFIXES = { + "java/", "javax/", "sun/", "jdk/", "com/sun/", + "org/prismlauncher/", "org/gtm/", "com/google/", + "org/apache/", "org/slf4j/", "org/lwjgl/", "org/objectweb/", + "io/", "okhttp3/", "okio/", "kotlin/", "scala/", + "org/json/", "com/mojang/", "org/spongepowered/", + "org/reflections/", "oshi/", "net/minecrell/", "org/checkerframework/" +}; + +void JNICALL ClassTransformer::classFileLoadHook(jvmtiEnv* jvmti, JNIEnv* jni, + jclass class_being_redefined, + jobject loader, const char* name, + jobject protection_domain, + jint class_data_len, + const unsigned char* class_data, + jint* new_class_data_len, + unsigned char** new_class_data) { + + // Early return for null class name + if (name == nullptr) { + return; + } + + std::string class_name(name); + + // Don't transform system classes or launcher classes + for (const auto& excluded_prefix : EXCLUDED_PREFIXES) { + if (class_name.find(excluded_prefix) == 0) { + return; + } + } + + // Only transform specific Minecraft classes + if (TARGET_CLASSES.find(class_name) != TARGET_CLASSES.end()) { + std::cout << "[FabricPP] Transforming class: " << class_name << std::endl; + transformClass(jvmti, class_data, class_data_len, new_class_data, new_class_data_len); + } +} + +bool ClassTransformer::shouldTransform(const std::string& class_name) { + return TARGET_CLASSES.find(class_name) != TARGET_CLASSES.end(); +} + +bool ClassTransformer::transformClass(jvmtiEnv* jvmti, + const unsigned char* original_data, + jint original_len, + unsigned char** new_data, + jint* new_len) { + if (jvmti == nullptr || original_data == nullptr || original_len == 0) { + return false; + } + + // For now, just copy without modification to avoid issues + unsigned char* copy = nullptr; + jvmtiError error = jvmti->Allocate(original_len, ©); + + if (error == JVMTI_ERROR_NONE && copy != nullptr) { + std::memcpy(copy, original_data, original_len); + *new_data = copy; + *new_len = original_len; + + std::cout << "[FabricPP] Successfully copied class (no transformation applied)" << std::endl; + return true; + } + + return false; +} \ No newline at end of file diff --git a/CppAgent/src/main/cpp/jvmti_handler.cpp b/CppAgent/src/main/cpp/jvmti_handler.cpp new file mode 100644 index 0000000..67576d6 --- /dev/null +++ b/CppAgent/src/main/cpp/jvmti_handler.cpp @@ -0,0 +1,16 @@ +#include "jvmti_handler.h" + +void JNICALL JvmtiHandler::vmInit(jvmtiEnv* jvmti, JNIEnv* jni, jthread thread) { + std::cout << "[FabricPP] 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 << "[FabricPP] Agent ready for class transformation" << std::endl; +} + +void JNICALL JvmtiHandler::vmDeath(jvmtiEnv* jvmti, JNIEnv* jni) { + std::cout << "[FabricPP] VM Shutting down" << std::endl; + JvmtiHandler::setAgentInitialized(false); +} \ No newline at end of file diff --git a/CppAgent/src/main/cpp/mod_manager.cpp b/CppAgent/src/main/cpp/mod_manager.cpp new file mode 100644 index 0000000..8d3a659 --- /dev/null +++ b/CppAgent/src/main/cpp/mod_manager.cpp @@ -0,0 +1,174 @@ +#include "mod_manager.h" +#include +#include +#include + +ModManager::ModManager() { + std::cout << "[FabricPP] ModManager initialized" << std::endl; +} + +ModManager::~ModManager() { + std::cout << "[FabricPP] ModManager destroyed" << std::endl; +} + +// Discover mods in the mods directory +void ModManager::discoverMods(const std::string& mods_dir) { + namespace fs = std::filesystem; + + std::cout << "[FabricPP] 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 << "[FabricPP] Created mods directory: " << mods_dir << std::endl; + + // Create a README + std::ofstream readme(mods_dir + "/README.txt"); + readme << "FabricPP 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 << "[FabricPP] Discovered " << mod_count << " mod file(s)" << std::endl; + std::cout << "[FabricPP] Loaded " << loaded_mods.size() << " mod(s) successfully" << std::endl; + + // Print loaded mods + if (!loaded_mods.empty()) { + std::cout << "\n[FabricPP] 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 << "[FabricPP] 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 << "[FabricPP] 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 << "[FabricPP] Loaded: " << mod.name << " v" << mod.version << std::endl; + + } catch (const std::exception& e) { + std::cerr << "[FabricPP] 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 << "[FabricPP] 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 << "[FabricPP] 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 << "[FabricPP] 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 << "[FabricPP] Mod '" << mod_name << "' " + << (enabled ? "enabled" : "disabled") << std::endl; + return; + } + } +} \ No newline at end of file diff --git a/CppAgent/src/main/headers/class_transformer.h b/CppAgent/src/main/headers/class_transformer.h new file mode 100644 index 0000000..05a82c9 --- /dev/null +++ b/CppAgent/src/main/headers/class_transformer.h @@ -0,0 +1,23 @@ +#pragma once +#include +#include + +class ClassTransformer { +public: + static void JNICALL classFileLoadHook(jvmtiEnv* jvmti, JNIEnv* jni, + jclass class_being_redefined, + jobject loader, const char* name, + jobject protection_domain, + jint class_data_len, + const unsigned char* class_data, + jint* new_class_data_len, + unsigned char** new_class_data); + +private: + static bool shouldTransform(const std::string& class_name); + static bool transformClass(jvmtiEnv* jvmti, + const unsigned char* original_data, + jint original_len, + unsigned char** new_data, + jint* new_len); +}; \ No newline at end of file diff --git a/CppAgent/src/main/headers/jvmti_handler.h b/CppAgent/src/main/headers/jvmti_handler.h new file mode 100644 index 0000000..e8918f5 --- /dev/null +++ b/CppAgent/src/main/headers/jvmti_handler.h @@ -0,0 +1,23 @@ +#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/CppAgent/src/main/headers/mod_manager.h b/CppAgent/src/main/headers/mod_manager.h new file mode 100644 index 0000000..15d62e5 --- /dev/null +++ b/CppAgent/src/main/headers/mod_manager.h @@ -0,0 +1,55 @@ +#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/JavaAgent/build.gradle.kts b/JavaAgent/build.gradle.kts new file mode 100644 index 0000000..d29fab2 --- /dev/null +++ b/JavaAgent/build.gradle.kts @@ -0,0 +1,56 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * This project uses @Incubating APIs which are subject to change. + */ + +plugins { + // Apply the java-library plugin for API and implementation separation. + `java-library` +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} +version = "1.0.0" + +tasks.withType().configureEach { + archiveBaseName.set(rootProject.name) + + from(sourceSets.main.get().output) + + dependsOn(configurations.runtimeClasspath) + from({ + configurations.runtimeClasspath.get().filter { it.name.endsWith("jar") }.map { zipTree(it) } + }) + val cppProject = project(":CppAgent") + val nativeLibPath = cppProject.layout.buildDirectory + .dir("lib/main/debug") // or "release" if you're building release + .map { it.asFile } + .get() + .listFiles { file -> file.name.matches(Regex("lib.*\\.(so|dll|dylib)")) } + ?.firstOrNull() + + if (nativeLibPath != null) { + from(nativeLibPath) { + into(".") // 👈 root of the jar + } + } else { + doFirst { + throw GradleException("Native library not found in expected CppAgent build path") + } + } + manifest { + attributes( + "Main-Class" to "org.faumaray.FabricPPAgent", + "Agent-Class" to "org.faumaray.FabricPPAgent", + "Premain-Class" to "org.faumaray.FabricPPAgent" + ) + } +} + +tasks.named("compileJava") { + dependsOn(":CppAgent:build") +} \ No newline at end of file diff --git a/JavaAgent/src/main/java/org/faumaray/FabricPPAgent.java b/JavaAgent/src/main/java/org/faumaray/FabricPPAgent.java new file mode 100644 index 0000000..89a2b76 --- /dev/null +++ b/JavaAgent/src/main/java/org/faumaray/FabricPPAgent.java @@ -0,0 +1,169 @@ +package org.faumaray; + +import java.lang.instrument.Instrumentation; +import java.io.*; +import java.nio.file.*; +import java.nio.file.attribute.PosixFilePermission; +import java.util.Set; + +/** + * FabricPP Java Agent Wrapper + * + * This is OPTIONAL - the C++ agent loads via Agent_OnLoad which happens + * BEFORE any Java code runs. This wrapper is only needed if you want + * to load the agent as a Java agent instead of a native JVMTI agent. + * + * For native loading (recommended), use: -agentpath:/path/to/libfabricpp_agent.so + * For Java agent loading, use: -javaagent:fabricpp-agent.jar + */ +public class FabricPPAgent { + private static final String LIBRARY_NAME_LINUX = "libfabricpp.so"; + private static final String LIBRARY_NAME_WINDOWS = "libfabricpp.dll"; + private static final String LIBRARY_NAME_MAC = "libfabricpp.dylib"; + private static final String TEMP_PREFIX = "fabricpp_"; + private static File extractedLibrary = null; + + // Native method declarations (bridge to C++) + private static native void nativeAgentStart(); + private static native void nativeAgentInit(String args, Instrumentation inst); + private static native void nativeCleanup(); + + static { + System.out.println("[FabricPP/Java] Java agent wrapper initializing..."); + loadNativeLibrary(); + } + + private static String getLibraryName() { + String os = System.getProperty("os.name").toLowerCase(); + if (os.contains("win")) { + return LIBRARY_NAME_WINDOWS; + } else if (os.contains("mac")) { + return LIBRARY_NAME_MAC; + } else { + return LIBRARY_NAME_LINUX; + } + } + + private static void loadNativeLibrary() { + try { + // Try system path first + try { + System.loadLibrary("fabricpp_agent"); + System.out.println("[FabricPP/Java] Loaded from system library path"); + return; + } catch (UnsatisfiedLinkError e) { + System.out.println("[FabricPP/Java] System library not found, extracting from JAR..."); + } + + // Extract from JAR + extractAndLoadLibrary(); + + } catch (Exception e) { + System.err.println("[FabricPP/Java] CRITICAL: Failed to load native library!"); + e.printStackTrace(); + System.err.println("\n" + + "========================================\n" + + "RECOMMENDED: Use native agent loading instead!\n" + + "Add to JVM args: -agentpath:/path/to/libfabricpp_agent.so\n" + + "This loads BEFORE any Java code runs.\n" + + "========================================\n"); + } + } + + private static void extractAndLoadLibrary() throws IOException { + String libraryName = getLibraryName(); + + // Get library from JAR resources + InputStream libStream = FabricPPAgent.class.getResourceAsStream("/" + libraryName); + if (libStream == null) { + throw new IOException("Native library not found in JAR: " + libraryName); + } + + // Create temp directory + Path tempDir = Files.createTempDirectory(TEMP_PREFIX); + extractedLibrary = tempDir.resolve(libraryName).toFile(); + extractedLibrary.deleteOnExit(); + tempDir.toFile().deleteOnExit(); + + // Extract library + try (InputStream in = libStream; + OutputStream out = new FileOutputStream(extractedLibrary)) { + byte[] buffer = new byte[8192]; + int bytesRead; + while ((bytesRead = in.read(buffer)) != -1) { + out.write(buffer, 0, bytesRead); + } + } + + // Set executable permissions (Unix-like systems) + try { + Set perms = Files.getPosixFilePermissions(extractedLibrary.toPath()); + perms.add(PosixFilePermission.OWNER_EXECUTE); + perms.add(PosixFilePermission.GROUP_EXECUTE); + perms.add(PosixFilePermission.OTHERS_EXECUTE); + Files.setPosixFilePermissions(extractedLibrary.toPath(), perms); + } catch (UnsupportedOperationException e) { + // Windows - use setExecutable + extractedLibrary.setExecutable(true, false); + } + + // Load the library + System.load(extractedLibrary.getAbsolutePath()); + System.out.println("[FabricPP/Java] Loaded from JAR: " + extractedLibrary.getAbsolutePath()); + } + + /** + * Java agent entry point - called when using -javaagent + * WARNING: This loads AFTER some Java classes have already loaded! + * For best results, use -agentpath instead. + */ + public static void premain(String args, Instrumentation inst) { + System.out.println("\n========================================"); + System.out.println("[FabricPP/Java] Java agent premain called"); + System.out.println("[FabricPP/Java] WARNING: Some classes may have already loaded!"); + System.out.println("[FabricPP/Java] For best results, use: -agentpath:/path/to/libfabricpp_agent.so"); + System.out.println("========================================\n"); + + try { + nativeAgentStart(); + nativeAgentInit(args != null ? args : "", inst); + System.out.println("[FabricPP/Java] Agent initialized - delegating to Minecraft"); + } catch (UnsatisfiedLinkError e) { + System.err.println("[FabricPP/Java] Native methods not available!"); + System.err.println("[FabricPP/Java] The C++ agent may not have loaded correctly."); + e.printStackTrace(); + } catch (Throwable t) { + System.err.println("[FabricPP/Java] Error during initialization:"); + t.printStackTrace(); + } + } + + /** + * Dynamic attach entry point + */ + public static void agentmain(String args, Instrumentation inst) { + System.out.println("[FabricPP/Java] Dynamic attach not fully supported"); + premain(args, inst); + } + + /** + * Cleanup on shutdown + */ + public static void cleanup() { + try { + if (extractedLibrary != null && extractedLibrary.exists()) { + extractedLibrary.delete(); + } + nativeCleanup(); + } catch (Throwable t) { + // Ignore cleanup errors + } + } + + // Shutdown hook + static { + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + cleanup(); + }, "FabricPP-Cleanup")); + } +} \ No newline at end of file diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..5cc6d19 --- /dev/null +++ b/flake.lock @@ -0,0 +1,61 @@ +{ + "nodes": { + "flake-utils": { + "inputs": { + "systems": "systems" + }, + "locked": { + "lastModified": 1731533236, + "narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "11707dc2f618dd54ca8739b309ec4fc024de578b", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1760284886, + "narHash": "sha256-TK9Kr0BYBQ/1P5kAsnNQhmWWKgmZXwUQr4ZMjCzWf2c=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "cf3f5c4def3c7b5f1fc012b3d839575dbe552d43", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "flake-utils": "flake-utils", + "nixpkgs": "nixpkgs" + } + }, + "systems": { + "locked": { + "lastModified": 1681028828, + "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", + "owner": "nix-systems", + "repo": "default", + "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", + "type": "github" + }, + "original": { + "owner": "nix-systems", + "repo": "default", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..72a3f97 --- /dev/null +++ b/flake.nix @@ -0,0 +1,56 @@ +{ + description = "A project using CMake and X11"; + + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; + flake-utils.url = "github:numtide/flake-utils"; + }; + outputs = + { + self, + nixpkgs, + flake-utils, + }: + flake-utils.lib.eachDefaultSystem ( + system: + let + pkgs = import nixpkgs { inherit system; }; + in + { + devShells.default = pkgs.mkShell { + name = "minecraft-jvmti-shell"; + nativeBuildInputs = with pkgs; [ + gcc + jdk + cmake + clang-tools + gradle + ]; + + buildInputs = with pkgs; [ + xorg.libX11 + xorg.libXrandr + xorg.libXcursor + xorg.libX11 + jdk + ]; + packages = with pkgs; [ + gcc + conan + xorg.libX11 + xorg.libXrandr + xorg.libXcursor + xorg.libX11 + jdk + ]; + #conan install . --output-folder=build --build=missing + #source build/build/Release/generators/conanbuild.sh + #cmake --preset conan-release + #cmake --build build/build/Release + shellHook = '' + + ''; + }; + } + ); +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..5154008 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,7 @@ +# This file was generated by the Gradle 'init' task. +# https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties + +org.gradle.configuration-cache=true +org.gradle.parallel=true +org.gradle.caching=true + diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..91f864d --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,10 @@ +# This file was generated by the Gradle 'init' task. +# https://docs.gradle.org/current/userguide/platforms.html#sub::toml-dependencies-format + +[versions] +commons-math3 = "3.6.1" +guava = "33.4.5-jre" + +[libraries] +commons-math3 = { module = "org.apache.commons:commons-math3", version.ref = "commons-math3" } +guava = { module = "com.google.guava:guava", version.ref = "guava" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1b33c55 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..d4081da --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..23d15a9 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..db3a6ac --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..3754258 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,7 @@ +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "0.10.0" +} + +rootProject.name = "fabricpp" + +include("CppAgent", "JavaAgent") \ No newline at end of file