From b34377d447e53e506c692552c3cf2c1e06dfb3f4 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Sun, 16 Aug 2026 18:53:31 +0800 Subject: [PATCH] Refactor: restructure libloader and drop config parsing - Move loader logic to core/ and rename plantform/ to platform/ - Remove config.toml parsing from loader; pass runtime_dir to Bootstrap directly - Rewrite JvmAttach: RAII detach, drop dead thread_local, merge acquire helpers - Fix initialize() missing namespace qualification - Make GLOB sources pick up new files with CONFIGURE_DEPENDS --- src/libloader/CMakeLists.txt | 12 +-- src/libloader/common/Loader.cpp | 101 ------------------ src/libloader/core/Entry.cpp | 29 +++++ src/libloader/core/Loader.cpp | 60 +++++++++++ src/libloader/includes/JvmAttach.hpp | 101 +++++++----------- src/libloader/includes/Loader.hpp | 11 +- .../windows/DllMain.cpp | 0 .../windows/ReflectiveLoader.c | 0 8 files changed, 139 insertions(+), 175 deletions(-) delete mode 100644 src/libloader/common/Loader.cpp create mode 100644 src/libloader/core/Entry.cpp create mode 100644 src/libloader/core/Loader.cpp rename src/libloader/{plantform => platform}/windows/DllMain.cpp (100%) rename src/libloader/{plantform => platform}/windows/ReflectiveLoader.c (100%) diff --git a/src/libloader/CMakeLists.txt b/src/libloader/CMakeLists.txt index 253a415..26e3ed2 100644 --- a/src/libloader/CMakeLists.txt +++ b/src/libloader/CMakeLists.txt @@ -1,14 +1,14 @@ -file(GLOB_RECURSE loader_sources - ${CMAKE_CURRENT_SOURCE_DIR}/common/*.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/common/*.c +file(GLOB_RECURSE loader_sources CONFIGURE_DEPENDS + ${CMAKE_CURRENT_SOURCE_DIR}/core/*.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/core/*.c ) if (WIN32) message(STATUS "Detected System: Windows") - file(GLOB_RECURSE windows_sources - ${CMAKE_CURRENT_SOURCE_DIR}/plantform/windows/*.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/plantform/windows/*.c + file(GLOB_RECURSE windows_sources CONFIGURE_DEPENDS + ${CMAKE_CURRENT_SOURCE_DIR}/platform/windows/*.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/platform/windows/*.c ) list(APPEND loader_sources ${windows_sources}) diff --git a/src/libloader/common/Loader.cpp b/src/libloader/common/Loader.cpp deleted file mode 100644 index 0d94365..0000000 --- a/src/libloader/common/Loader.cpp +++ /dev/null @@ -1,101 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -namespace JuiceAgent::Loader { - -static bool invoke_juiceagent_init(JNIEnv* env, const LoaderConfig& config) { - const char* bootstrap_class = "cn/xiaozhou233/juiceagent/api/JuiceAgentBootstrap"; - const char* method_name = "start"; - - std::string args = JuiceAgent::Config::Utils::serialize_loader_config(config); - spdlog::debug("Invoke args: {}", args); - - if (!JuiceAgent::Utils::call_java_impl(env, bootstrap_class, method_name, args.c_str())) { - spdlog::error("Failed to init JuiceAgent!"); - return false; - } - - spdlog::info("JuiceAgentBootstrap.start invoked successfully"); - return true; -} - -static void init(const char* runtime_dir, JNIEnv* env, jvmtiEnv* jvmti) { - if (!runtime_dir) { - spdlog::warn("Runtime directory is not set!"); - } - - // Load configuration - JuiceAgent::Config::Config cfg(runtime_dir ? runtime_dir : ""); - if (!cfg.is_valid()) { - spdlog::error("Failed to load configuration!"); - - // TODO: Use default values - // Before impl TODO, must return, or crash will happen - return; - } - - // Print configuration - LoaderConfig config = JuiceAgent::Config::Utils::get_loader_config(cfg); - JuiceAgent::Config::Utils::print_loader_config(config); - - // Save bytes to file - std::string hash = - JuiceAgent::Resource::juiceagent_api_bytes_sha256; - - std::string file_name = - hash.substr(0, 8) + "_" + - JuiceAgent::Resource::juiceagent_api_bytes_name; - - std::string juiceagent_api_path = - JuiceAgent::Utils::File::write_to_tempfile( - JuiceAgent::Resource::juiceagent_api_bytes, - JuiceAgent::Resource::juiceagent_api_bytes_len, - file_name - ); - - spdlog::debug("JuiceAgent API path: {}", juiceagent_api_path); - spdlog::debug("JuiceAgent API size: {}", JuiceAgent::Resource::juiceagent_api_bytes_len); - spdlog::debug("JuiceAgent API sha256: {}", JuiceAgent::Resource::juiceagent_api_bytes_sha256); - - // Load JuiceAgent API to system classloader - jvmtiError status = jvmti->AddToSystemClassLoaderSearch(juiceagent_api_path.c_str()); - if (status != JVMTI_ERROR_NONE) { - spdlog::error("Failed to add JuiceAgent API to system classloader! code: {}", static_cast(status)); - return; - } - - spdlog::info("JuiceAgent API loaded to system classloader!"); - - // Init JuiceAgent - if (!invoke_juiceagent_init(env, config)) { - spdlog::error("Failed to init JuiceAgent!"); - } -} - - -void entrypoint(const char* runtime_dir) { - // Attach to the JVM - Jvm jvm; - if (!jvm.attach()) { - spdlog::error("Failed to attach to JVM!"); - return; - } - - // Get jvm and jni env - JNIEnv* env = jvm.get_env(); - auto* jvmti = jvm.get_jvmti(); - if (!env || !jvmti) { - spdlog::error("Failed to get jni env or jvmti env!"); - return; - } - - // Init JuiceAgent - init(runtime_dir, env, jvmti); -} - -} diff --git a/src/libloader/core/Entry.cpp b/src/libloader/core/Entry.cpp new file mode 100644 index 0000000..3a71201 --- /dev/null +++ b/src/libloader/core/Entry.cpp @@ -0,0 +1,29 @@ +#include +#include +#include + +void JuiceAgent::Loader::entrypoint(const char* path) { + // Attach to the JVM + JuiceAgent::Loader::JvmAttach jvmAttach; + + if(!jvmAttach.attach()) { + spdlog::error("Failed to attach to JVM!"); + return; + } + + // Get JNIEnv + JNIEnv* env = jvmAttach.get_env(); + if(!env) { + spdlog::error("Failed to get JNIEnv!"); + return; + } + + // Get JVMTI environment + jvmtiEnv* jvmti = jvmAttach.get_jvmti(); + if(!jvmti) { + spdlog::error("Failed to get JVMTI environment!"); + return; + } + + JuiceAgent::Loader::preload(path, env, jvmti); +} \ No newline at end of file diff --git a/src/libloader/core/Loader.cpp b/src/libloader/core/Loader.cpp new file mode 100644 index 0000000..3b40069 --- /dev/null +++ b/src/libloader/core/Loader.cpp @@ -0,0 +1,60 @@ +#include +#include +#include +#include +#include + +// Preload section +// Check parameters and load the runtime +void JuiceAgent::Loader::preload(const char* runtime_dir, JNIEnv* env, jvmtiEnv* jvmti) { + // Check parameters + if(!runtime_dir) { + spdlog::warn("[PreLoad] Runtime directory is not specified!"); + } + spdlog::info("[PreLoad] Runtime directory: {}", runtime_dir ? runtime_dir : "NULL"); + + // Extract JuiceAgent API to temp file + std::string hash = + JuiceAgent::Resource::juiceagent_api_bytes_sha256; + + std::string file_name = + hash.substr(0, 8) + "_" + + JuiceAgent::Resource::juiceagent_api_bytes_name; + + std::string juiceagent_api_path = + JuiceAgent::Utils::File::write_to_tempfile( + JuiceAgent::Resource::juiceagent_api_bytes, + JuiceAgent::Resource::juiceagent_api_bytes_len, + file_name + ); + + // Debug + spdlog::debug("JuiceAgent API path: {}", juiceagent_api_path); + spdlog::debug("JuiceAgent API size: {}", JuiceAgent::Resource::juiceagent_api_bytes_len); + spdlog::debug("JuiceAgent API sha256: {}", JuiceAgent::Resource::juiceagent_api_bytes_sha256); + + // Load JuiceAgent API + jvmtiError status = jvmti->AddToSystemClassLoaderSearch(juiceagent_api_path.c_str()); + if (status != JVMTI_ERROR_NONE) { + spdlog::error("Failed to add JuiceAgent API to system classloader! code: {}", static_cast(status)); + return; + } + + spdlog::info("JuiceAgent API loaded to system classloader!"); + + // Init JuiceAgent via JuiceAgent API + JuiceAgent::Loader::initialize(runtime_dir, env, jvmti); +} + +void JuiceAgent::Loader::initialize(const char* runtime_dir, JNIEnv* env, jvmtiEnv* jvmti) { + const char* bootstrap_class = "cn/xiaozhou233/juiceagent/api/JuiceAgentBootstrap"; + const char* method_name = "start"; + + bool result = JuiceAgent::Utils::call_java_impl(env, bootstrap_class, method_name, runtime_dir); + if (!result) { + spdlog::error("Failed to initialize JuiceAgent!"); + return; + } + + spdlog::info("JuiceAgent initialized!"); +} \ No newline at end of file diff --git a/src/libloader/includes/JvmAttach.hpp b/src/libloader/includes/JvmAttach.hpp index e335161..d42f5bf 100644 --- a/src/libloader/includes/JvmAttach.hpp +++ b/src/libloader/includes/JvmAttach.hpp @@ -1,7 +1,7 @@ #pragma once -#include #include +#include #include #include @@ -9,29 +9,50 @@ namespace JuiceAgent::Loader { -class Jvm { +// RAII wrapper: attaches to the running JVM (with retry) and detaches on destruction. +class JvmAttach { public: - explicit Jvm(int max_try = 30, int retry_delay_ms = 1000) + explicit JvmAttach(int max_try = 30, int retry_delay_ms = 1000) : max_try_(max_try), retry_delay_ms_(retry_delay_ms) {} + ~JvmAttach() { detach(); } + + JvmAttach(const JvmAttach&) = delete; + JvmAttach& operator=(const JvmAttach&) = delete; + JavaVM* get_jvm() const { return jvm_; } JNIEnv* get_env() const { return env_; } jvmtiEnv* get_jvmti() const { return jvmti_; } bool attach() { - reset(); + jvm_ = nullptr; + env_ = nullptr; + jvmti_ = nullptr; + attached_ = false; - return acquire_jvm() && acquire_env() && acquire_jvmti(); + return retry("JavaVM", [this] { + return JNI_GetCreatedJavaVMs(&jvm_, 1, nullptr) == JNI_OK && jvm_; + }) && retry("JNIEnv", [this] { + if (jvm_->GetEnv(reinterpret_cast(&env_), JNI_VERSION_1_8) == JNI_OK && env_) + return true; + env_ = nullptr; + if (jvm_->AttachCurrentThread(reinterpret_cast(&env_), nullptr) == JNI_OK && env_) { + attached_ = true; + return true; + } + return false; + }) && retry("JVMTI", [this] { + return jvm_->GetEnv(reinterpret_cast(&jvmti_), JVMTI_VERSION_1_2) == JNI_OK && jvmti_; + }); } - bool detach() { + bool detach() noexcept { if (jvm_ && attached_) { jint res = jvm_->DetachCurrentThread(); if (res != JNI_OK) { spdlog::debug("DetachCurrentThread failed: {}", res); return false; } - spdlog::debug("Thread detached"); attached_ = false; env_ = nullptr; @@ -40,69 +61,23 @@ public: } private: - static inline thread_local JNIEnv* env_ = nullptr; - - JavaVM* jvm_ = nullptr; - jvmtiEnv* jvmti_ = nullptr; - - bool attached_ = false; - int max_try_; - int retry_delay_ms_; - - void reset() { - jvm_ = nullptr; - jvmti_ = nullptr; - env_ = nullptr; - attached_ = false; - } - - void retry(const char* what, int attempt) { - spdlog::debug("Failed to get {}, attempt {}/{}", what, attempt, max_try_); - std::this_thread::sleep_for(std::chrono::milliseconds(retry_delay_ms_)); - } - template - bool acquire(const char* what, Fn&& attempt) { + bool retry(const char* what, Fn&& attempt) { for (int i = 1; i <= max_try_; i++) { - if (attempt()) { + if (attempt()) return true; - } - retry(what, i); + spdlog::debug("Failed to get {}, attempt {}/{}", what, i, max_try_); + std::this_thread::sleep_for(std::chrono::milliseconds(retry_delay_ms_)); } return false; } - bool acquire_jvm() { - return acquire("JavaVM", [this] { - jvm_ = nullptr; - return JNI_GetCreatedJavaVMs(&jvm_, 1, nullptr) == JNI_OK && jvm_ != nullptr; - }); - } - - bool acquire_env() { - return acquire("JNIEnv", [this] { - env_ = nullptr; - if (jvm_->GetEnv(reinterpret_cast(&env_), JNI_VERSION_1_6) == JNI_OK && env_ != nullptr) { - return true; - } - - env_ = nullptr; - if (jvm_->AttachCurrentThread(reinterpret_cast(&env_), nullptr) == JNI_OK && env_ != nullptr) { - attached_ = true; - return true; - } - - env_ = nullptr; - return false; - }); - } - - bool acquire_jvmti() { - return acquire("JVMTI", [this] { - jvmti_ = nullptr; - return jvm_->GetEnv(reinterpret_cast(&jvmti_), JVMTI_VERSION_1_2) == JNI_OK && jvmti_ != nullptr; - }); - } + JavaVM* jvm_ = nullptr; + JNIEnv* env_ = nullptr; + jvmtiEnv* jvmti_ = nullptr; + bool attached_ = false; + int max_try_; + int retry_delay_ms_; }; } // namespace JuiceAgent::Loader diff --git a/src/libloader/includes/Loader.hpp b/src/libloader/includes/Loader.hpp index dbac22b..8ed1758 100644 --- a/src/libloader/includes/Loader.hpp +++ b/src/libloader/includes/Loader.hpp @@ -1,9 +1,10 @@ #pragma once +#include +#include + namespace JuiceAgent::Loader { - -// Attach to the JVM and initialize JuiceAgent. -// runtime_dir: directory containing config.toml, or nullptr to use defaults. -void entrypoint(const char* runtime_dir); - + void entrypoint(const char* runtime_dir); + void preload(const char* runtime_dir, JNIEnv* env, jvmtiEnv* jvmti); + void initialize(const char* runtime_dir, JNIEnv* env, jvmtiEnv* jvmti); } // namespace JuiceAgent::Loader diff --git a/src/libloader/plantform/windows/DllMain.cpp b/src/libloader/platform/windows/DllMain.cpp similarity index 100% rename from src/libloader/plantform/windows/DllMain.cpp rename to src/libloader/platform/windows/DllMain.cpp diff --git a/src/libloader/plantform/windows/ReflectiveLoader.c b/src/libloader/platform/windows/ReflectiveLoader.c similarity index 100% rename from src/libloader/plantform/windows/ReflectiveLoader.c rename to src/libloader/platform/windows/ReflectiveLoader.c