Feat: add Config/Utils headers and Loader module, wire entrypoint into DllMain

This commit is contained in:
xiaozhou233 committed 2026-08-15 12:26:12 +08:00
1 parent 998f4d139e
commit ce08b19170
11 files changed
+19863

No files matched your search

+3
View File
@@ -18,6 +18,9 @@ add_library(loader SHARED ${loader_sources})
target_include_directories(loader PRIVATE
${CMAKE_SOURCE_DIR}/includes
${CMAKE_SOURCE_DIR}/includes/jvm
${CMAKE_SOURCE_DIR}/includes/jvm/win32
${CMAKE_CURRENT_SOURCE_DIR}/includes
)
target_link_libraries(loader PRIVATE
+129
View File
@@ -0,0 +1,129 @@
#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";
const char* method_desc = "(Ljava/lang/String;)V";
using JuiceAgent::Utils::check_and_clear_exception;
// Find Java class
JuiceAgent::Utils::LocalRef<jclass> cls(env, env->FindClass(bootstrap_class));
if (!cls.get() || check_and_clear_exception(env, "FindClass")) {
spdlog::error("Failed to find class: {}", bootstrap_class);
return false;
}
// Find static method
jmethodID method_id = env->GetStaticMethodID(cls, method_name, method_desc);
if (!method_id || check_and_clear_exception(env, "GetStaticMethodID")) {
spdlog::error("Failed to find method: {}", method_name);
return false;
}
// Serialize InjectionInfo to string
std::string args = JuiceAgent::Config::Utils::serialize_loader_config(config);
spdlog::debug("Invoke args: {}", args);
// Create Java string
jstring jArgs = env->NewStringUTF(args.c_str());
if (!jArgs || check_and_clear_exception(env, "NewStringUTF")) {
spdlog::error("Failed to create jstring");
return false;
}
// Call the static method
env->CallStaticVoidMethod(cls, method_id, jArgs);
// Check for exceptions
if (check_and_clear_exception(env, "CallStaticVoidMethod")) {
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);
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
jint status = jvmti->AddToSystemClassLoaderSearch(juiceagent_api_path.c_str());
if (status != JNI_OK) {
spdlog::error("Failed to add JuiceAgent API to system classloader! code: {}", 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
JuiceAgent::Loader::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);
}
}
+115
View File
@@ -0,0 +1,115 @@
#pragma once
#include <thread>
#include <chrono>
#include <JuiceAgent/Logger.hpp>
#include <jvm/jni.h>
#include <jvm/jvmti.h>
namespace JuiceAgent::Loader {
class Jvm {
public:
explicit Jvm(int max_try = 30, int retry_delay_ms = 1000)
: max_try_(max_try), retry_delay_ms_(retry_delay_ms) {}
JavaVM* get_jvm() const { return jvm_; }
JNIEnv* get_env() const { return env_; }
jvmtiEnv* get_jvmti() const { return jvmti_; }
bool attach() {
reset();
return acquire_jvm() && acquire_env() && acquire_jvmti();
}
bool detach() {
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;
}
return true;
}
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;
}
bool 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_));
return false;
}
bool acquire_jvm() {
for (int i = 1; i <= max_try_; i++) {
jint status = JNI_GetCreatedJavaVMs(&jvm_, 1, nullptr);
if (status == JNI_OK && jvm_ != nullptr) {
spdlog::debug("Got JavaVM");
return true;
}
retry("JavaVM", i);
}
return false;
}
bool acquire_env() {
for (int i = 1; i <= max_try_; i++) {
jint status = jvm_->GetEnv(reinterpret_cast<void**>(&env_), JNI_VERSION_1_6);
if (status == JNI_OK && env_ != nullptr) {
spdlog::debug("Got JNIEnv (already attached)");
return true;
}
status = jvm_->AttachCurrentThread(reinterpret_cast<void**>(&env_), nullptr);
if (status == JNI_OK && env_ != nullptr) {
attached_ = true;
spdlog::debug("Attached current thread");
return true;
}
retry("JNIEnv attach", i);
}
return false;
}
bool acquire_jvmti() {
for (int i = 1; i <= max_try_; i++) {
jint status = jvm_->GetEnv(reinterpret_cast<void**>(&jvmti_), JVMTI_VERSION_1_2);
if (status == JNI_OK && jvmti_ != nullptr) {
spdlog::debug("Got JVMTI");
return true;
}
retry("JVMTI", i);
}
return false;
}
};
} // namespace JuiceAgent::Loader
+9
View File
@@ -0,0 +1,9 @@
#pragma once
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);
} // namespace JuiceAgent::Loader
@@ -1,6 +1,7 @@
#include <windows.h>
#include "JuiceAgent/Logger.hpp"
#include "Loader.hpp"
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved) {
switch (fdwReason) {
@@ -9,6 +10,13 @@ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved) {
Logger::init("libloader.log");
spdlog::info("DllMain: DLL_PROCESS_ATTACH");
// Get the runtime directory from the lpReserved parameter
const char* runtime_dir = (const char*)lpReserved;
spdlog::info("DllMain: runtime_dir: {}", runtime_dir);
JuiceAgent::Loader::entrypoint(runtime_dir);
break;
}