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
This commit is contained in:
xiaozhou233 committed 2026-08-16 18:53:31 +08:00
1 parent f2ce4e6a5a
commit b34377d447
8 files changed
+139 -175

No files matched your search

+6 -6
View File
@@ -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})
-101
View File
@@ -1,101 +0,0 @@
#include <Loader.hpp>
#include <JvmAttach.hpp>
#include <JuiceAgent/Logger.hpp>
#include <JuiceAgent/Config.hpp>
#include <JuiceAgent/Utils.hpp>
#include <JuiceAgent/JuiceAgent.hpp>
#include <JuiceAgent/JuiceAgent-API-1.4.1+build.1.hpp>
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<int>(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);
}
}
+29
View File
@@ -0,0 +1,29 @@
#include <Loader.hpp>
#include <JvmAttach.hpp>
#include <JuiceAgent/Logger.hpp>
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);
}
+60
View File
@@ -0,0 +1,60 @@
#include <jvm/jni.h>
#include <Loader.hpp>
#include <JuiceAgent/Logger.hpp>
#include <JuiceAgent/Utils.hpp>
#include <JuiceAgent/JuiceAgent-API-1.4.1+build.1.hpp>
// 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<int>(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!");
}
+38 -63
View File
@@ -1,7 +1,7 @@
#pragma once
#include <thread>
#include <chrono>
#include <thread>
#include <JuiceAgent/Logger.hpp>
#include <jvm/jni.h>
@@ -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<void**>(&env_), JNI_VERSION_1_8) == JNI_OK && env_)
return true;
env_ = nullptr;
if (jvm_->AttachCurrentThread(reinterpret_cast<void**>(&env_), nullptr) == JNI_OK && env_) {
attached_ = true;
return true;
}
return false;
}) && retry("JVMTI", [this] {
return jvm_->GetEnv(reinterpret_cast<void**>(&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<typename Fn>
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<void**>(&env_), JNI_VERSION_1_6) == JNI_OK && env_ != nullptr) {
return true;
}
env_ = nullptr;
if (jvm_->AttachCurrentThread(reinterpret_cast<void**>(&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<void**>(&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
+6 -5
View File
@@ -1,9 +1,10 @@
#pragma once
#include <jvm/jni.h>
#include <jvm/jvmti.h>
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