From eb7fd31817855b4c13ab936e41e0b766adc767c2 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Wed, 14 Oct 2026 21:01:14 +0800 Subject: [PATCH] Feat: initialize built-in / custom jar loader and fix entry class lookup - Loader: dispatch initialize() on JarLoader.Mode; BuiltIn serializes the config and calls JuiceAgentBootstrap.start, CustomJar calls the configured EntryClass.EntryMethod - Utils: normalize class names to the JNI internal form ('.' -> '/') so JNI FindClass accepts Java binary names like Example.Main (fixes NoClassDefFoundError on custom jar entry) - Utils: rework Serializer, drop the unused Deserializer/LocalRef, add to_java_string_array / toDelimitedString and a no-argument call_static_java_method overload - Config: remove the unused serialize_loader_config helper --- includes/JuiceAgent/Config.hpp | 10 - includes/JuiceAgent/Utils.hpp | 331 ++++++++++++++------------------- src/libloader/core/Loader.cpp | 40 +++- 3 files changed, 176 insertions(+), 205 deletions(-) diff --git a/includes/JuiceAgent/Config.hpp b/includes/JuiceAgent/Config.hpp index 8e2172e..9a2aac3 100644 --- a/includes/JuiceAgent/Config.hpp +++ b/includes/JuiceAgent/Config.hpp @@ -251,16 +251,6 @@ namespace Utils { spdlog::info("JuiceAgentNativeLibraryPath: {}", config.JuiceAgentNativeLibraryPath); spdlog::info("RuntimeDir: {}", config.RuntimeDir); } - - inline std::string serialize_loader_config(const Config& config, const LoaderConfig& loader_config) - { - JuiceAgent::Utils::Serializer ser; - ser.add_kv("Version", config.get("JuiceAgent.Version", -1)); - ser.add_kv("JuiceAgentNativeLibraryPath", loader_config.JuiceAgentNativeLibraryPath); - ser.add_kv("RuntimeDir", loader_config.RuntimeDir); - - return ser.serialize(); - } } } // namespace JuiceAgent::Config \ No newline at end of file diff --git a/includes/JuiceAgent/Utils.hpp b/includes/JuiceAgent/Utils.hpp index 7d78fd1..b31d817 100644 --- a/includes/JuiceAgent/Utils.hpp +++ b/includes/JuiceAgent/Utils.hpp @@ -10,51 +10,28 @@ #include #include #include +#include +#include +#include namespace JuiceAgent::Utils { - template - class LocalRef { - public: - LocalRef(JNIEnv* env, T ref = nullptr) - : _env(env), _ref(ref) {} + // JNIEnv::FindClass expects the internal form of a class name where the + // package separator is '/' (e.g. "Example/Main"). Configs and docs use the + // Java binary name with '.' (e.g. "Example.Main"), so normalize it here to + // keep both forms working. + inline std::string to_jni_class_name(const char* name) + { + std::string result(name ? name : ""); - ~LocalRef() - { - reset(); - } - - LocalRef(const LocalRef&) = delete; - LocalRef& operator=(const LocalRef&) = delete; - - LocalRef(LocalRef&& other) noexcept - : _env(other._env), _ref(other._ref) - { - other._ref = nullptr; - } - - T get() const - { - return _ref; - } - - operator T() const - { - return _ref; - } - - void reset(T ref = nullptr) - { - if (_ref) { - _env->DeleteLocalRef(_ref); + for (char& c : result) { + if (c == '.') { + c = '/'; } - _ref = ref; } - private: - JNIEnv* _env; - T _ref; - }; + return result; + } inline bool check_and_clear_exception(JNIEnv* env, const char* context) { @@ -68,7 +45,8 @@ namespace JuiceAgent::Utils return true; } - inline bool call_java_impl(JNIEnv* env, const char* clazz, const char* method, const char* params) + // Call a static Java method with a single string parameter + inline bool call_static_java_method(JNIEnv* env, const char* clazz, const char* method, const char* params) { if (!env || !clazz || !method) { spdlog::error("Invalid JNI arguments"); @@ -79,7 +57,8 @@ namespace JuiceAgent::Utils spdlog::debug("Calling Java method: {}.{} {}", clazz, method, signature); - jclass cls = env->FindClass(clazz); + std::string jni_class = to_jni_class_name(clazz); + jclass cls = env->FindClass(jni_class.c_str()); if (!cls) { check_and_clear_exception(env, "FindClass failed"); spdlog::error("Class not found: {}", clazz); @@ -118,210 +97,180 @@ namespace JuiceAgent::Utils return success; } + + inline bool call_static_java_method(JNIEnv* env, const char* clazz, const char* method) + { + if (!env || !clazz || !method) { + spdlog::error("Invalid JNI arguments"); + return false; + } + constexpr const char* signature = "()V"; + + spdlog::debug("Calling Java method: {}.{} {}", clazz, method, signature); + + std::string jni_class = to_jni_class_name(clazz); + jclass cls = env->FindClass(jni_class.c_str()); + if (!cls) { + check_and_clear_exception(env, "FindClass failed"); + spdlog::error("Class not found: {}", clazz); + return false; + } + + jmethodID mid = env->GetStaticMethodID(cls, method, signature); + if (!mid) { + check_and_clear_exception(env, "GetStaticMethodID failed"); + spdlog::error("Method not found: {}", method); + env->DeleteLocalRef(cls); + return false; + } + + env->CallStaticVoidMethod(cls, mid); + + bool success = !env->ExceptionCheck(); + check_and_clear_exception(env, "CallStaticVoidMethod failed"); + + env->DeleteLocalRef(cls); + + return success; + } + class Serializer { public: template - Serializer& add_kv(const std::string& key, const T& value) + Serializer& add_kv(std::string_view key, const T& value) { - s += escape(key); + append_escaped(key); s += '='; - if constexpr (std::is_same_v) { + using ValueType = std::decay_t; + + if constexpr (std::is_same_v) { s += value ? "true" : "false"; } - else if constexpr (std::is_arithmetic_v) { - s += escape(std::to_string(value)); + else if constexpr (std::is_integral_v) { + append_number(value); + } + else if constexpr (std::is_floating_point_v) { + append_number(value); } else { - s += escape(value); + append_escaped(std::string_view(value)); } s += ';'; return *this; } - void clear() + void clear() noexcept { s.clear(); } - bool empty() const + bool empty() const noexcept { return s.empty(); } - const std::string& serialize() const + const std::string& serialize() const noexcept { return s; } private: - static std::string escape(const std::string& input) + void append_escaped(std::string_view input) { - std::string out; - out.reserve(input.size()); - for (char c : input) { if (c == '=' || c == ';' || c == '\\') { - out += '\\'; + s += '\\'; } - out += c; - } - return out; + s += c; + } + } + + template + void append_number(T value) + { + char buffer[64]; + + auto [end, ec] = std::to_chars( + buffer, + buffer + sizeof(buffer), + value + ); + + if (ec == std::errc{}) { + s.append(buffer, end); + } } std::string s; }; - class Deserializer { - public: - Deserializer() = default; + inline jobjectArray to_java_string_array( + JNIEnv* env, + const std::vector& values) + { - explicit Deserializer(const std::string& input) - { - parse(input); + if (!env) { + return nullptr; } - void parse(const std::string& input) - { - data.clear(); - - std::string key; - std::string value; - bool reading_key = true; - bool escaped = false; - - auto commit = [&]() { - if (!key.empty()) { - data[unescape(key)] = unescape(value); - } - key.clear(); - value.clear(); - reading_key = true; - }; - - for (char c : input) { - if (escaped) { - (reading_key ? key : value) += c; - escaped = false; - } - else if (c == '\\') { - escaped = true; - } - else if (reading_key && c == '=') { - reading_key = false; - } - else if (c == ';') { - commit(); - } - else { - (reading_key ? key : value) += c; - } - } - - commit(); + jclass string_class = env->FindClass("java/lang/String"); + if (!string_class) { + return nullptr; } - bool has(const std::string& key) const - { - return data.find(key) != data.end(); + jobjectArray result = env->NewObjectArray( + static_cast(values.size()), + string_class, + nullptr + ); + + if (!result) { + env->DeleteLocalRef(string_class); + return nullptr; } - template - T get(const std::string& key, T def) const - { - auto it = data.find(key); - if (it == data.end()) { - return def; + for (jsize i = 0; i < static_cast(values.size()); ++i) { + jstring value = env->NewStringUTF(values[i].c_str()); + + if (!value) { + env->DeleteLocalRef(result); + env->DeleteLocalRef(string_class); + return nullptr; } - return convert(it->second, def); - } + env->SetObjectArrayElement(result, i, value); + env->DeleteLocalRef(value); - void clear() - { - data.clear(); - } - - bool empty() const - { - return data.empty(); - } - - std::size_t size() const - { - return data.size(); - } - - private: - static std::string unescape(const std::string& input) - { - std::string out; - out.reserve(input.size()); - - bool escaped = false; - - for (char c : input) { - if (escaped) { - out += c; - escaped = false; - } - else if (c == '\\') { - escaped = true; - } - else { - out += c; - } - } - - return out; - } - - static bool to_bool(const std::string& v, bool def) - { - if (v == "true" || v == "1") { - return true; - } - if (v == "false" || v == "0") { - return false; - } - return def; - } - - template - static T convert(const std::string& v, T def) - { - if constexpr (std::is_same_v) { - return v; - } - else if constexpr (std::is_same_v) { - return to_bool(v, def); - } - else if constexpr (std::is_integral_v) { - try { - return static_cast(std::stoll(v)); - } - catch (...) { - return def; - } - } - else if constexpr (std::is_floating_point_v) { - try { - return static_cast(std::stold(v)); - } - catch (...) { - return def; - } - } - else { - return def; + if (env->ExceptionCheck()) { + env->DeleteLocalRef(result); + env->DeleteLocalRef(string_class); + return nullptr; } } - std::unordered_map data; - }; + env->DeleteLocalRef(string_class); + return result; + } + + inline std::string toDelimitedString(const std::vector& values, + const std::string& delimiter = ",") + { + std::string result; + + for (const auto& value : values) { + if (!result.empty()) { + result += delimiter; + } + result += value; + } + + return result; + } + class File { public: diff --git a/src/libloader/core/Loader.cpp b/src/libloader/core/Loader.cpp index 2da701e..cd4b486 100644 --- a/src/libloader/core/Loader.cpp +++ b/src/libloader/core/Loader.cpp @@ -4,8 +4,9 @@ #include #include #include - +#include #include +#include // Preload section // Check parameters and load the runtime @@ -50,7 +51,7 @@ void JuiceAgent::Loader::preload(const char* runtime_dir, JNIEnv* env, jvmtiEnv* } else if(jar_loader_mode == "CustomJar") { spdlog::info("[PreLoad] JarLoader mode: CustomJar"); - std::string jar_path = cfg.get("JarLoader.JarPath"); + std::string jar_path = cfg.getPath("JarLoader.JarPath"); if(!load_custom(jvmti, jar_path.c_str())) { spdlog::error("[PreLoad] Failed to load custom jar: {}", jar_path); @@ -66,7 +67,38 @@ void JuiceAgent::Loader::preload(const char* runtime_dir, JNIEnv* env, jvmtiEnv* void JuiceAgent::Loader::initialize(const char* runtime_dir, JNIEnv* env, jvmtiEnv* jvmti, JuiceAgent::Config::Config& cfg) { std::string jar_loader_mode = cfg.get("JarLoader.Mode"); - // TODO: Implement this + if(jar_loader_mode == "BuiltIn") { + const char* bootstrap_class = "cn/xiaozhou233/juiceagent/api/JuiceAgentBootstrap"; + const char* method_name = "start"; - // spdlog::info("JuiceAgent initialized!"); + JuiceAgent::Utils::Serializer ser; + ser.add_kv("Version", cfg.get("JuiceAgent.Version", -1)); + ser.add_kv("JuiceAgentNativeLibraryPath", cfg.getPath("JuiceAgent.JuiceAgentNativeLibraryPath", (cfg.getRuntimeDir()/"libagent.dll").string())); + ser.add_kv("RuntimeDir", cfg.getRuntimeDir().string()); + + std::string args = ser.serialize(); + spdlog::debug("Serialized config: {}", args); + + bool result = JuiceAgent::Utils::call_static_java_method(env, bootstrap_class, method_name, args.c_str()); + if (!result) { + spdlog::error("Failed to initialize JuiceAgent! (call_static_java_method)"); + return; + } + } else if(jar_loader_mode == "CustomJar") { + spdlog::info("[Initialize] JarLoader mode: CustomJar"); + + std::string entry_class = cfg.get("JarLoader.EntryClass"); + std::string entry_method = cfg.get("JarLoader.EntryMethod"); + spdlog::debug("[Initialize] Entry class: {}, Entry method: {}", entry_class, entry_method); + bool result = JuiceAgent::Utils::call_static_java_method(env, entry_class.c_str(), entry_method.c_str()); + if (!result) { + spdlog::error("Failed to invoke custom jar entry! (call_static_java_method)"); + return; + } + } else { + spdlog::error("[Initialize] Invalid JarLoader mode: {}", jar_loader_mode); + return; + } + + spdlog::info("JuiceAgent initialized!"); } \ No newline at end of file